@playcraft/devkit 1.0.5 → 1.0.6

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.
Files changed (39) hide show
  1. package/LICENSE +21 -21
  2. package/cli/bin/playable-scripts.js +1 -1
  3. package/cli/commands/build.js +1 -11
  4. package/cli/commands/builds.js +14 -14
  5. package/core/batch-build.js +93 -100
  6. package/core/cos-uploader.js +50 -35
  7. package/core/index.d.ts +169 -169
  8. package/core/loaders/gltf-loader.js +19 -19
  9. package/core/plugins/AdikteevInjectorPlugin.js +11 -11
  10. package/core/plugins/BigoAdsInjectorPlugin.js +4 -4
  11. package/core/plugins/DAPIInjectorPlugin.js +4 -4
  12. package/core/plugins/DebuggerInjectionPlugin.js +5 -5
  13. package/core/plugins/ExitAPIInjectorPlugin.js +9 -9
  14. package/core/plugins/FflateCompressionPlugin.js +43 -43
  15. package/core/plugins/LiftoffInjectorPlugin.js +11 -11
  16. package/core/plugins/MRAIDInjectorPlugin.js +3 -3
  17. package/core/plugins/MintegralInjectorPlugin.js +4 -4
  18. package/core/plugins/PangleInjectorPlugin.js +3 -3
  19. package/core/plugins/SnapchatInjectorPlugin.js +4 -4
  20. package/core/plugins/TikTokInjectorPlugin.js +3 -3
  21. package/core/plugins/UnityInjectorPlugin.js +13 -13
  22. package/core/resources/snapchat-config.json +1 -1
  23. package/core/resources/tiktok-config.json +1 -1
  24. package/core/utils/buildDefines.js +2 -2
  25. package/core/utils/buildTemplateString.js +2 -2
  26. package/core/utils/generateAdikteevHtmlWebpackPluginConfig.js +26 -26
  27. package/core/utils/generateInMobiHtmlWebpackPluginConfig.js +16 -16
  28. package/core/utils/injectSDKPlugins.js +10 -10
  29. package/core/utils/logOptions.js +2 -2
  30. package/core/utils/mergeOptions.js +5 -5
  31. package/core/utils/parseArgvOptions.js +4 -4
  32. package/core/utils/resolveChannelFold2Zip.js +12 -12
  33. package/core/webpack.build.js +12 -12
  34. package/core/webpack.common.js +2 -2
  35. package/core/webpack.dev.js +12 -12
  36. package/defines.d.ts +54 -54
  37. package/package.json +80 -82
  38. package/cli/commands/pack.js +0 -71
  39. package/core/utils/validateThemeData.js +0 -28
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2025-present Smoud
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2025-present Smoud
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";process.on("unhandledRejection",err=>{throw err});const spawn=require("cross-spawn");const args=process.argv.slice(2);const scriptIndex=args.findIndex(x=>x==="build"||x==="dev"||x==="builds"||x==="pack");const script=scriptIndex===-1?args[0]:args[scriptIndex];const nodeArgs=scriptIndex>0?args.slice(0,scriptIndex):[];if(["build","dev","builds","pack"].includes(script)){const result=spawn.sync(process.execPath,nodeArgs.concat(require.resolve("../commands/"+script)).concat(args.slice(scriptIndex+1)),{stdio:"inherit"});if(result.signal){if(result.signal==="SIGKILL"){console.log("The build failed because the process exited too early. "+"This probably means the system ran out of memory or someone called "+"`kill -9` on the process.")}else if(result.signal==="SIGTERM"){console.log("The build failed because the process exited too early. "+"Someone might have called `kill` or `killall`, or the system could "+"be shutting down.")}process.exit(1)}process.exit(result.status)}else{console.log("Unknown script \""+script+"\".")}
2
+ "use strict";process.on("unhandledRejection",err=>{throw err});const spawn=require("cross-spawn");const args=process.argv.slice(2);const scriptIndex=args.findIndex(x=>x==="build"||x==="dev"||x==="builds");const script=scriptIndex===-1?args[0]:args[scriptIndex];const nodeArgs=scriptIndex>0?args.slice(0,scriptIndex):[];if(["build","dev","builds"].includes(script)){const result=spawn.sync(process.execPath,nodeArgs.concat(require.resolve("../commands/"+script)).concat(args.slice(scriptIndex+1)),{stdio:"inherit"});if(result.signal){if(result.signal==="SIGKILL"){console.log("The build failed because the process exited too early. "+"This probably means the system ran out of memory or someone called "+"`kill -9` on the process.")}else if(result.signal==="SIGTERM"){console.log("The build failed because the process exited too early. "+"Someone might have called `kill` or `killall`, or the system could "+"be shutting down.")}process.exit(1)}process.exit(result.status)}else{console.log("Unknown script \""+script+"\".")}
@@ -1,11 +1 @@
1
- "use strict";process.env.BABEL_ENV="production";process.env.NODE_ENV="production";const fs=require("fs");const path=require("path");const{runBuild}=require("../../core/webpack.build.js");const{validateThemeData}=require("../../core/utils/validateThemeData");/**
2
- * Detect the current theme name from the theme entry file.
3
- * Supports patterns like:
4
- * export { default } from './themeName';
5
- * import Theme from './themeName';
6
- * export { default } from "./themeName";
7
- */function detectCurrentTheme(projectRoot){// Try to load builds.config.js for theme config
8
- const buildsConfigPath=path.join(projectRoot,"builds.config.js");let themeConfig={sourceDir:"src/theme",entryFile:"src/theme/index.ts"};if(fs.existsSync(buildsConfigPath)){try{delete require.cache[buildsConfigPath];const config=require(buildsConfigPath);if(config.themes){themeConfig={...themeConfig,...config.themes}}}catch(e){// ignore
9
- }}const entryPath=path.join(projectRoot,themeConfig.entryFile);if(!fs.existsSync(entryPath)){return{themeName:null,themeConfig}}const content=fs.readFileSync(entryPath,"utf8");// Match: export { default } from './themeName' or import ... from './themeName'
10
- const match=content.match(/from\s+['"]\.\/([^'"]+)['"]/);if(match){return{themeName:match[1],themeConfig}}return{themeName:null,themeConfig}}// --- Main ---
11
- const projectRoot=process.cwd();const{themeName,themeConfig}=detectCurrentTheme(projectRoot);if(themeName){const themeBaseDir=path.join(projectRoot,themeConfig.sourceDir||"src/theme");const schemaPath=path.join(themeBaseDir,"theme.schema.json5");if(fs.existsSync(schemaPath)){console.log(`\x1b[36m[build] 校验主题数据: ${themeName}\x1b[0m`);const{merged,errors}=validateThemeData(themeName,projectRoot,themeConfig);if(errors){console.error(`\x1b[31m[build] 主题 "${themeName}" 数据校验失败:\x1b[0m`);errors.forEach(e=>console.error(`\x1b[31m - ${e}\x1b[0m`));process.exit(1)}console.log(`\x1b[32m[build] 主题 "${themeName}" 数据校验通过`)}}runBuild();
1
+ "use strict";process.env.BABEL_ENV="production";process.env.NODE_ENV="production";const{runBuild}=require("../../core/webpack.build.js");runBuild();
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- "use strict";/**
3
- * Batch Builds Command for playable-scripts
4
- *
5
- * 支持:
6
- * - 单个主题下多个渠道的并发构建
7
- * - 独立临时目录,避免并发冲突
8
- * - 灵活的配置系统
9
- *
10
- * 使用方法:
11
- * playable-scripts builds # 使用默认配置
12
- * playable-scripts builds -t "theme1,theme2" # 指定主题
13
- * playable-scripts builds -c "google,facebook" # 指定渠道
14
- * playable-scripts builds -t "theme1" -c "google" # 指定主题和渠道
15
- * playable-scripts builds --parallel 3 # 设置并发数
2
+ "use strict";/**
3
+ * Batch Builds Command for playable-scripts
4
+ *
5
+ * 支持:
6
+ * - 单个主题下多个渠道的并发构建
7
+ * - 独立临时目录,避免并发冲突
8
+ * - 灵活的配置系统
9
+ *
10
+ * 使用方法:
11
+ * playable-scripts builds # 使用默认配置
12
+ * playable-scripts builds -t "theme1,theme2" # 指定主题
13
+ * playable-scripts builds -c "google,facebook" # 指定渠道
14
+ * playable-scripts builds -t "theme1" -c "google" # 指定主题和渠道
15
+ * playable-scripts builds --parallel 3 # 设置并发数
16
16
  */process.on("unhandledRejection",err=>{throw err});const{buildBatch}=require("../../core/batch-build");buildBatch();
