UNPKG

@oppo-minigame/cli

Version:

Command line interface for rapid OPPO minigame development

1 lines 27.2 kB
const fs=require("fs-extra"),path=require("path"),chalk=require("chalk"),{select:select,input:input}=require("@inquirer/prompts"),{packLog:packLog,packError:packError,parseJSONFile:parseJSONFile,replaceFileContent:replaceFileContent,traverseDir:traverseDir,shellExecSilentlyAsync:shellExecSilentlyAsync,shellOpenDirectory:shellOpenDirectory,shellExit:shellExit,POSITIVE_INT_REG:POSITIVE_INT_REG,LINUX_PATH_REG:LINUX_PATH_REG,FULL_RPK_REG:FULL_RPK_REG,RPK_REG:RPK_REG,EMAIL_REG:EMAIL_REG,INQUIRE_QUESTION_KEY:INQUIRE_QUESTION_KEY,INQUIRE_CHOICE_NO:INQUIRE_CHOICE_NO,INQUIRE_CHOICE_YES:INQUIRE_CHOICE_YES,packSpinner:packSpinner,execInstallRpkProcess:execInstallRpkProcess,copyDirRecursivelyAsync:copyDirRecursivelyAsync,sleep:sleep}=require("../utils"),{SIGN_RELEASE_DIR:SIGN_RELEASE_DIR,SIGN_DIR_NAME:SIGN_DIR_NAME,CERTIFICATE_FILE_NAME:CERTIFICATE_FILE_NAME,PRIVATE_FILE_NAME:PRIVATE_FILE_NAME,MANIFEST_FILE_NAME:MANIFEST_FILE_NAME}=require("../config/config"),{recordGameName:recordGameName,recordGamePackage:recordGamePackage}=require("../oplus/obus-report"),GAME_ENTRY_FILE="game.js",WX_GAME_CONFIG_FILE="game.json",WX_PACKAGE_CONFIG_FILE="package.json",WX_PROJECT_CONFIG_FILE="project.config.json",WX_PROJECT_PRIVATE_CONFIG_FILE="project.private.config.json",QUICK_GAME_WX_ENTRY_FILE="wx-game.js",PRIVACY_PROTECTION_CONFIG_FILE_NO_EXT="privacy-protection-config",PRIVACY_PROTECTION_CONFIG_FILE="privacy-protection-config.json",PRIVACY_POLICY_FILE="privacyPolicy.txt",USER_POLICY_FILE="userPolicy.txt",PRIVACY_PROTECTION_CONFIG_TYPE_NONE="0",PRIVACY_PROTECTION_CONFIG_TYPE_PRIVACY_ONLY="1",PRIVACY_PROTECTION_CONFIG_TYPE_PRIVACY_USER="2",QUICK_GAME_TEMPLATE_LOGO_FILE="logo.png",WX_QUICK_GAME_CONFIG_DIR_SUFFIX="-oppo-config",DEFAULT_PROJECT_NAME="DemoProject",DEFAULT_PACKAGE_NAME_FRONT="com.company.game",DEFAULT_ORIENTATION="portrait",DEFAULT_MIN_PLATFORM_VERSION=1139,DEFAULT_VERSION_NAME="1.0.0",DEFAULT_VERSION_CODE=1,DEFAULT_ICON_PATH="/logo.png",INVALID_INPUT_MSG="输入不合法,请重新输入",OPEN_SSL_EXEC_NAME="openssl",OPEN_SSL_DOWNLOAD_LINK="https://ie-activity-cn.heytapimage.com/static/minigame/ThirdParty/tools/0b9a673c5dc0b21e65c979a4c50e818c.zip",GAME_ENGINE_UNITY="unity";let obusSDK,cmdPackage,cmdProjectName,cmdVersionCode,cmdVersionName,cmdMinPlatformVersion,cmdIcon,wxGameDir="",wxGameConfigPath="",wxGameConfigObj=null,wxGameProjectConfigObj=null,wxGameProjectPrivateConfigObj=null,wxGameProjectConfigPath="",wxGameProjectPrivateConfigPath="",wxQuickGameConfigDirPath="",wxQuickGamePrivacyPolicyConfigPath="",wxQuickGameUserPolicyConfigPath="",wxQuickGameCopyExcludes=[],currentPhase=1,quickGameDir="",quickGameConfigPath="",quickGameToolkitPath="",quickGameToolkitTPLPath="",distRpkPath="",quickGameConfig=null,cachedReleaseSignDirPath="",cachedReleaseCertificatePath="",cachedReleasePrivateKeyPath="",quickGameReleaseCertificatePath="",quickGameReleasePrivateKeyPath="",quickGameReleaseSignDirPath="",transferWay=0,privacyProtectionConfigType="0",scriptToolkitDirPath="",scriptToolkitNum=0;function concatPackage(e){return`${e}.nearme.gamecenter`}async function createWXQuickGameConfigDirectory(){await fs.exists(wxQuickGameConfigDirPath)||await fs.mkdir(wxQuickGameConfigDirPath)}async function isReleaseSignCached(){return await fs.exists(cachedReleaseCertificatePath)&&await fs.exists(cachedReleasePrivateKeyPath)}function setTransferWay(e){transferWay=e?1:2}function isAllPassTransfer(){return 1===transferWay}function writeQuickGameConfigToDiskAsync(){return quickGameConfig?fs.writeFile(quickGameConfigPath,JSON.stringify(quickGameConfig)):Promise.resolve()}async function initDataCollection(){obusSDK=require("../oplus/obus-report"),process.on("SIGINT",async()=>{await reportAbort()}),process.on("SIGHUP",async()=>{await reportAbort()}),await obusSDK.reportWXTransferStart()}async function initEnvironment(e){const a=packSpinner("初始化环境");wxGameDir=e||process.cwd(),wxGameConfigPath=path.join(wxGameDir,"game.json"),wxGameProjectConfigPath=path.join(wxGameDir,"project.config.json"),wxGameProjectPrivateConfigPath=path.join(wxGameDir,"project.private.config.json"),quickGameDir=path.join(path.dirname(wxGameDir),path.basename(wxGameDir)+"-oppo-transfer"),quickGameReleaseSignDirPath=path.join(quickGameDir,SIGN_DIR_NAME,SIGN_RELEASE_DIR),quickGameReleaseCertificatePath=path.join(quickGameReleaseSignDirPath,CERTIFICATE_FILE_NAME),quickGameReleasePrivateKeyPath=path.join(quickGameReleaseSignDirPath,PRIVATE_FILE_NAME),wxQuickGameConfigDirPath=path.join(path.dirname(wxGameDir),path.basename(wxGameDir)+"-oppo-config"),wxQuickGamePrivacyPolicyConfigPath=path.join(wxQuickGameConfigDirPath,"privacyPolicy.txt"),wxQuickGameUserPolicyConfigPath=path.join(wxQuickGameConfigDirPath,"userPolicy.txt"),cachedReleaseSignDirPath=path.join(wxQuickGameConfigDirPath,SIGN_DIR_NAME,SIGN_RELEASE_DIR),cachedReleaseCertificatePath=path.join(cachedReleaseSignDirPath,CERTIFICATE_FILE_NAME),cachedReleasePrivateKeyPath=path.join(cachedReleaseSignDirPath,PRIVATE_FILE_NAME),quickGameConfigPath=path.join(quickGameDir,MANIFEST_FILE_NAME),quickGameToolkitPath=path.resolve(__dirname,"..",".."),quickGameToolkitTPLPath=path.join(quickGameToolkitPath,"tpl");let i="";if("win32"===process.platform?i="win":"darwin"===process.platform&&(i="mac/apps"),i&&(scriptToolkitDirPath=path.join(quickGameToolkitTPLPath,"tools",i)),scriptToolkitDirPath&&await fs.exists(scriptToolkitDirPath)){const e=await fs.readdir(scriptToolkitDirPath);for(file of(scriptToolkitNum=e.length,e))wxQuickGameCopyExcludes.push(file)}a.succeed()}async function validateWXGameDir(){const e=packSpinner("检查微信小游戏工程",wxGameDir);if(!await fs.exists(path.join(wxGameDir,"game.js"))){const a="微信小游戏工程缺少启动模块";e.fail(a,"game.js"),await reportEndThenExit(a)}if(!await fs.exists(path.join(wxGameDir,"game.json"))){const a="微信小游戏工程缺少配置模块";e.fail(a,"game.json"),await reportEndThenExit(a)}e.succeed()}async function validateQGGameDir(){const e=packSpinner("检查 OPPO 小游戏工程",quickGameDir);await fs.exists(quickGameDir)||(e.fail("OPPO 小游戏工程缺失,请先进行微信小游戏转化流程",quickGameDir),shellExit()),await fs.exists(path.join(quickGameDir,"game.js"))||(e.fail("OPPO 小游戏工程缺少启动模块","game.js"),shellExit()),await fs.exists(path.join(quickGameDir,MANIFEST_FILE_NAME))||(e.fail("OPPO 小游戏工程缺少配置模块",MANIFEST_FILE_NAME),shellExit()),e.succeed()}async function chooseTransferWay(){currentPhase=2,isAllPassTransfer()||(packLog("选择转化方式"),await reportAbortGuard(async()=>{setTransferWay("yes"===await select({message:"是否自动一键转化?",choices:[INQUIRE_CHOICE_YES,INQUIRE_CHOICE_NO]}))}))}async function constructConfigProject(){if(currentPhase=3,isAllPassTransfer())return;let e;if(await reportAbortGuard(async()=>{e=await select({message:`是否需要对开放能力进行配置?\n${chalk.yellow("(若未配置,广告、登录、支付等能力可能无法使用,配置完成再重新转换)")}`,choices:[INQUIRE_CHOICE_NO,INQUIRE_CHOICE_YES]})}),"yes"===e){async function a(e){const a=path.join(quickGameToolkitTPLPath,"weixin_config"),i=e+".json",t=path.join(wxQuickGameConfigDirPath,i);await fs.exists(t)||await fs.copyFile(path.join(a,i),t);const n=path.join(a,e+"-schema.json"),o=("win32"===process.platform?"file:///":"file://")+n,c=await fs.readJSON(t);await fs.exists(n)&&c.$schema!==o&&(c.$schema=o,await fs.writeJson(t,c,{spaces:2}))}const i=packSpinner("构建配置工程",wxQuickGameConfigDirPath);await createWXQuickGameConfigDirectory(),await a("privacy-protection-config"),await fs.createFile(wxQuickGamePrivacyPolicyConfigPath),await fs.createFile(wxQuickGameUserPolicyConfigPath),await a("ad-info"),await a("game-service-config"),shellOpenDirectory(wxQuickGameConfigDirPath),i.succeed(),await reportEndThenExit()}}async function cacheQuickGameAssets(){await fs.exists(quickGameReleaseCertificatePath)&&await fs.exists(quickGameReleasePrivateKeyPath)&&(await fs.emptyDir(cachedReleaseSignDirPath),await fs.copy(quickGameReleaseCertificatePath,cachedReleaseCertificatePath),await fs.copy(quickGameReleasePrivateKeyPath,cachedReleasePrivateKeyPath))}async function constructQuickGameProject(){currentPhase=4;const e=packSpinner("构建转化工程",quickGameDir);await InjectWXAdapters(),await copyDirRecursivelyAsync(wxGameDir,quickGameDir,["game.js","game.json","package.json","project.config.json","project.private.config.json"]),await fs.copy(path.join(wxGameDir,"game.js"),path.join(quickGameDir,"wx-game.js")),quickGameConfig?await writeQuickGameConfigToDiskAsync():await fs.copyFile(path.join(quickGameToolkitTPLPath,MANIFEST_FILE_NAME),quickGameConfigPath);const a=path.join(quickGameDir,"logo.png");if(await fs.exists(a)||await fs.copyFile(path.join(quickGameToolkitTPLPath,"logo.png"),a),await fs.exists(wxQuickGameConfigDirPath)){wxQuickGameCopyExcludes.push(PRIVACY_PROTECTION_CONFIG_FILE);const e=path.join(wxQuickGameConfigDirPath,PRIVACY_PROTECTION_CONFIG_FILE);if(await fs.exists(e)){const a=await fs.readJson(e);if(a.policyType&&("0"===a.policyType||"1"===a.policyType||"2"===a.policyType))switch(privacyProtectionConfigType=a.policyType,a.policyType){case"0":wxQuickGameCopyExcludes.push("privacyPolicy.txt","userPolicy.txt");break;case"1":wxQuickGameCopyExcludes.push("userPolicy.txt")}}await copyDirRecursivelyAsync(wxQuickGameConfigDirPath,quickGameDir,wxQuickGameCopyExcludes)}e.succeed()}async function InjectWXAdapters(){await copyDirRecursivelyAsync(path.join(quickGameToolkitTPLPath,"weixin"),quickGameDir)}async function transferWXConfigToQuickGame(){function e(e,a){return e?"number"==typeof e?POSITIVE_INT_REG.test(e.toString())?e:a:"string"==typeof e&&POSITIVE_INT_REG.test(e)?e:a:a}function a(e,a){return e in wxGameConfigObj&&wxGameConfigObj[e]?wxGameConfigObj[e]:a}function i(e,a){return e in wxGameProjectPrivateConfigObj&&wxGameProjectPrivateConfigObj[e]?wxGameProjectPrivateConfigObj[e]:e in wxGameProjectConfigObj&&wxGameProjectConfigObj[e]?wxGameProjectConfigObj[e]:a}function t(){console.log("项目名称:",quickGameConfig.name)}function n(){console.log("包名:",quickGameConfig.package)}function o(){console.log("版本名称:",quickGameConfig.versionName)}function c(){console.log("版本号:",quickGameConfig.versionCode)}function r(){console.log("最小平台版本:",quickGameConfig.minPlatformVersion)}function s(){console.log("图标路径:",quickGameConfig.icon)}function m(e){return e&&FULL_RPK_REG.test(e)}function l(e){return e&&POSITIVE_INT_REG.test(e)}function u(){return l(cmdMinPlatformVersion)&&+cmdMinPlatformVersion>=1139}function f(){let e=!!quickGameConfig.name;if(e)try{quickGameConfig.name=decodeURIComponent(quickGameConfig.name)}catch{e=!1}if(!e)try{quickGameConfig.name=decodeURIComponent(i("projectname","DemoProject"))}catch{quickGameConfig.name="DemoProject"}recordGameName(quickGameConfig.name)}function p(){FULL_RPK_REG.test(quickGameConfig.package)||(quickGameConfig.package=concatPackage(RPK_REG.test(quickGameConfig.name)?quickGameConfig.name:"com.company.game"),recordGamePackage(quickGameConfig.package))}function g(){quickGameConfig.versionName=quickGameConfig.versionName&&"string"==typeof quickGameConfig.versionName?quickGameConfig.versionName:"1.0.0"}function k(){quickGameConfig.versionCode=e(quickGameConfig.versionCode,1)}function G(){quickGameConfig.minPlatformVersion=e(quickGameConfig.minPlatformVersion,1139),quickGameConfig.minPlatformVersion<1139&&(quickGameConfig.minPlatformVersion=1139)}function P(){var e;(e=cmdIcon)&&LINUX_PATH_REG.test(e)?quickGameConfig.icon=cmdIcon:(void 0!==cmdIcon&&packLog(chalk.yellow(`指定的图标路径 <${cmdIcon}> 不合法,改用默认策略`)),C())}function C(){quickGameConfig.icon=quickGameConfig.icon&&"string"==typeof quickGameConfig.icon&&LINUX_PATH_REG.test(quickGameConfig.icon)?quickGameConfig.icon:"/logo.png"}currentPhase=5,readWXConfigs(),isAllPassTransfer()?(packLog(chalk.yellow("自动填写项目配置,默认使用转化后的 oppo 配置,否则使用微信配置,都不存在使用缺省值")),function(){let e=!!cmdProjectName;if(e)try{quickGameConfig.name=decodeURIComponent(cmdProjectName),recordGameName(quickGameConfig.name)}catch{e=!1}e||(void 0!==cmdProjectName&&packLog(chalk.yellow(`指定的项目名称 <${cmdProjectName}> 不合法,改用默认策略`)),f())}(),t(),m(cmdPackage)?(quickGameConfig.package=cmdPackage,recordGamePackage(quickGameConfig.package)):(void 0!==cmdPackage&&packLog(chalk.yellow(`指定的包名 <${cmdPackage}> 不合法,改用默认策略`)),p()),n(),cmdVersionName?quickGameConfig.versionName=cmdVersionName:(void 0!==cmdVersionName&&packLog(chalk.yellow(`指定的版本名称 <${cmdVersionName}> 不合法,改用默认策略`)),g()),o(),l(cmdVersionCode)?quickGameConfig.versionCode=+cmdVersionCode:(void 0!==cmdVersionCode&&packLog(chalk.yellow(`指定的版本号 <${cmdVersionCode}> 不合法,改用默认策略`)),k()),c(),u()?quickGameConfig.minPlatformVersion=+cmdMinPlatformVersion:(void 0!==cmdMinPlatformVersion&&packLog(chalk.yellow(`指定的最小平台版本 <${cmdMinPlatformVersion}> 不合法,需大于 <1139>,改用默认策略`)),G()),r(),P(),s()):await async function(){let e;packLog(chalk.yellow("逐项填写项目配置,默认建议转化后的 oppo 配置,否则建议微信配置,都不存在建议缺省值"));let a="string"==typeof cmdProjectName&&cmdProjectName;if(a)try{cmdProjectName=decodeURIComponent(cmdProjectName)}catch{a=!1}a||void 0===cmdProjectName||packLog(chalk.yellow(`指定的项目名称 <${cmdProjectName}> 不合法`)),cmdProjectName?(f(),t()):(f(),await reportAbortGuard(async()=>{e=await input({message:"请输入项目名称:",default:quickGameConfig.name,validate:e=>!!e||"项目名称不能为空"}),quickGameConfig.name=e,recordGameName(quickGameConfig.name)}));const i=m(cmdPackage);void 0===cmdPackage||i||packLog(chalk.yellow(`指定的包名 <${cmdPackage}> 不合法`)),i?(p(),n()):(p(),await reportAbortGuard(async()=>{e=await input({message:`请输入包名\n${chalk.yellow("以英文句号分隔,以 .nearme.gamecenter 结尾,不能包含下划线以外的特殊符号,不能出现oppo字样,英文句号分隔的每一段以字母开头且不能以下划线结尾")}\n`,default:quickGameConfig.package,validate:e=>!!FULL_RPK_REG.test(e)||"输入不合法,请重新输入"}),quickGameConfig.package=e,recordGamePackage(quickGameConfig.package)})),"string"!=typeof cmdVersionName||cmdVersionName||packLog(chalk.yellow(`指定的版本名称 <${cmdVersionName}> 不合法`)),cmdVersionName?(g(),o()):(g(),await reportAbortGuard(async()=>{e=await input({message:"请输入版本名称(1.0.0, x.x.x):",default:quickGameConfig.versionName}),quickGameConfig.versionName=e}));const P=l(cmdVersionCode);void 0===cmdVersionCode||P||packLog(chalk.yellow(`指定的版本号 <${cmdVersionCode}> 不合法`)),P?(k(),c()):(k(),await reportAbortGuard(async()=>{e=await input({message:"请输入版本号(1, 2, 3...):",default:quickGameConfig.versionCode,validate:e=>!!POSITIVE_INT_REG.test(e)||"版本号需为正整数,请重新输入"}),quickGameConfig.versionCode=+e}));const d=u();void 0===cmdMinPlatformVersion||d||packLog(chalk.yellow(`指定的最小平台版本 <${cmdMinPlatformVersion}> 不合法,需大于 <1139>`)),d?(G(),r()):(G(),await reportAbortGuard(async()=>{e=await input({message:"请输入最小平台版本(不小于 1139):",default:quickGameConfig.minPlatformVersion,validate:e=>!(!POSITIVE_INT_REG.test(e)||+e<1139)||"输入不合法,请重新输入"}),quickGameConfig.minPlatformVersion=+e}));const E=cmdIcon&&LINUX_PATH_REG.test(cmdIcon);void 0===cmdIcon||E||packLog(chalk.yellow(`指定的图标路径 <${cmdIcon}> 不合法`)),E?(C(),s()):(C(),await reportAbortGuard(async()=>{e=await input({message:"请输入 icon 相对路径(/logo.png, /xxx/logo.png):",default:quickGameConfig.icon,validate:e=>!!LINUX_PATH_REG.test(e)||"输入不合法,请重新输入"}),quickGameConfig.icon=e}))}(),packLog(chalk.yellow("其他配置自动迁移至 oppo"));const d=chalk.red("无");quickGameConfig.orientation=a("deviceOrientation","portrait"),console.log("设备方向:",quickGameConfig.orientation),quickGameConfig.openDataContext=a("openDataContext",void 0),console.log("开放数据域:",quickGameConfig.openDataContext?quickGameConfig.openDataContext:d);let E=a("subpackages",void 0);E||(E=a("subPackages",void 0));const h="main_sub",w=E&&E.length;if(w){for(const e of E)if("main"===e.name){let a=-1;const i=E.map(e=>e.name);for(const e of i)if(/main_sub\d+/.test(e)&&e!==h){const i=+e.substring(8);i>a&&(a=i)}-1===a?a=1:++a,e.name="main_sub"+a,e.origin="main"}quickGameConfig.subpackages=E}console.log("分包:",w?E.map(e=>e.name):d),quickGameConfig.appid=i("appid",void 0),console.log("appid:",quickGameConfig.appid?quickGameConfig.appid:d),delete quickGameConfig.plugins,console.log("插件:",chalk.red("暂不支持")),quickGameConfig.privacyPolicy=privacyProtectionConfigType;let y="";"0"===privacyProtectionConfigType?y="不使用":"1"===privacyProtectionConfigType?y='只使用"隐私协议"':"2"===privacyProtectionConfigType&&(y='使用"隐私协议"和"用户协议"'),console.log("隐私政策:",y||d),wxGameConfigObj.plugins&&wxGameConfigObj.plugins.UnityPlugin&&(quickGameConfig.gameEngine="unity"),quickGameConfig.isWXTransfer=!0,await writeQuickGameConfigToDiskAsync()}function readWXConfigs(){wxGameConfigObj=parseJSONFile(wxGameConfigPath),wxGameProjectConfigObj=parseJSONFile(wxGameProjectConfigPath),wxGameProjectPrivateConfigObj=parseJSONFile(wxGameProjectPrivateConfigPath)}async function readQuickGameConfig(){await fs.exists(quickGameConfigPath)&&!quickGameConfig&&(quickGameConfig=parseJSONFile(quickGameConfigPath),reportGameName(quickGameConfig.name),reportGamePackage(quickGameConfig.package))}async function handleGameEngineBugs(){currentPhase=6;const e=packSpinner("适配游戏引擎"),a=path.join(quickGameDir,"cocos","cocos2d-js-min.js");replaceFileContent(a,{map:/BASELINE_OFFSET:.*?,/,to:"BASELINE_OFFSET:.26,"});const i=path.join(quickGameDir,"cocos-js","cc.js");replaceFileContent(i,{map:/var\s\w*?=(\w*?\("BASELINE_RATIO",.*?\))/,replaceCaptures:["-.26"]});const t=path.join(quickGameDir,"libs","laya.core.js");replaceFileContent(t,{map:/Config.useRetinalCanvas\s*=\s*.*?([,;])/,to:"Config.useRetinalCanvas=true$1"});const n=path.join(quickGameDir,"js","index.js");replaceFileContent(n,{map:/"useRetinalCanvas"\s*:\s*.*?([,}])/,to:'"useRetinalCanvas":true$1'}),e.succeed()}async function injectUnityPlugin(){if(currentPhase=8,!quickGameConfig.gameEngine||"unity"!==quickGameConfig.gameEngine)return;const e="注入 UnityPlugin",a=packSpinner(e),i=path.resolve(__dirname,"..","..","tpl","unity_v2","plugins");let t=await fs.readdir(i);t=t.filter(e=>{if("string"!=typeof e)return!1;const a=e.split("."),i=a.length;if(3!==i)return!1;for(let e=0;e<i;e++)if(!/^\d+$/.test(a[e]))return!1;return!0});const n="UnityPlugin.js";async function o(e){await fs.copy(path.join(i,e,n),path.join(quickGameDir,n))}const c=wxGameConfigObj.plugins.UnityPlugin;if(c.version&&-1!==t.indexOf(c.version))return await o(c.version),void a.succeed(e,c.version);function r(e,a){const i=e.split("."),t=a.split("."),n=parseInt(i[0]),o=parseInt(i[1]),c=parseInt(i[2]),r=parseInt(t[0]),s=parseInt(t[1]),m=parseInt(t[2]);return n===r?o===s?c-m:o-s:n-r}t.sort(r);const s=t[t.length-1];if(c.version){if(r(c.version,s)>=0)await o(s),a.succeed(e,`版本配置过高,使用最新支持版本 ${s}`);else for(const i of t)if(r(i,c.version)>=0){await o(i),a.succeed(e,`版本 ${c.version} 不存在,使用向上兼容版本 ${i}`);break}}else await o(s),a.succeed(e,`没有配置版本,使用最新支持版本 ${s}`)}async function packQuickGame(){currentPhase=9;let e=!1;if(isAllPassTransfer())e=await isReleaseSignCached();else{let a;if(await reportAbortGuard(async()=>{a=await select({message:"是否打正式包",choices:[INQUIRE_CHOICE_NO,INQUIRE_CHOICE_YES]})}),"yes"===a)if(await isReleaseSignCached())packLog("使用之前生成的 release 证书"),await fs.copy(cachedReleaseCertificatePath,quickGameReleaseCertificatePath),await fs.copy(cachedReleasePrivateKeyPath,quickGameReleasePrivateKeyPath),e=!0;else{let i=null,t=null;if("win32"!==process.platform)i="openssl";else{const e=path.join(quickGameToolkitPath,"thirdParty","openSSLWin64"),a=path.join(e,"bin"),n=path.join(a,"openssl.exe");if(t=path.join(a,"cnf","openssl.cnf"),await fs.exists(n))i=n;else{await fs.emptyDir(e);let a=packSpinner("下载 OpenSSL");const t=e+".zip",o="下载OpenSSL失败";try{await shellExecSilentlyAsync(`curl -o ${t} ${OPEN_SSL_DOWNLOAD_LINK}`),await fs.exists(t)||(a.fail(),await reportEndThenExit(o))}catch(e){a.fail(),await reportEndThenExit(o)}a.succeed(),a=packSpinner("解压 OpenSSL");try{await shellExecSilentlyAsync(`tar -xf ${t} -C ${e}`)}catch(e){a.fail(),await fs.remove(t),await reportEndThenExit("解压OpenSSL失败")}a.succeed(),i=n,await fs.remove(t)}}if(i){let n,o,c,r,s,m,l;packLog("准备生成证书","请根据实际情况填写信息"),await reportAbortGuard(async()=>{a=await input({message:`请输入国家地区代码:\n${chalk.yellow("(2 位英文字母, 如 CN)")}\n`,default:"CN",validate:e=>!!/^[a-zA-Z]{2}$/.test(e)||"输入不合法,请重新输入"}),n=a}),await reportAbortGuard(async()=>{a=await input({message:"请输入省份:",default:"GuangDong"}),o=a}),await reportAbortGuard(async()=>{a=await input({message:"请输入城市:",default:"ShenZhen"}),c=a}),await reportAbortGuard(async()=>{a=await input({message:`请输入组织名称:\n${chalk.yellow("(不可为空)")}\n`,validate:e=>!!e||"输入不合法,请重新输入"}),r=a}),await reportAbortGuard(async()=>{a=await input({message:`请输入部门名称:\n${chalk.yellow("(不可为空)")}\n`,validate:e=>!!e||"输入不合法,请重新输入"}),s=a}),await reportAbortGuard(async()=>{a=await input({message:`请输入通用名称:\n${chalk.yellow("(服务域名或您的名称,不可为空)")}\n`,validate:e=>!!e||"输入不合法,请重新输入"}),m=a}),await reportAbortGuard(async()=>{a=await input({message:"请输入电子邮箱",validate:e=>!!EMAIL_REG.test(e)||"电子邮箱格式不合法,请重新输入"}),l=a});const u=packSpinner("生成私钥和证书");await fs.emptyDir(quickGameReleaseSignDirPath);try{const e=`${i} req -newkey rsa:2048 -nodes -keyout "${quickGameReleasePrivateKeyPath}" -x509 -days 3650 -out "${quickGameReleaseCertificatePath}" -subj /C="${n}"/ST="${o}"/L="${c}"/O="${r}"/OU="${s}"/CN="${m}"/emailAddress="${l}"`;t?await shellExecSilentlyAsync(`set OPENSSL_CONF=${t}&${e}`):await shellExecSilentlyAsync(e)}catch(e){u.fail();let a="生成证书和私钥失败";e&&(e instanceof Error&&e.message?a=e.message:"string"==typeof e&&(a=e)),await reportEndThenExit(a)}u.succeed(),packLog("私钥",quickGameReleasePrivateKeyPath),packLog("证书",quickGameReleaseCertificatePath),e=!0}else packError("OpenSSL 不存在"),await reportEndThenExit("OpenSSL不存在")}}const a=e?"release":"develop";quickGameConfig.envVersion!==a&&(quickGameConfig.envVersion=a,await writeQuickGameConfigToDiskAsync()),packLog("开始打包流程");const i=require("./commands/pack");distRpkPath=await i.start({pub_dir:quickGameDir,isDebugEnv:!e,subpack:quickGameConfig.subpackages&&quickGameConfig.subpackages.length>0,async fail(e){await reportEndThenExit(e)}})}async function installQuickGame(){currentPhase=11,await execInstallRpkProcess(distRpkPath,{async fail(e){await reportEndThenExit(e)}})}async function copyToolkit(){if(currentPhase=10,!scriptToolkitDirPath||!scriptToolkitNum)return;const e=packSpinner("配置实用工具");await createWXQuickGameConfigDirectory(),await copyDirRecursivelyAsync(scriptToolkitDirPath,wxQuickGameConfigDirPath),e.succeed()}async function transformForCompatibility(){currentPhase=7;const e=quickGameConfig.gameEngine&&"unity"===quickGameConfig.gameEngine;if(isAllPassTransfer()&&!e)return;if(!isAllPassTransfer()){let e;if(await reportAbortGuard(async()=>{e=await select({name:INQUIRE_QUESTION_KEY,message:`当前不支持 es6 及部分 js 新语法特性,是否进行兼容转化\n${chalk.yellow("此操作较耗时,unity 游戏建议进行,其他游戏根据实际情况选择")}`,choices:[INQUIRE_CHOICE_NO,INQUIRE_CHOICE_YES]})}),"no"===e)return}const a=packSpinner("进行兼容转化"),i=require("@babel/core"),t=[require("@babel/plugin-transform-modules-commonjs"),require("@babel/plugin-transform-optional-chaining"),require("@babel/plugin-transform-nullish-coalescing-operator")],n=[];await traverseDir(quickGameDir,n);for(const e of n)if(e.endsWith(".js")&&!path.dirname(e).endsWith("wx-adapter"))try{const a=await i.transformFileAsync(e,{sourceType:"unambiguous",plugins:t});a&&a.code&&await fs.writeFile(e,a.code)}catch{a.fail(`[${e}] 兼容转化失败`),await reportEndThenExit("兼容转化失败")}a.succeed("完成兼容转化")}async function transfer(e){await initDataCollection(),e.yes&&setTransferWay(!0),cmdPackage=e.package,cmdProjectName=e.projectName,cmdVersionCode=e.versionCode,cmdVersionName=e.versionName,cmdMinPlatformVersion=e.minPlatformVersion,cmdIcon=e.icon,e.configOnly?await transferConfig(e.pub_dir):e.adapterOnly?await transferAdapters(e.pub_dir):await transferAll(e.pub_dir),await reportEnd()}async function transferAll(e){await initEnvironment(e),await readQuickGameConfig(),await cacheQuickGameAssets(),await validateWXGameDir(),await chooseTransferWay(),await constructConfigProject();const a=packSpinner("清理转化工程");await fs.emptyDir(quickGameDir),a.succeed(),await constructQuickGameProject(),await readQuickGameConfig(),await transferWXConfigToQuickGame(),await handleGameEngineBugs(),await transformForCompatibility(),await injectUnityPlugin(),await packQuickGame(),await copyToolkit(),await installQuickGame()}async function transferConfig(e){e=redirectPubDirInConfigDir(e),await initEnvironment(e),await validateWXGameDir(),await validateQGGameDir(),await readQuickGameConfig(),await transferWXConfigToQuickGame(),await packQuickGame(),await installQuickGame()}async function transferAdapters(e){e=redirectPubDirInConfigDir(e),await initEnvironment(e),await validateQGGameDir(),readWXConfigs(),await readQuickGameConfig();const a=packSpinner("注入适配模块");await InjectWXAdapters(),a.succeed(),await injectUnityPlugin(),await packQuickGame(),await installQuickGame()}function redirectPubDirInConfigDir(e){if((e=e||process.cwd()).endsWith("-oppo-config")){const a=path.basename(e),i=a.substring(0,a.lastIndexOf("-oppo-config"));e=path.resolve(e,"..",i)}return e}async function reportAbortGuard(e){try{arguments.length>1?await e.call(this,arguments.slice(1)):await e.apply(this)}catch{await reportAbort()}}function reportGamePackage(e){obusSDK&&e&&obusSDK.recordGamePackage(e)}function reportGameName(e){obusSDK&&e&&obusSDK.recordGameName(e)}async function reportEnd(e){const a=packSpinner("转化结束","\n");obusSDK&&await obusSDK.reportWXTransferEnd(currentPhase,transferWay,e),a.succeed()}async function reportEndThenExit(e){await reportEnd(e),shellExit()}async function reportAbort(){await reportEndThenExit("abort")}module.exports=transfer;