@playcraft/build 0.1.88 → 0.1.90
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 +7 -0
- package/dist/delivery/command-isolation.js +252 -0
- package/dist/delivery/commands.d.ts +5 -0
- package/dist/delivery/commands.js +137 -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.js +1 -1
- package/dist/validation/html-validator.d.ts +2 -0
- package/dist/validation/html-validator.js +16 -14
- package/dist/validation/package-validator.d.ts +2 -0
- package/dist/validation/package-validator.js +24 -15
- package/dist/validation/profiles.d.ts +13 -1
- package/dist/validation/profiles.js +27 -0
- package/dist/validation/types.d.ts +5 -0
- package/dist/validation/validation-runner.d.ts +11 -1
- package/dist/validation/validation-runner.js +37 -2
- package/dist/validation/zip-reader.d.ts +7 -1
- package/dist/validation/zip-reader.js +150 -25
- 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 +15 -3
|
@@ -0,0 +1,877 @@
|
|
|
1
|
+
import fs from 'fs/promises';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { fileURLToPath } from 'url';
|
|
4
|
+
import { resolveScriptSourcePath, buildScriptFolderPath, resolveTargetPathFromImportMap, } from './source-builder-asset-paths.js';
|
|
5
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
6
|
+
/**
|
|
7
|
+
* Analyze script file import dependencies and add missing dependency scripts to config.assets.
|
|
8
|
+
* This handles cases like: BoardRandomFiller.mjs imports ./BoardShapeGenerator.mjs,
|
|
9
|
+
* which is not directly referenced in the scene or templates.
|
|
10
|
+
*/
|
|
11
|
+
async function collectScriptImportDependencies(projectConfig, projectDir, importMap,
|
|
12
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
13
|
+
configAssets) {
|
|
14
|
+
const assets = projectConfig.format === 'playcanvas'
|
|
15
|
+
? projectConfig.assets
|
|
16
|
+
: projectConfig.assets;
|
|
17
|
+
// Build folder ID -> name mapping
|
|
18
|
+
const folderMap = new Map();
|
|
19
|
+
for (const [assetId, asset] of Object.entries(assets)) {
|
|
20
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
21
|
+
if (asset.type === 'folder') {
|
|
22
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
23
|
+
folderMap.set(assetId, asset.name);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
// Build reverse mapping: targetPath -> assetId (for ALL script assets, not just configAssets)
|
|
27
|
+
const targetPathToAssetId = new Map();
|
|
28
|
+
for (const [assetId, asset] of Object.entries(assets)) {
|
|
29
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
30
|
+
const assetData = asset;
|
|
31
|
+
if (assetData.type !== 'script')
|
|
32
|
+
continue;
|
|
33
|
+
const filename = assetData.file?.filename || assetData.name + '.mjs';
|
|
34
|
+
const pathIds = assetData.path || [];
|
|
35
|
+
const folderPath = buildScriptFolderPath(pathIds, folderMap);
|
|
36
|
+
const targetPath = resolveTargetPathFromImportMap(folderPath, filename, importMap);
|
|
37
|
+
if (targetPath) {
|
|
38
|
+
targetPathToAssetId.set(targetPath.replace(/\\/g, '/'), assetId);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
// Regex to extract import specifiers from script content
|
|
42
|
+
const importRegex = /(from\s+['"])([^'"]+)(['"])|(\bimport\s*\(\s*['"])([^'"]+)(['"]\s*\))/g;
|
|
43
|
+
const importsMap = importMap.content.imports || {};
|
|
44
|
+
// Iteratively discover new script dependencies
|
|
45
|
+
const processedScripts = new Set();
|
|
46
|
+
let newDepsFound = true;
|
|
47
|
+
while (newDepsFound) {
|
|
48
|
+
newDepsFound = false;
|
|
49
|
+
const currentScriptIds = Object.keys(configAssets).filter(
|
|
50
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
51
|
+
(id) => configAssets[id].type === 'script' && !processedScripts.has(id));
|
|
52
|
+
for (const scriptId of currentScriptIds) {
|
|
53
|
+
processedScripts.add(scriptId);
|
|
54
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
55
|
+
const assetData = assets[scriptId];
|
|
56
|
+
if (!assetData)
|
|
57
|
+
continue;
|
|
58
|
+
// Resolve source file path
|
|
59
|
+
const sourcePath = await resolveScriptSourcePath(assetData, scriptId, projectDir);
|
|
60
|
+
if (!sourcePath)
|
|
61
|
+
continue;
|
|
62
|
+
let content;
|
|
63
|
+
try {
|
|
64
|
+
content = await fs.readFile(sourcePath, 'utf-8');
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
// Get current script's target path for relative path resolution
|
|
70
|
+
const filename = assetData.file?.filename || assetData.name + '.mjs';
|
|
71
|
+
const pathIds = assetData.path || [];
|
|
72
|
+
const folderPath = buildScriptFolderPath(pathIds, folderMap);
|
|
73
|
+
const scriptTargetPath = resolveTargetPathFromImportMap(folderPath, filename, importMap);
|
|
74
|
+
if (!scriptTargetPath)
|
|
75
|
+
continue;
|
|
76
|
+
const scriptDir = path.dirname(scriptTargetPath).replace(/\\/g, '/');
|
|
77
|
+
// Parse all import statements
|
|
78
|
+
let match;
|
|
79
|
+
importRegex.lastIndex = 0;
|
|
80
|
+
while ((match = importRegex.exec(content)) !== null) {
|
|
81
|
+
const modulePath = match[2] || match[5];
|
|
82
|
+
if (!modulePath)
|
|
83
|
+
continue;
|
|
84
|
+
let resolvedTargetPath = null;
|
|
85
|
+
if (modulePath.startsWith('./') || modulePath.startsWith('../')) {
|
|
86
|
+
// Relative import: resolve against script's directory
|
|
87
|
+
const joined = path.posix.join(scriptDir, modulePath);
|
|
88
|
+
resolvedTargetPath = path.posix.normalize(joined);
|
|
89
|
+
}
|
|
90
|
+
else if (!modulePath.startsWith('/') && !modulePath.startsWith('http')) {
|
|
91
|
+
// Import Map alias: resolve via import map
|
|
92
|
+
resolvedTargetPath = resolveModulePathViaImportMap(modulePath, importsMap);
|
|
93
|
+
}
|
|
94
|
+
if (!resolvedTargetPath)
|
|
95
|
+
continue;
|
|
96
|
+
resolvedTargetPath = resolvedTargetPath.replace(/\\/g, '/');
|
|
97
|
+
// Look up the asset by target path
|
|
98
|
+
const depAssetId = targetPathToAssetId.get(resolvedTargetPath);
|
|
99
|
+
if (depAssetId === undefined) {
|
|
100
|
+
console.warn(`Warning: resolvedTargetPath '${resolvedTargetPath}' not found in targetPathToAssetId`);
|
|
101
|
+
}
|
|
102
|
+
else if (!configAssets[depAssetId]) {
|
|
103
|
+
// Found a missing dependency — add it to configAssets
|
|
104
|
+
configAssets[depAssetId] = assets[depAssetId];
|
|
105
|
+
newDepsFound = true;
|
|
106
|
+
console.log(
|
|
107
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
108
|
+
`📜 [ScriptDeps] ${assetData.name} imports ${assets[depAssetId].name} (${depAssetId}) — added to configAssets`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* 生成 ESM 模板文件
|
|
116
|
+
*/
|
|
117
|
+
export async function generateESMTemplate(projectConfig, options,
|
|
118
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
119
|
+
config) {
|
|
120
|
+
const templatesDir = path.resolve(__dirname, '../../templates');
|
|
121
|
+
const outputDir = options.outputDir;
|
|
122
|
+
// 1. 生成 index.html (修复 Import Map 路径)
|
|
123
|
+
const htmlTemplate = await fs.readFile(path.join(templatesDir, 'index.esm.html'), 'utf-8');
|
|
124
|
+
const projectName = projectConfig.format === 'playcanvas'
|
|
125
|
+
? projectConfig.project.name || 'PlayCanvas Project'
|
|
126
|
+
: projectConfig.manifest.name || 'PlayCanvas Project';
|
|
127
|
+
// 修复 Import Map 中的路径(将 ./Lib/ 改为 ./)
|
|
128
|
+
const fixedImportMap = fixImportMapPaths(options.importMap?.content || { imports: {} });
|
|
129
|
+
const importMapJson = JSON.stringify(fixedImportMap, null, 2);
|
|
130
|
+
const html = htmlTemplate
|
|
131
|
+
.replace(/\{\{PROJECT_NAME\}\}/g, projectName)
|
|
132
|
+
.replace(/\{\{IMPORT_MAP\}\}/g, importMapJson);
|
|
133
|
+
await fs.writeFile(path.join(outputDir, 'index.html'), html, 'utf-8');
|
|
134
|
+
// 2. 复制 PlayCanvas Engine(UMD 格式)和 ESM 包装器
|
|
135
|
+
const jsDir = path.join(outputDir, 'js');
|
|
136
|
+
await fs.mkdir(jsDir, { recursive: true });
|
|
137
|
+
// 复制 UMD 引擎
|
|
138
|
+
const engineSourcePath = path.join(templatesDir, 'playcanvas-stable.min.js');
|
|
139
|
+
const engineTargetPath = path.join(jsDir, 'playcanvas-engine-umd.js');
|
|
140
|
+
try {
|
|
141
|
+
await fs.copyFile(engineSourcePath, engineTargetPath);
|
|
142
|
+
console.log('[SourceBuilder] PlayCanvas Engine (UMD) 已复制');
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
console.warn('[SourceBuilder] 警告: 无法复制 PlayCanvas Engine:', error);
|
|
146
|
+
}
|
|
147
|
+
// 复制 ESM 包装器
|
|
148
|
+
const wrapperSourcePath = path.join(templatesDir, 'playcanvas-esm-wrapper.mjs');
|
|
149
|
+
const wrapperTargetPath = path.join(jsDir, 'playcanvas-engine.mjs');
|
|
150
|
+
try {
|
|
151
|
+
await fs.copyFile(wrapperSourcePath, wrapperTargetPath);
|
|
152
|
+
console.log('[SourceBuilder] PlayCanvas ESM 包装器已复制');
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
console.warn('[SourceBuilder] 警告: 无法复制 ESM 包装器:', error);
|
|
156
|
+
}
|
|
157
|
+
// 3. 分析脚本文件的 import 依赖,将缺失的依赖脚本添加到 config.assets
|
|
158
|
+
if (options.importMap) {
|
|
159
|
+
await collectScriptImportDependencies(projectConfig, options.projectDir, options.importMap, config.assets);
|
|
160
|
+
}
|
|
161
|
+
// 4. 收集用户脚本的导入路径(传入 config.assets 以包含 template 依赖 + import 依赖的脚本)
|
|
162
|
+
const scriptImportPaths = await collectESMScriptImports(projectConfig, options, config.assets);
|
|
163
|
+
// 5. 从 Import Map 中提取 gameRule 路径
|
|
164
|
+
let gameRulePath = '';
|
|
165
|
+
if (options.importMap?.content?.imports) {
|
|
166
|
+
const imports = options.importMap.content.imports;
|
|
167
|
+
if (imports['gameRule']) {
|
|
168
|
+
// 将 "./Generated/..." 格式转换为相对于 js/ 目录的路径 "../Generated/..."
|
|
169
|
+
gameRulePath = imports['gameRule'];
|
|
170
|
+
if (gameRulePath.startsWith('./')) {
|
|
171
|
+
gameRulePath = '..' + gameRulePath.slice(1); // "./" -> "../"
|
|
172
|
+
}
|
|
173
|
+
console.log(`[SourceBuilder] GameRule 路径: ${gameRulePath}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
// 5.1 从场景 SystemManager 的 GameConfig.json 中收集 Rule 脚本
|
|
177
|
+
if (options.importMap && projectConfig.format === 'playcanvas') {
|
|
178
|
+
const allAssets = projectConfig.assets || {};
|
|
179
|
+
const pcScenes = projectConfig.scenes;
|
|
180
|
+
// Iterate over selected scenes (from config.scenes) and find the scene data
|
|
181
|
+
for (const sceneRef of config.scenes || []) {
|
|
182
|
+
// Extract scene file ID from url (e.g. "4577025.json" -> "4577025")
|
|
183
|
+
const sceneFileId = (sceneRef.url || '').replace(/\.json$/, '');
|
|
184
|
+
const sceneData = pcScenes?.[sceneFileId];
|
|
185
|
+
if (!sceneData?.entities)
|
|
186
|
+
continue;
|
|
187
|
+
// Find SystemManager entity
|
|
188
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
189
|
+
for (const [, entity] of Object.entries(sceneData.entities)) {
|
|
190
|
+
if (entity?.name !== 'SystemManager')
|
|
191
|
+
continue;
|
|
192
|
+
const smScript = entity.components?.script?.scripts?.systemManager;
|
|
193
|
+
if (!smScript?.attributes?.gameConfigAsset)
|
|
194
|
+
continue;
|
|
195
|
+
const jsonAssetId = String(smScript.attributes.gameConfigAsset);
|
|
196
|
+
const jsonAsset = allAssets[jsonAssetId];
|
|
197
|
+
if (!jsonAsset || jsonAsset.type !== 'json')
|
|
198
|
+
continue;
|
|
199
|
+
// Read the GameConfig JSON file
|
|
200
|
+
const jsonFilePath = await resolveScriptSourcePath(jsonAsset, jsonAssetId, options.projectDir, allAssets);
|
|
201
|
+
if (!jsonFilePath)
|
|
202
|
+
continue;
|
|
203
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
204
|
+
let gameConfig;
|
|
205
|
+
try {
|
|
206
|
+
const content = await fs.readFile(jsonFilePath, 'utf-8');
|
|
207
|
+
gameConfig = JSON.parse(content);
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
console.warn(`[SourceBuilder] 无法读取 GameConfig.json (${jsonAssetId})`);
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
const ruleName = gameConfig?.Gameplay?.Rule;
|
|
214
|
+
if (!ruleName)
|
|
215
|
+
continue;
|
|
216
|
+
// Resolve Rule script: look for a script asset named "{ruleName}.mjs"
|
|
217
|
+
const ruleFileName = `${ruleName}.mjs`;
|
|
218
|
+
let ruleAssetId = null;
|
|
219
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
220
|
+
for (const [assetId, asset] of Object.entries(allAssets)) {
|
|
221
|
+
if (asset.type === 'script' &&
|
|
222
|
+
(asset.file?.filename === ruleFileName || asset.name === ruleFileName)) {
|
|
223
|
+
ruleAssetId = assetId;
|
|
224
|
+
break;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (ruleAssetId && !config.assets[ruleAssetId]) {
|
|
228
|
+
config.assets[ruleAssetId] = allAssets[ruleAssetId];
|
|
229
|
+
console.log(`📜 [GameConfig] Rule "${ruleName}" → 资源 ${ruleAssetId} — added to configAssets`);
|
|
230
|
+
// Also collect its import dependencies
|
|
231
|
+
if (options.importMap) {
|
|
232
|
+
await collectScriptImportDependencies(projectConfig, options.projectDir, options.importMap, config.assets);
|
|
233
|
+
}
|
|
234
|
+
// Rebuild script import paths to include the new Rule script
|
|
235
|
+
const newPaths = await collectESMScriptImports(projectConfig, options, config.assets);
|
|
236
|
+
for (const p of newPaths) {
|
|
237
|
+
if (!scriptImportPaths.includes(p)) {
|
|
238
|
+
scriptImportPaths.push(p);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
else if (ruleAssetId) {
|
|
243
|
+
console.log(`📜 [GameConfig] Rule "${ruleName}" → 资源 ${ruleAssetId} — already in configAssets`);
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
console.warn(`⚠️ [GameConfig] Rule "${ruleName}" 对应的脚本 ${ruleFileName} 未找到`);
|
|
247
|
+
}
|
|
248
|
+
// Use the rule path from 5.1 if Import Map didn't provide a gameRule mapping (step 5)
|
|
249
|
+
if (ruleAssetId && !gameRulePath) {
|
|
250
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
251
|
+
const ruleAsset = allAssets[ruleAssetId];
|
|
252
|
+
// Build folder map for path resolution
|
|
253
|
+
const folderMap = new Map();
|
|
254
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
255
|
+
for (const [aid, a] of Object.entries(allAssets)) {
|
|
256
|
+
if (a.type === 'folder')
|
|
257
|
+
folderMap.set(aid, a.name);
|
|
258
|
+
}
|
|
259
|
+
const ruleFilename = ruleAsset.file?.filename || ruleAsset.name + '.mjs';
|
|
260
|
+
const ruleFolderPath = buildScriptFolderPath(ruleAsset.path || [], folderMap);
|
|
261
|
+
const targetPath = resolveTargetPathFromImportMap(ruleFolderPath, ruleFilename, options.importMap);
|
|
262
|
+
if (targetPath) {
|
|
263
|
+
gameRulePath = '../' + targetPath;
|
|
264
|
+
console.log(`📜 [GameConfig] 使用 5.1 收集的 Rule 路径: ${gameRulePath}`);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
// 6. 生成 js/index.mjs(包含脚本导入),使用过滤后的 config.scenes
|
|
271
|
+
await generateESMEntry(projectConfig, outputDir, scriptImportPaths, config.scenes, gameRulePath);
|
|
272
|
+
// 7. 在 ESM 模式下,复制用户脚本为独立文件,并更新 config.assets 中的 URL
|
|
273
|
+
if (options.importMap) {
|
|
274
|
+
const scriptUrlMap = await copyUserScriptsForESM(projectConfig, options.projectDir, outputDir, options.importMap, config.assets);
|
|
275
|
+
console.log('[SourceBuilder] 用户脚本已复制为独立 ESM 模块');
|
|
276
|
+
// 更新 config.assets 中脚本的 URL
|
|
277
|
+
if (scriptUrlMap.size > 0 && config.assets) {
|
|
278
|
+
for (const [scriptId, newUrl] of scriptUrlMap) {
|
|
279
|
+
if (config.assets[scriptId] && config.assets[scriptId].file) {
|
|
280
|
+
config.assets[scriptId].file.url = newUrl;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
// 重新写入 config.json
|
|
284
|
+
await fs.writeFile(path.join(outputDir, 'config.json'), JSON.stringify(config, null, 2), 'utf-8');
|
|
285
|
+
console.log(`[SourceBuilder] 更新了 ${scriptUrlMap.size} 个脚本的 URL`);
|
|
286
|
+
}
|
|
287
|
+
// 8. 复制 Import Map 中引用的第三方库文件
|
|
288
|
+
await copyImportMapLibraries(projectConfig, options.projectDir, outputDir, options.importMap);
|
|
289
|
+
}
|
|
290
|
+
// 9. 复制其他必要的模板文件
|
|
291
|
+
const templateFiles = [
|
|
292
|
+
'__start__.js', // 可能不需要了,但先保留
|
|
293
|
+
'__modules__.js',
|
|
294
|
+
'__loading__.js',
|
|
295
|
+
'styles.css',
|
|
296
|
+
'manifest.json',
|
|
297
|
+
];
|
|
298
|
+
for (const file of templateFiles) {
|
|
299
|
+
const sourcePath = path.join(templatesDir, file);
|
|
300
|
+
const targetPath = path.join(outputDir, file);
|
|
301
|
+
try {
|
|
302
|
+
await fs.copyFile(sourcePath, targetPath);
|
|
303
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
304
|
+
}
|
|
305
|
+
catch (error) {
|
|
306
|
+
// 某些文件可能不存在,忽略
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* 修复 Import Map 中的路径
|
|
312
|
+
* 将 ./Lib/xxx.mjs 等错误路径修复为正确的相对路径
|
|
313
|
+
* 并添加必要的模块映射(如 playcanvas)
|
|
314
|
+
*/
|
|
315
|
+
function fixImportMapPaths(importMap) {
|
|
316
|
+
const fixedImports = {};
|
|
317
|
+
// 添加 playcanvas 引擎映射(脚本中使用 import from 'playcanvas')
|
|
318
|
+
fixedImports['playcanvas'] = './js/playcanvas-engine.mjs';
|
|
319
|
+
for (const [key, value] of Object.entries(importMap.imports || {})) {
|
|
320
|
+
// 修复 ./Lib/ 路径(通常第三方库文件会被复制到根目录)
|
|
321
|
+
let fixedValue = value;
|
|
322
|
+
if (value.startsWith('./Lib/')) {
|
|
323
|
+
// 将 ./Lib/xxx.mjs 改为 ./xxx.mjs
|
|
324
|
+
fixedValue = './' + value.slice(6);
|
|
325
|
+
}
|
|
326
|
+
fixedImports[key] = fixedValue;
|
|
327
|
+
}
|
|
328
|
+
return { imports: fixedImports };
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* 收集 ESM 脚本的导入路径
|
|
332
|
+
* @param configAssets - generateConfig 过滤后的 config.assets,包含 template 依赖的脚本
|
|
333
|
+
*/
|
|
334
|
+
async function collectESMScriptImports(projectConfig, options,
|
|
335
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
336
|
+
configAssets) {
|
|
337
|
+
// 获取资产(支持 PlayCanvas 和 PlayCraft 两种格式)
|
|
338
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
339
|
+
let assets;
|
|
340
|
+
if (projectConfig.format === 'playcanvas') {
|
|
341
|
+
assets = projectConfig.assets;
|
|
342
|
+
}
|
|
343
|
+
else {
|
|
344
|
+
assets = projectConfig.assets;
|
|
345
|
+
}
|
|
346
|
+
// 收集所有需要导入的脚本 ID:
|
|
347
|
+
// 1. config.assets 中的 script 类型资产(已包含场景依赖 + template 依赖的脚本)
|
|
348
|
+
// 2. 回退到 settings.scripts(当没有 configAssets 时)
|
|
349
|
+
const scriptIdsToImport = new Set();
|
|
350
|
+
if (configAssets) {
|
|
351
|
+
console.log(`📜 [DEBUG-ESMImports] 使用 configAssets 收集脚本, configAssets 总数: ${Object.keys(configAssets).length}`);
|
|
352
|
+
for (const [assetId, asset] of Object.entries(configAssets)) {
|
|
353
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
354
|
+
if (asset.type === 'script') {
|
|
355
|
+
scriptIdsToImport.add(assetId);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
console.log(`[ESMImports] 从 configAssets 收集到 ${scriptIdsToImport.size} 个脚本`);
|
|
359
|
+
}
|
|
360
|
+
else {
|
|
361
|
+
console.log(`[ESMImports] configAssets 未传入, 回退到 settings.scripts`);
|
|
362
|
+
// Fallback: use settings.scripts
|
|
363
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
364
|
+
let scriptIds;
|
|
365
|
+
if (projectConfig.format === 'playcanvas') {
|
|
366
|
+
scriptIds = projectConfig.project.settings?.scripts || [];
|
|
367
|
+
}
|
|
368
|
+
else {
|
|
369
|
+
scriptIds = projectConfig.manifest.settings?.scripts || [];
|
|
370
|
+
}
|
|
371
|
+
for (const id of scriptIds) {
|
|
372
|
+
scriptIdsToImport.add(String(id));
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
const importPaths = [];
|
|
376
|
+
// 构建文件夹 ID 到名称的映射
|
|
377
|
+
const folderMap = new Map();
|
|
378
|
+
for (const [assetId, asset] of Object.entries(assets)) {
|
|
379
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
380
|
+
const assetData = asset;
|
|
381
|
+
if (assetData.type === 'folder') {
|
|
382
|
+
folderMap.set(assetId, assetData.name);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
// 遍历每个脚本,构建导入路径
|
|
386
|
+
for (const scriptId of scriptIdsToImport) {
|
|
387
|
+
const asset = assets[String(scriptId)];
|
|
388
|
+
if (!asset || asset.type !== 'script')
|
|
389
|
+
continue;
|
|
390
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
391
|
+
const assetData = asset;
|
|
392
|
+
// 获取正确的文件名(带扩展名)
|
|
393
|
+
const filename = assetData.file?.filename || assetData.name + '.mjs';
|
|
394
|
+
// 获取脚本的文件夹路径
|
|
395
|
+
const pathIds = assetData.path || [];
|
|
396
|
+
const folderPath = buildScriptFolderPath(pathIds, folderMap);
|
|
397
|
+
// 根据 import map 确定目标路径
|
|
398
|
+
if (options.importMap) {
|
|
399
|
+
const targetPath = resolveTargetPathFromImportMap(folderPath, filename, options.importMap);
|
|
400
|
+
console.log(`[ESM Imports] ${assetData.name}: folderPath=${folderPath}, filename=${filename}, targetPath=${targetPath}`);
|
|
401
|
+
if (targetPath) {
|
|
402
|
+
// 生成相对于 js/ 目录的导入路径
|
|
403
|
+
// 入口文件在 js/index.mjs,脚本在根目录,所以需要 ../
|
|
404
|
+
importPaths.push('../' + targetPath);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return importPaths;
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* 生成 ESM 入口文件 js/index.mjs
|
|
412
|
+
*/
|
|
413
|
+
async function generateESMEntry(projectConfig, outputDir, scriptImportPaths = [], configScenes, gameRulePath = '') {
|
|
414
|
+
const templatesDir = path.resolve(__dirname, '../../templates');
|
|
415
|
+
const esmTemplate = await fs.readFile(path.join(templatesDir, 'index.esm.mjs'), 'utf-8');
|
|
416
|
+
// 获取项目设置
|
|
417
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
418
|
+
let settings;
|
|
419
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
420
|
+
let scripts = [];
|
|
421
|
+
if (projectConfig.format === 'playcanvas') {
|
|
422
|
+
const pcProject = projectConfig;
|
|
423
|
+
settings = pcProject.project.settings || {};
|
|
424
|
+
scripts = settings.scripts || [];
|
|
425
|
+
}
|
|
426
|
+
else {
|
|
427
|
+
const pcProject = projectConfig;
|
|
428
|
+
settings = pcProject.manifest.settings || {};
|
|
429
|
+
scripts = settings.scripts || [];
|
|
430
|
+
}
|
|
431
|
+
// 确定场景路径(优先使用传入的 configScenes,否则从原始 projectConfig 获取)
|
|
432
|
+
let scenePath = '';
|
|
433
|
+
if (configScenes && configScenes.length > 0) {
|
|
434
|
+
// 使用过滤后的配置场景
|
|
435
|
+
scenePath = configScenes[0].url;
|
|
436
|
+
}
|
|
437
|
+
else if (projectConfig.format === 'playcanvas') {
|
|
438
|
+
const pcProject = projectConfig;
|
|
439
|
+
if (pcProject.scenes) {
|
|
440
|
+
const scenes = Array.isArray(pcProject.scenes)
|
|
441
|
+
? pcProject.scenes
|
|
442
|
+
: Object.values(pcProject.scenes);
|
|
443
|
+
if (scenes.length > 0) {
|
|
444
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
445
|
+
const firstScene = scenes[0];
|
|
446
|
+
scenePath = firstScene.url || firstScene.file || `${firstScene.id || 'scene'}.json`;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
else {
|
|
451
|
+
const pcProject = projectConfig;
|
|
452
|
+
if (pcProject.scenes && pcProject.scenes.length > 0) {
|
|
453
|
+
const firstScene = pcProject.scenes[0];
|
|
454
|
+
scenePath = firstScene.url || `${firstScene.id || 'scene'}.json`;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
// 构建 CONTEXT_OPTIONS
|
|
458
|
+
const contextOptions = {
|
|
459
|
+
antialias: settings.antiAlias ?? true,
|
|
460
|
+
alpha: false,
|
|
461
|
+
preserveDrawingBuffer: settings.preserveDrawingBuffer ?? false,
|
|
462
|
+
deviceTypes: ['webgl2', 'webgl1'],
|
|
463
|
+
powerPreference: settings.powerPreference || 'high-performance',
|
|
464
|
+
};
|
|
465
|
+
// 构建 INPUT_SETTINGS
|
|
466
|
+
const inputSettings = {
|
|
467
|
+
useKeyboard: settings.useKeyboard ?? true,
|
|
468
|
+
useMouse: settings.useMouse ?? true,
|
|
469
|
+
useGamepads: settings.useGamepads ?? false,
|
|
470
|
+
useTouch: settings.useTouch ?? true,
|
|
471
|
+
};
|
|
472
|
+
// 提取预加载模块(WASM 等)
|
|
473
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
474
|
+
const preloadModules = [];
|
|
475
|
+
// TODO: 从 assets 中提取 WASM 模块
|
|
476
|
+
// 生成脚本导入路径数组(延迟加载)
|
|
477
|
+
console.log(`[ESMEntry] 生成 ${scriptImportPaths.length} 个脚本导入路径`);
|
|
478
|
+
// 替换模板占位符
|
|
479
|
+
const entry = esmTemplate
|
|
480
|
+
.replace(/\{\{SCRIPT_IMPORT_PATHS\}\}/g, JSON.stringify(scriptImportPaths))
|
|
481
|
+
.replace(/\{\{GAME_RULE_PATH\}\}/g, gameRulePath)
|
|
482
|
+
.replace(/\{\{ASSET_PREFIX\}\}/g, '')
|
|
483
|
+
.replace(/\{\{SCRIPT_PREFIX\}\}/g, '')
|
|
484
|
+
.replace(/\{\{SCENE_PATH\}\}/g, scenePath)
|
|
485
|
+
.replace(/\{\{CONTEXT_OPTIONS\}\}/g, JSON.stringify(contextOptions))
|
|
486
|
+
.replace(/\{\{SCRIPTS\}\}/g, JSON.stringify(scripts))
|
|
487
|
+
.replace(/\{\{INPUT_SETTINGS\}\}/g, JSON.stringify(inputSettings))
|
|
488
|
+
.replace(/\{\{PRELOAD_MODULES\}\}/g, JSON.stringify(preloadModules))
|
|
489
|
+
.replace(/\{\{LEGACY_SCRIPTS\}\}/g, String(settings.useLegacyScripts ?? false));
|
|
490
|
+
// 写入 js/index.mjs
|
|
491
|
+
const jsDir = path.join(outputDir, 'js');
|
|
492
|
+
await fs.mkdir(jsDir, { recursive: true });
|
|
493
|
+
await fs.writeFile(path.join(jsDir, 'index.mjs'), entry, 'utf-8');
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* 在 ESM 模式下复制用户脚本为独立文件
|
|
497
|
+
* @param configAssets - generateConfig 过滤后的 config.assets,包含 template 依赖的脚本
|
|
498
|
+
* @returns 脚本ID到新URL的映射
|
|
499
|
+
*/
|
|
500
|
+
async function copyUserScriptsForESM(projectConfig, projectDir, outputDir, importMap,
|
|
501
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
502
|
+
configAssets) {
|
|
503
|
+
const scriptUrlMap = new Map();
|
|
504
|
+
// 获取资产(支持 PlayCanvas 和 PlayCraft 两种格式)
|
|
505
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
506
|
+
let assets;
|
|
507
|
+
if (projectConfig.format === 'playcanvas') {
|
|
508
|
+
assets = projectConfig.assets;
|
|
509
|
+
}
|
|
510
|
+
else {
|
|
511
|
+
assets = projectConfig.assets;
|
|
512
|
+
}
|
|
513
|
+
// 收集所有需要复制的脚本 ID:
|
|
514
|
+
// 1. config.assets 中的 script 类型资产(已包含场景依赖 + template 依赖的脚本)
|
|
515
|
+
// 2. 回退到 settings.scripts(当没有 configAssets 时)
|
|
516
|
+
const scriptIdsToProcess = new Set();
|
|
517
|
+
if (configAssets) {
|
|
518
|
+
for (const [assetId, asset] of Object.entries(configAssets)) {
|
|
519
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
520
|
+
if (asset.type === 'script') {
|
|
521
|
+
scriptIdsToProcess.add(assetId);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
else {
|
|
526
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
527
|
+
let scriptIds;
|
|
528
|
+
if (projectConfig.format === 'playcanvas') {
|
|
529
|
+
scriptIds = projectConfig.project.settings?.scripts || [];
|
|
530
|
+
}
|
|
531
|
+
else {
|
|
532
|
+
scriptIds = projectConfig.manifest.settings?.scripts || [];
|
|
533
|
+
}
|
|
534
|
+
for (const id of scriptIds) {
|
|
535
|
+
scriptIdsToProcess.add(String(id));
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
console.log(`[copyUserScriptsForESM] 复制 ${scriptIdsToProcess.size} 个脚本`);
|
|
539
|
+
// 构建文件夹 ID 到名称的映射
|
|
540
|
+
const folderMap = new Map();
|
|
541
|
+
for (const [assetId, asset] of Object.entries(assets)) {
|
|
542
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
543
|
+
const assetData = asset;
|
|
544
|
+
if (assetData.type === 'folder') {
|
|
545
|
+
folderMap.set(assetId, assetData.name);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
// 遍历每个脚本
|
|
549
|
+
for (const scriptId of scriptIdsToProcess) {
|
|
550
|
+
const asset = assets[String(scriptId)];
|
|
551
|
+
if (!asset || asset.type !== 'script')
|
|
552
|
+
continue;
|
|
553
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
554
|
+
const assetData = asset;
|
|
555
|
+
// 获取脚本源文件路径(使用统一的解析函数,支持 PlayCraft Git 仓库结构)
|
|
556
|
+
const sourcePath = await resolveScriptSourcePath(assetData, String(scriptId), projectDir, assets);
|
|
557
|
+
if (!sourcePath) {
|
|
558
|
+
console.warn(`[ESM] 无法找到脚本 ${assetData.name} 的源文件,跳过`);
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
// 获取脚本的文件夹路径
|
|
562
|
+
const pathIds = assetData.path || [];
|
|
563
|
+
const folderPath = buildScriptFolderPath(pathIds, folderMap);
|
|
564
|
+
// 获取正确的文件名(带扩展名)
|
|
565
|
+
const scriptFilename = assetData.file?.filename || assetData.name + '.mjs';
|
|
566
|
+
// 根据 import map 确定目标路径
|
|
567
|
+
const targetPath = resolveTargetPathFromImportMap(folderPath, scriptFilename, importMap);
|
|
568
|
+
if (!targetPath) {
|
|
569
|
+
console.warn(`[ESM] 无法为脚本 ${assetData.name} 确定目标路径,跳过`);
|
|
570
|
+
continue;
|
|
571
|
+
}
|
|
572
|
+
console.log(`[ESM] 脚本 ${assetData.name}: folderPath=${folderPath}, targetPath=${targetPath}`);
|
|
573
|
+
// 复制文件(并重写 import 语句中的 Import Map 别名)
|
|
574
|
+
const outputPath = path.join(outputDir, targetPath);
|
|
575
|
+
try {
|
|
576
|
+
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
|
577
|
+
// 读取源文件
|
|
578
|
+
let content = await fs.readFile(sourcePath, 'utf-8');
|
|
579
|
+
// 修复已知的代码问题(如未定义变量的错误日志)
|
|
580
|
+
console.log(`[copyUserScriptsForESM] 处理脚本: ${assetData.name}`);
|
|
581
|
+
content = fixKnownCodeIssues(content, assetData.name);
|
|
582
|
+
// 重写 import 语句,将 Import Map 别名转换为相对路径
|
|
583
|
+
content = rewriteImportsWithImportMap(content, targetPath, importMap);
|
|
584
|
+
// 重写 pc.app 访问,确保在 ESM 模式下能正确获取 app 实例
|
|
585
|
+
content = rewritePcAppAccess(content);
|
|
586
|
+
// 写入目标文件
|
|
587
|
+
await fs.writeFile(outputPath, content, 'utf-8');
|
|
588
|
+
// 记录脚本ID到新URL的映射
|
|
589
|
+
scriptUrlMap.set(String(scriptId), targetPath);
|
|
590
|
+
}
|
|
591
|
+
catch (error) {
|
|
592
|
+
console.warn(`[ESM] 无法复制脚本 ${assetData.name}:`, error);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return scriptUrlMap;
|
|
596
|
+
}
|
|
597
|
+
/**
|
|
598
|
+
* 重写脚本内容中的 import 语句
|
|
599
|
+
* 将 Import Map 别名转换为相对于脚本位置的相对路径
|
|
600
|
+
*/
|
|
601
|
+
function rewriteImportsWithImportMap(content, scriptTargetPath, importMap) {
|
|
602
|
+
const imports = importMap.content.imports || {};
|
|
603
|
+
// 获取脚本所在目录(相对于输出根目录)
|
|
604
|
+
const scriptDir = path.dirname(scriptTargetPath);
|
|
605
|
+
// 正则匹配 import 语句中的模块说明符
|
|
606
|
+
// 匹配: import ... from 'xxx' 或 import ... from "xxx" 或 import('xxx') 等
|
|
607
|
+
const importRegex = /(from\s+['"])([^'"]+)(['"])|(\bimport\s*\(\s*['"])([^'"]+)(['"]\s*\))/g;
|
|
608
|
+
return content.replace(importRegex, (match, p1, p2, p3, p4, p5, p6) => {
|
|
609
|
+
const prefix = p1 || p4;
|
|
610
|
+
const modulePath = p2 || p5;
|
|
611
|
+
const suffix = p3 || p6;
|
|
612
|
+
// 如果已经是相对路径(./ 或 ../)或绝对路径(/ 或 http),不处理
|
|
613
|
+
if (modulePath.startsWith('./') ||
|
|
614
|
+
modulePath.startsWith('../') ||
|
|
615
|
+
modulePath.startsWith('/') ||
|
|
616
|
+
modulePath.startsWith('http://') ||
|
|
617
|
+
modulePath.startsWith('https://')) {
|
|
618
|
+
return match;
|
|
619
|
+
}
|
|
620
|
+
// 尝试通过 Import Map 解析模块路径
|
|
621
|
+
const resolvedPath = resolveModulePathViaImportMap(modulePath, imports);
|
|
622
|
+
if (resolvedPath) {
|
|
623
|
+
// 计算从脚本位置到解析后路径的相对路径
|
|
624
|
+
const relativePath = calculateRelativePath(scriptDir, resolvedPath);
|
|
625
|
+
return prefix + relativePath + suffix;
|
|
626
|
+
}
|
|
627
|
+
// 如果无法解析,保持原样
|
|
628
|
+
return match;
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* 通过 Import Map 解析模块路径
|
|
633
|
+
* 注意:需要应用与 fixImportMapPaths 相同的路径修复逻辑
|
|
634
|
+
*/
|
|
635
|
+
function resolveModulePathViaImportMap(modulePath, imports) {
|
|
636
|
+
// 1. 精确匹配
|
|
637
|
+
if (imports[modulePath]) {
|
|
638
|
+
let resolved = imports[modulePath];
|
|
639
|
+
// 去掉开头的 ./
|
|
640
|
+
if (resolved.startsWith('./')) {
|
|
641
|
+
resolved = resolved.slice(2);
|
|
642
|
+
}
|
|
643
|
+
// 修复 Lib/ 路径(与 fixImportMapPaths 保持一致)
|
|
644
|
+
// 将 Lib/xxx.mjs 改为 xxx.mjs(因为这些文件会被复制到根目录)
|
|
645
|
+
if (resolved.startsWith('Lib/')) {
|
|
646
|
+
resolved = resolved.slice(4);
|
|
647
|
+
}
|
|
648
|
+
return resolved;
|
|
649
|
+
}
|
|
650
|
+
// 2. 前缀匹配(目录别名)
|
|
651
|
+
for (const [prefix, target] of Object.entries(imports)) {
|
|
652
|
+
if (prefix.endsWith('/') && modulePath.startsWith(prefix)) {
|
|
653
|
+
const remainder = modulePath.slice(prefix.length);
|
|
654
|
+
let targetBase = target;
|
|
655
|
+
// 去掉开头的 ./
|
|
656
|
+
if (targetBase.startsWith('./')) {
|
|
657
|
+
targetBase = targetBase.slice(2);
|
|
658
|
+
}
|
|
659
|
+
// 修复 Lib/ 路径
|
|
660
|
+
if (targetBase.startsWith('Lib/')) {
|
|
661
|
+
targetBase = targetBase.slice(4);
|
|
662
|
+
}
|
|
663
|
+
// 去掉结尾的 /
|
|
664
|
+
if (targetBase.endsWith('/')) {
|
|
665
|
+
targetBase = targetBase.slice(0, -1);
|
|
666
|
+
}
|
|
667
|
+
return targetBase + '/' + remainder;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
return null;
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* 计算从源目录到目标路径的相对路径
|
|
674
|
+
*/
|
|
675
|
+
function calculateRelativePath(fromDir, toPath) {
|
|
676
|
+
// 将路径统一使用正斜杠
|
|
677
|
+
fromDir = fromDir.replace(/\\/g, '/');
|
|
678
|
+
toPath = toPath.replace(/\\/g, '/');
|
|
679
|
+
// 分割路径
|
|
680
|
+
const fromParts = fromDir ? fromDir.split('/').filter((p) => p) : [];
|
|
681
|
+
const toParts = toPath.split('/').filter((p) => p);
|
|
682
|
+
// 找到共同前缀
|
|
683
|
+
let commonLength = 0;
|
|
684
|
+
for (let i = 0; i < Math.min(fromParts.length, toParts.length); i++) {
|
|
685
|
+
if (fromParts[i] === toParts[i]) {
|
|
686
|
+
commonLength++;
|
|
687
|
+
}
|
|
688
|
+
else {
|
|
689
|
+
break;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
// 计算需要向上走多少级
|
|
693
|
+
const upCount = fromParts.length - commonLength;
|
|
694
|
+
// 构建相对路径
|
|
695
|
+
const upPath = '../'.repeat(upCount);
|
|
696
|
+
const downPath = toParts.slice(commonLength).join('/');
|
|
697
|
+
const result = upPath + downPath;
|
|
698
|
+
// 如果结果为空或不以 ./ 或 ../ 开头,添加 ./
|
|
699
|
+
if (!result || (!result.startsWith('./') && !result.startsWith('../'))) {
|
|
700
|
+
return './' + result;
|
|
701
|
+
}
|
|
702
|
+
return result;
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* 修复已知的代码问题
|
|
706
|
+
* 这些是项目源代码中的 bug,需要在打包时自动修复
|
|
707
|
+
*/
|
|
708
|
+
function fixKnownCodeIssues(content, scriptName) {
|
|
709
|
+
let modified = content;
|
|
710
|
+
let fixCount = 0;
|
|
711
|
+
// 修复 1: GameplaySystem.mjs 中 ruleName 未定义的问题
|
|
712
|
+
// 原代码: console.error(`[LC] Load game rule '${ruleName}' failed`);
|
|
713
|
+
// 问题: ruleName 变量在上面被注释掉了,但错误日志仍然引用它
|
|
714
|
+
if (content.includes("console.error(`[LC] Load game rule '${ruleName}' failed`)")) {
|
|
715
|
+
modified = modified.replace("console.error(`[LC] Load game rule '${ruleName}' failed`)", 'console.error(`[LC] Load game rule failed - GameplaySystem.gameRule is null`)');
|
|
716
|
+
fixCount++;
|
|
717
|
+
console.log(`[SourceBuilder] 修复 ${scriptName}: ruleName 未定义问题`);
|
|
718
|
+
}
|
|
719
|
+
// 修复 2: AimAdjustmentBar.mjs 中 sprite 可能为 null 的问题
|
|
720
|
+
// 原代码: const frameKey = this.wheel.element.sprite.frameKeys[frameNum];
|
|
721
|
+
// 问题: sprite 资源可能还没加载完成或引用丢失
|
|
722
|
+
if (content.includes('this.wheel.element.sprite.frameKeys[frameNum]')) {
|
|
723
|
+
// 直接替换整行
|
|
724
|
+
const oldLine = 'const frameKey = this.wheel.element.sprite.frameKeys[frameNum];';
|
|
725
|
+
const newLines = `const sprite = this.wheel.element.sprite;
|
|
726
|
+
if (!sprite || !sprite.frameKeys || !sprite.atlas) {
|
|
727
|
+
console.warn('[AimAdjustmentBar] Sprite not ready, skipping wheel initialization');
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
const frameKey = sprite.frameKeys[frameNum];`;
|
|
731
|
+
if (content.includes(oldLine)) {
|
|
732
|
+
modified = modified.replace(oldLine, newLines);
|
|
733
|
+
// 同时替换 atlas 的访问
|
|
734
|
+
const oldAtlas = 'const atlas = this.wheel.element.sprite.atlas;';
|
|
735
|
+
const newAtlas = 'const atlas = sprite.atlas;';
|
|
736
|
+
modified = modified.replace(oldAtlas, newAtlas);
|
|
737
|
+
// 添加对 atlas.frames 的空值检查
|
|
738
|
+
const oldRect = 'const rect = atlas.frames[frameKey].rect;';
|
|
739
|
+
const newRect = `if (!atlas.frames || !atlas.frames[frameKey]) {
|
|
740
|
+
console.warn('[AimAdjustmentBar] Atlas frame not found:', frameKey);
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
const rect = atlas.frames[frameKey].rect;`;
|
|
744
|
+
modified = modified.replace(oldRect, newRect);
|
|
745
|
+
fixCount++;
|
|
746
|
+
console.log(`[SourceBuilder] 修复 ${scriptName}: sprite 空值检查`);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
// 可以在这里添加更多已知问题的修复...
|
|
750
|
+
if (fixCount > 0) {
|
|
751
|
+
console.log(`[SourceBuilder] 共修复 ${scriptName} 中的 ${fixCount} 个已知问题`);
|
|
752
|
+
}
|
|
753
|
+
return modified;
|
|
754
|
+
}
|
|
755
|
+
/**
|
|
756
|
+
* 重写 pc.app 访问为 window.pc.app
|
|
757
|
+
*
|
|
758
|
+
* 问题背景:
|
|
759
|
+
* 在 ESM 模式下,用户脚本通过 `import * as pc from 'playcanvas'` 导入。
|
|
760
|
+
* ESM 命名空间对象是静态的、冻结的,无法在运行时添加 `app` 属性。
|
|
761
|
+
* 但 PlayCanvas 脚本习惯使用 `pc.app.root`、`pc.app.assets` 等方式访问应用实例。
|
|
762
|
+
*
|
|
763
|
+
* 解决方案:
|
|
764
|
+
* 将代码中的 `pc.app` 重写为 `window.pc.app`,因为 `window.pc` 是可变的,
|
|
765
|
+
* 在 index.esm.mjs 中会设置 `window.pc.app = app`。
|
|
766
|
+
*/
|
|
767
|
+
function rewritePcAppAccess(content) {
|
|
768
|
+
// 匹配 pc.app 的访问模式
|
|
769
|
+
// 不匹配已经是 window.pc.app 的情况
|
|
770
|
+
// 使用负向后瞻确保前面不是 window. 或其他字母
|
|
771
|
+
// 使用两个步骤:
|
|
772
|
+
// 1. 先统计需要替换的数量
|
|
773
|
+
// 2. 再执行替换
|
|
774
|
+
const pcAppRegex = /(?<!window\.)(?<!\w)pc\.app\b/g;
|
|
775
|
+
// 统计匹配数量(在替换前)
|
|
776
|
+
const matches = content.match(pcAppRegex);
|
|
777
|
+
const matchCount = matches ? matches.length : 0;
|
|
778
|
+
// 如果没有需要替换的内容,直接返回
|
|
779
|
+
if (matchCount === 0) {
|
|
780
|
+
return content;
|
|
781
|
+
}
|
|
782
|
+
// 执行替换
|
|
783
|
+
const modified = content.replace(pcAppRegex, 'window.pc.app');
|
|
784
|
+
console.log(`[SourceBuilder] 重写了 ${matchCount} 处 pc.app -> window.pc.app`);
|
|
785
|
+
return modified;
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* 复制 Import Map 中引用的第三方库文件
|
|
789
|
+
* 例如 planck.mjs 等
|
|
790
|
+
*/
|
|
791
|
+
async function copyImportMapLibraries(projectConfig, projectDir, outputDir, importMap) {
|
|
792
|
+
const imports = importMap.content.imports || {};
|
|
793
|
+
const assets = projectConfig.format === 'playcanvas'
|
|
794
|
+
? projectConfig.assets
|
|
795
|
+
: projectConfig.assets;
|
|
796
|
+
for (const [key, value] of Object.entries(imports)) {
|
|
797
|
+
// 跳过目录前缀(以 / 结尾的)
|
|
798
|
+
if (key.endsWith('/'))
|
|
799
|
+
continue;
|
|
800
|
+
// 跳过 playcanvas 引擎(由模板处理)
|
|
801
|
+
if (key === 'playcanvas')
|
|
802
|
+
continue;
|
|
803
|
+
// 处理单个文件的导入(如 "planck": "./Lib/planck.mjs")
|
|
804
|
+
let targetPath = value;
|
|
805
|
+
// 修复路径(./Lib/ -> ./)
|
|
806
|
+
if (targetPath.startsWith('./Lib/')) {
|
|
807
|
+
targetPath = './' + targetPath.slice(6);
|
|
808
|
+
}
|
|
809
|
+
// 移除 ./ 前缀
|
|
810
|
+
const outputRelPath = targetPath.startsWith('./') ? targetPath.slice(2) : targetPath;
|
|
811
|
+
const outputPath = path.join(outputDir, outputRelPath);
|
|
812
|
+
// 检查目标文件是否已存在(可能已被 copyUserScriptsForESM 复制)
|
|
813
|
+
try {
|
|
814
|
+
await fs.access(outputPath);
|
|
815
|
+
console.log(`[ESM] 第三方库已存在,跳过: ${key} -> ${outputRelPath}`);
|
|
816
|
+
continue;
|
|
817
|
+
}
|
|
818
|
+
catch {
|
|
819
|
+
// 文件不存在,需要复制
|
|
820
|
+
}
|
|
821
|
+
// 查找源文件
|
|
822
|
+
// 1. 首先检查是否是 asset 引用(通过 name 查找),使用统一的解析函数
|
|
823
|
+
let sourceFound = false;
|
|
824
|
+
const filename = path.basename(outputRelPath);
|
|
825
|
+
for (const [assetId, asset] of Object.entries(assets)) {
|
|
826
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
827
|
+
const assetData = asset;
|
|
828
|
+
if (assetData.type !== 'script')
|
|
829
|
+
continue;
|
|
830
|
+
if (assetData.name !== key && assetData.file?.filename !== filename)
|
|
831
|
+
continue;
|
|
832
|
+
// 使用统一的解析函数查找源文件(支持 PlayCraft Git 仓库结构)
|
|
833
|
+
const sourcePath = await resolveScriptSourcePath(assetData, assetId, projectDir, assets);
|
|
834
|
+
if (sourcePath) {
|
|
835
|
+
try {
|
|
836
|
+
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
|
837
|
+
await fs.copyFile(sourcePath, outputPath);
|
|
838
|
+
console.log(`[ESM] 复制第三方库: ${key} -> ${outputRelPath}`);
|
|
839
|
+
sourceFound = true;
|
|
840
|
+
}
|
|
841
|
+
catch (error) {
|
|
842
|
+
console.warn(`[ESM] 无法复制第三方库 ${key}:`, error);
|
|
843
|
+
}
|
|
844
|
+
break;
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
// 2. 如果没有在 assets 中找到,尝试在项目目录中直接查找
|
|
848
|
+
if (!sourceFound) {
|
|
849
|
+
// 尝试原始路径(例如 ./Lib/planck.mjs)
|
|
850
|
+
const originalPath = value.startsWith('./') ? value.slice(2) : value;
|
|
851
|
+
const candidates = [
|
|
852
|
+
path.join(projectDir, originalPath),
|
|
853
|
+
path.join(projectDir, filename),
|
|
854
|
+
path.join(projectDir, 'Lib', filename),
|
|
855
|
+
// PlayCraft Git 仓库结构
|
|
856
|
+
path.join(projectDir, 'assets', filename),
|
|
857
|
+
path.join(projectDir, 'assets', originalPath),
|
|
858
|
+
];
|
|
859
|
+
for (const candidate of candidates) {
|
|
860
|
+
try {
|
|
861
|
+
await fs.access(candidate);
|
|
862
|
+
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
|
863
|
+
await fs.copyFile(candidate, outputPath);
|
|
864
|
+
console.log(`[ESM] 复制第三方库(从目录): ${key} -> ${outputRelPath}`);
|
|
865
|
+
sourceFound = true;
|
|
866
|
+
break;
|
|
867
|
+
}
|
|
868
|
+
catch {
|
|
869
|
+
// 继续尝试
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
if (!sourceFound) {
|
|
874
|
+
console.warn(`[ESM] 未找到第三方库 ${key} 的源文件`);
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
}
|