@@ -1,55 +1,54 @@
1
1
  #!/usr/bin/env node
2
- "use strict";/**
3
- * 批量构建核心模块
4
- *
5
- * 核心特性:
6
- * 1. 支持单个主题下多个渠道的并发构建
7
- * 2. 每个构建任务使用独立的临时目录(dist-temp-{taskId})
8
- * 3. 构建完成后自动移动到目标目录并清理临时目录
9
- * 4. 支持灵活的配置系统
10
- */const{execSync,exec}=require("child_process");const fs=require("fs");const path=require("path");const os=require("os");const{promisify}=require("util");const{createCOSClient,uploadDirectoryToCOS,uploadFileToCOS,purgeCDNCache}=require("./cos-uploader");const{validateThemeData}=require("./utils/validateThemeData");const execAsync=promisify(exec);/**
11
- * 更新 preview.json 文件
12
- */async function updatePreviewJson(cosConfig,cosPrefix,currentTheme,previewLinks){const previewJsonKey=cosPrefix?`${cosPrefix}/preview.json`:"preview.json";// 读取现有的 preview.json 文件
13
- let existingPreviewData={};try{const cos=createCOSClient(cosConfig);const getObjectResult=await new Promise((resolve,reject)=>{cos.getObject({Bucket:cosConfig.Bucket,Region:cosConfig.Region,Key:previewJsonKey},(err,data)=>{if(err){if(err.statusCode===404){// 文件不存在,使用空对象
2
+ "use strict";/**
3
+ * 批量构建核心模块
4
+ *
5
+ * 核心特性:
6
+ * 1. 支持单个主题下多个渠道的并发构建
7
+ * 2. 每个构建任务使用独立的临时目录(dist-temp-{taskId})
8
+ * 3. 构建完成后自动移动到目标目录并清理临时目录
9
+ * 4. 支持灵活的配置系统
10
+ */const{execSync,exec}=require("child_process");const fs=require("fs");const path=require("path");const os=require("os");const{promisify}=require("util");const{fetchTemporaryCredentials,createCOSClient,uploadDirectoryToCOS,uploadFileToCOS,purgeCDNCache}=require("./cos-uploader");const execAsync=promisify(exec);/**
11
+ * 更新 preview.json 文件
12
+ */async function updatePreviewJson(cosConfig,cosPrefix,currentTheme,previewLinks,credentials=null){const previewJsonKey=cosPrefix?`${cosPrefix}/preview.json`:"preview.json";// 如果没有传入凭证,尝试获取一次
13
+ if(!credentials){try{credentials=await fetchTemporaryCredentials()}catch(error){log(`获取临时凭证失败,跳过 preview.json 更新: ${error.message}`,"warn");return}}// 读取现有的 preview.json 文件
14
+ let existingPreviewData={};try{const cos=await createCOSClient(null,credentials);const getObjectResult=await new Promise((resolve,reject)=>{cos.getObject({Bucket:credentials.bucket,Region:credentials.region,Key:previewJsonKey},(err,data)=>{if(err){if(err.statusCode===404){// 文件不存在,使用空对象
14
15
  resolve(null)}else{reject(err)}}else{resolve(data)}})});if(getObjectResult&&getObjectResult.Body){existingPreviewData=JSON.parse(getObjectResult.Body.toString())}}catch(error){// 如果读取失败,使用空对象继续
15
- console.log(`[${new Date().toLocaleTimeString()}] 🔍 读取现有 preview.json 失败,将创建新文件: ${error.message}`)}// 更新预览数据
16
+ log(`读取现有 preview.json 失败,将创建新文件: ${error.message}`,"debug")}// 更新预览数据
16
17
  const updatedPreviewData={...existingPreviewData};// 获取当前时间
17
18
  const currentTime=new Date().toISOString();// 更新当前主题的预览链接
18
19
  const currentThemeLinks=previewLinks.filter(link=>link.theme===currentTheme);currentThemeLinks.forEach(link=>{const fileName=link.file.replace(/\.[^.]+$/,"");// 去掉文件扩展名
19
20
  updatedPreviewData[fileName]={url:link.url,update_time:currentTime}});// 将更新后的数据写入临时文件
20
21
  const tempDir=path.join(os.tmpdir(),"playable-preview");if(!fs.existsSync(tempDir)){fs.mkdirSync(tempDir,{recursive:true})}const tempPreviewPath=path.join(tempDir,"preview.json");fs.writeFileSync(tempPreviewPath,JSON.stringify(updatedPreviewData,null,2),"utf8");// 上传更新后的 preview.json 文件
21
- await uploadFileToCOS(cosConfig,tempPreviewPath,previewJsonKey);// 刷新 CDN 缓存
22
- const cdnDomain=cosConfig.CdnDomain;if(cdnDomain){const previewJsonUrl=`https://${cdnDomain}/${previewJsonKey}`;try{await purgeCDNCache(cosConfig,[previewJsonUrl]);console.log(`[${new Date().toLocaleTimeString()}] ✅ CDN 缓存已刷新: ${previewJsonUrl}`)}catch(error){console.log(`[${new Date().toLocaleTimeString()}] ⚠️ CDN 缓存刷新失败: ${error.message}`)}}// 清理临时文件
23
- fs.unlinkSync(tempPreviewPath);console.log(`[${new Date().toLocaleTimeString()}] ✅ preview.json 文件已更新并上传`)}// ==================== 默认配置 ====================
24
- /**
25
- * 计算默认并发数
26
- * 策略: CPU 核心数 - 1,最小为 2,最大为 8
27
- * 例如:
28
- * - 4 核 CPU → 3 并发
29
- * - 8 核 CPU → 7 并发
30
- * - 16 核 CPU → 8 并发(限制最大值)
22
+ await uploadFileToCOS(null,tempPreviewPath,previewJsonKey,credentials);// 刷新 CDN 缓存
23
+ const cdnDomain="static.aix.intlgame.com";const previewJsonUrl=`https://${cdnDomain}/${previewJsonKey}`;try{await purgeCDNCache(null,[previewJsonUrl],credentials);log(`✓ CDN 缓存已刷新: ${previewJsonUrl}`,"success")}catch(error){log(`⚠️ CDN 缓存刷新失败: ${error.message}`,"warn")}// 清理临时文件
24
+ fs.unlinkSync(tempPreviewPath);log(`✓ preview.json 文件已更新并上传`,"success")}// ==================== 默认配置 ====================
25
+ /**
26
+ * 计算默认并发数
27
+ * 策略: CPU 核心数 - 1,最小为 2,最大为 8
28
+ * 例如:
29
+ * - 4 核 CPU → 3 并发
30
+ * - 8 核 CPU → 7 并发
31
+ * - 16 核 CPU → 8 并发(限制最大值)
31
32
  */function getDefaultParallel(){const cpuCount=os.cpus().length;const calculated=Math.max(2,cpuCount-1);// 至少 2 个并发
32
33
  const parallel=Math.min(8,calculated);// 最多 8 个并发
33
34
  return parallel}const DEFAULT_CONFIG={title:"Phaser Game",appName:"",// 用于从远程仓库拉取配置
34
35
  channels:["google","facebook","tiktok","applovin","ironsource","unity","moloco","liftoff","bigoads"],themes:{enabled:true,sourceDir:"src/theme",entryFile:"src/theme/index.ts",whitelist:null},naming:{language:"EN",format:"\u65E0",supplier:"AIX",follower:"ZQL"},build:{outputDir:"dist-all",tempDirPrefix:"dist-temp",continueOnError:true,cleanTemp:true,parallel:getDefaultParallel()// 根据 CPU 核心数自动设置
35
- },// COS 配置(可选)
36
- cosConfig:null// 如果配置,则自动为每个主题生成 preview 渠道并上传
37
- };// ==================== 工具函数 ====================
36
+ }};// ==================== 工具函数 ====================
38
37
  let isExiting=false;let backupContent=null;let backupPath=null;const activeTempDirs=new Set;// 跟踪所有活动的临时目录
39
38
  function log(message,level="info"){const timestamp=new Date().toLocaleTimeString();const colors={info:"\x1B[36m",success:"\x1B[32m",error:"\x1B[31m",warn:"\x1B[33m",debug:"\x1B[90m"};const reset="\x1B[0m";const prefix={info:"\uD83D\uDCE6",success:"\u2705",error:"\u274C",warn:"\u26A0\uFE0F",debug:"\uD83D\uDD0D"}[level]||"\u2139\uFE0F";console.log(`${colors[level]}[${timestamp}] ${prefix} ${message}${reset}`)}function getCurrentMonth(){const month=new Date().getMonth()+1;return`${month}月交付`}function getCurrentDate(){const date=new Date;const year=date.getFullYear();const month=String(date.getMonth()+1).padStart(2,"0");const day=String(date.getDate()).padStart(2,"0");return`${year}${month}${day}`}function defaultFileNameGenerator(config,themeName,channel){const parts=[themeName,config.naming.language,config.naming.format,getCurrentMonth(),getCurrentDate(),config.naming.supplier,config.naming.follower,channel.toLowerCase()].filter(item=>!!item);return parts.join("-")}function getAllThemes(config,projectRoot){const themesDir=path.join(projectRoot,config.themes.sourceDir);if(!fs.existsSync(themesDir)){log(`主题目录不存在: ${themesDir}`,"warn");return[]}const entries=fs.readdirSync(themesDir,{withFileTypes:true});let themes=entries.filter(entry=>entry.isDirectory()).map(entry=>entry.name).sort();if(config.themes.whitelist&&typeof config.themes.whitelist==="function"){themes=themes.filter(config.themes.whitelist);log(`应用主题白名单过滤: ${themes.length} 个主题`,"debug")}return themes}function backupEntryFile(config,projectRoot){const entryPath=path.join(projectRoot,config.themes.entryFile);if(!fs.existsSync(entryPath)){throw new Error(`入口文件不存在: ${entryPath}`)}backupPath=entryPath;backupContent=fs.readFileSync(entryPath,"utf8");log(`已备份入口文件: ${config.themes.entryFile}`,"debug")}function restoreEntryFile(){if(backupPath&&backupContent){fs.writeFileSync(backupPath,backupContent,"utf8");log(`已恢复入口文件`,"debug");backupPath=null;backupContent=null}}function switchTheme(config,themeName,projectRoot){const entryPath=path.join(projectRoot,config.themes.entryFile);// 使用配置文件中的 generateEntryFile 函数(如果提供)
40
39
  let content;if(config.themes.switching&&typeof config.themes.switching.generateEntryFile==="function"){content=config.themes.switching.generateEntryFile(themeName)}else{// 兼容旧格式:简化的 export 语句
41
- const themePath=`./${themeName}`;content=`export { default } from '${themePath}';\n`}fs.writeFileSync(entryPath,content,"utf8");log(`已切换主题: ${themeName}`,"debug")}/**
42
- * 生成唯一的任务 ID
43
- */function generateTaskId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}/**
44
- * 创建独立的临时目录
45
- */function createTempDir(config,projectRoot,taskId){const tempDir=path.join(projectRoot,`${config.build.tempDirPrefix}-${taskId}`);if(fs.existsSync(tempDir)){fs.rmSync(tempDir,{recursive:true,force:true})}fs.mkdirSync(tempDir,{recursive:true});activeTempDirs.add(tempDir);return tempDir}/**
46
- * 清理临时目录
47
- */function cleanTempDir(tempDir){if(fs.existsSync(tempDir)){try{fs.rmSync(tempDir,{recursive:true,force:true});activeTempDirs.delete(tempDir);log(`已清理目录: ${path.basename(tempDir)}`,"debug")}catch(error){log(`清理临时目录失败: ${error.message}`,"warn")}}}/**
48
- * 清理所有活动的临时目录
49
- */function cleanAllTempDirs(){for(const tempDir of activeTempDirs){cleanTempDir(tempDir)}activeTempDirs.clear()}/**
50
- * 递归复制目录
51
- */function copyDirRecursive(src,dest){if(!fs.existsSync(dest)){fs.mkdirSync(dest,{recursive:true})}const entries=fs.readdirSync(src,{withFileTypes:true});for(const entry of entries){const srcPath=path.join(src,entry.name);const destPath=path.join(dest,entry.name);if(entry.isDirectory()){copyDirRecursive(srcPath,destPath)}else{fs.copyFileSync(srcPath,destPath)}}}/**
52
- * 构建单个渠道(使用独立临时目录)
40
+ const themePath=`./${themeName}`;content=`export { default } from '${themePath}';\n`}fs.writeFileSync(entryPath,content,"utf8");log(`已切换主题: ${themeName}`,"debug")}/**
41
+ * 生成唯一的任务 ID
42
+ */function generateTaskId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}/**
43
+ * 创建独立的临时目录
44
+ */function createTempDir(config,projectRoot,taskId){const tempDir=path.join(projectRoot,`${config.build.tempDirPrefix}-${taskId}`);if(fs.existsSync(tempDir)){fs.rmSync(tempDir,{recursive:true,force:true})}fs.mkdirSync(tempDir,{recursive:true});activeTempDirs.add(tempDir);return tempDir}/**
45
+ * 清理临时目录
46
+ */function cleanTempDir(tempDir){if(fs.existsSync(tempDir)){try{fs.rmSync(tempDir,{recursive:true,force:true});activeTempDirs.delete(tempDir);log(`已清理目录: ${path.basename(tempDir)}`,"debug")}catch(error){log(`清理临时目录失败: ${error.message}`,"warn")}}}/**
47
+ * 清理所有活动的临时目录
48
+ */function cleanAllTempDirs(){for(const tempDir of activeTempDirs){cleanTempDir(tempDir)}activeTempDirs.clear()}/**
49
+ * 递归复制目录
50
+ */function copyDirRecursive(src,dest){if(!fs.existsSync(dest)){fs.mkdirSync(dest,{recursive:true})}const entries=fs.readdirSync(src,{withFileTypes:true});for(const entry of entries){const srcPath=path.join(src,entry.name);const destPath=path.join(dest,entry.name);if(entry.isDirectory()){copyDirRecursive(srcPath,destPath)}else{fs.copyFileSync(srcPath,destPath)}}}/**
51
+ * 构建单个渠道(使用独立临时目录)
53
52
  */async function buildChannel(config,themeName,channel,outputDir,projectRoot,isChannelFold2Zip){const taskId=generateTaskId();const tempDir=createTempDir(config,projectRoot,taskId);log(`开始构建: 主题=${themeName}, 渠道=${channel}, 任务ID=${taskId.substr(0,8)}...`);try{// 生成文件名
54
53
  const fileName=config.naming.generator?config.naming.generator(themeName,channel,getCurrentDate(),getCurrentMonth()):defaultFileNameGenerator(config,themeName,channel);log(`文件名: ${fileName}`,"debug");// 执行构建,指定独立的输出目录(使用绝对路径)
55
54
  // 注意:
@@ -70,11 +69,11 @@ const zipFileName=`${channel}.zip`;const srcZipPath=path.join(tempDir,zipFileNam
70
69
  copyTempFiles(outputDir,themeName,channel)}}else{// 普通模式:移动所有文件到 outputDir/themeName/channel/
71
70
  copyTempFiles(outputDir,themeName,channel)}}// 清理临时目录
72
71
  if(config.build.cleanTemp){cleanTempDir(tempDir)}return{success:true,theme:themeName,channel}}catch(error){log(`构建失败: ${themeName}/${channel} - ${error.message}`,"error");// 清理临时目录
73
- if(config.build.cleanTemp){cleanTempDir(tempDir)}if(!config.build.continueOnError){throw error}return{success:false,theme:themeName,channel,error:error.message}}}/**
74
- * 并发构建多个渠道
72
+ if(config.build.cleanTemp){cleanTempDir(tempDir)}if(!config.build.continueOnError){throw error}return{success:false,theme:themeName,channel,error:error.message}}}/**
73
+ * 并发构建多个渠道
75
74
  */async function buildChannelsInParallel(config,themeName,channels,outputDir,projectRoot,isChannelFold2Zip){const maxParallel=config.build.parallel||3;const results=[];// 分批并发构建
76
- for(let i=0;i<channels.length;i+=maxParallel){const batch=channels.slice(i,i+maxParallel);const batchPromises=batch.map(channel=>buildChannel(config,themeName,channel,outputDir,projectRoot,isChannelFold2Zip));const batchResults=await Promise.allSettled(batchPromises);batchResults.forEach((result,index)=>{if(result.status==="fulfilled"){results.push(result.value)}else{var _result$reason;results.push({success:false,theme:themeName,channel:batch[index],error:((_result$reason=result.reason)===null||_result$reason===void 0?void 0:_result$reason.message)||"\u672A\u77E5\u9519\u8BEF"})}})}return results}/**
77
- * 解析命令行参数
75
+ for(let i=0;i<channels.length;i+=maxParallel){const batch=channels.slice(i,i+maxParallel);const batchPromises=batch.map(channel=>buildChannel(config,themeName,channel,outputDir,projectRoot,isChannelFold2Zip));const batchResults=await Promise.allSettled(batchPromises);batchResults.forEach((result,index)=>{if(result.status==="fulfilled"){results.push(result.value)}else{var _result$reason;results.push({success:false,theme:themeName,channel:batch[index],error:((_result$reason=result.reason)===null||_result$reason===void 0?void 0:_result$reason.message)||"\u672A\u77E5\u9519\u8BEF"})}})}return results}/**
76
+ * 解析命令行参数
78
77
  */function parseArgs(){const args=process.argv.slice(2);const result={themes:null,channels:null,parallel:null,isChannelFold2Zip:false};for(let i=0;i<args.length;i++){const currentArg=args[i];const nextArg=args[i+1];// 支持 -t 和 --themes 格式
79
78
  if(currentArg==="-t"||currentArg==="--themes"){if(nextArg&&!nextArg.startsWith("-")){result.themes=nextArg.split(",").map(t=>t.trim()).filter(Boolean);i++}}// 支持 -c 和 --channels 格式
80
79
  else if(currentArg==="-c"||currentArg==="--channels"){if(nextArg&&!nextArg.startsWith("-")){result.channels=nextArg.split(",").map(c=>c.trim()).filter(Boolean);i++}}// 支持 -p 和 --parallel 格式
@@ -84,48 +83,42 @@ else if(currentArg.startsWith("--channels=")){result.channels=currentArg.substri
84
83
  else if(currentArg.startsWith("--parallel=")){result.parallel=parseInt(currentArg.substring(11),10)}// 支持 --is-channel-fold2zip 参数
85
84
  else if(currentArg==="--is-channel-fold2zip"){result.isChannelFold2Zip=true}// 兼容位置参数:第一个参数作为主题,第二个作为渠道
86
85
  else if(!currentArg.startsWith("-")&&result.themes===null){result.themes=[currentArg]}else if(!currentArg.startsWith("-")&&result.themes!==null&&result.channels===null){result.channels=[currentArg]}}return result}// 远程配置仓库地址
87
- const REMOTE_CONFIG_REPO="";/**
88
- * 执行命令并返回结果
89
- * @param {string} command - 要执行的命令
90
- * @param {object} options - execSync 选项
91
- * @returns {string|null} 命令输出,失败返回 null
92
- */function execCommand(command,options={}){const{execSync}=require("child_process");try{return execSync(command,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],...options}).trim()}catch(error){return null}}/**
93
- * 从远程仓库获取配置文件内容
94
- * 使用 git clone 方式获取,读取后删除临时目录
95
- *
96
- * @param {string} appName - 应用名称,对应远程仓库中的文件夹名
97
- * @returns {Promise<object|null>} 远程配置对象,失败返回 null
98
- */async function fetchRemoteConfig(appName){if(!appName||!REMOTE_CONFIG_REPO)return null;const os=require("os");// 使用系统临时目录
99
- const tempDir=path.join(os.tmpdir(),`playable-config-${Date.now()}`);log(`尝试从远程仓库拉取配置: ${appName}`,"info");log(`仓库地址: ${REMOTE_CONFIG_REPO}`,"debug");try{// 创建临时目录
100
- fs.mkdirSync(tempDir,{recursive:true});// 克隆远程仓库到临时目录
101
- log("\u514B\u9686\u8FDC\u7A0B\u914D\u7F6E\u4ED3\u5E93...","info");const cloneResult=execCommand(`git clone --depth 1 --quiet "${REMOTE_CONFIG_REPO}" "${tempDir}"`,{timeout:30000});if(cloneResult===null){log("git clone \u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u548C\u4ED3\u5E93\u6743\u9650","error");return null}log("\u2713 \u8FDC\u7A0B\u914D\u7F6E\u4ED3\u5E93\u514B\u9686\u6210\u529F","success");// 检查 appName 对应的文件夹是否存在
102
- const appConfigDir=path.join(tempDir,appName);if(!fs.existsSync(appConfigDir)){log(`远程仓库中未找到 "${appName}" 文件夹`,"warn");// 列出可用的配置文件夹供参考
103
- const availableDirs=fs.readdirSync(tempDir).filter(name=>{const itemPath=path.join(tempDir,name);return fs.statSync(itemPath).isDirectory()&&!name.startsWith(".")});if(availableDirs.length>0){log(`可用的 appName: ${availableDirs.join(", ")}`,"info")}return null}// 检查配置文件是否存在
104
- const configFilePath=path.join(appConfigDir,"build.config.js");if(!fs.existsSync(configFilePath)){log(`"${appName}" 文件夹中未找到 build.config.js`,"warn");return null}// 读取配置文件内容并解析
105
- // 使用 vm 模块执行,避免 require 缓存问题
106
- const vm=require("vm");const configContent=fs.readFileSync(configFilePath,"utf-8");const sandbox={module:{exports:{}},exports:{},require:require};sandbox.exports=sandbox.module.exports;try{vm.runInNewContext(configContent,sandbox);log(`✓ 成功加载远程配置: ${appName}`,"success");return sandbox.module.exports}catch(parseError){log(`解析远程配置文件失败: ${parseError.message}`,"error");return null}}catch(error){log(`获取远程配置失败: ${error.message}`,"warn");return null}finally{// 无论成功与否,都删除临时目录
107
- if(fs.existsSync(tempDir)){try{fs.rmSync(tempDir,{recursive:true,force:true});log("\u5DF2\u6E05\u7406\u4E34\u65F6\u76EE\u5F55","debug")}catch(cleanupError){log(`清理临时目录失败: ${cleanupError.message}`,"debug")}}}}/**
108
- * 加载配置文件
109
- *
110
- * 优先级: 本地 builds.config.js > 远程配置 > build.json > 默认值
111
- *
112
- * 配置合并逻辑:
113
- * 1. 首先读取本地 builds.config.js
114
- * 2. 如果配置了 appName,从远程仓库拉取对应配置并合并(本地优先)
115
- * 3. 读取 build.json 作为补充(向后兼容)
116
- *
117
- * 兼容性说明:
118
- * - builds.config.js: 新的推荐配置文件,支持所有配置项
119
- * - build.json: 旧的配置文件,向后兼容,仅读取 app, name, google_play_url, app_store_url
120
- *
121
- * 字段映射:
122
- * - build.json.app + build.json.name → title (如果 builds.config.js 未指定)
123
- * - build.json.google_play_url → googlePlayUrl
124
- * - build.json.app_store_url → appStoreUrl
125
- *
126
- * 忽略字段:
127
- * - filename: 由批量构建自动生成
128
- * - version: 不在批量构建中使用
86
+ const REMOTE_CONFIG_REPO="https://git.woa.com/maclerylin/playable-build-config.git";/**
87
+ * 执行命令并返回结果
88
+ * @param {string} command - 要执行的命令
89
+ * @param {object} options - execSync 选项
90
+ * @returns {string|null} 命令输出,失败返回 null
91
+ */function execCommand(command,options={}){const{execSync}=require("child_process");try{return execSync(command,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],...options}).trim()}catch(error){return null}}/**
92
+ * 从远程仓库获取配置文件内容
93
+ * 使用 git clone 方式获取,读取后删除临时目录
94
+ *
95
+ * @param {string} appName - 应用名称,对应远程仓库中的文件夹名
96
+ * @returns {Promise<object|null>} 远程配置对象,失败返回 null
97
+ */async function fetchRemoteConfig(appName){if(!appName)return null;const https=require("https");const http=require("http");const url=require("url");// 构建远程配置文件 URL
98
+ const configUrl=`https://wd-act.woa.com/aix/playable-build-config/${encodeURIComponent(appName)}/build.config.js`;log(`尝试从远程 URL 获取配置: ${appName}`,"info");log(`URL: ${configUrl}`,"debug");try{// 发起 HTTP 请求获取配置文件
99
+ const configContent=await new Promise((resolve,reject)=>{const parsedUrl=url.parse(configUrl);const protocol=parsedUrl.protocol==="https:"?https:http;const request=protocol.get(configUrl,response=>{if(response.statusCode!==200){reject(new Error(`HTTP ${response.statusCode}: ${response.statusMessage}`));return}let data="";response.on("data",chunk=>data+=chunk);response.on("end",()=>resolve(data))});request.on("error",reject);request.setTimeout(30000,()=>{request.destroy();reject(new Error("Request timeout"))})});log("\u2713 \u8FDC\u7A0B\u914D\u7F6E\u6587\u4EF6\u4E0B\u8F7D\u6210\u529F","success");// 使用 vm 模块执行配置文件,避免 require 缓存问题
100
+ const vm=require("vm");const sandbox={module:{exports:{}},exports:{},require:require};sandbox.exports=sandbox.module.exports;try{vm.runInNewContext(configContent,sandbox);log(`✓ 成功加载远程配置: ${appName}`,"success");return sandbox.module.exports}catch(parseError){log(`解析远程配置文件失败: ${parseError.message}`,"error");log(`配置内容预览: ${configContent.substring(0,200)}...`,"debug");return null}}catch(error){log(`获取远程配置失败: ${error.message}`,"warn");return null}}/**
101
+ * 加载配置文件
102
+ *
103
+ * 优先级: 本地 builds.config.js > 远程配置 > build.json > 默认值
104
+ *
105
+ * 配置合并逻辑:
106
+ * 1. 首先读取本地 builds.config.js
107
+ * 2. 如果配置了 appName,从远程仓库拉取对应配置并合并(本地优先)
108
+ * 3. 读取 build.json 作为补充(向后兼容)
109
+ *
110
+ * 兼容性说明:
111
+ * - builds.config.js: 新的推荐配置文件,支持所有配置项
112
+ * - build.json: 旧的配置文件,向后兼容,仅读取 app, name, google_play_url, app_store_url
113
+ *
114
+ * 字段映射:
115
+ * - build.json.app + build.json.name → title (如果 builds.config.js 未指定)
116
+ * - build.json.google_play_url → googlePlayUrl
117
+ * - build.json.app_store_url → appStoreUrl
118
+ *
119
+ * 忽略字段:
120
+ * - filename: 由批量构建自动生成
121
+ * - version: 不在批量构建中使用
129
122
  */async function loadConfig(projectRoot){var _localConfig;const buildsConfigPath=path.join(projectRoot,"builds.config.js");const buildJsonPath=path.join(projectRoot,"build.json");let config={...DEFAULT_CONFIG};let localConfig=null;// 1. 先尝试加载本地 builds.config.js
130
123
  if(fs.existsSync(buildsConfigPath)){log("\u52A0\u8F7D\u914D\u7F6E\u6587\u4EF6: builds.config.js","debug");// 清除 require 缓存,确保读取最新配置
131
124
  delete require.cache[buildsConfigPath];localConfig=require(buildsConfigPath)}else{log("\u672A\u627E\u5230 builds.config.js\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u914D\u7F6E","debug")}// 2. 如果配置了 appName,从远程仓库拉取配置并合并
@@ -135,10 +128,10 @@ if(localConfig){config=mergeConfig(config,localConfig)}// 5. 尝试加载 build.
135
128
  if(fs.existsSync(buildJsonPath)){try{const buildJson=JSON.parse(fs.readFileSync(buildJsonPath,"utf8"));log("\u68C0\u6D4B\u5230 build.json\uFF0C\u8BFB\u53D6\u517C\u5BB9\u914D\u7F6E","debug");// 合并 app + name 为 title(仅当 builds.config.js 未指定时)
136
129
  if(!config.title||config.title===DEFAULT_CONFIG.title){if(buildJson.app&&buildJson.name){config.title=`${buildJson.app} ${buildJson.name}`;log(` ├─ title: "${config.title}" (来自 build.json)`,"debug")}else if(buildJson.app){config.title=buildJson.app;log(` ├─ title: "${config.title}" (来自 build.json.app)`,"debug")}else if(buildJson.name){config.title=buildJson.name;log(` ├─ title: "${config.title}" (来自 build.json.name)`,"debug")}}// 读取商店链接(如果 builds.config.js 未指定)
137
130
  if(buildJson.google_play_url&&!config.googlePlayUrl){config.googlePlayUrl=buildJson.google_play_url;log(` ├─ googlePlayUrl: "${config.googlePlayUrl}" (来自 build.json)`,"debug")}if(buildJson.app_store_url&&!config.appStoreUrl){config.appStoreUrl=buildJson.app_store_url;log(` └─ appStoreUrl: "${config.appStoreUrl}" (来自 build.json)`,"debug")}// 忽略的字段
138
- if(buildJson.filename){log(" \u26A0\uFE0F build.json.filename \u5C06\u88AB\u5FFD\u7565\uFF08\u7531\u6279\u91CF\u6784\u5EFA\u81EA\u52A8\u751F\u6210\uFF09","debug")}if(buildJson.version){log(" \u26A0\uFE0F build.json.version \u5C06\u88AB\u5FFD\u7565\uFF08\u4E0D\u5728\u6279\u91CF\u6784\u5EFA\u4E2D\u4F7F\u7528\uFF09","debug")}}catch(error){log(`⚠️ 解析 build.json 失败: ${error.message}`,"warn")}}console.log("config",config);return config}/**
139
- * 深度合并配置
140
- */function mergeConfig(defaultConfig,userConfig){const result={...defaultConfig};for(const key in userConfig){if(typeof userConfig[key]==="object"&&!Array.isArray(userConfig[key])){result[key]={...defaultConfig[key],...userConfig[key]}}else{result[key]=userConfig[key]}}return result}/**
141
- * 打印配置摘要
131
+ if(buildJson.filename){log(" \u26A0\uFE0F build.json.filename \u5C06\u88AB\u5FFD\u7565\uFF08\u7531\u6279\u91CF\u6784\u5EFA\u81EA\u52A8\u751F\u6210\uFF09","debug")}if(buildJson.version){log(" \u26A0\uFE0F build.json.version \u5C06\u88AB\u5FFD\u7565\uFF08\u4E0D\u5728\u6279\u91CF\u6784\u5EFA\u4E2D\u4F7F\u7528\uFF09","debug")}}catch(error){log(`⚠️ 解析 build.json 失败: ${error.message}`,"warn")}}console.log("config",config);return config}/**
132
+ * 深度合并配置
133
+ */function mergeConfig(defaultConfig,userConfig){const result={...defaultConfig};for(const key in userConfig){if(typeof userConfig[key]==="object"&&!Array.isArray(userConfig[key])){result[key]={...defaultConfig[key],...userConfig[key]}}else{result[key]=userConfig[key]}}return result}/**
134
+ * 打印配置摘要
142
135
  */function printSummary(config,themes,channels){var _os$cpus$;const totalBuilds=themes.length*channels.length;const cpuCount=os.cpus().length;const cpuModel=((_os$cpus$=os.cpus()[0])===null||_os$cpus$===void 0?void 0:_os$cpus$.model)||"Unknown";log("========================================");log("\u5F00\u59CB\u6279\u91CF\u6784\u5EFA\u4EFB\u52A1");log(`项目: ${config.title}`);log(`主题数: ${themes.length}`);log(`渠道数: ${channels.length}`);log(`总构建数: ${totalBuilds}`);log(`CPU: ${cpuCount} 核心 (${cpuModel.substring(0,40)}${cpuModel.length>40?"...":""})`);log(`并发数: ${config.build.parallel} (自动优化)`);log("========================================\n");if(themes.length<=10){log(`主题列表: ${themes.join(", ")}`,"debug")}log(`渠道列表: ${channels.join(", ")}`,"debug");log("")}// ==================== 主函数 ====================
