@hyext/builder-revues 1.0.10 → 1.0.14
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/index.js +1203 -16
- package/package.json +8 -7
- package/static/framework/.DS_Store +0 -0
- package/static/framework/script/game-service.js +1 -26923
- package/static/framework/script/service.js +1 -1
- package/static/framework/script/view.js +1 -1
- package/static/template/miniapp-page-manager.hbs +3 -0
- package/static/template/minigame-page-manager.hbs +3 -0
package/dist/index.js
CHANGED
@@ -3,19 +3,1206 @@
|
|
3
3
|
* (c) 2024-2024 Alex
|
4
4
|
* Released under the MIT License.
|
5
5
|
*/
|
6
|
-
|
7
|
-
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
function k(e,t,n,o){return new(n||(n=Promise))((function(a,i){function r(e){try{u(o.next(e))}catch(e){i(e)}}function s(e){try{u(o.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?a(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,s)}u((o=o.apply(e,t||[])).next())}))}!function(e){e[e.Integration=0]="Integration",e[e.Separate=1]="Separate"}(m||(m={}));const I=y.default.tmpdir(),w=h.default.join(I,".revue_cache"),T=m.Integration,_=process.env.HYEXT_BUILD_ENV||"dev",O=h.default.resolve(__dirname,"../static"),E=h.default.join(O,"template");var U;!function(e){e.miniProgram="miniProgram",e.miniProgramPlugin="miniProgramPlugin",e.miniGame="miniGame",e.miniGamePlugin="miniGamePlugin"}(U||(U={}));const $=v.default.gray("·");var C=(e=>{e=` ${e}`;return{log(...t){const n=i.format.apply(i.format,t);console.log(v.default.white(e),$,n)},fatal(...t){t[0]instanceof Error&&(t[0]=t[0].message.trim());const n=i.format.apply(i.format,t);console.error(v.default.red(e),$,n),process.exit(1)},success(...t){const n=i.format.apply(i.format,t);console.log(v.default.green(e),$,n)}}})("REVUE");const M="project.config.json";function F(e,t){g.default.copyFileSync(h.default.join(e,M),h.default.join(t,M))}function N(){g.default.existsSync(w)||g.default.mkdirSync(w)}function q(e,t,o){return k(this,void 0,void 0,(function*(){const a="prod"===e,i=a?{minify:!0,autoPrefixWXSS:!0,minifyWXSS:!0}:{};N(),yield n.compilerManager.init({projectPath:t,outputPath:o,cachePath:w,compileSettings:i});const r=a?"compile":"compileDev";yield n.compilerManager[r](),F(t,o)}))}function D(e,t,o){return k(this,void 0,void 0,(function*(){N(),yield n.compilerManager.init({projectPath:t,outputPath:o,cachePath:w,compileSettings:{cocos:!0,minify:"prod"===e}});const a="dev"===e?"compileDev":"compile";yield n.compilerManager[a](),F(t,o)}))}const B=Date.now(),V="production"!==process.env.HYEXT_BUILD_ENV?"//test-hd.huya.com/h5/hyext-sentry-setup-script/test/sentry-setup.js":`//a.msstatic.com/huya/hd/h5/hyext-sentry-setup-script/sentry-setup.js?hash=${B}`;function R(e,t,n){const o=g.default.readFileSync(e).toString();g.default.outputFileSync(t,function(e,t,n){return j.default.compile(e,{noEscape:!0})(t,n)}(o,n))}j.default.registerHelper("toJSON",(function(e){return new j.default.SafeString(JSON.stringify(e))}));const z={context:{deviceOrientation:"portrait"},hooks:{onMergedMainPackge:new u.SyncHook(["IOnMergedMainPackge"]),onSrartBefore:new u.SyncHook(["IOnSrartBefore"])}};class G{apply(e){e.hooks.onMergedMainPackge.tap("InjectWebviewUrlParamsPlugin",(t=>{const{compileType:n,mainPath:o}=t,a=n===U.miniGame;if(a){const t=g.default.readJsonSync(h.default.join(o,"game.json"));"string"==typeof t.deviceOrientation&&t.deviceOrientation.includes("landscape")&&(e.context.deviceOrientation="landscape")}e.context.webviewUrlParams={isLandscape:0,disablePopGesture:1,hideStatusBar:a?1:0,hideBar:1,bounces:0,hideloading:1}}))}}function L(){const e=z.context.webviewUrlParams;return e?(t=e,Object.keys(t).reduce(((e,n)=>e+`&${n}=${encodeURIComponent(t[n])}`),"")):"";var t}const J={test:"//test-extsdk.msstatic.com",prod:"//extsdk-msstatic.cdn.huya.com"};function H(e,t){const o=h.default.join(e,"package"),a=function(e){const t=h.default.join(e,"packageConfig.json");return g.default.readJSONSync(t)}(o),i=a.findIndex((e=>{return(t=e).name===n.pkgFileType.MainPkg&&"."===t.root;var t}));if(-1===i)throw new Error("无法找到主包构建信息");const r=a[i];a.splice(i,1);const s=a;return s.length>0&&function(e,t,n,o){const a=h.default.join(e,t.name);n.forEach((t=>{const n=h.default.join(e,t.name),i=h.default.join(n,t.root),r=h.default.join(a,t.root);o&&o(n,a,t),g.default.moveSync(i,r,{overwrite:!0}),g.default.removeSync(h.default.join(e,t.name))}))}(o,r,s,t),{mainPakConf:r,packagePath:o}}function W(e,t){const n=require.resolve(t);let o=h.default.join(n,"../");"dist"===h.default.basename(o)?g.default.copySync(o,e):(o=h.default.resolve(o,"../"),o=h.default.join(o,"dist"),g.default.existsSync(o)?g.default.copySync(o,e):C.log(`Builder can't resolve ${t} entry from ${n}`))}function X(e){const{builderConfig:t,mainPakConf:n,extUuid:o}=e;return t.supportExtTypes.map((e=>{const a=`index_${e}.html`;return{extType:e,entryPath:"package/"+n.name+"/"+a,sdkUrl:(i={extType:e,extUuid:o,hostId:t.hostId,isTestEnv:t.isTestEnv},`${i.isTestEnv?J.test:J.prod}/sdk/${i.extType}/${i.hostId}/${i.extUuid||0}/sdk.js`),entryFilename:a};var i}))}function K(e){!function(e){const{releasePath:t,mainPath:n,entrys:o,debug:a,dev:i,extInfo:r}=e,s=h.default.join(O,"template"),u=T===m.Integration?h.default.relative(n,t):"",c=[{input:h.default.join(s,"game-frame.hbs"),output:h.default.join(n,"game-frame.html"),data:{sourcePathPrefix:u}}];i&&c.push({input:h.default.join(s,"remote-debugger.hbs"),output:h.default.join(n,"remote-debugger.html"),data:{extInfo:r,paramsStr:L()}});const l=o.map((e=>({input:h.default.join(s,"minigame-page-manager.hbs"),output:h.default.join(n,e.entryFilename),data:{sourcePathPrefix:u,hyextSDKUrl:e.sdkUrl,debug:a,sentryScript:i?void 0:V,buildEnv:_,extInfo:Object.assign(Object.assign({},r),{envVersion:i?"develop":"release",extType:e.extType}),deviceOrientation:z.context.deviceOrientation}})));l.concat(c).forEach((e=>{R(e.input,e.output,e.data)}))}(e),function(e){const t=r.sync("**/**.wasm",{cwd:e,ignore:Y,nodir:!0,absolute:!1});t.length&&console.log("transform wasm to base64 files: \n",t),t.forEach((t=>{const n=h.default.join(e,t),o=g.default.readFileSync(n).toString("base64");g.default.outputFileSync(n+".txt",o)}))}(e.mainPath)}const Y=["node_modules/**/*","**/node_modules/**","**/.git/**",".git/**/*","**/.svn/**",".svn/**/*",".DS_Store","**/.DS_Store"];function A(e,t,n){const o=n.name+".js",a=n.name+".js.map",i=h.default.join(e,o),r=h.default.join(e,a);g.default.existsSync(i)&&g.default.outputFileSync(h.default.join(t,o),g.default.readFileSync(i)),g.default.existsSync(r)&&g.default.outputFileSync(h.default.join(t,a),g.default.readFileSync(r))}function Q(e){!function(e){const{packagePath:t,releasePath:n,mainPath:o,entrys:a,debug:i,dev:r,extInfo:s}=e,u=function(e){const t=h.default.join(e,"packageExtConfig.json");return g.default.readJSONSync(t)}(t),c=T===m.Integration?h.default.relative(o,n):"",l=JSON.stringify(u),d=[{input:h.default.join(E,"service.hbs"),output:h.default.join(o,"service.html"),data:{sourcePathPrefix:c}}];r&&d.push({input:h.default.join(E,"remote-debugger.hbs"),output:h.default.join(o,"remote-debugger.html"),data:{extInfo:s,paramsStr:L()}});a.map((e=>({input:h.default.join(E,"miniapp-page-manager.hbs"),output:h.default.join(o,e.entryFilename),data:{sourcePathPrefix:c,packageExtConfig:l,hyextSDKUrl:e.sdkUrl,debug:i,buildEnv:_,sentryScript:V,extInfo:Object.assign(Object.assign({},s),{envVersion:r?"develop":"release",version:"",extType:e.extType})}}))).concat(d).forEach((e=>{R(e.input,e.output,e.data)}))}(e)}function Z(e,t,n){const o={packagePath:"",mainPath:"",releasePath:t,entrys:[],extInfo:n.extInfo,debug:n.debug,dev:n.dev},a=a=>{let i;return C.log("正在合并分包..."),a||function(e){const t=h.default.join(O,"framework");if(T===m.Integration){g.default.copySync(t,h.default.join(e,"framework"));const n=h.default.join(e,"sdk");g.default.mkdirSync(n),W(n,"@revues/web-sdk-core"),W(n,"@revues/web-frame"),W(n,"@revues/hyext-adapter")}}(t),"game"==e.compileType?(i=function(e,t){const n=t.builderConfig,{mainPakConf:o,packagePath:a}=H(e),i=h.default.join(a,o.name),r=X({builderConfig:n,mainPakConf:o,extUuid:t.extInfo.extUuid});return z.hooks.onMergedMainPackge.call({mainConf:o,mainPath:i,compileType:U.miniGame}),{packagePath:a,mainPath:i,entrys:r,mainPublicPath:"package/"+o.name}}(t,n),!a&&K(Object.assign(Object.assign({},o),i))):(i=function(e,t){const n=t.builderConfig,{mainPakConf:o,packagePath:a}=H(e,A),i=h.default.join(a,o.name),r=X({builderConfig:n,mainPakConf:o,extUuid:t.extInfo.extUuid});return z.hooks.onMergedMainPackge.call({mainConf:o,mainPath:i,compileType:U.miniProgram}),{entrys:r,mainPublicPath:"package/"+o.name,mainPath:i,packagePath:a}}(t,n),!a&&Q(Object.assign(Object.assign({},o),i))),C.success("合并分包完成"),i};return Object.assign(Object.assign({},a(!1)),{retry:a})}class ee{apply(e){e.hooks.onSrartBefore.tap("RemoveUnlessDIrPlugin",(e=>{const{inputPath:t}=e,n=h.default.join(t,"release"),o=h.default.join(t,"dist");te(n),te(o)}))}}function te(e){g.default.existsSync(e)&&g.default.removeSync(e)}var ne={cert:g.default.readFileSync(h.default.join(O,"./certs/cert.pem")),key:g.default.readFileSync(h.default.join(O,"./certs/key.pem")),passphrase:""};function oe(e){return k(this,void 0,void 0,(function*(){try{const t=yield b.default.get(e,{responseType:"arraybuffer"}),n=Buffer.from(t.data),o=function(e){var t;const n=e.split("?")[0],o=n.split("/"),[a,i]=null===(t=o[o.length-1])||void 0===t?void 0:t.split(".");if(null==i||""==i)throw new Error(`url:${e}格式错误,无法获取文件信息`);return{filename:a,ext:i}}(e);return`data:image/${o.ext};base64,${n.toString("base64")}`}catch(t){throw new Error(`urlToBase64 failed, url is "${e}", error msg is ${t.message}`)}}))}function ae(e,t){return k(this,void 0,void 0,(function*(){const{baseURI:n,entrys:o,outputPath:a}=t,i=h.default.join(a,"build-result"),r={},s=L(),u=o.map((e=>{const t={type:"HTML",content:{pages:[{path:ie(e,s)}],baseURI:n}};return r[e.extType]=t,{type:e.extType,buildResult:{[e.extType]:t}}}));if("development"===e){const e=u.map((e=>g.default.outputFile(h.default.join(i,e.type+".json"),JSON.stringify(e.buildResult,null,2))));yield Promise.all(e)}return r}))}function ie(e,t){const n=e.extType;let o=e.entryPath;return n.endsWith("_h5")&&(o+="?__module_busi__=kiwi-ExtSDK"+t),o}const re=e=>{var t;const n=(()=>{const e=y.default.networkInterfaces(),t=S.default.flatten(S.default.values(e));return S.default.filter((e=>/(ipv)?4/gi.test(e.family)&&!/^127\./.test(e.address)),t)})();return n&&n.length>1&&(C.log(`检测到本机有多个 ip 地址:\n- ${n.map((e=>e.address)).join("\n- ")}`),C.log("请在 project.config.json 的 host 中指定正确的 ip"),process.exit(1)),n&&n.length<=0&&(C.log("未能找到本机 ip 地址, 本地开发 app 侧将无法加载小程序"),process.exit(1)),null===(t=n[0])||void 0===t?void 0:t.address},se=new Set(["app_inner_h5","web_video_com","app_panel_h5","zs_anchor_panel_h5","pc_anchor_panel","pc_panel"]);function ue(e,t){const n=Object.assign({},t);return function(e){let t=[];e&&0!==e.length?e.forEach((e=>{se.has(e)||t.push(e)})):C.fatal("请在project.config.json相应地方填写supportExtTypes."),t.length>0&&C.fatal(`未支持的小程序类型:${t.join("|")}.`)}(t.supportExtTypes),function(e){null==e.hostId&&(e.hostId="huyaext")}(n),"development"===e&&function(e){e.https=!0,null==e.host&&(e.host=re()||""),null==e.port&&(e.port=18080)}(n),n}function ce(e){return`${e.https?"https":"http"}://${e.host}:${e.port}/`}function le(e){return"game"===e.compileType?"miniGame":"miniProgram"}const de=new class{constructor(){var e;e=z,(new G).apply(e),(new ee).apply(e)}build(e){return k(this,void 0,void 0,(function*(){const{inputPath:t,outputPath:n,publicPath:o,projectConfig:a,config:i,extUuid:r,extName:s,extVersion:u,extVersionId:c,extLogo:l}=e,d=ue("production",i);g.default.existsSync(n)&&g.default.removeSync(n),yield g.default.copy(t,n,{overwrite:!0});const{entrys:p}=Z(a,n,{builderConfig:d,extInfo:{projectType:le(a),extUuid:r,extName:s,extVersion:u,extVersionId:c,extLogo:yield oe(l)}});return yield ae("production",{entrys:p,baseURI:o,outputPath:n})}))}start(e){var t;return k(this,void 0,void 0,(function*(){const{debug:o,inputPath:a,projectConfig:i,outputPath:r,config:s}=e;z.hooks.onSrartBefore.call({inputPath:a});const u=ue("development",s),c=function(e){const t=e.appId||e.appid;return null==t||""===t?C.fatal("请填写正确的appid"):t.length>10&&C.fatal("appid错误,请登录 https://ext.huya.com/ 在您的小程序概要中查看小程序ID"),t}(i),l=(d=i).projectname||d.projectName||"小程序";var d;const p={extUuid:c,extName:l,projectType:le(i),extVersion:void 0,extVersionId:void 0,extLogo:void 0};let f=e=>{};const m=(g=`${l}-${c}`,h.default.join(I,".revues-projects",g));var g;"game"==i.compileType?yield function(e,t,o){return k(this,void 0,void 0,(function*(){yield D("dev",e,t),n.compilerManager.watch({graphId:"game"},((a,i)=>k(this,void 0,void 0,(function*(){C.log("detected change:",i),C.log("recompile..."),n.compilerManager.destroy(),yield n.compilerManager.init({projectPath:e,outputPath:t,cachePath:w,compileSettings:{cocos:!0}}),yield n.compilerManager.compileDev(!0),o&&o()}))))}))}(a,m,(()=>{f(!0)})):yield function(e,t,o){return k(this,void 0,void 0,(function*(){yield q("dev",e,t),n.compilerManager.watch({graphId:"miniprogram"},((e,t)=>k(this,void 0,void 0,(function*(){yield n.compilerManager.compileSingleCode({type:e,filePath:t,graphId:"miniprogram"}),o&&o()}))))}))}(a,m,(()=>{f(!0)}));const{entrys:y,mainPublicPath:v,retry:j}=Z(i,m,{builderConfig:u,extInfo:p,debug:o,dev:!0});return f=j,C.log("启动 live server 服务..."),C.success("本地访问地址:",ce(u)+(null===(t=y[0])||void 0===t?void 0:t.entryPath)),C.success("扫码预览地址:",ce(u)+v+"/remote-debugger.html"),function(e){var t={port:e.port,host:e.host,root:e.root,open:!1,ignore:e.ignore,file:"index.html",wait:1e3,mount:e.mount,logLevel:1,https:ne};x.default.start(t)}(Object.assign(Object.assign({},u),{root:m,ignore:"node_modules"})),yield ae("development",{entrys:y,baseURI:ce(u),outputPath:r})}))}release(e){return k(this,void 0,void 0,(function*(){const{contextPath:t,releasePath:n,projectConfig:o}=e;g.default.existsSync(n)&&g.default.removeSync(n),C.log("开始打包");const a=o.projectName||o.projectname||"project",i=h.default.join(n,a);"game"==o.compileType?yield D("prod",t,i):yield q("prod",t,i);const r=h.default.join(n,a);var s;yield(s=r,new Promise(((e,t)=>{const n=g.default.createWriteStream(`${s}.zip`),o=P.default("zip",{zlib:{level:9}});n.on("close",(()=>{const t=o.pointer();e({name:`${h.default.basename(s)}.zip`,size:t})})),o.on("warning",(e=>{if("ENOENT"!==e.code)throw e})),o.on("error",(e=>{throw t(e),e})),o.pipe(n),o.directory(`${s}`,!1),o.finalize()}))),C.success("打包成功,zip包地址:"+r)}))}config(){}providedProjectConfig(){}clearCache(){try{g.default.existsSync(w)&&g.default.removeSync(w),C.success("项目缓存清除成功~")}catch(e){C.success("项目缓存清除失败 \n"+e.message)}}};module.exports=de,exports.default=de;
|
6
|
+
'use strict';
|
7
|
+
|
8
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
9
|
+
|
10
|
+
var fs = require('fs-extra');
|
11
|
+
var path = require('path');
|
12
|
+
var codeCompiler = require('@revues/code-compiler');
|
13
|
+
var os = require('os');
|
14
|
+
var chalk = require('chalk');
|
15
|
+
var util = require('util');
|
16
|
+
var download = require('download');
|
17
|
+
var glob = require('glob');
|
18
|
+
var handlebars = require('handlebars');
|
19
|
+
var tapable = require('tapable');
|
20
|
+
var liveServer = require('live-server');
|
21
|
+
var archiver = require('archiver');
|
22
|
+
var axios = require('axios');
|
23
|
+
var R = require('ramda');
|
24
|
+
|
25
|
+
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
26
|
+
|
27
|
+
var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
|
28
|
+
var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
|
29
|
+
var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
|
30
|
+
var chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
|
31
|
+
var download__default = /*#__PURE__*/_interopDefaultLegacy(download);
|
32
|
+
var handlebars__default = /*#__PURE__*/_interopDefaultLegacy(handlebars);
|
33
|
+
var liveServer__default = /*#__PURE__*/_interopDefaultLegacy(liveServer);
|
34
|
+
var archiver__default = /*#__PURE__*/_interopDefaultLegacy(archiver);
|
35
|
+
var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
|
36
|
+
var R__default = /*#__PURE__*/_interopDefaultLegacy(R);
|
37
|
+
|
38
|
+
/*! *****************************************************************************
|
39
|
+
Copyright (c) Microsoft Corporation.
|
40
|
+
|
41
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
42
|
+
purpose with or without fee is hereby granted.
|
43
|
+
|
44
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
45
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
46
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
47
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
48
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
49
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
50
|
+
PERFORMANCE OF THIS SOFTWARE.
|
51
|
+
***************************************************************************** */
|
52
|
+
|
53
|
+
function __awaiter(thisArg, _arguments, P, generator) {
|
54
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
55
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
56
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
57
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
58
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
59
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
60
|
+
});
|
61
|
+
}
|
62
|
+
|
63
|
+
var EDeployMode;
|
64
|
+
(function (EDeployMode) {
|
65
|
+
EDeployMode[EDeployMode["Integration"] = 0] = "Integration";
|
66
|
+
EDeployMode[EDeployMode["Separate"] = 1] = "Separate";
|
67
|
+
})(EDeployMode || (EDeployMode = {}));
|
68
|
+
|
69
|
+
const tempDir = os__default["default"].tmpdir();
|
70
|
+
const cacheDir = path__default["default"].join(tempDir, '.revue_cache'); // 项目缓存
|
71
|
+
const projectCacheDir = path__default["default"].join(tempDir, '.revues-projects'); // 项目缓存
|
72
|
+
const PluginRootDir = "__plugin__";
|
73
|
+
const pluginCacheDir = path__default["default"].join(projectCacheDir, PluginRootDir);
|
74
|
+
const PluginDownloadUrl = 'https://hd.huya.com/h5/static-source/alex/wx-plugin';
|
75
|
+
// 根据环境变量判断 要不要把运行框架代码留在项目内 还是 CDN
|
76
|
+
const deployMode = EDeployMode.Integration;
|
77
|
+
const buildEnv = process.env.HYEXT_BUILD_ENV || 'dev'; // 'production' | 'test' | 'dev'
|
78
|
+
const staticPath = path__default["default"].resolve(__dirname, '../static' );
|
79
|
+
const templatePath = path__default["default"].join(staticPath, 'template');
|
80
|
+
var COMPILE_TYPE;
|
81
|
+
(function (COMPILE_TYPE) {
|
82
|
+
COMPILE_TYPE["miniProgram"] = "miniProgram";
|
83
|
+
COMPILE_TYPE["miniProgramPlugin"] = "miniProgramPlugin";
|
84
|
+
COMPILE_TYPE["miniGame"] = "miniGame";
|
85
|
+
COMPILE_TYPE["miniGamePlugin"] = "miniGamePlugin";
|
86
|
+
})(COMPILE_TYPE || (COMPILE_TYPE = {}));
|
87
|
+
|
88
|
+
const sep = chalk__default["default"].gray('·');
|
89
|
+
const createLogger = (prefix) => {
|
90
|
+
prefix = ` ${prefix}`;
|
91
|
+
const logger = {
|
92
|
+
log(...args) {
|
93
|
+
const msg = util.format.apply(util.format, args);
|
94
|
+
console.log(chalk__default["default"].white(prefix), sep, msg);
|
95
|
+
},
|
96
|
+
fatal(...args) {
|
97
|
+
if (args[0] instanceof Error)
|
98
|
+
args[0] = args[0].message.trim();
|
99
|
+
const msg = util.format.apply(util.format, args);
|
100
|
+
console.error(chalk__default["default"].red(prefix), sep, msg);
|
101
|
+
process.exit(1);
|
102
|
+
},
|
103
|
+
success(...args) {
|
104
|
+
const msg = util.format.apply(util.format, args);
|
105
|
+
console.log(chalk__default["default"].green(prefix), sep, msg);
|
106
|
+
}
|
107
|
+
};
|
108
|
+
return logger;
|
109
|
+
};
|
110
|
+
var logger = createLogger('REVUE');
|
111
|
+
|
112
|
+
const filename = 'project.config.json';
|
113
|
+
function copyProjectConfigJSON(srcDir, destDir) {
|
114
|
+
fs__default["default"].copyFileSync(path__default["default"].join(srcDir, filename), path__default["default"].join(destDir, filename));
|
115
|
+
}
|
116
|
+
|
117
|
+
function initCacheDir() {
|
118
|
+
if (fs__default["default"].existsSync(cacheDir))
|
119
|
+
return;
|
120
|
+
fs__default["default"].mkdirSync(cacheDir);
|
121
|
+
}
|
122
|
+
|
123
|
+
var PluginStatus;
|
124
|
+
(function (PluginStatus) {
|
125
|
+
PluginStatus[PluginStatus["Fail"] = -1] = "Fail";
|
126
|
+
PluginStatus[PluginStatus["None"] = 0] = "None";
|
127
|
+
PluginStatus[PluginStatus["OK"] = 1] = "OK"; // 可用
|
128
|
+
})(PluginStatus || (PluginStatus = {}));
|
129
|
+
function getPluginDownloadUrl(provider, version) {
|
130
|
+
return `${PluginDownloadUrl}/${provider}-${version}.zip`;
|
131
|
+
}
|
132
|
+
function updatePluginStatus(item, status) {
|
133
|
+
item.status = status;
|
134
|
+
}
|
135
|
+
function resolveConfigFile(projectPath) {
|
136
|
+
return __awaiter(this, void 0, void 0, function* () {
|
137
|
+
const files = ['app', 'game', 'plugin'];
|
138
|
+
for (let i = 0; i < files.length; i++) {
|
139
|
+
const filePath = path__default["default"].join(projectPath, `${files[i]}.json`);
|
140
|
+
if (yield fs__default["default"].exists(filePath)) {
|
141
|
+
return {
|
142
|
+
data: yield fs__default["default"].readJson(filePath),
|
143
|
+
fileType: files[i]
|
144
|
+
};
|
145
|
+
}
|
146
|
+
}
|
147
|
+
// throw new Error(`can't found ${files.map((item) => `${item}.json`).join('|')}`)
|
148
|
+
return null;
|
149
|
+
});
|
150
|
+
}
|
151
|
+
function tryLoadPlugins(projectPath) {
|
152
|
+
return __awaiter(this, void 0, void 0, function* () {
|
153
|
+
const info = yield resolveConfigFile(projectPath);
|
154
|
+
if (info != null) {
|
155
|
+
const { data, fileType } = info;
|
156
|
+
if (fileType === 'game') {
|
157
|
+
return yield loadPlugins(projectPath, pluginCacheDir, data);
|
158
|
+
}
|
159
|
+
else {
|
160
|
+
const mainPakPluginResult = yield loadPlugins(projectPath, pluginCacheDir, data);
|
161
|
+
if (data.subpackages && data.subpackages.length > 0) {
|
162
|
+
const subPakPluginConfig = yield loadSubPakPlugins(data, projectPath);
|
163
|
+
if (subPakPluginConfig.length > 0) {
|
164
|
+
return {
|
165
|
+
plugins: [...mainPakPluginResult.plugins, ...subPakPluginConfig]
|
166
|
+
};
|
167
|
+
}
|
168
|
+
}
|
169
|
+
return mainPakPluginResult;
|
170
|
+
}
|
171
|
+
}
|
172
|
+
return {
|
173
|
+
plugins: []
|
174
|
+
};
|
175
|
+
});
|
176
|
+
}
|
177
|
+
function loadSubPakPlugins(config, projectPath) {
|
178
|
+
return __awaiter(this, void 0, void 0, function* () {
|
179
|
+
let subPakPluginConfig = [];
|
180
|
+
for (let i = 0; i < config.subpackages.length; i++) {
|
181
|
+
const subPkgConfig = config.subpackages[i];
|
182
|
+
if (subPkgConfig.export != null) {
|
183
|
+
subPkgConfig.export = subPkgConfig.rootDir + '/' + subPkgConfig.export;
|
184
|
+
}
|
185
|
+
const res = yield loadPlugins(projectPath, pluginCacheDir, subPkgConfig);
|
186
|
+
subPakPluginConfig = subPakPluginConfig.concat(res.plugins);
|
187
|
+
}
|
188
|
+
return subPakPluginConfig;
|
189
|
+
});
|
190
|
+
}
|
191
|
+
function loadPlugins(projectPath, pluginOutputPath, config) {
|
192
|
+
return __awaiter(this, void 0, void 0, function* () {
|
193
|
+
const pluginDir = pluginOutputPath;
|
194
|
+
const pluginConfig = config.gamePlugins || config.plugins;
|
195
|
+
if (pluginConfig != null) {
|
196
|
+
const queue = Object.keys(pluginConfig).map(key => {
|
197
|
+
const conf = pluginConfig[key];
|
198
|
+
return resolvePluginConfig(pluginDir, key, conf);
|
199
|
+
});
|
200
|
+
if (queue.length > 0) {
|
201
|
+
yield fs__default["default"].ensureDir(pluginDir);
|
202
|
+
yield downloadPluginBatch(queue);
|
203
|
+
return yield processPluginQueue(queue, projectPath);
|
204
|
+
}
|
205
|
+
}
|
206
|
+
return {
|
207
|
+
plugins: []
|
208
|
+
};
|
209
|
+
});
|
210
|
+
}
|
211
|
+
function processPluginQueue(queue, projectPath) {
|
212
|
+
return __awaiter(this, void 0, void 0, function* () {
|
213
|
+
let successQueue = queue.filter(item => item.status === PluginStatus.OK);
|
214
|
+
const failQueue = queue.filter(item => item.status === PluginStatus.Fail);
|
215
|
+
if (failQueue.length > 0) {
|
216
|
+
const localQueue = tryGetLocalPluginQueue(failQueue, projectPath);
|
217
|
+
if (localQueue.length > 0) {
|
218
|
+
successQueue = successQueue.concat(localQueue);
|
219
|
+
}
|
220
|
+
}
|
221
|
+
return {
|
222
|
+
plugins: injectPluginJson(successQueue)
|
223
|
+
};
|
224
|
+
});
|
225
|
+
}
|
226
|
+
function injectPluginJson(queue) {
|
227
|
+
return queue.map(item => {
|
228
|
+
const root = item.localDir || item.releasePath;
|
229
|
+
const json = fs__default["default"].readJSONSync(path__default["default"].join(root, 'plugin.json'));
|
230
|
+
item.json = json;
|
231
|
+
return item;
|
232
|
+
});
|
233
|
+
}
|
234
|
+
function tryGetLocalPluginQueue(queue, projectPath) {
|
235
|
+
return queue
|
236
|
+
.filter(item => item.path != null)
|
237
|
+
.map(item => {
|
238
|
+
item.localDir = resolveLocalPluginDirPath(projectPath, item);
|
239
|
+
logPlugin('use local plugin <projectRoot>/' + item.path, item);
|
240
|
+
updatePluginStatus(item, PluginStatus.OK);
|
241
|
+
return item;
|
242
|
+
});
|
243
|
+
}
|
244
|
+
function resolveLocalPluginDirPath(projectPath, item) {
|
245
|
+
return path__default["default"].join(projectPath, item.path);
|
246
|
+
}
|
247
|
+
function downloadPluginBatch(queue) {
|
248
|
+
return __awaiter(this, void 0, void 0, function* () {
|
249
|
+
const job = queue.map(item => downloadPlugin(item));
|
250
|
+
yield Promise.all(job);
|
251
|
+
});
|
252
|
+
}
|
253
|
+
function logPlugin(action, item) {
|
254
|
+
logger.success(`${action} provider:` + item.provider + ', version:' + item.version);
|
255
|
+
}
|
256
|
+
function downloadPlugin(item) {
|
257
|
+
return __awaiter(this, void 0, void 0, function* () {
|
258
|
+
if (!(yield fs__default["default"].exists(item.releasePath))) {
|
259
|
+
try {
|
260
|
+
yield download__default["default"](item.request, item.releasePath, { extract: true });
|
261
|
+
updatePluginStatus(item, PluginStatus.OK);
|
262
|
+
logPlugin('load success', item);
|
263
|
+
}
|
264
|
+
catch (error) {
|
265
|
+
updatePluginStatus(item, PluginStatus.Fail);
|
266
|
+
logPlugin('load fail: ' + error.message + '\n', item);
|
267
|
+
}
|
268
|
+
}
|
269
|
+
else {
|
270
|
+
updatePluginStatus(item, PluginStatus.OK);
|
271
|
+
logPlugin('reuse', item);
|
272
|
+
}
|
273
|
+
});
|
274
|
+
}
|
275
|
+
function resolvePluginConfig(pluginDir, key, props) {
|
276
|
+
const dir = path__default["default"].join(pluginDir, props.provider, props.version);
|
277
|
+
const resolvedConfig = Object.assign(Object.assign({}, props), { key, id: props.provider, releasePath: path__default["default"].join(dir, props.provider), dir: dir, status: PluginStatus.None });
|
278
|
+
resolvedConfig.request = getPluginDownloadUrl(props.provider, props.version);
|
279
|
+
return resolvedConfig;
|
280
|
+
}
|
281
|
+
|
282
|
+
function compile(mode, projectPath, outputPath) {
|
283
|
+
return __awaiter(this, void 0, void 0, function* () {
|
284
|
+
const isProd = mode === 'prod';
|
285
|
+
const compileSettings = isProd ? {
|
286
|
+
minify: true,
|
287
|
+
autoPrefixWXSS: true,
|
288
|
+
minifyWXSS: true,
|
289
|
+
es6: true
|
290
|
+
} : { es6: true };
|
291
|
+
const { plugins, } = yield tryLoadPlugins(projectPath);
|
292
|
+
initCacheDir();
|
293
|
+
yield codeCompiler.compilerManager.init({
|
294
|
+
projectPath,
|
295
|
+
outputPath,
|
296
|
+
cachePath: cacheDir,
|
297
|
+
compileSettings,
|
298
|
+
plugins
|
299
|
+
});
|
300
|
+
const action = isProd ? 'compile' : 'compileDev';
|
301
|
+
yield codeCompiler.compilerManager[action]();
|
302
|
+
copyProjectConfigJSON(projectPath, outputPath);
|
303
|
+
});
|
304
|
+
}
|
305
|
+
function compileDevPluginForProd(projectPath, outputPath) {
|
306
|
+
return __awaiter(this, void 0, void 0, function* () {
|
307
|
+
const compileSettings = {
|
308
|
+
minify: true,
|
309
|
+
autoPrefixWXSS: true,
|
310
|
+
minifyWXSS: true,
|
311
|
+
};
|
312
|
+
initCacheDir();
|
313
|
+
yield codeCompiler.compilerManager.init({
|
314
|
+
projectPath,
|
315
|
+
outputPath,
|
316
|
+
cachePath: cacheDir,
|
317
|
+
compileSettings,
|
318
|
+
});
|
319
|
+
yield codeCompiler.compilerManager.compileDevPlugin({ outputPath, remove: true });
|
320
|
+
});
|
321
|
+
}
|
322
|
+
function compileGame(mode, projectPath, outputPath) {
|
323
|
+
return __awaiter(this, void 0, void 0, function* () {
|
324
|
+
initCacheDir();
|
325
|
+
const { plugins } = yield tryLoadPlugins(projectPath);
|
326
|
+
const initOptions = {
|
327
|
+
projectPath,
|
328
|
+
outputPath,
|
329
|
+
cachePath: cacheDir,
|
330
|
+
plugins,
|
331
|
+
compileSettings: {
|
332
|
+
cocos: true,
|
333
|
+
minify: mode === 'prod'
|
334
|
+
}
|
335
|
+
};
|
336
|
+
yield codeCompiler.compilerManager.init(Object.assign({}, initOptions));
|
337
|
+
const action = mode === 'dev' ? 'compileDev' : 'compile';
|
338
|
+
yield codeCompiler.compilerManager[action]();
|
339
|
+
copyProjectConfigJSON(projectPath, outputPath);
|
340
|
+
return initOptions;
|
341
|
+
});
|
342
|
+
}
|
343
|
+
function watchGame(opts) {
|
344
|
+
return __awaiter(this, void 0, void 0, function* () {
|
345
|
+
const { projectPath, outputPath, cb } = opts;
|
346
|
+
const initedOpts = yield compileGame('dev', projectPath, outputPath);
|
347
|
+
codeCompiler.compilerManager.watch({ graphId: 'game', }, (type, filePath) => __awaiter(this, void 0, void 0, function* () {
|
348
|
+
logger.log('detected change:', filePath);
|
349
|
+
logger.log('recompile...');
|
350
|
+
codeCompiler.compilerManager.destroy();
|
351
|
+
yield codeCompiler.compilerManager.init(Object.assign({}, initedOpts));
|
352
|
+
yield codeCompiler.compilerManager.compileDev(true);
|
353
|
+
cb && cb();
|
354
|
+
}));
|
355
|
+
});
|
356
|
+
}
|
357
|
+
function watchMiniProgram(opts) {
|
358
|
+
return __awaiter(this, void 0, void 0, function* () {
|
359
|
+
const { projectPath, outputPath, cb } = opts;
|
360
|
+
yield compile('dev', projectPath, outputPath);
|
361
|
+
codeCompiler.compilerManager.watch({ graphId: 'miniprogram' }, (type, filePath) => __awaiter(this, void 0, void 0, function* () {
|
362
|
+
yield codeCompiler.compilerManager.compileSingleCode({
|
363
|
+
type,
|
364
|
+
filePath,
|
365
|
+
graphId: 'miniprogram'
|
366
|
+
});
|
367
|
+
cb && cb();
|
368
|
+
}));
|
369
|
+
});
|
370
|
+
}
|
371
|
+
function watchDevPlugin(opts) {
|
372
|
+
return __awaiter(this, void 0, void 0, function* () {
|
373
|
+
const { projectPath, outputPath, cb } = opts;
|
374
|
+
yield compile('dev', projectPath, outputPath);
|
375
|
+
// 开发插件时,需要监听 miniprogramRoot 和 pluginRoot
|
376
|
+
codeCompiler.compilerManager.watch({ graphId: 'miniprogram' }, (type, filePath) => __awaiter(this, void 0, void 0, function* () {
|
377
|
+
yield codeCompiler.compilerManager.compileSingleCode({
|
378
|
+
type,
|
379
|
+
filePath,
|
380
|
+
graphId: 'miniprogram'
|
381
|
+
});
|
382
|
+
cb && cb();
|
383
|
+
}));
|
384
|
+
codeCompiler.compilerManager.watch({ graphId: 'plugin' }, (type, filePath) => __awaiter(this, void 0, void 0, function* () {
|
385
|
+
yield codeCompiler.compilerManager.compileSingleCode({
|
386
|
+
type,
|
387
|
+
filePath,
|
388
|
+
graphId: 'plugin'
|
389
|
+
});
|
390
|
+
cb && cb();
|
391
|
+
}));
|
392
|
+
});
|
393
|
+
}
|
394
|
+
const watchHandlerMapByCompileType = {
|
395
|
+
plugin: watchDevPlugin,
|
396
|
+
game: watchGame,
|
397
|
+
miniprogram: watchMiniProgram
|
398
|
+
};
|
399
|
+
function watch(opts) {
|
400
|
+
return __awaiter(this, void 0, void 0, function* () {
|
401
|
+
const { projectConfig } = opts;
|
402
|
+
// @ts-ignore
|
403
|
+
const handler = watchHandlerMapByCompileType[projectConfig.compileType];
|
404
|
+
if (handler != null) {
|
405
|
+
yield handler(opts);
|
406
|
+
}
|
407
|
+
else {
|
408
|
+
throw new Error('Unsupported compileType: ' + String(projectConfig.compileType));
|
409
|
+
}
|
410
|
+
});
|
411
|
+
}
|
412
|
+
function packNpm(opts) {
|
413
|
+
return __awaiter(this, void 0, void 0, function* () {
|
414
|
+
initCacheDir();
|
415
|
+
const reporter = opts.reporter || ((stats) => {
|
416
|
+
console.log('pack reporter', stats);
|
417
|
+
});
|
418
|
+
const ignore = opts.ignore || [];
|
419
|
+
const initOptions = {
|
420
|
+
projectPath: opts.projectPath,
|
421
|
+
outputPath: '/mock',
|
422
|
+
cachePath: cacheDir
|
423
|
+
};
|
424
|
+
yield codeCompiler.compilerManager.init(Object.assign({}, initOptions));
|
425
|
+
yield codeCompiler.compilerManager.packNpm({
|
426
|
+
reporter,
|
427
|
+
ignore
|
428
|
+
});
|
429
|
+
});
|
430
|
+
}
|
431
|
+
|
432
|
+
const hash = Date.now();
|
433
|
+
const sentryScriptUrlOnProd = '//a.msstatic.com/huya/hd/h5/hyext-sentry-setup-script/sentry-setup.js';
|
434
|
+
const sentryScriptUrlOnTest = '//test-hd.huya.com/h5/hyext-sentry-setup-script/test/sentry-setup.js';
|
435
|
+
const sentryScriptUrl = process.env.HYEXT_BUILD_ENV !== 'production'
|
436
|
+
? sentryScriptUrlOnTest
|
437
|
+
: sentryScriptUrlOnProd + `?hash=${hash}`;
|
438
|
+
|
439
|
+
handlebars__default["default"].registerHelper('toJSON', function (object) {
|
440
|
+
return new handlebars__default["default"].SafeString(JSON.stringify(object));
|
441
|
+
});
|
442
|
+
function render(content, data, opts) {
|
443
|
+
const temp = handlebars__default["default"].compile(content, {
|
444
|
+
noEscape: true
|
445
|
+
});
|
446
|
+
return temp(data, opts);
|
447
|
+
}
|
448
|
+
function renderTemplate(input, output, data) {
|
449
|
+
const content = fs__default["default"]
|
450
|
+
.readFileSync(input)
|
451
|
+
.toString();
|
452
|
+
fs__default["default"].outputFileSync(output, render(content, data));
|
453
|
+
}
|
454
|
+
|
455
|
+
function objectToParamsStr(obj) {
|
456
|
+
return Object.keys(obj).reduce((str, key) => {
|
457
|
+
// @ts-ignore
|
458
|
+
str += `&${key}=${encodeURIComponent(obj[key])}`;
|
459
|
+
return str;
|
460
|
+
}, '');
|
461
|
+
}
|
462
|
+
|
463
|
+
const PluginDriver = {
|
464
|
+
context: { deviceOrientation: 'portrait', },
|
465
|
+
hooks: {
|
466
|
+
onMergedMainPackge: new tapable.SyncHook(['IOnMergedMainPackge']),
|
467
|
+
onSrartBefore: new tapable.SyncHook(['IOnSrartBefore']),
|
468
|
+
}
|
469
|
+
};
|
470
|
+
|
471
|
+
class InjectWebviewUrlParamsPlugin {
|
472
|
+
apply(pluginDriver) {
|
473
|
+
pluginDriver.hooks.onMergedMainPackge.tap('InjectWebviewUrlParamsPlugin', opts => {
|
474
|
+
const { compileType, mainPath } = opts;
|
475
|
+
const isGame = compileType === COMPILE_TYPE.miniGame;
|
476
|
+
if (isGame) {
|
477
|
+
const gameJson = fs__default["default"].readJsonSync(path__default["default"].join(mainPath, 'game.json'));
|
478
|
+
if (typeof gameJson.deviceOrientation === 'string' &&
|
479
|
+
gameJson.deviceOrientation.includes('landscape')) {
|
480
|
+
pluginDriver.context.deviceOrientation = 'landscape';
|
481
|
+
}
|
482
|
+
}
|
483
|
+
pluginDriver.context.webviewUrlParams = {
|
484
|
+
isLandscape: 0,
|
485
|
+
disablePopGesture: 1,
|
486
|
+
hideStatusBar: isGame ? 1 : 0,
|
487
|
+
hideBar: 1,
|
488
|
+
bounces: 0,
|
489
|
+
hideloading: 1
|
490
|
+
};
|
491
|
+
});
|
492
|
+
}
|
493
|
+
}
|
494
|
+
function makeWebviewUrlParamsStr() {
|
495
|
+
const params = PluginDriver.context.webviewUrlParams;
|
496
|
+
return params ? objectToParamsStr(params) : '';
|
497
|
+
}
|
498
|
+
|
499
|
+
const HOST = {
|
500
|
+
test: '//test-extsdk.msstatic.com',
|
501
|
+
prod: '//extsdk-msstatic.cdn.huya.com'
|
502
|
+
};
|
503
|
+
// $1是动态的extType
|
504
|
+
function getSDKUrlTemplate(opts) {
|
505
|
+
return `${opts.isTestEnv ? HOST.test : HOST.prod}/sdk/${opts.extType}/${opts.hostId}/${opts.extUuid || 0}/sdk.js`;
|
506
|
+
}
|
507
|
+
|
508
|
+
function isMainPackage(config) {
|
509
|
+
return config.name === codeCompiler.pkgFileType.MainPkg && config.root === '.';
|
510
|
+
}
|
511
|
+
function getPackageConfig(basePath) {
|
512
|
+
const filePath = path__default["default"].join(basePath, 'packageConfig.json');
|
513
|
+
return fs__default["default"].readJSONSync(filePath);
|
514
|
+
}
|
515
|
+
function getPackageExtConfig(basePath) {
|
516
|
+
const filePath = path__default["default"].join(basePath, 'packageExtConfig.json');
|
517
|
+
return fs__default["default"].readJSONSync(filePath);
|
518
|
+
}
|
519
|
+
function mergeSubPackagesToMainPackage(packagePath, main, subList, onMoveBefore) {
|
520
|
+
const mainPath = path__default["default"].join(packagePath, main.name);
|
521
|
+
subList.forEach(conf => {
|
522
|
+
const subRoot = path__default["default"].join(packagePath, conf.name);
|
523
|
+
const subPath = path__default["default"].join(subRoot, conf.root);
|
524
|
+
const dest = path__default["default"].join(mainPath, conf.root);
|
525
|
+
onMoveBefore && onMoveBefore(subRoot, mainPath, conf);
|
526
|
+
fs__default["default"].moveSync(subPath, dest, { overwrite: true });
|
527
|
+
fs__default["default"].removeSync(path__default["default"].join(packagePath, conf.name));
|
528
|
+
});
|
529
|
+
}
|
530
|
+
|
531
|
+
function mergeMainPackage(releasePath, onMoveBefore) {
|
532
|
+
const packagePath = path__default["default"].join(releasePath, 'package');
|
533
|
+
const packageConfig = getPackageConfig(packagePath);
|
534
|
+
const targetIndex = packageConfig.findIndex(item => {
|
535
|
+
return isMainPackage(item);
|
536
|
+
});
|
537
|
+
if (targetIndex === -1) {
|
538
|
+
throw new Error('无法找到主包构建信息');
|
539
|
+
}
|
540
|
+
const mainPakConf = packageConfig[targetIndex];
|
541
|
+
packageConfig.splice(targetIndex, 1);
|
542
|
+
const subPakConfList = packageConfig;
|
543
|
+
if (subPakConfList.length > 0) {
|
544
|
+
// 合并分包资源到主包
|
545
|
+
mergeSubPackagesToMainPackage(packagePath, mainPakConf, subPakConfList, onMoveBefore);
|
546
|
+
}
|
547
|
+
return {
|
548
|
+
mainPakConf,
|
549
|
+
packagePath
|
550
|
+
};
|
551
|
+
}
|
552
|
+
function injectNpm(dest, packageName) {
|
553
|
+
const nodePath = require.resolve(packageName);
|
554
|
+
let dirPath = path__default["default"].join(nodePath, '../');
|
555
|
+
let dirname = path__default["default"].basename(dirPath);
|
556
|
+
if (dirname === 'dist') {
|
557
|
+
fs__default["default"].copySync(dirPath, dest);
|
558
|
+
}
|
559
|
+
else {
|
560
|
+
// 开发模式 可能是src/index
|
561
|
+
dirPath = path__default["default"].resolve(dirPath, '../');
|
562
|
+
dirPath = path__default["default"].join(dirPath, 'dist');
|
563
|
+
if (fs__default["default"].existsSync(dirPath)) {
|
564
|
+
fs__default["default"].copySync(dirPath, dest);
|
565
|
+
}
|
566
|
+
else {
|
567
|
+
logger.log(`Builder can't resolve ${packageName} entry from ${nodePath}`);
|
568
|
+
}
|
569
|
+
}
|
570
|
+
}
|
571
|
+
function genEntrys(props) {
|
572
|
+
const { builderConfig, mainPakConf, extUuid } = props;
|
573
|
+
return builderConfig.supportExtTypes.map(extType => {
|
574
|
+
const entryFilename = `index_${extType}.html`;
|
575
|
+
return {
|
576
|
+
extType,
|
577
|
+
entryPath: 'package/' + mainPakConf.name + '/' + entryFilename,
|
578
|
+
sdkUrl: getSDKUrlTemplate({
|
579
|
+
extType,
|
580
|
+
extUuid,
|
581
|
+
hostId: builderConfig.hostId,
|
582
|
+
isTestEnv: builderConfig.isTestEnv
|
583
|
+
}),
|
584
|
+
entryFilename
|
585
|
+
};
|
586
|
+
});
|
587
|
+
}
|
588
|
+
|
589
|
+
// TODO: 改异步
|
590
|
+
// 合并游戏分包到主包
|
591
|
+
function mergeGamePackage(releasePath, opts) {
|
592
|
+
const builderConfig = opts.builderConfig;
|
593
|
+
const { mainPakConf, packagePath } = mergeMainPackage(releasePath);
|
594
|
+
const mainPath = path__default["default"].join(packagePath, mainPakConf.name);
|
595
|
+
const entrys = genEntrys({
|
596
|
+
builderConfig,
|
597
|
+
mainPakConf,
|
598
|
+
extUuid: opts.extInfo.extUuid
|
599
|
+
});
|
600
|
+
PluginDriver.hooks.onMergedMainPackge.call({
|
601
|
+
mainConf: mainPakConf,
|
602
|
+
mainPath,
|
603
|
+
compileType: COMPILE_TYPE.miniGame
|
604
|
+
});
|
605
|
+
return {
|
606
|
+
packagePath,
|
607
|
+
mainPath,
|
608
|
+
entrys,
|
609
|
+
mainPublicPath: 'package/' + mainPakConf.name
|
610
|
+
};
|
611
|
+
}
|
612
|
+
function renderGame(opts) {
|
613
|
+
// 渲染模版
|
614
|
+
renderGameTemplate(opts);
|
615
|
+
// wasn文件 会被 cocos 同步请求,由于二进制文件同步请求失败 所以改为 base64 文本
|
616
|
+
transformWasnFileToBase64File(opts.mainPath);
|
617
|
+
}
|
618
|
+
// mark 热更新 整个函数不会重渲染。
|
619
|
+
function renderGameTemplate(opts) {
|
620
|
+
const { releasePath, mainPath, entrys, debug, dev, extInfo, builderConfig } = opts;
|
621
|
+
const templatePath = path__default["default"].join(staticPath, 'template');
|
622
|
+
const sourcePathPrefix = deployMode === EDeployMode.Integration
|
623
|
+
? path__default["default"].relative(mainPath, releasePath)
|
624
|
+
: '';
|
625
|
+
const renderConfigList = [
|
626
|
+
{
|
627
|
+
input: path__default["default"].join(templatePath, 'game-frame.hbs'),
|
628
|
+
output: path__default["default"].join(mainPath, 'game-frame.html'),
|
629
|
+
data: {
|
630
|
+
sourcePathPrefix
|
631
|
+
}
|
632
|
+
}
|
633
|
+
];
|
634
|
+
if (dev) {
|
635
|
+
renderConfigList.push({
|
636
|
+
input: path__default["default"].join(templatePath, 'remote-debugger.hbs'),
|
637
|
+
output: path__default["default"].join(mainPath, 'remote-debugger.html'),
|
638
|
+
data: {
|
639
|
+
extInfo,
|
640
|
+
paramsStr: makeWebviewUrlParamsStr()
|
641
|
+
}
|
642
|
+
});
|
643
|
+
}
|
644
|
+
const entryRenderConfList = entrys.map(info => {
|
645
|
+
return {
|
646
|
+
input: path__default["default"].join(templatePath, 'minigame-page-manager.hbs'),
|
647
|
+
output: path__default["default"].join(mainPath, info.entryFilename),
|
648
|
+
data: {
|
649
|
+
sourcePathPrefix,
|
650
|
+
hyextSDKUrl: info.sdkUrl,
|
651
|
+
debug,
|
652
|
+
sentryScript: dev ? undefined : sentryScriptUrl,
|
653
|
+
buildEnv: buildEnv,
|
654
|
+
extInfo: Object.assign(Object.assign({}, extInfo), { envVersion: dev ? 'develop' : 'release', extType: info.extType }),
|
655
|
+
deviceOrientation: PluginDriver.context.deviceOrientation,
|
656
|
+
builderConfig: builderConfig
|
657
|
+
}
|
658
|
+
};
|
659
|
+
});
|
660
|
+
entryRenderConfList.concat(renderConfigList).forEach(config => {
|
661
|
+
renderTemplate(config.input, config.output, config.data);
|
662
|
+
});
|
663
|
+
}
|
664
|
+
const ignorePath = [
|
665
|
+
'node_modules/**/*',
|
666
|
+
'**/node_modules/**',
|
667
|
+
'**/.git/**',
|
668
|
+
'.git/**/*',
|
669
|
+
'**/.svn/**',
|
670
|
+
'.svn/**/*',
|
671
|
+
'.DS_Store',
|
672
|
+
'**/.DS_Store'
|
673
|
+
];
|
674
|
+
function transformWasnFileToBase64File(mainPath) {
|
675
|
+
const files = glob.sync('**/**.wasm', {
|
676
|
+
cwd: mainPath,
|
677
|
+
ignore: ignorePath,
|
678
|
+
nodir: true,
|
679
|
+
absolute: false
|
680
|
+
});
|
681
|
+
files.length && console.log('transform wasm to base64 files: \n', files);
|
682
|
+
files.forEach(file => {
|
683
|
+
const abs = path__default["default"].join(mainPath, file);
|
684
|
+
const text = fs__default["default"].readFileSync(abs).toString('base64');
|
685
|
+
fs__default["default"].outputFileSync(abs + '.txt', text);
|
686
|
+
});
|
687
|
+
}
|
688
|
+
|
689
|
+
function copyServiceBundleToDest(subRoot, mainRoot, config) {
|
690
|
+
const bundleName = config.name + '.js';
|
691
|
+
const bundleMapName = config.name + '.js.map';
|
692
|
+
const bundlePath = path__default["default"].join(subRoot, bundleName);
|
693
|
+
const bundleMapPath = path__default["default"].join(subRoot, bundleMapName);
|
694
|
+
if (fs__default["default"].existsSync(bundlePath)) {
|
695
|
+
fs__default["default"].outputFileSync(path__default["default"].join(mainRoot, bundleName), fs__default["default"].readFileSync(bundlePath));
|
696
|
+
}
|
697
|
+
if (fs__default["default"].existsSync(bundleMapPath)) {
|
698
|
+
fs__default["default"].outputFileSync(path__default["default"].join(mainRoot, bundleMapName), fs__default["default"].readFileSync(bundleMapPath));
|
699
|
+
}
|
700
|
+
}
|
701
|
+
function mergeMiniprogramPackage(releasePath, opts) {
|
702
|
+
const builderConfig = opts.builderConfig;
|
703
|
+
const { mainPakConf, packagePath } = mergeMainPackage(releasePath, copyServiceBundleToDest);
|
704
|
+
const mainPath = path__default["default"].join(packagePath, mainPakConf.name);
|
705
|
+
const entrys = genEntrys({
|
706
|
+
builderConfig,
|
707
|
+
mainPakConf,
|
708
|
+
extUuid: opts.extInfo.extUuid
|
709
|
+
});
|
710
|
+
PluginDriver.hooks.onMergedMainPackge.call({
|
711
|
+
mainConf: mainPakConf,
|
712
|
+
mainPath,
|
713
|
+
compileType: COMPILE_TYPE.miniProgram
|
714
|
+
});
|
715
|
+
return { entrys, mainPublicPath: 'package/' + mainPakConf.name, mainPath, packagePath };
|
716
|
+
}
|
717
|
+
function renderMiniProgram(opts) {
|
718
|
+
renderMiniprogramTemplate(opts);
|
719
|
+
}
|
720
|
+
function renderMiniprogramTemplate(opts) {
|
721
|
+
const { packagePath, releasePath, mainPath, entrys, debug, dev, extInfo, builderConfig } = opts;
|
722
|
+
const extConfig = getPackageExtConfig(packagePath);
|
723
|
+
const sourcePathPrefix = deployMode === EDeployMode.Integration
|
724
|
+
? path__default["default"].relative(mainPath, releasePath)
|
725
|
+
: '';
|
726
|
+
const packageExtConfigStr = JSON.stringify(extConfig);
|
727
|
+
const renderConfigList = [
|
728
|
+
{
|
729
|
+
input: path__default["default"].join(templatePath, 'service.hbs'),
|
730
|
+
output: path__default["default"].join(mainPath, 'service.html'),
|
731
|
+
data: {
|
732
|
+
sourcePathPrefix
|
733
|
+
}
|
734
|
+
}
|
735
|
+
];
|
736
|
+
if (dev) {
|
737
|
+
renderConfigList.push({
|
738
|
+
input: path__default["default"].join(templatePath, 'remote-debugger.hbs'),
|
739
|
+
output: path__default["default"].join(mainPath, 'remote-debugger.html'),
|
740
|
+
data: {
|
741
|
+
extInfo,
|
742
|
+
paramsStr: makeWebviewUrlParamsStr()
|
743
|
+
}
|
744
|
+
});
|
745
|
+
}
|
746
|
+
const entryRenderConfList = entrys.map(info => {
|
747
|
+
return {
|
748
|
+
input: path__default["default"].join(templatePath, 'miniapp-page-manager.hbs'),
|
749
|
+
output: path__default["default"].join(mainPath, info.entryFilename),
|
750
|
+
data: {
|
751
|
+
sourcePathPrefix,
|
752
|
+
packageExtConfig: packageExtConfigStr,
|
753
|
+
hyextSDKUrl: info.sdkUrl,
|
754
|
+
debug,
|
755
|
+
buildEnv: buildEnv,
|
756
|
+
// sentryScript: dev ? undefined : sentryScriptUrl,
|
757
|
+
sentryScript: sentryScriptUrl,
|
758
|
+
extInfo: Object.assign(Object.assign({}, extInfo), { envVersion: dev ? 'develop' : 'release', version: '', extType: info.extType }),
|
759
|
+
builderConfig
|
760
|
+
}
|
761
|
+
};
|
762
|
+
});
|
763
|
+
entryRenderConfList.concat(renderConfigList).forEach(config => {
|
764
|
+
renderTemplate(config.input, config.output, config.data);
|
765
|
+
});
|
766
|
+
}
|
767
|
+
|
768
|
+
function mergePackages(projectConfig, outputPath, opts) {
|
769
|
+
const baseRenderOpts = {
|
770
|
+
packagePath: '',
|
771
|
+
mainPath: '',
|
772
|
+
releasePath: outputPath,
|
773
|
+
entrys: [],
|
774
|
+
extInfo: opts.extInfo,
|
775
|
+
debug: opts.debug,
|
776
|
+
dev: opts.dev,
|
777
|
+
builderConfig: opts.builderConfig
|
778
|
+
};
|
779
|
+
const implement = (watch) => {
|
780
|
+
logger.log('正在合并分包...');
|
781
|
+
let mergeResult;
|
782
|
+
if (!watch) {
|
783
|
+
injectRuntimeLib(outputPath);
|
784
|
+
}
|
785
|
+
if (projectConfig.compileType == 'game') {
|
786
|
+
mergeResult = mergeGamePackage(outputPath, opts);
|
787
|
+
!watch && renderGame(Object.assign(Object.assign({}, baseRenderOpts), mergeResult));
|
788
|
+
}
|
789
|
+
else {
|
790
|
+
mergeResult = mergeMiniprogramPackage(outputPath, opts);
|
791
|
+
!watch && renderMiniProgram(Object.assign(Object.assign({}, baseRenderOpts), mergeResult));
|
792
|
+
}
|
793
|
+
logger.success('合并分包完成');
|
794
|
+
return mergeResult;
|
795
|
+
};
|
796
|
+
return Object.assign(Object.assign({}, implement(false)), { retry: implement });
|
797
|
+
}
|
798
|
+
function injectRuntimeLib(releasePath) {
|
799
|
+
const frameworkPath = path__default["default"].join(staticPath, 'framework');
|
800
|
+
// 安置本地框架文件
|
801
|
+
if (deployMode === EDeployMode.Integration) {
|
802
|
+
// 迁移运行框架
|
803
|
+
fs__default["default"].copySync(frameworkPath, path__default["default"].join(releasePath, 'framework'));
|
804
|
+
// 迁移SDK
|
805
|
+
const sdkPath = path__default["default"].join(releasePath, 'sdk');
|
806
|
+
fs__default["default"].mkdirSync(sdkPath);
|
807
|
+
injectNpm(sdkPath, '@revues/web-sdk-core');
|
808
|
+
injectNpm(sdkPath, '@revues/web-frame');
|
809
|
+
injectNpm(sdkPath, '@revues/hyext-adapter');
|
810
|
+
// TODO: 这段代码是测试 @revues/js-sdk 增加构建变量去决定执行
|
811
|
+
// injectNpm(sdkPath, '@revues/js-sdk')
|
812
|
+
}
|
813
|
+
}
|
814
|
+
|
815
|
+
class RemoveUnlessDirPlugin {
|
816
|
+
apply(pluginDriver) {
|
817
|
+
pluginDriver.hooks.onSrartBefore.tap('RemoveUnlessDIrPlugin', (opts) => {
|
818
|
+
const { inputPath } = opts;
|
819
|
+
const releasePath = path__default["default"].join(inputPath, 'release');
|
820
|
+
const distPath = path__default["default"].join(inputPath, 'dist');
|
821
|
+
remove(releasePath);
|
822
|
+
remove(distPath);
|
823
|
+
});
|
824
|
+
}
|
825
|
+
}
|
826
|
+
function remove(v) {
|
827
|
+
if (fs__default["default"].existsSync(v)) {
|
828
|
+
fs__default["default"].removeSync(v);
|
829
|
+
}
|
830
|
+
}
|
831
|
+
|
832
|
+
function initPlugins(pluginDriver) {
|
833
|
+
new InjectWebviewUrlParamsPlugin().apply(pluginDriver);
|
834
|
+
new RemoveUnlessDirPlugin().apply(pluginDriver);
|
835
|
+
}
|
836
|
+
|
837
|
+
var httpsConf = {
|
838
|
+
cert: fs__default["default"].readFileSync(path__default["default"].join(staticPath, "./certs/cert.pem")),
|
839
|
+
key: fs__default["default"].readFileSync(path__default["default"].join(staticPath, "./certs/key.pem")),
|
840
|
+
passphrase: ""
|
841
|
+
};
|
842
|
+
|
843
|
+
function startLiveServer(opts) {
|
844
|
+
var params = {
|
845
|
+
port: opts.port,
|
846
|
+
host: opts.host,
|
847
|
+
root: opts.root,
|
848
|
+
open: false,
|
849
|
+
ignore: opts.ignore,
|
850
|
+
file: "index.html",
|
851
|
+
wait: 1000,
|
852
|
+
mount: opts.mount,
|
853
|
+
logLevel: 1,
|
854
|
+
https: httpsConf
|
855
|
+
};
|
856
|
+
// @ts-expect-error
|
857
|
+
liveServer__default["default"].start(params);
|
858
|
+
}
|
859
|
+
|
860
|
+
function compress(output) {
|
861
|
+
return new Promise((resolve, reject) => {
|
862
|
+
const stream = fs__default["default"].createWriteStream(`${output}.zip`), archive = archiver__default["default"]('zip', { zlib: { level: 9 } });
|
863
|
+
stream.on('close', () => {
|
864
|
+
const size = archive.pointer();
|
865
|
+
resolve({ name: `${path__default["default"].basename(output)}.zip`, size });
|
866
|
+
}),
|
867
|
+
archive.on('warning', e => {
|
868
|
+
if ('ENOENT' !== e.code)
|
869
|
+
throw e;
|
870
|
+
}),
|
871
|
+
archive.on('error', e => {
|
872
|
+
reject(e);
|
873
|
+
throw e;
|
874
|
+
}),
|
875
|
+
archive.pipe(stream),
|
876
|
+
archive.directory(`${output}`, false),
|
877
|
+
archive.finalize();
|
878
|
+
});
|
879
|
+
}
|
880
|
+
|
881
|
+
function urlToBase64(url) {
|
882
|
+
return __awaiter(this, void 0, void 0, function* () {
|
883
|
+
try {
|
884
|
+
const res = yield axios__default["default"].get(url, { responseType: 'arraybuffer' });
|
885
|
+
const buffer = Buffer.from(res.data);
|
886
|
+
const info = getFileInfoByUrl(url);
|
887
|
+
return `data:image/${info.ext};base64,` + `${buffer.toString('base64')}`;
|
888
|
+
}
|
889
|
+
catch (e) {
|
890
|
+
throw new Error(`urlToBase64 failed, url is "${url}", error msg is ${e.message}`);
|
891
|
+
}
|
892
|
+
});
|
893
|
+
}
|
894
|
+
function getFileInfoByUrl(url) {
|
895
|
+
var _a;
|
896
|
+
const main = url.split('?')[0];
|
897
|
+
const arr = main.split('/');
|
898
|
+
const [filename, ext] = (_a = arr[arr.length - 1]) === null || _a === void 0 ? void 0 : _a.split('.');
|
899
|
+
if (ext == null || ext == '') {
|
900
|
+
throw new Error(`url:${url}格式错误,无法获取文件信息`);
|
901
|
+
}
|
902
|
+
return {
|
903
|
+
filename,
|
904
|
+
ext
|
905
|
+
};
|
906
|
+
}
|
907
|
+
|
908
|
+
// 36PX
|
909
|
+
function makeBuildResults(mode, opts) {
|
910
|
+
return __awaiter(this, void 0, void 0, function* () {
|
911
|
+
const { baseURI, entrys, outputPath } = opts;
|
912
|
+
const releasePath = path__default["default"].join(outputPath, 'build-result');
|
913
|
+
const buildResultMap = {};
|
914
|
+
const paramsStr = makeWebviewUrlParamsStr();
|
915
|
+
const buildResultList = entrys.map(info => {
|
916
|
+
const result = {
|
917
|
+
type: 'HTML',
|
918
|
+
content: {
|
919
|
+
pages: [
|
920
|
+
{
|
921
|
+
path: getPagePath(info, paramsStr)
|
922
|
+
}
|
923
|
+
],
|
924
|
+
baseURI
|
925
|
+
}
|
926
|
+
};
|
927
|
+
buildResultMap[info.extType] = result;
|
928
|
+
return {
|
929
|
+
type: info.extType,
|
930
|
+
buildResult: {
|
931
|
+
[info.extType]: result
|
932
|
+
}
|
933
|
+
};
|
934
|
+
});
|
935
|
+
if (mode === 'development') {
|
936
|
+
const fsTasks = buildResultList.map((buildResultInfo) => {
|
937
|
+
return fs__default["default"].outputFile(path__default["default"].join(releasePath, buildResultInfo.type + '.json'), JSON.stringify(buildResultInfo.buildResult, null, 2));
|
938
|
+
});
|
939
|
+
yield Promise.all(fsTasks);
|
940
|
+
}
|
941
|
+
return buildResultMap;
|
942
|
+
});
|
943
|
+
}
|
944
|
+
function getPagePath(entryInfo, extraParams) {
|
945
|
+
const extType = entryInfo.extType;
|
946
|
+
let entry = entryInfo.entryPath;
|
947
|
+
// 移动端需要补 __module_busi__
|
948
|
+
if (extType.endsWith('_h5')) {
|
949
|
+
entry += '?__module_busi__=kiwi-ExtSDK' + extraParams;
|
950
|
+
}
|
951
|
+
return entry;
|
952
|
+
}
|
953
|
+
|
954
|
+
const getIPAddress = () => {
|
955
|
+
const ifaces = os__default["default"].networkInterfaces();
|
956
|
+
const addresses = R__default["default"].flatten(R__default["default"].values(ifaces));
|
957
|
+
const address = R__default["default"].filter((iface) => /(ipv)?4/ig.test(iface.family) && !/^127\./.test(iface.address), addresses);
|
958
|
+
return address;
|
959
|
+
};
|
960
|
+
const getPublicIP = (config) => {
|
961
|
+
var _a;
|
962
|
+
const address = getIPAddress();
|
963
|
+
/*
|
964
|
+
* 有多个 ip 地址又没有在 config.host 中指定的话, 直接退出
|
965
|
+
*/
|
966
|
+
if (address && address.length > 1) {
|
967
|
+
logger.log(`检测到本机有多个 ip 地址:\n- ${address
|
968
|
+
.map((x) => x.address)
|
969
|
+
.join('\n- ')}`);
|
970
|
+
logger.log('请在 project.config.json 的 host 中指定正确的 ip');
|
971
|
+
process.exit(1);
|
972
|
+
}
|
973
|
+
if (address && address.length <= 0) {
|
974
|
+
logger.log('未能找到本机 ip 地址, 本地开发 app 侧将无法加载小程序');
|
975
|
+
process.exit(1);
|
976
|
+
}
|
977
|
+
return (_a = address[0]) === null || _a === void 0 ? void 0 : _a.address;
|
978
|
+
};
|
979
|
+
|
980
|
+
const supportedExtTypeSet = new Set([
|
981
|
+
"app_inner_h5",
|
982
|
+
'web_video_com',
|
983
|
+
'app_panel_h5',
|
984
|
+
'zs_anchor_panel_h5',
|
985
|
+
'pc_anchor_panel',
|
986
|
+
'pc_panel'
|
987
|
+
]);
|
988
|
+
function checkExtTypes(extTypes) {
|
989
|
+
let unsupportList = [];
|
990
|
+
if (!extTypes || extTypes.length === 0) {
|
991
|
+
logger.fatal('请在project.config.json相应地方填写supportExtTypes.');
|
992
|
+
}
|
993
|
+
else {
|
994
|
+
extTypes.forEach((item) => {
|
995
|
+
if (!supportedExtTypeSet.has(item)) {
|
996
|
+
unsupportList.push(item);
|
997
|
+
}
|
998
|
+
});
|
999
|
+
}
|
1000
|
+
if (unsupportList.length > 0) {
|
1001
|
+
logger.fatal(`未支持的小程序类型:${unsupportList.join('|')}.`);
|
1002
|
+
}
|
1003
|
+
}
|
1004
|
+
function processDevConfig(config) {
|
1005
|
+
// 强制开启
|
1006
|
+
config.https = true;
|
1007
|
+
if (config.host == null) {
|
1008
|
+
config.host = getPublicIP() || ''; // 用ip地址不用localshot
|
1009
|
+
}
|
1010
|
+
if (config.port == null) {
|
1011
|
+
config.port = 18080;
|
1012
|
+
}
|
1013
|
+
}
|
1014
|
+
function processGlobalConfig(config) {
|
1015
|
+
if (config.hostId == null) {
|
1016
|
+
config.hostId = 'huyaext';
|
1017
|
+
}
|
1018
|
+
}
|
1019
|
+
function processBuilderConfigJSON(mode, config) {
|
1020
|
+
const opts = Object.assign({}, config);
|
1021
|
+
checkExtTypes(config.supportExtTypes);
|
1022
|
+
processGlobalConfig(opts);
|
1023
|
+
if (mode === 'development') {
|
1024
|
+
processDevConfig(opts);
|
1025
|
+
}
|
1026
|
+
return opts;
|
1027
|
+
}
|
1028
|
+
function getDevBaseURI(config) {
|
1029
|
+
const protocol = config.https ? 'https' : 'http';
|
1030
|
+
return `${protocol}://${config.host}:${config.port}/`;
|
1031
|
+
}
|
1032
|
+
|
1033
|
+
function checkAppId(project) {
|
1034
|
+
const appId = project.appId || project.appid;
|
1035
|
+
if (appId == null || appId === '') {
|
1036
|
+
logger.fatal('请填写正确的appid');
|
1037
|
+
}
|
1038
|
+
else if (appId.length > 10) {
|
1039
|
+
logger.fatal('appid错误,请登录 https://ext.huya.com/ 在您的小程序概要中查看小程序ID');
|
1040
|
+
}
|
1041
|
+
return appId;
|
1042
|
+
}
|
1043
|
+
function checkProjectName(project) {
|
1044
|
+
return project.projectname || project.projectName || '小程序';
|
1045
|
+
}
|
1046
|
+
function getProjectType(project) {
|
1047
|
+
return project.compileType === 'game' ? 'miniGame' : 'miniProgram';
|
1048
|
+
}
|
1049
|
+
|
1050
|
+
function copyPluginAssetsToRoot(outputPath, projectConfig) {
|
1051
|
+
return __awaiter(this, void 0, void 0, function* () {
|
1052
|
+
const appid = checkAppId(projectConfig);
|
1053
|
+
const targetPath = path__default["default"].join(outputPath, PluginRootDir, appid);
|
1054
|
+
if (fs__default["default"].existsSync(targetPath)) {
|
1055
|
+
yield fs__default["default"].copy(targetPath, outputPath);
|
1056
|
+
fs__default["default"].removeSync(path__default["default"].join(outputPath, PluginRootDir));
|
1057
|
+
}
|
1058
|
+
});
|
1059
|
+
}
|
1060
|
+
function formatPluginZipName(zipPath, releasePath, projectConfig) {
|
1061
|
+
const newZipPath = path__default["default"].join(releasePath, `${checkAppId(projectConfig)}-${projectConfig.version || '1.0.0'}.zip`);
|
1062
|
+
if (fs__default["default"].existsSync(zipPath)) {
|
1063
|
+
fs__default["default"].renameSync(zipPath, newZipPath);
|
1064
|
+
return newZipPath;
|
1065
|
+
}
|
1066
|
+
return zipPath;
|
1067
|
+
}
|
1068
|
+
|
1069
|
+
function getTempProjectDir(projecName) {
|
1070
|
+
return path__default["default"].join(projectCacheDir, projecName);
|
1071
|
+
}
|
1072
|
+
class RevueBuilder {
|
1073
|
+
constructor() {
|
1074
|
+
// 单例 PluginDriver 更加灵活
|
1075
|
+
initPlugins(PluginDriver);
|
1076
|
+
}
|
1077
|
+
// 这里拿到打包好的代码 原样输出 + build result
|
1078
|
+
build(opts) {
|
1079
|
+
return __awaiter(this, void 0, void 0, function* () {
|
1080
|
+
const { inputPath, outputPath, publicPath, projectConfig, config, extUuid, extName, extVersion, extVersionId, extLogo } = opts;
|
1081
|
+
const processedConfig = processBuilderConfigJSON('production', config);
|
1082
|
+
fs__default["default"].existsSync(outputPath) && fs__default["default"].removeSync(outputPath);
|
1083
|
+
// 把 inputPath 的文件 迁移到 outputPath
|
1084
|
+
yield fs__default["default"].copy(inputPath, outputPath, { overwrite: true });
|
1085
|
+
const { entrys } = mergePackages(projectConfig, outputPath, {
|
1086
|
+
builderConfig: processedConfig,
|
1087
|
+
extInfo: {
|
1088
|
+
projectType: getProjectType(projectConfig),
|
1089
|
+
extUuid,
|
1090
|
+
extName,
|
1091
|
+
extVersion,
|
1092
|
+
extVersionId,
|
1093
|
+
extLogo: yield urlToBase64(extLogo)
|
1094
|
+
}
|
1095
|
+
});
|
1096
|
+
return yield makeBuildResults('production', {
|
1097
|
+
entrys: entrys,
|
1098
|
+
baseURI: publicPath,
|
1099
|
+
outputPath
|
1100
|
+
});
|
1101
|
+
});
|
1102
|
+
}
|
1103
|
+
start(opts) {
|
1104
|
+
var _a;
|
1105
|
+
return __awaiter(this, void 0, void 0, function* () {
|
1106
|
+
const { inputPath, projectConfig, outputPath: outputPath$1, config } = opts;
|
1107
|
+
PluginDriver.hooks.onSrartBefore.call({ inputPath });
|
1108
|
+
const debugWsc = !!projectConfig.debugWsc;
|
1109
|
+
const processedConfig = processBuilderConfigJSON('development', config);
|
1110
|
+
const appId = checkAppId(projectConfig);
|
1111
|
+
const projectName = checkProjectName(projectConfig);
|
1112
|
+
const extInfo = {
|
1113
|
+
extUuid: appId,
|
1114
|
+
extName: projectName,
|
1115
|
+
projectType: getProjectType(projectConfig),
|
1116
|
+
extVersion: undefined,
|
1117
|
+
extVersionId: undefined,
|
1118
|
+
extLogo: undefined
|
1119
|
+
};
|
1120
|
+
let retryRef = (watch) => { };
|
1121
|
+
const outputPath = getTempProjectDir(`${projectName}-${appId}`)
|
1122
|
+
;
|
1123
|
+
yield watch({
|
1124
|
+
projectConfig,
|
1125
|
+
projectPath: inputPath,
|
1126
|
+
outputPath,
|
1127
|
+
cb: () => {
|
1128
|
+
retryRef(true);
|
1129
|
+
}
|
1130
|
+
});
|
1131
|
+
const { entrys, mainPublicPath, retry } = mergePackages(projectConfig, outputPath, {
|
1132
|
+
builderConfig: processedConfig,
|
1133
|
+
extInfo,
|
1134
|
+
debug: debugWsc,
|
1135
|
+
dev: true
|
1136
|
+
});
|
1137
|
+
retryRef = retry;
|
1138
|
+
logger.log('启动 live server 服务...');
|
1139
|
+
logger.success('本地访问地址:', getDevBaseURI(processedConfig) + ((_a = entrys[0]) === null || _a === void 0 ? void 0 : _a.entryPath));
|
1140
|
+
logger.success('扫码预览地址:', getDevBaseURI(processedConfig) + mainPublicPath + '/remote-debugger.html');
|
1141
|
+
startLiveServer(Object.assign(Object.assign({}, processedConfig), { root: outputPath, ignore: 'node_modules' }));
|
1142
|
+
return yield makeBuildResults('development', {
|
1143
|
+
entrys,
|
1144
|
+
baseURI: getDevBaseURI(processedConfig),
|
1145
|
+
outputPath: outputPath$1
|
1146
|
+
});
|
1147
|
+
});
|
1148
|
+
}
|
1149
|
+
// 这里仅仅在 client 打包 小程序/小游戏
|
1150
|
+
release(opts) {
|
1151
|
+
return __awaiter(this, void 0, void 0, function* () {
|
1152
|
+
const { contextPath, releasePath, projectConfig, zip = true } = opts;
|
1153
|
+
if (fs__default["default"].existsSync(releasePath)) {
|
1154
|
+
fs__default["default"].removeSync(releasePath);
|
1155
|
+
}
|
1156
|
+
logger.log('开始打包');
|
1157
|
+
const projectName = projectConfig.projectName || projectConfig.projectname || 'project';
|
1158
|
+
const outputPath = path__default["default"].join(releasePath, projectName);
|
1159
|
+
const compileType = projectConfig.compileType;
|
1160
|
+
if (compileType == 'game') {
|
1161
|
+
yield compileGame('prod', contextPath, outputPath);
|
1162
|
+
}
|
1163
|
+
else if (compileType == 'plugin') {
|
1164
|
+
yield compileDevPluginForProd(contextPath, outputPath);
|
1165
|
+
}
|
1166
|
+
else {
|
1167
|
+
yield compile('prod', contextPath, outputPath);
|
1168
|
+
}
|
1169
|
+
if (compileType === 'plugin') {
|
1170
|
+
// 统一将插件构建产物放到文件夹根目录
|
1171
|
+
yield copyPluginAssetsToRoot(outputPath, projectConfig);
|
1172
|
+
}
|
1173
|
+
if (zip) {
|
1174
|
+
let zipPath = outputPath + '.zip';
|
1175
|
+
yield compress(outputPath);
|
1176
|
+
if (compileType === 'plugin') {
|
1177
|
+
zipPath = formatPluginZipName(zipPath, releasePath, projectConfig);
|
1178
|
+
}
|
1179
|
+
logger.success('打包成功,zip包地址:' + zipPath);
|
1180
|
+
}
|
1181
|
+
});
|
1182
|
+
}
|
1183
|
+
packNpm(opts) {
|
1184
|
+
return packNpm(opts);
|
1185
|
+
}
|
1186
|
+
config() { }
|
1187
|
+
providedProjectConfig() { }
|
1188
|
+
clearCache() {
|
1189
|
+
try {
|
1190
|
+
if (fs__default["default"].existsSync(cacheDir)) {
|
1191
|
+
fs__default["default"].removeSync(cacheDir);
|
1192
|
+
}
|
1193
|
+
logger.success('项目缓存清除成功~');
|
1194
|
+
if (fs__default["default"].existsSync(pluginCacheDir)) {
|
1195
|
+
fs__default["default"].removeSync(pluginCacheDir);
|
1196
|
+
}
|
1197
|
+
logger.success('插件缓存清除成功~');
|
1198
|
+
}
|
1199
|
+
catch (error) {
|
1200
|
+
logger.success('缓存清除失败 \n' + error.message);
|
1201
|
+
}
|
1202
|
+
}
|
1203
|
+
}
|
1204
|
+
const revueBuilder = new RevueBuilder();
|
1205
|
+
|
1206
|
+
module.exports = revueBuilder;
|
1207
|
+
|
1208
|
+
exports["default"] = revueBuilder;
|