@hyext/builder-revues 1.0.12 → 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 CHANGED
@@ -3,19 +3,1206 @@
3
3
  * (c) 2024-2024 Alex
4
4
  * Released under the MIT License.
5
5
  */
6
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("fs-extra"),t=require("path"),n=require("@revues/code-compiler"),i=require("os"),o=require("chalk"),a=require("util"),r=require("download"),u=require("glob"),s=require("handlebars"),c=require("tapable"),l=require("live-server"),d=require("archiver"),p=require("axios"),f=require("ramda");function g(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var m,h=g(e),y=g(t),v=g(i),j=g(o),P=g(r),x=g(s),b=g(l),S=g(d),k=g(p),w=g(f);
7
- /*! *****************************************************************************
8
- Copyright (c) Microsoft Corporation.
9
-
10
- Permission to use, copy, modify, and/or distribute this software for any
11
- purpose with or without fee is hereby granted.
12
-
13
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
- PERFORMANCE OF THIS SOFTWARE.
20
- ***************************************************************************** */
21
- function I(e,t,n,i){return new(n||(n=Promise))((function(o,a){function r(e){try{s(i.next(e))}catch(e){a(e)}}function u(e){try{s(i.throw(e))}catch(e){a(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,u)}s((i=i.apply(e,t||[])).next())}))}!function(e){e[e.Integration=0]="Integration",e[e.Separate=1]="Separate"}(m||(m={}));const O=v.default.tmpdir(),T=y.default.join(O,".revue_cache"),_=y.default.join(O,".revues-projects"),C="__plugin__",$=y.default.join(_,C),E="https://hd.huya.com/h5/static-source/alex/wx-plugin",M=m.Integration,U=process.env.HYEXT_BUILD_ENV||"dev",F=y.default.resolve(__dirname,"../static"),N=y.default.join(F,"template");var D;!function(e){e.miniProgram="miniProgram",e.miniProgramPlugin="miniProgramPlugin",e.miniGame="miniGame",e.miniGamePlugin="miniGamePlugin"}(D||(D={}));const q=j.default.gray("·");var z=(e=>{e=` ${e}`;return{log(...t){const n=a.format.apply(a.format,t);console.log(j.default.white(e),q,n)},fatal(...t){t[0]instanceof Error&&(t[0]=t[0].message.trim());const n=a.format.apply(a.format,t);console.error(j.default.red(e),q,n),process.exit(1)},success(...t){const n=a.format.apply(a.format,t);console.log(j.default.green(e),q,n)}}})("REVUE");const B="project.config.json";function V(e,t){h.default.copyFileSync(y.default.join(e,B),y.default.join(t,B))}function R(){h.default.existsSync(T)||h.default.mkdirSync(T)}var J;function K(e,t){e.status=t}function G(e){return I(this,void 0,void 0,(function*(){const t=yield function(e){return I(this,void 0,void 0,(function*(){const t=["app","game","plugin"];for(let n=0;n<t.length;n++){const i=y.default.join(e,`${t[n]}.json`);if(yield h.default.exists(i))return{data:yield h.default.readJson(i),fileType:t[n]}}return null}))}(e);if(null!=t){const{data:n,fileType:i}=t;if("game"===i)return yield L(e,$,n);{const t=yield L(e,$,n);if(n.subpackages&&n.subpackages.length>0){const i=yield function(e,t){return I(this,void 0,void 0,(function*(){let n=[];for(let i=0;i<e.subpackages.length;i++){const o=e.subpackages[i];null!=o.export&&(o.export=o.rootDir+"/"+o.export);const a=yield L(t,$,o);n=n.concat(a.plugins)}return n}))}(n,e);if(i.length>0)return{plugins:[...t.plugins,...i]}}return t}}return{plugins:[]}}))}function L(e,t,n){return I(this,void 0,void 0,(function*(){const i=t,o=n.gamePlugins||n.plugins;if(null!=o){const t=Object.keys(o).map((e=>{const t=o[e];return function(e,t,n){const i=y.default.join(e,n.provider,n.version),o=Object.assign(Object.assign({},n),{key:t,id:n.provider,releasePath:y.default.join(i,n.provider),dir:i,status:J.None});return o.request=function(e,t){return`${E}/${e}-${t}.zip`}(n.provider,n.version),o}(i,e,t)}));if(t.length>0)return yield h.default.ensureDir(i),yield function(e){return I(this,void 0,void 0,(function*(){const t=e.map((e=>function(e){return I(this,void 0,void 0,(function*(){if(yield h.default.exists(e.releasePath))K(e,J.OK),H("reuse",e);else try{yield P.default(e.request,e.releasePath,{extract:!0}),K(e,J.OK),H("load success",e)}catch(t){K(e,J.Fail),H("load fail: "+t.message+"\n",e)}}))}(e)));yield Promise.all(t)}))}(t),yield function(e,t){return I(this,void 0,void 0,(function*(){let n=e.filter((e=>e.status===J.OK));const i=e.filter((e=>e.status===J.Fail));if(i.length>0){const e=function(e,t){return e.filter((e=>null!=e.path)).map((e=>(e.localDir=function(e,t){return y.default.join(e,t.path)}(t,e),H("use local plugin <projectRoot>/"+e.path,e),K(e,J.OK),e)))}(i,t);e.length>0&&(n=n.concat(e))}return{plugins:W(n)}}))}(t,e)}return{plugins:[]}}))}function W(e){return e.map((e=>{const t=e.localDir||e.releasePath,n=h.default.readJSONSync(y.default.join(t,"plugin.json"));return e.json=n,e}))}function H(e,t){z.success(`${e} provider:`+t.provider+", version:"+t.version)}function X(e,t,i){return I(this,void 0,void 0,(function*(){const o="prod"===e,a=o?{minify:!0,autoPrefixWXSS:!0,minifyWXSS:!0}:{},{plugins:r}=yield G(t);R(),yield n.compilerManager.init({projectPath:t,outputPath:i,cachePath:T,compileSettings:a,plugins:r});const u=o?"compile":"compileDev";yield n.compilerManager[u](),V(t,i)}))}function Y(e,t,i){return I(this,void 0,void 0,(function*(){R();const{plugins:o}=yield G(t),a={projectPath:t,outputPath:i,cachePath:T,plugins:o,compileSettings:{cocos:!0,minify:"prod"===e}};yield n.compilerManager.init(Object.assign({},a));const r="dev"===e?"compileDev":"compile";return yield n.compilerManager[r](),V(t,i),a}))}!function(e){e[e.Fail=-1]="Fail",e[e.None=0]="None",e[e.OK=1]="OK"}(J||(J={}));const A={plugin:function(e){return I(this,void 0,void 0,(function*(){const{projectPath:t,outputPath:i,cb:o}=e;yield X("dev",t,i),n.compilerManager.watch({graphId:"miniprogram"},((e,t)=>I(this,void 0,void 0,(function*(){yield n.compilerManager.compileSingleCode({type:e,filePath:t,graphId:"miniprogram"}),o&&o()})))),n.compilerManager.watch({graphId:"plugin"},((e,t)=>I(this,void 0,void 0,(function*(){yield n.compilerManager.compileSingleCode({type:e,filePath:t,graphId:"plugin"}),o&&o()}))))}))},game:function(e){return I(this,void 0,void 0,(function*(){const{projectPath:t,outputPath:i,cb:o}=e,a=yield Y("dev",t,i);n.compilerManager.watch({graphId:"game"},((e,t)=>I(this,void 0,void 0,(function*(){z.log("detected change:",t),z.log("recompile..."),n.compilerManager.destroy(),yield n.compilerManager.init(Object.assign({},a)),yield n.compilerManager.compileDev(!0),o&&o()}))))}))},miniprogram:function(e){return I(this,void 0,void 0,(function*(){const{projectPath:t,outputPath:i,cb:o}=e;yield X("dev",t,i),n.compilerManager.watch({graphId:"miniprogram"},((e,t)=>I(this,void 0,void 0,(function*(){yield n.compilerManager.compileSingleCode({type:e,filePath:t,graphId:"miniprogram"}),o&&o()}))))}))}};const Q=Date.now(),Z="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=${Q}`;function ee(e,t,n){const i=h.default.readFileSync(e).toString();h.default.outputFileSync(t,function(e,t,n){return x.default.compile(e,{noEscape:!0})(t,n)}(i,n))}x.default.registerHelper("toJSON",(function(e){return new x.default.SafeString(JSON.stringify(e))}));const te={context:{deviceOrientation:"portrait"},hooks:{onMergedMainPackge:new c.SyncHook(["IOnMergedMainPackge"]),onSrartBefore:new c.SyncHook(["IOnSrartBefore"])}};class ne{apply(e){e.hooks.onMergedMainPackge.tap("InjectWebviewUrlParamsPlugin",(t=>{const{compileType:n,mainPath:i}=t,o=n===D.miniGame;if(o){const t=h.default.readJsonSync(y.default.join(i,"game.json"));"string"==typeof t.deviceOrientation&&t.deviceOrientation.includes("landscape")&&(e.context.deviceOrientation="landscape")}e.context.webviewUrlParams={isLandscape:0,disablePopGesture:1,hideStatusBar:o?1:0,hideBar:1,bounces:0,hideloading:1}}))}}function ie(){const e=te.context.webviewUrlParams;return e?(t=e,Object.keys(t).reduce(((e,n)=>e+`&${n}=${encodeURIComponent(t[n])}`),"")):"";var t}const oe={test:"//test-extsdk.msstatic.com",prod:"//extsdk-msstatic.cdn.huya.com"};function ae(e,t){const i=y.default.join(e,"package"),o=function(e){const t=y.default.join(e,"packageConfig.json");return h.default.readJSONSync(t)}(i),a=o.findIndex((e=>{return(t=e).name===n.pkgFileType.MainPkg&&"."===t.root;var t}));if(-1===a)throw new Error("无法找到主包构建信息");const r=o[a];o.splice(a,1);const u=o;return u.length>0&&function(e,t,n,i){const o=y.default.join(e,t.name);n.forEach((t=>{const n=y.default.join(e,t.name),a=y.default.join(n,t.root),r=y.default.join(o,t.root);i&&i(n,o,t),h.default.moveSync(a,r,{overwrite:!0}),h.default.removeSync(y.default.join(e,t.name))}))}(i,r,u,t),{mainPakConf:r,packagePath:i}}function re(e,t){const n=require.resolve(t);let i=y.default.join(n,"../");"dist"===y.default.basename(i)?h.default.copySync(i,e):(i=y.default.resolve(i,"../"),i=y.default.join(i,"dist"),h.default.existsSync(i)?h.default.copySync(i,e):z.log(`Builder can't resolve ${t} entry from ${n}`))}function ue(e){const{builderConfig:t,mainPakConf:n,extUuid:i}=e;return t.supportExtTypes.map((e=>{const o=`index_${e}.html`;return{extType:e,entryPath:"package/"+n.name+"/"+o,sdkUrl:(a={extType:e,extUuid:i,hostId:t.hostId,isTestEnv:t.isTestEnv},`${a.isTestEnv?oe.test:oe.prod}/sdk/${a.extType}/${a.hostId}/${a.extUuid||0}/sdk.js`),entryFilename:o};var a}))}function se(e){!function(e){const{releasePath:t,mainPath:n,entrys:i,debug:o,dev:a,extInfo:r,builderConfig:u}=e,s=y.default.join(F,"template"),c=M===m.Integration?y.default.relative(n,t):"",l=[{input:y.default.join(s,"game-frame.hbs"),output:y.default.join(n,"game-frame.html"),data:{sourcePathPrefix:c}}];a&&l.push({input:y.default.join(s,"remote-debugger.hbs"),output:y.default.join(n,"remote-debugger.html"),data:{extInfo:r,paramsStr:ie()}});const d=i.map((e=>({input:y.default.join(s,"minigame-page-manager.hbs"),output:y.default.join(n,e.entryFilename),data:{sourcePathPrefix:c,hyextSDKUrl:e.sdkUrl,debug:o,sentryScript:a?void 0:Z,buildEnv:U,extInfo:Object.assign(Object.assign({},r),{envVersion:a?"develop":"release",extType:e.extType}),deviceOrientation:te.context.deviceOrientation,builderConfig:u}})));d.concat(l).forEach((e=>{ee(e.input,e.output,e.data)}))}(e),function(e){const t=u.sync("**/**.wasm",{cwd:e,ignore:ce,nodir:!0,absolute:!1});t.length&&console.log("transform wasm to base64 files: \n",t),t.forEach((t=>{const n=y.default.join(e,t),i=h.default.readFileSync(n).toString("base64");h.default.outputFileSync(n+".txt",i)}))}(e.mainPath)}const ce=["node_modules/**/*","**/node_modules/**","**/.git/**",".git/**/*","**/.svn/**",".svn/**/*",".DS_Store","**/.DS_Store"];function le(e,t,n){const i=n.name+".js",o=n.name+".js.map",a=y.default.join(e,i),r=y.default.join(e,o);h.default.existsSync(a)&&h.default.outputFileSync(y.default.join(t,i),h.default.readFileSync(a)),h.default.existsSync(r)&&h.default.outputFileSync(y.default.join(t,o),h.default.readFileSync(r))}function de(e){!function(e){const{packagePath:t,releasePath:n,mainPath:i,entrys:o,debug:a,dev:r,extInfo:u,builderConfig:s}=e,c=function(e){const t=y.default.join(e,"packageExtConfig.json");return h.default.readJSONSync(t)}(t),l=M===m.Integration?y.default.relative(i,n):"",d=JSON.stringify(c),p=[{input:y.default.join(N,"service.hbs"),output:y.default.join(i,"service.html"),data:{sourcePathPrefix:l}}];r&&p.push({input:y.default.join(N,"remote-debugger.hbs"),output:y.default.join(i,"remote-debugger.html"),data:{extInfo:u,paramsStr:ie()}});o.map((e=>({input:y.default.join(N,"miniapp-page-manager.hbs"),output:y.default.join(i,e.entryFilename),data:{sourcePathPrefix:l,packageExtConfig:d,hyextSDKUrl:e.sdkUrl,debug:a,buildEnv:U,sentryScript:Z,extInfo:Object.assign(Object.assign({},u),{envVersion:r?"develop":"release",version:"",extType:e.extType}),builderConfig:s}}))).concat(p).forEach((e=>{ee(e.input,e.output,e.data)}))}(e)}function pe(e,t,n){const i={packagePath:"",mainPath:"",releasePath:t,entrys:[],extInfo:n.extInfo,debug:n.debug,dev:n.dev,builderConfig:n.builderConfig},o=o=>{let a;return z.log("正在合并分包..."),o||function(e){const t=y.default.join(F,"framework");if(M===m.Integration){h.default.copySync(t,y.default.join(e,"framework"));const n=y.default.join(e,"sdk");h.default.mkdirSync(n),re(n,"@revues/web-sdk-core"),re(n,"@revues/web-frame"),re(n,"@revues/hyext-adapter")}}(t),"game"==e.compileType?(a=function(e,t){const n=t.builderConfig,{mainPakConf:i,packagePath:o}=ae(e),a=y.default.join(o,i.name),r=ue({builderConfig:n,mainPakConf:i,extUuid:t.extInfo.extUuid});return te.hooks.onMergedMainPackge.call({mainConf:i,mainPath:a,compileType:D.miniGame}),{packagePath:o,mainPath:a,entrys:r,mainPublicPath:"package/"+i.name}}(t,n),!o&&se(Object.assign(Object.assign({},i),a))):(a=function(e,t){const n=t.builderConfig,{mainPakConf:i,packagePath:o}=ae(e,le),a=y.default.join(o,i.name),r=ue({builderConfig:n,mainPakConf:i,extUuid:t.extInfo.extUuid});return te.hooks.onMergedMainPackge.call({mainConf:i,mainPath:a,compileType:D.miniProgram}),{entrys:r,mainPublicPath:"package/"+i.name,mainPath:a,packagePath:o}}(t,n),!o&&de(Object.assign(Object.assign({},i),a))),z.success("合并分包完成"),a};return Object.assign(Object.assign({},o(!1)),{retry:o})}class fe{apply(e){e.hooks.onSrartBefore.tap("RemoveUnlessDIrPlugin",(e=>{const{inputPath:t}=e,n=y.default.join(t,"release"),i=y.default.join(t,"dist");ge(n),ge(i)}))}}function ge(e){h.default.existsSync(e)&&h.default.removeSync(e)}var me={cert:h.default.readFileSync(y.default.join(F,"./certs/cert.pem")),key:h.default.readFileSync(y.default.join(F,"./certs/key.pem")),passphrase:""};function he(e){return I(this,void 0,void 0,(function*(){try{const t=yield k.default.get(e,{responseType:"arraybuffer"}),n=Buffer.from(t.data),i=function(e){var t;const n=e.split("?")[0],i=n.split("/"),[o,a]=null===(t=i[i.length-1])||void 0===t?void 0:t.split(".");if(null==a||""==a)throw new Error(`url:${e}格式错误,无法获取文件信息`);return{filename:o,ext:a}}(e);return`data:image/${i.ext};base64,${n.toString("base64")}`}catch(t){throw new Error(`urlToBase64 failed, url is "${e}", error msg is ${t.message}`)}}))}function ye(e,t){return I(this,void 0,void 0,(function*(){const{baseURI:n,entrys:i,outputPath:o}=t,a=y.default.join(o,"build-result"),r={},u=ie(),s=i.map((e=>{const t={type:"HTML",content:{pages:[{path:ve(e,u)}],baseURI:n}};return r[e.extType]=t,{type:e.extType,buildResult:{[e.extType]:t}}}));if("development"===e){const e=s.map((e=>h.default.outputFile(y.default.join(a,e.type+".json"),JSON.stringify(e.buildResult,null,2))));yield Promise.all(e)}return r}))}function ve(e,t){const n=e.extType;let i=e.entryPath;return n.endsWith("_h5")&&(i+="?__module_busi__=kiwi-ExtSDK"+t),i}const je=e=>{var t;const n=(()=>{const e=v.default.networkInterfaces(),t=w.default.flatten(w.default.values(e));return w.default.filter((e=>/(ipv)?4/gi.test(e.family)&&!/^127\./.test(e.address)),t)})();return n&&n.length>1&&(z.log(`检测到本机有多个 ip 地址:\n- ${n.map((e=>e.address)).join("\n- ")}`),z.log("请在 project.config.json 的 host 中指定正确的 ip"),process.exit(1)),n&&n.length<=0&&(z.log("未能找到本机 ip 地址, 本地开发 app 侧将无法加载小程序"),process.exit(1)),null===(t=n[0])||void 0===t?void 0:t.address},Pe=new Set(["app_inner_h5","web_video_com","app_panel_h5","zs_anchor_panel_h5","pc_anchor_panel","pc_panel"]);function xe(e,t){const n=Object.assign({},t);return function(e){let t=[];e&&0!==e.length?e.forEach((e=>{Pe.has(e)||t.push(e)})):z.fatal("请在project.config.json相应地方填写supportExtTypes."),t.length>0&&z.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=je()||""),null==e.port&&(e.port=18080)}(n),n}function be(e){return`${e.https?"https":"http"}://${e.host}:${e.port}/`}function Se(e){const t=e.appId||e.appid;return null==t||""===t?z.fatal("请填写正确的appid"):t.length>10&&z.fatal("appid错误,请登录 https://ext.huya.com/ 在您的小程序概要中查看小程序ID"),t}function ke(e){return"game"===e.compileType?"miniGame":"miniProgram"}const we=new class{constructor(){var e;e=te,(new ne).apply(e),(new fe).apply(e)}build(e){return I(this,void 0,void 0,(function*(){const{inputPath:t,outputPath:n,publicPath:i,projectConfig:o,config:a,extUuid:r,extName:u,extVersion:s,extVersionId:c,extLogo:l}=e,d=xe("production",a);h.default.existsSync(n)&&h.default.removeSync(n),yield h.default.copy(t,n,{overwrite:!0});const{entrys:p}=pe(o,n,{builderConfig:d,extInfo:{projectType:ke(o),extUuid:r,extName:u,extVersion:s,extVersionId:c,extLogo:yield he(l)}});return yield ye("production",{entrys:p,baseURI:i,outputPath:n})}))}start(e){var t;return I(this,void 0,void 0,(function*(){const{debug:n,inputPath:i,projectConfig:o,outputPath:a,config:r}=e;te.hooks.onSrartBefore.call({inputPath:i});const u=xe("development",r),s=Se(o),c=(l=o).projectname||l.projectName||"小程序";var l;const d={extUuid:s,extName:c,projectType:ke(o),extVersion:void 0,extVersionId:void 0,extLogo:void 0};let p=e=>{};const f=(g=`${c}-${s}`,y.default.join(_,g));var g;yield function(e){return I(this,void 0,void 0,(function*(){const{projectConfig:t}=e,n=A[t.compileType];if(null==n)throw new Error("Unsupported compileType: "+String(t.compileType));yield n(e)}))}({projectConfig:o,projectPath:i,outputPath:f,cb:()=>{p(!0)}});const{entrys:m,mainPublicPath:h,retry:v}=pe(o,f,{builderConfig:u,extInfo:d,debug:n,dev:!0});return p=v,z.log("启动 live server 服务..."),z.success("本地访问地址:",be(u)+(null===(t=m[0])||void 0===t?void 0:t.entryPath)),z.success("扫码预览地址:",be(u)+h+"/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:me};b.default.start(t)}(Object.assign(Object.assign({},u),{root:f,ignore:"node_modules"})),yield ye("development",{entrys:m,baseURI:be(u),outputPath:a})}))}release(e){return I(this,void 0,void 0,(function*(){const{contextPath:t,releasePath:i,projectConfig:o,zip:a=!0}=e;h.default.existsSync(i)&&h.default.removeSync(i),z.log("开始打包");const r=o.projectName||o.projectname||"project",u=y.default.join(i,r),s=o.compileType;if("game"==s?yield Y("prod",t,u):"plugin"==s?yield function(e,t){return I(this,void 0,void 0,(function*(){R(),yield n.compilerManager.init({projectPath:e,outputPath:t,cachePath:T,compileSettings:{minify:!0,autoPrefixWXSS:!0,minifyWXSS:!0}}),yield n.compilerManager.compileDevPlugin({outputPath:t,remove:!0})}))}(t,u):yield X("prod",t,u),"plugin"===s&&(yield function(e,t){return I(this,void 0,void 0,(function*(){const n=Se(t),i=y.default.join(e,C,n);h.default.existsSync(i)&&(yield h.default.copy(i,e),h.default.removeSync(y.default.join(e,C)))}))}(u,o)),a){let e=u+".zip";yield(c=u,new Promise(((e,t)=>{const n=h.default.createWriteStream(`${c}.zip`),i=S.default("zip",{zlib:{level:9}});n.on("close",(()=>{const t=i.pointer();e({name:`${y.default.basename(c)}.zip`,size:t})})),i.on("warning",(e=>{if("ENOENT"!==e.code)throw e})),i.on("error",(e=>{throw t(e),e})),i.pipe(n),i.directory(`${c}`,!1),i.finalize()}))),"plugin"===s&&(e=function(e,t,n){const i=y.default.join(t,`${Se(n)}-${n.version||"1.0.0"}.zip`);return h.default.existsSync(e)?(h.default.renameSync(e,i),i):e}(e,i,o)),z.success("打包成功,zip包地址:"+e)}var c}))}config(){}providedProjectConfig(){}clearCache(){try{h.default.existsSync(T)&&h.default.removeSync(T),z.success("项目缓存清除成功~"),h.default.existsSync($)&&h.default.removeSync($),z.success("插件缓存清除成功~")}catch(e){z.success("缓存清除失败 \n"+e.message)}}};module.exports=we,exports.default=we;
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;