143
136
  async function buildBatch(){const projectRoot=process.cwd();const startTime=Date.now();try{// 加载配置(包含远程配置合并)
144
137
  const config=await loadConfig(projectRoot);// 解析命令行参数
@@ -146,23 +139,23 @@ const args=parseArgs();// 应用命令行参数
146
139
  if(args.parallel!==null){config.build.parallel=args.parallel}// 是否启用渠道折叠为 zip 模式
147
140
  const isChannelFold2Zip=args.isChannelFold2Zip;if(isChannelFold2Zip){log("\u5DF2\u542F\u7528 --is-channel-fold2zip \u6A21\u5F0F\uFF1A\u6240\u6709\u6E20\u9053\u8F93\u51FA\u5C06\u538B\u7F29\u4E3A zip \u6587\u4EF6","info")}// 确定主题列表
148
141
  let themes;if(!config.themes.enabled){themes=[config.title.replace(/\s+/g,"-")]}else if(args.themes){themes=args.themes;log(`使用命令行指定的主题: ${themes.join(", ")}`,"info")}else{themes=getAllThemes(config,projectRoot);if(themes.length===0){throw new Error("\u672A\u627E\u5230\u4EFB\u4F55\u4E3B\u9898")}}// 确定渠道列表
149
- let channels=args.channels||config.channels;// 检查是否需要生成预览链接
150
- const needPreview=config.cosConfig&&config.cosConfig.enabled!==false&&config.cosConfig.SecretId&&config.cosConfig.SecretKey&&config.cosConfig.Bucket&&config.cosConfig.Region&&config.cosConfig.CdnDomain;// 如果配置了 COS,添加 preview 渠道
151
- if(needPreview){if(!channels.includes("preview")){channels=[...channels,"preview"];log("\u68C0\u6D4B\u5230 COS \u914D\u7F6E\uFF0C\u5DF2\u6DFB\u52A0 preview \u6E20\u9053","info")}}// 打印摘要
142
+ let channels=args.channels||config.channels;// 始终添加 preview 渠道,用于收集上传文件
143
+ if(!channels.includes("preview")){channels=[...channels,"preview"];log("\u5DF2\u6DFB\u52A0 preview \u6E20\u9053","info")}// 打印摘要
152
144
  printSummary(config,themes,channels);// 备份入口文件(如果启用主题切换)
153
145
  if(config.themes.enabled){backupEntryFile(config,projectRoot)}// 批量构建
154
146
  const outputDir=path.join(projectRoot,config.build.outputDir);const allResults=[];const previewLinks=[];// 存储预览链接
155
147
  // 批量构建前,清理一下目录
156
- cleanTempDir(outputDir);for(const theme of themes){// 切换主题
157
- if(config.themes.enabled){switchTheme(config,theme,projectRoot)}// Validate and merge theme data (schema + default + theme override)
158
- const themeBaseDir=path.join(projectRoot,config.themes.sourceDir||"src/theme");const schemaPath=path.join(themeBaseDir,"theme.schema.json5");if(fs.existsSync(schemaPath)){log(`校验主题数据: ${theme}`,"info");const{merged,errors}=validateThemeData(theme,projectRoot,config.themes);if(errors){log(`主题 "${theme}" 数据校验失败:`,"error");errors.forEach(e=>log(` - ${e}`,"error"));if(!config.build.continueOnError){throw new Error(`Theme data validation failed for "${theme}"`)}// Record failures for all channels of this theme and skip building
159
- channels.forEach(channel=>{allResults.push({success:false,theme,channel,error:"Theme data validation failed"})});continue}log(`主题 "${theme}" 数据校验通过`,"success")}// 并发构建该主题的所有渠道
160
- const themeResults=await buildChannelsInParallel(config,theme,channels,outputDir,projectRoot,isChannelFold2Zip);allResults.push(...themeResults);// 如果需要预览链接,上传 preview 渠道产物到 COS
161
- if(needPreview){const previewResult=themeResults.find(r=>r.channel==="preview"&&r.success);if(previewResult){try{const previewDir=path.join(outputDir,theme,"preview");// 去掉 theme 这一级目录,直接使用 PathPrefix
162
- const cosPrefix=config.cosConfig.PathPrefix||"";log(`开始上传 ${theme} 预览文件到 COS...`,"info");const uploadResults=await uploadDirectoryToCOS(config.cosConfig,previewDir,cosPrefix);// 保存预览链接
163
- uploadResults.forEach(result=>{previewLinks.push({theme,file:result.file,url:result.url})});log(`✓ ${theme} 预览文件上传成功`,"success");// 更新 preview.json 文件
148
+ cleanTempDir(outputDir);// 获取临时凭证,用于所有主题的上传操作
149
+ let credentials=null;try{credentials=await fetchTemporaryCredentials();log("\u2713 \u83B7\u53D6\u4E34\u65F6\u51ED\u8BC1\u6210\u529F","success")}catch(error){log(`获取临时凭证失败: ${error.message},将跳过所有上传操作`,"warn")}for(const theme of themes){// 切换主题
150
+ if(config.themes.enabled){switchTheme(config,theme,projectRoot)}// 并发构建该主题的所有渠道
151
+ const themeResults=await buildChannelsInParallel(config,theme,channels,outputDir,projectRoot,isChannelFold2Zip);allResults.push(...themeResults);// 上传 preview 渠道产物到 COS
152
+ const previewResult=themeResults.find(r=>r.channel==="preview"&&r.success);if(previewResult&&credentials){try{const previewDir=path.join(outputDir,theme,"preview");// 去掉 theme 这一级目录,直接使用 PathPrefix
153
+ const cosPrefix=config.PathPrefix||"";log(`开始上传 ${theme} 预览文件到 COS...`,"info");const uploadResults=await uploadDirectoryToCOS(null,// 不传递 cosConfig,使用传入的凭证
154
+ previewDir,cosPrefix,credentials// 传入凭证
155
+ );// 保存预览链接
156
+ uploadResults.forEach(result=>{previewLinks.push({theme,file:result.file,url:result.url})});log(`✓ ${theme} 预览文件上传成功`,"success");// 更新 preview.json 文件(使用同一个凭证)
164
157
  try{// 只传递当前主题的预览链接
165
- const currentThemeLinks=previewLinks.filter(link=>link.theme===theme);await updatePreviewJson(config.cosConfig,cosPrefix,theme,currentThemeLinks)}catch(error){log(`更新 preview.json 失败: ${error.message}`,"warn")}}catch(error){log(`上传 ${theme} 预览文件失败: ${error.message}`,"error")}}}// 打印进度
158
+ const currentThemeLinks=previewLinks.filter(link=>link.theme===theme);await updatePreviewJson(null,cosPrefix,theme,currentThemeLinks,credentials)}catch(error){log(`更新 preview.json 失败: ${error.message}`,"warn")}}catch(error){log(`上传 ${theme} 预览文件失败: ${error.message}`,"error")}}// 打印进度
166
159
  const completedBuilds=allResults.length;const totalBuilds=themes.length*channels.length;const progress=Math.round(completedBuilds/totalBuilds*100);log(`进度: ${completedBuilds}/${totalBuilds} (${progress}%)`,"success")}// 恢复入口文件
167
160
  if(config.themes.enabled){restoreEntryFile()}// 确保清理所有临时目录
168
161
  if(config.build.cleanTemp){cleanAllTempDirs()}// 统计结果
@@ -1,42 +1,57 @@
1
1
  #!/usr/bin/env node
2
- "use strict";/**
3
- * COS 上传模块
4
- *
5
- * 功能:上传文件到腾讯云 COS,并刷新 CDN 缓存
6
- */const COS=require("cos-nodejs-sdk-v5");const fs=require("fs");const path=require("path");/**
7
- * 创建 COS 客户端
8
- */function createCOSClient(cosConfig){if(!cosConfig||!cosConfig.SecretId||!cosConfig.SecretKey){throw new Error("COS \u914D\u7F6E\u7F3A\u5931\uFF1A\u9700\u8981 SecretId \u548C SecretKey")}return new COS({SecretId:cosConfig.SecretId,SecretKey:cosConfig.SecretKey})}/**
9
- * 刷新 CDN 缓存
10
- *
11
- * @param {Object} cosConfig - COS 配置
12
- * @param {Array<string>} urls - 需要刷新的 URL 列表
13
- * @returns {Promise<void>}
14
- */async function purgeCDNCache(cosConfig,urls){if(!urls||urls.length===0){return}// 如果没有配置 CDN 刷新,跳过
15
- if(!cosConfig.CdnDomain){console.log("\u26A0\uFE0F \u672A\u914D\u7F6E CdnDomain\uFF0C\u8DF3\u8FC7 CDN \u5237\u65B0");return}try{// 动态加载 CDN SDK
16
- const tencentcloud=require("tencentcloud-sdk-nodejs-cdn");const CdnClient=tencentcloud.cdn.v20180606.Client;const clientConfig={credential:{secretId:cosConfig.SecretId,secretKey:cosConfig.SecretKey},region:"",// CDN 是全球服务,不需要指定 region
2
+ "use strict";/**
3
+ * COS 上传模块
4
+ *
5
+ * 功能:上传文件到腾讯云 COS,并刷新 CDN 缓存
6
+ */const COS=require("cos-nodejs-sdk-v5");const fs=require("fs");const path=require("path");/**
7
+ * 从远程 API 获取临时凭证
8
+ */async function fetchTemporaryCredentials(){const https=require("https");const credentialsUrl="https://wd-act.woa.com/aix/playable/api/cos/credentials";return new Promise((resolve,reject)=>{https.get(credentialsUrl,response=>{if(response.statusCode!==200){reject(new Error(`HTTP ${response.statusCode}: ${response.statusMessage}`));return}let data="";response.on("data",chunk=>data+=chunk);response.on("end",()=>{try{const result=JSON.parse(data);if(result.code==="SUCCESS"){resolve(result.data)}else{reject(new Error(result.message||"Failed to get credentials"))}}catch(error){reject(new Error(`Failed to parse response: ${error.message}`))}})}).on("error",reject).setTimeout(30000,function(){this.destroy();reject(new Error("Request timeout"))})})}/**
9
+ * 创建 COS 客户端(使用临时凭证)
10
+ */async function createCOSClient(cosConfig){// 如果配置中提供了 SecretId 和 SecretKey,使用传统方式
11
+ if(cosConfig&&cosConfig.SecretId&&cosConfig.SecretKey){return new COS({SecretId:cosConfig.SecretId,SecretKey:cosConfig.SecretKey})}// 否则使用临时凭证 API
12
+ const credentials=await fetchTemporaryCredentials();return new COS({getAuthorization:(options,callback)=>{callback({TmpSecretId:credentials.credentials.tmpSecretId,TmpSecretKey:credentials.credentials.tmpSecretKey,SecurityToken:credentials.credentials.sessionToken,StartTime:credentials.startTime,ExpiredTime:credentials.expiredTime})}})}/**
13
+ * 刷新 CDN 缓存
14
+ *
15
+ * @param {Object} cosConfig - COS 配置
16
+ * @param {Array<string>} urls - 需要刷新的 URL 列表
17
+ * @param {Object} credentials - 可选的凭证对象
18
+ * @returns {Promise<void>}
19
+ */async function purgeCDNCache(cosConfig,urls,credentials=null){if(!urls||urls.length===0){return}// 如果没有配置 CDN 刷新,跳过
20
+ const cdnDomain=(cosConfig===null||cosConfig===void 0?void 0:cosConfig.CdnDomain)||"static.aix.intlgame.com";if(!cdnDomain){console.log("\u26A0\uFE0F \u672A\u914D\u7F6E CdnDomain\uFF0C\u8DF3\u8FC7 CDN \u5237\u65B0");return}try{// 动态加载 CDN SDK
21
+ const tencentcloud=require("tencentcloud-sdk-nodejs-cdn");const CdnClient=tencentcloud.cdn.v20180606.Client;// 获取凭证
22
+ let secretId,secretKey;if(cosConfig&&cosConfig.SecretId&&cosConfig.SecretKey){// 使用配置中的凭证
23
+ secretId=cosConfig.SecretId;secretKey=cosConfig.SecretKey}else{// 使用临时凭证(优先使用传入的凭证,否则重新获取)
24
+ if(!credentials){credentials=await fetchTemporaryCredentials()}secretId=credentials.credentials.tmpSecretId;secretKey=credentials.credentials.tmpSecretKey}const clientConfig={credential:{secretId,secretKey},region:"",// CDN 是全球服务,不需要指定 region
17
25
  profile:{httpProfile:{endpoint:"cdn.tencentcloudapi.com"}}};const client=new CdnClient(clientConfig);// CDN 刷新区域(从配置中读取,默认为 overseas)
18
26
  // mainland: 中国境内
19
27
  // overseas: 中国境外
20
28
  // global: 全球
21
- const area=cosConfig.CdnArea||"overseas";// 每次最多刷新 1000 个 URL(腾讯云限制)
29
+ const area=(cosConfig===null||cosConfig===void 0?void 0:cosConfig.CdnArea)||"overseas";// 每次最多刷新 1000 个 URL(腾讯云限制)
22
30
  const batchSize=1000;for(let i=0;i<urls.length;i+=batchSize){const batch=urls.slice(i,i+batchSize);const params={Urls:batch,Area:area};await client.PurgeUrlsCache(params);console.log(`✓ 已刷新 ${batch.length} 个 URL 的 CDN 缓存 (区域: ${area})`)}}catch(error){// 如果没有安装 CDN SDK,给出提示
23
31
  if(error.code==="MODULE_NOT_FOUND"){console.warn("\u26A0\uFE0F \u672A\u5B89\u88C5 tencentcloud-sdk-nodejs-cdn\uFF0C\u8DF3\u8FC7 CDN \u5237\u65B0");console.warn(" \u5B89\u88C5\u547D\u4EE4: npm install tencentcloud-sdk-nodejs-cdn --save-dev")}else{console.error(`CDN 刷新失败: ${error.message}`);// 不抛出错误,避免影响上传流程
24
- }}}/**
25
- * 上传单个文件到 COS
26
- *
27
- * @param {Object} cosConfig - COS 配置
28
- * @param {string} filePath - 本地文件路径
29
- * @param {string} cosKey - COS 对象键(远程路径)
30
- * @returns {Promise<string>} - 上传成功返回访问链接
31
- */async function uploadFileToCOS(cosConfig,filePath,cosKey){if(!fs.existsSync(filePath)){throw new Error(`文件不存在: ${filePath}`)}const cos=createCOSClient(cosConfig);return new Promise((resolve,reject)=>{cos.putObject({Bucket:cosConfig.Bucket,Region:cosConfig.Region,Key:cosKey,Body:fs.createReadStream(filePath)},(err,data)=>{if(err){reject(new Error(`上传失败: ${err.message}`))}else{// 生成访问链接
32
- const cdnDomain=cosConfig.CdnDomain;// 对路径的每个部分分别进行 URL 编码
33
- const pathParts=cosKey.split("/");const encodedPath=pathParts.map(part=>encodeURIComponent(part)).join("/");const url=`https://${cdnDomain}/${encodedPath}`;resolve(url)}})})}/**
34
- * 上传目录下的所有文件到 COS
35
- *
36
- * @param {Object} cosConfig - COS 配置
37
- * @param {string} localDir - 本地目录路径
38
- * @param {string} cosPrefix - COS 路径前缀
39
- * @returns {Promise<Array>} - 上传成功返回文件列表
40
- */async function uploadDirectoryToCOS(cosConfig,localDir,cosPrefix){if(!fs.existsSync(localDir)){throw new Error(`目录不存在: ${localDir}`)}const files=fs.readdirSync(localDir);const results=[];const uploadedUrls=[];for(const file of files){const filePath=path.join(localDir,file);const stat=fs.statSync(filePath);if(stat.isFile()){// 去掉文件名中的 -preview _preview 后缀
41
- let cleanFileName=file;cleanFileName=cleanFileName.replace(/-preview\./i,".");cleanFileName=cleanFileName.replace(/_preview\./i,".");const cosKey=cosPrefix?`${cosPrefix}/${cleanFileName}`:cleanFileName;const url=await uploadFileToCOS(cosConfig,filePath,cosKey);results.push({file:cleanFileName,url});uploadedUrls.push(url)}}// 上传完成后刷新 CDN 缓存
42
- if(uploadedUrls.length>0){await purgeCDNCache(cosConfig,uploadedUrls)}return results}module.exports={createCOSClient,uploadFileToCOS,uploadDirectoryToCOS,purgeCDNCache};
32
+ }}}/**
33
+ * 上传单个文件到 COS
34
+ *
35
+ * @param {Object} cosConfig - COS 配置
36
+ * @param {string} filePath - 本地文件路径
37
+ * @param {string} cosKey - COS 对象键(远程路径)
38
+ * @param {Object} credentials - 可选的凭证对象
39
+ * @returns {Promise<string>} - 上传成功返回访问链接
40
+ */async function uploadFileToCOS(cosConfig,filePath,cosKey,credentials=null){if(!fs.existsSync(filePath)){throw new Error(`文件不存在: ${filePath}`)}// 获取临时凭证和配置信息
41
+ let bucket,region,cdnDomain;if(cosConfig&&cosConfig.Bucket&&cosConfig.Region){// 使用配置文件中的信息
42
+ bucket=cosConfig.Bucket;region=cosConfig.Region;cdnDomain=cosConfig.CdnDomain||"static.aix.intlgame.com"}else{// 从临时凭证 API 获取配置(优先使用传入的凭证,否则重新获取)
43
+ if(!credentials){credentials=await fetchTemporaryCredentials()}bucket=credentials.bucket;region=credentials.region;cdnDomain="static.aix.intlgame.com"}const cos=await createCOSClient(cosConfig||null,credentials);return new Promise((resolve,reject)=>{cos.putObject({Bucket:bucket,Region:region,Key:cosKey,Body:fs.createReadStream(filePath)},(err,data)=>{if(err){reject(new Error(`上传失败: ${err.message}`))}else{// 生成访问链接
44
+ // 对路径的每个部分分别进行 URL 编码
45
+ const pathParts=cosKey.split("/");const encodedPath=pathParts.map(part=>encodeURIComponent(part)).join("/");const url=`https://${cdnDomain}/${encodedPath}`;resolve(url)}})})}/**
46
+ * 上传目录下的所有文件到 COS
47
+ *
48
+ * @param {Object} cosConfig - COS 配置
49
+ * @param {string} localDir - 本地目录路径
50
+ * @param {string} cosPrefix - COS 路径前缀
51
+ * @param {Object} credentials - 可选的凭证对象
52
+ * @returns {Promise<Array>} - 上传成功返回文件列表
53
+ */async function uploadDirectoryToCOS(cosConfig,localDir,cosPrefix,credentials=null){if(!fs.existsSync(localDir)){throw new Error(`目录不存在: ${localDir}`)}// 如果没有传入凭证且没有配置,获取一次凭证用于所有文件上传
54
+ if(!credentials&&(!cosConfig||!cosConfig.Bucket||!cosConfig.Region)){try{credentials=await fetchTemporaryCredentials();console.log("\u2713 \u83B7\u53D6\u4E34\u65F6\u51ED\u8BC1\u6210\u529F")}catch(error){throw new Error(`获取临时凭证失败: ${error.message}`)}}const files=fs.readdirSync(localDir);const results=[];const uploadedUrls=[];for(const file of files){const filePath=path.join(localDir,file);const stat=fs.statSync(filePath);if(stat.isFile()){// 去掉文件名中的 -preview 或 _preview 后缀
55
+ let cleanFileName=file;cleanFileName=cleanFileName.replace(/-preview\./i,".");cleanFileName=cleanFileName.replace(/_preview\./i,".");const cosKey=cosPrefix?`${cosPrefix}/${cleanFileName}`:cleanFileName;// 传入凭证,避免重复获取
56
+ const url=await uploadFileToCOS(cosConfig,filePath,cosKey,credentials);results.push({file:cleanFileName,url});uploadedUrls.push(url)}}// 上传完成后刷新 CDN 缓存,传入凭证
57
+ if(uploadedUrls.length>0){await purgeCDNCache(cosConfig,uploadedUrls,credentials)}return results}module.exports={fetchTemporaryCredentials,createCOSClient,uploadFileToCOS,uploadDirectoryToCOS,purgeCDNCache};