miniprogram-ci 2.1.7 → 2.1.8

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.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.packNpmManually=exports.packNpm=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),fs_1=tslib_1.__importDefault(require("fs")),rimraf_1=tslib_1.__importDefault(require("rimraf")),lodash_1=tslib_1.__importDefault(require("lodash")),glob_1=tslib_1.__importDefault(require("glob")),source_map_1=tslib_1.__importDefault(require("source-map")),locales_1=tslib_1.__importDefault(require("../../../../utils/locales/locales")),error_1=require("../../../../utils/error"),log=tslib_1.__importStar(require("../../../../utils/log")),projectconfig_1=require("../json/projectconfig"),config_1=require("../../../../config/config"),filterdeps_1=tslib_1.__importDefault(require("./filterdeps")),acorn=require("acorn"),NPM_RECORD={start_time:Date.now(),pack_time:0,miniprogram_pack_num:0,other_pack_num:0,warn_not_found_num:0,warn_require_var_num:0,warn_require_rename_num:0,extra1:"",extra2:"",extra3:""},REPORT_LIST=["pack_time","miniprogram_pack_num","other_pack_num","warn_not_found_num","warn_require_var_num","warn_require_rename_num","extra1","extra2","extra3"];function wrap(e,t){return function(...a){if(a.length){const e=a.pop();"function"!=typeof e&&a.push(e)}return new Promise((r,n)=>{a.push((e,t)=>{e?n(e):r(t)}),e.apply(t||null,a)})}}const statSync=wrap(fs_1.default.stat),mkdirSync=wrap(fs_1.default.mkdir),readFileSync=wrap(fs_1.default.readFile),writeFileSync=wrap(fs_1.default.writeFile),accessSync=wrap(fs_1.default.access),renameSync=wrap(fs_1.default.rename),globSync=wrap(glob_1.default);let seed=+new Date;function getId(){return++seed}function startRecord(){NPM_RECORD.start_time=Date.now(),REPORT_LIST.forEach(e=>NPM_RECORD[e]=e.startsWith("extra")?"":0)}function endRecord(e){NPM_RECORD.pack_time=Date.now()-NPM_RECORD.start_time;const t={};REPORT_LIST.forEach(e=>t[e]=NPM_RECORD[e]);try{null==e||e(t)}catch(e){}}async function recursiveMkdir(e){const t=path_1.default.posix.dirname(e);try{await accessSync(t)}catch(e){await recursiveMkdir(t)}try{await accessSync(e);const t=await statSync(e);t&&!t.isDirectory()&&(await renameSync(e,e+".bak"),log.warn(e+" already exists but is not a directory, so it will be rename to a file with the suffix ending in '.bak'"),await mkdirSync(e))}catch(t){await mkdirSync(e)}}async function copyFile(e,t){const a=await readFileSync(e);await writeFile(a,t)}async function writeFile(e,t){await recursiveMkdir(path_1.default.posix.dirname(t)),await writeFileSync(t,e)}function walkNode(e,t){t(e),Object.keys(e).forEach(a=>{const r=e[a];Array.isArray(r)&&r.forEach(e=>{(null==e?void 0:e.type)&&walkNode(e,t)}),(null==r?void 0:r.type)&&walkNode(r,t)})}function parseDeps(e,t,a){const r=[];let n,o=[];try{n=acorn.parse(e,{sourceType:"module",locations:!0,allowHashBang:!0,onComment(t,a,r,n){t||"#"!==e[r]||o.push({start:r,end:n,adjustContent:""})}})}catch(e){const a=`parse js file (${t}) failed: ${e.message}`;throw console.error(a),e.message=a,e}return walkNode(n,n=>{const{callee:i}=n,s=n.arguments;if("CallExpression"===n.type&&i&&"Identifier"===i.type&&"require"===i.name&&s&&1===s.length&&("Literal"===s[0].type?r.push(s[0].value):(a.push({jsPath:t,code:e.substring(n.start,n.end),startLine:n.loc.start.line,endLine:n.loc.end.line,tips:"require variable is not allowed",msg:locales_1.default.config.NOT_ALLOWED_REQUIRE_VAR.format()}),NPM_RECORD.warn_require_var_num++)),"ExpressionStatement"===n.type&&n.expression&&"use strict"===n.expression.value&&o.push({start:n.start,end:n.end,adjustContent:""}),"ImportDeclaration"===n.type){const{source:e}=n,{specifiers:t}=n,a={start:n.start,end:n.end,adjustContent:""},i=[];e&&"Literal"===e.type&&(r.push(e.value),i.push(`var __TEMP__ = require('${e.value}');`)),t&&Array.isArray(t)&&t.forEach(e=>{if("ImportSpecifier"===e.type){const{local:t}=e,{imported:a}=e;"Identifier"===t.type&&"Identifier"===a.type&&i.push(`var ${t.name} = __TEMP__['${a.name}'];`)}else if("ImportDefaultSpecifier"===e.type){const{local:t}=e;"Identifier"===t.type&&i.push(`var ${t.name} = __REQUIRE_DEFAULT__(__TEMP__);`)}else if("ImportNamespaceSpecifier"===e.type){const{local:t}=e;"Identifier"===t.type&&i.push(`var ${t.name} = __REQUIRE_WILDCARD__(__TEMP__);`)}}),a.adjustContent=i.join(""),o.push(a)}if("ExportNamedDeclaration"===n.type){const{source:t}=n,{specifiers:a}=n,{declaration:i}=n;let s=!1;const p={start:n.start,end:n.end,adjustContent:""},c=['if (!exports.__esModule) Object.defineProperty(exports, "__esModule", { value: true });'];if(t&&"Literal"===t.type&&(r.push(t.value),c.push(`var __TEMP__ = require('${t.value}');`),s=!0),i){if("VariableDeclaration"===i.type){const{declarations:t}=i;t&&Array.isArray(t)&&t.forEach(t=>{if("VariableDeclarator"===t.type){const{id:a}=t,{init:r}=t;a&&"Identifier"===a.type&&(p.notAddLines=!0,c.push(`var ${a.name} = exports.${a.name} = ${r?e.substring(r.start,r.end):"undefined"};`))}})}else if("FunctionDeclaration"===i.type){const{id:t}=i;t&&"Identifier"===t.type&&(p.notAddLines=!0,c.push(`${e.substring(i.start,i.end)};exports.${t.name} = ${t.name}`))}else if("ClassDeclaration"===i.type){const{id:t}=i;t&&"Identifier"===t.type&&(p.notAddLines=!0,c.push(`${e.substring(i.start,i.end)};exports.${t.name} = ${t.name}`))}}else;a&&Array.isArray(a)&&a.forEach(e=>{if("ExportSpecifier"===e.type){const{local:t}=e,{exported:a}=e;"Identifier"===t.type&&"Identifier"===a.type&&c.push(`Object.defineProperty(exports, '${a.name}', { enumerable: true, configurable: true, get: function() { return ${s?"__TEMP__.":""}${t.name}; } });`)}}),p.adjustContent=c.join(""),o.push(p)}else if("ExportAllDeclaration"===n.type){const{source:e}=n,t={start:n.start,end:n.end,adjustContent:""},a=['if (!exports.__esModule) Object.defineProperty(exports, "__esModule", { value: true });'];e&&"Literal"===e.type&&(r.push(e.value),a.push(`var __TEMP__ = require('${e.value}');`)),a.push('Object.keys(__TEMP__).forEach(function(k) { if (k === "default" || k === "__esModule") return; Object.defineProperty(exports, k, { enumerable: true, configurable: true, get: function() { return __TEMP__[k]; } }); });'),t.adjustContent=a.join(""),o.push(t)}else if("ExportDefaultDeclaration"===n.type){const{declaration:t}=n,a={start:n.start,end:n.end,adjustContent:""},r=['if (!exports.__esModule) Object.defineProperty(exports, "__esModule", { value: true });'];if(t)if(a.notAddLines=!0,t.id){const{id:a}=t;r.push(`${e.substring(t.start,t.end)};exports.default = ${a.name}`)}else r.push(`exports.default = ${e.substring(t.start,t.end)};`);a.adjustContent=r.join(""),o.push(a)}const{expression:p}=n;"ExpressionStatement"===n.type&&p&&"AssignmentExpression"===p.type&&"Identifier"===p.right.type&&"require"===p.right.name&&(a.push({jsPath:t,code:e.substring(n.start,n.end),startLine:n.loc.start.line,endLine:n.loc.end.line,tips:"assign require function to a variable is not allowed",msg:locales_1.default.config.NOT_ALLOWED_REQUIRE_ASSIGN.format()}),NPM_RECORD.warn_require_rename_num++);const{declarations:c}=n;"VariableDeclaration"===n.type&&c.length>0&&c.forEach(r=>{const{init:o}=r;"VariableDeclarator"===r.type&&o&&"Identifier"===o.type&&"require"===o.name&&(a.push({jsPath:t,code:e.substring(n.start,n.end),startLine:n.loc.start.line,endLine:n.loc.end.line,tips:"assign require function to a variable is not allowed",msg:locales_1.default.config.NOT_ALLOWED_REQUIRE_ASSIGN.format()}),NPM_RECORD.warn_require_rename_num++)})}),o=o.sort((e,t)=>t.start-e.start),o.forEach(t=>{const a=e.substring(t.start,t.end),r=t.notAddLines?0:a.split("\n").length;e=e.substring(0,t.start)+t.adjustContent+new Array(r).join("\n")+e.substring(t.end)}),{deps:r,parsedContent:e}}async function parseJs(e,t,a,r,n,o){if(n[t=path_1.default.posix.normalize(t)])return n[t];const i=await readFileSync(t,"utf8"),s=getId(),p=path_1.default.posix.relative(e,t);if(t.endsWith(".json")){const e={id:s,name:p,content:"module.exports = "+i,deps:[],depsMap:{}};return n[t]=s,r.push(e),s}const{deps:c,parsedContent:_}=parseDeps(i,t,o),u={id:s,name:p,content:_,deps:c,depsMap:{}};n[t]=s,r.push(u);for(const i of c){let s,p=path_1.default.posix.join(path_1.default.posix.dirname(t),i);if(!p.endsWith(".js")&&!p.endsWith(".json")){const e=p+".js";try{await accessSync(e),p=e}catch(e){}}try{const e=await statSync(p);(null==e?void 0:e.isDirectory())&&(p=path_1.default.posix.join(p,"index.js"))}catch(e){}p.endsWith(".js")||p.endsWith(".json")||(p+=".js");try{await accessSync(p),s=await parseJs(e,p,a,r,n,o)}catch(e){}s&&(u.depsMap[i]=s)}return s}function addJsToMap(e,t,a,r){const n=t.split("\n").length;for(let o=1;o<=n;o++)e.addMapping({generated:{line:r+o,column:0},original:{line:o,column:0},source:a}),e.setSourceContent(a,t)}function findOutsideDeps(e){const t=new Set;return e.forEach(e=>{e.deps.forEach(a=>{Object.keys(e.depsMap).includes(a)||t.add(a)})}),Array.from(t)}async function packJs(e,t,a){try{const t=await statSync(e);(null==t?void 0:t.isDirectory())&&(e=path_1.default.posix.join(e,"index.js"))}catch(e){}e.endsWith(".js")||e.endsWith(".json")||(e+=".js");try{await accessSync(e)}catch(t){return a.push({jsPath:e,code:"",tips:"entry file is not found",msg:locales_1.default.config.NOT_FOUND_NPM_ENTRY.format()}),void NPM_RECORD.warn_not_found_num++}const r=new source_map_1.default.SourceMapGenerator({file:"index.js"}),n=[];await parseJs(path_1.default.posix.dirname(e),e,t,n,{},a);const o=findOutsideDeps(n),i=["module.exports = (function() {","var __MODS__ = {};","var __DEFINE__ = function(modId, func, req) { var m = { exports: {}, _tempexports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; };",'var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = __MODS__[modId].m; m._exports = m._tempexports; var desp = Object.getOwnPropertyDescriptor(m, "exports"); if (desp && desp.configurable) Object.defineProperty(m, "exports", { set: function (val) { if(typeof val === "object" && val !== m._exports) { m._exports.__proto__ = val.__proto__; Object.keys(val).forEach(function (k) { m._exports[k] = val[k]; }); } m._tempexports = val }, get: function () { return m._tempexports; } }); __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); } return __MODS__[modId].m.exports; };',"var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } };","var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; };"];if(n.length){const e=n.shift();i.push(`__DEFINE__(${e.id}, function(require, module, exports) {`),addJsToMap(r,e.content,e.name,i.length),i.push(e.content),i.push(`}, function(modId) {var map = ${JSON.stringify(e.depsMap)}; return __REQUIRE__(map[modId], modId); })`);for(const e of n)i.push(`__DEFINE__(${e.id}, function(require, module, exports) {`),addJsToMap(r,e.content,e.name,i.length),i.push(e.content),i.push(`}, function(modId) { var map = ${JSON.stringify(e.depsMap)}; return __REQUIRE__(map[modId], modId); })`);i.push(`return __REQUIRE__(${e.id});`)}return i.push("})()"),i.push("//miniprogram-npm-outsideDeps="+JSON.stringify(o)),i.push("//# sourceMappingURL=index.js.map"),{js:i.join("\n"),map:r.toString()}}async function checkIsMiniprogramPack(e,t){let a="miniprogram_dist";t.miniprogram&&"string"==typeof t.miniprogram&&(a=t.miniprogram);try{const t=path_1.default.posix.join(e,a);await accessSync(t);const r=await statSync(t);if(null==r?void 0:r.isDirectory())return t}catch(e){}return""}async function packNpm(e,t={}){const{projectPath:a}=e,r=e.type,n=await(0,projectconfig_1.getProjectConfigJSON)(e),o=n.pluginRoot||"",i=n.miniprogramRoot||"",s="miniProgramPlugin"===r||"miniGamePlugin"===r,{ignores:p,reporter:c}=t;if(!a)throw new error_1.CodeError(locales_1.default.config.SHOULD_NOT_BE_EMPTY.format("projectPath"),config_1.PARAM_ERROR);if("miniProgramPlugin"===r&&!o)throw new error_1.CodeError(locales_1.default.config.SHOULD_NOT_BE_EMPTY.format('project.config.json "pluginRoot"'),config_1.PARAM_ERROR);startRecord();const _=path_1.default.isAbsolute(a)?a:path_1.default.posix.join(process.cwd(),a),u=[{searchRoot:path_1.default.posix.join(_,i),paths:await globSync("**/package.json",{cwd:path_1.default.posix.join(_,i),nodir:!0,dot:!0,ignore:(p||[]).concat("**/node_modules/**")})}];s&&u.push({searchRoot:path_1.default.posix.join(_,o),paths:await globSync("**/package.json",{cwd:path_1.default.posix.join(_,o),nodir:!0,dot:!0,ignore:(p||[]).concat("**/node_modules/**")})});lodash_1.default.flattenDeep(u.map(e=>e.paths.map(t=>path_1.default.posix.join(e.searchRoot,path_1.default.dirname(t),"miniprogram_npm")))).forEach(e=>rimraf_1.default.sync(e));const l=[];for(const e of u)for(const t of e.paths){const a=path_1.default.dirname(path_1.default.posix.join(e.searchRoot,t)),r=lodash_1.default.xorWith(e.paths,[t]).map(e=>path_1.default.posix.join(path_1.default.posix.dirname(e),"/**")).filter(e=>"**"!==e);let n=await globSync("**/package.json",{cwd:a.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:(p||[]).concat(r).concat(["node_modules/@types/**"])});if(n=await(0,filterdeps_1.default)(a,n),n&&n.length)for(const e of n){const t=path_1.default.posix.join(a,e);let r=await readFileSync(t,"utf8");const n=path_1.default.dirname(t);let o=n.replace(/([\b/\\])node_modules([\b/\\])/g,(e,t,a)=>`${t}miniprogram_npm${a}`),i=path_1.default.basename(o);const s=i.split("@");s.length&&(i=s.pop()||""),o=o.replace(path_1.default.basename(o),i),r=JSON.parse(r);const p=path_1.default.posix.join(n,r.main||"index.js"),c=await checkIsMiniprogramPack(n,r);if(c){const e=await globSync("**/*",{cwd:c.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:"**/node_modules/**"});for(const t of e)await copyFile(path_1.default.posix.join(c,t),path_1.default.posix.join(o,t));NPM_RECORD.miniprogram_pack_num++}else{const e=await packJs(p,o,l);if(!e)continue;await writeFile(e.js,path_1.default.posix.join(o,"./index.js")),await writeFile(e.map,path_1.default.posix.join(o,"./index.js.map")),NPM_RECORD.other_pack_num++}}}if(endRecord(c),NPM_RECORD.miniprogram_pack_num+NPM_RECORD.other_pack_num<=0)throw new Error("__NO_NODE_MODULES__ "+locales_1.default.config.NOT_FOUND_NODE_MODULES.format());return"function"==typeof e.updateFileAndDirs&&e.updateFileAndDirs(),l}async function packNpmManually(e){let{packageJsonPath:t,miniprogramNpmDistDir:a}=e;const r=e.ignores||[],n={pack_time:0,miniprogram_pack_num:0,other_pack_num:0,warn_not_found_num:0,warn_require_var_num:0,warn_require_rename_num:0},o=[];if(!a)throw new Error("param miniprogramNpmDistDir is required");if(!t)throw new Error("param packageJsonPath is required");if(path_1.default.isAbsolute(a)||(a=path_1.default.join(process.cwd(),a)),path_1.default.isAbsolute(t)||(t=path_1.default.join(process.cwd(),t)),!fs_1.default.existsSync(t))throw new Error(`param packageJsonPath: ${t} file is not exited`);const i=path_1.default.dirname(t);let s=await globSync("**/package.json",{cwd:i.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:(r||[]).concat(["node_modules/@types/**"])});if(s=await(0,filterdeps_1.default)(i,s),!s||!s.length)return log.warn("No miniprogram_npm package was built."),{miniProgramPackNum:0,otherNpmPackNum:0,warnList:[]};s=s.filter(e=>e.startsWith("node_modules"));for(const e of s){const t=path_1.default.posix.join(i,e);let r=await readFileSync(t,"utf8");const s=path_1.default.dirname(t);let p=s.replace(/([\b/\\])node_modules([\b/\\])/g,(e,t,a)=>`${t}miniprogram_npm${a}`);p=path_1.default.posix.normalize(path_1.default.posix.join(a,"miniprogram_npm",p.split(/[/\\]miniprogram_npm[/\\]/)[1]));let c=path_1.default.basename(p);const _=c.split("@");_.length&&(c=_.pop()||""),p=p.replace(path_1.default.basename(p),c),r=JSON.parse(r);const u=path_1.default.posix.join(s,r.main||"index.js"),l=await checkIsMiniprogramPack(s,r);if(l){const e=await globSync("**/*",{cwd:l.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:"**/node_modules/**"});for(const t of e)await copyFile(path_1.default.posix.join(l,t),path_1.default.posix.join(p,t));n.miniprogram_pack_num++}else{const e=await packJs(u,p,o);if(!e)continue;await writeFile(e.js,path_1.default.posix.join(p,"./index.js")),await writeFile(e.map,path_1.default.posix.join(p,"./index.js.map")),n.other_pack_num++}}return{miniProgramPackNum:n.miniprogram_pack_num,otherNpmPackNum:n.other_pack_num,warnList:o}}exports.packNpm=packNpm,exports.packNpmManually=packNpmManually;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.packNpmManually=exports.packNpm=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),fs_1=tslib_1.__importDefault(require("fs")),rimraf_1=tslib_1.__importDefault(require("rimraf")),lodash_1=tslib_1.__importDefault(require("lodash")),glob_1=tslib_1.__importDefault(require("glob")),source_map_1=tslib_1.__importDefault(require("source-map")),locales_1=tslib_1.__importDefault(require("../../../../utils/locales/locales")),error_1=require("../../../../utils/error"),log=tslib_1.__importStar(require("../../../../utils/log")),projectconfig_1=require("../json/projectconfig"),config_1=require("../../../../config/config"),filterdeps_1=tslib_1.__importDefault(require("./filterdeps")),acorn=require("acorn"),NPM_RECORD={start_time:Date.now(),pack_time:0,miniprogram_pack_num:0,other_pack_num:0,warn_not_found_num:0,warn_require_var_num:0,warn_require_rename_num:0,extra1:"",extra2:"",extra3:""},REPORT_LIST=["pack_time","miniprogram_pack_num","other_pack_num","warn_not_found_num","warn_require_var_num","warn_require_rename_num","extra1","extra2","extra3"];function wrap(e,t){return function(...a){if(a.length){const e=a.pop();"function"!=typeof e&&a.push(e)}return new Promise((n,r)=>{a.push((e,t)=>{e?r(e):n(t)}),e.apply(t||null,a)})}}const statSync=wrap(fs_1.default.stat),mkdirSync=wrap(fs_1.default.mkdir),readFileSync=wrap(fs_1.default.readFile),writeFileSync=wrap(fs_1.default.writeFile),accessSync=wrap(fs_1.default.access),renameSync=wrap(fs_1.default.rename),globSync=wrap(glob_1.default);let seed=+new Date;function getId(){return++seed}function startRecord(){NPM_RECORD.start_time=Date.now(),REPORT_LIST.forEach(e=>NPM_RECORD[e]=e.startsWith("extra")?"":0)}function endRecord(e){NPM_RECORD.pack_time=Date.now()-NPM_RECORD.start_time;const t={};REPORT_LIST.forEach(e=>t[e]=NPM_RECORD[e]);try{null==e||e(t)}catch(e){}}async function recursiveMkdir(e){const t=path_1.default.posix.dirname(e);try{await accessSync(t)}catch(e){await recursiveMkdir(t)}try{await accessSync(e);const t=await statSync(e);t&&!t.isDirectory()&&(await renameSync(e,e+".bak"),log.warn(e+" already exists but is not a directory, so it will be rename to a file with the suffix ending in '.bak'"),await mkdirSync(e))}catch(t){await mkdirSync(e)}}async function copyFile(e,t){const a=await readFileSync(e);await writeFile(a,t)}async function writeFile(e,t){await recursiveMkdir(path_1.default.posix.dirname(t)),await writeFileSync(t,e)}function walkNode(e,t){t(e),Object.keys(e).forEach(a=>{const n=e[a];Array.isArray(n)&&n.forEach(e=>{(null==e?void 0:e.type)&&walkNode(e,t)}),(null==n?void 0:n.type)&&walkNode(n,t)})}function parseDeps(e,t,a){const n=[];let r,o=[];try{r=acorn.parse(e,{sourceType:"module",locations:!0,allowHashBang:!0,onComment(t,a,n,r){t||"#"!==e[n]||o.push({start:n,end:r,adjustContent:""})}})}catch(e){const a=`parse js file (${t}) failed: ${e.message}`;throw console.error(a),e.message=a,e}return walkNode(r,r=>{const{callee:i}=r,s=r.arguments;if("CallExpression"===r.type&&i&&"Identifier"===i.type&&"require"===i.name&&s&&1===s.length&&("Literal"===s[0].type?n.push(s[0].value):(a.push({jsPath:t,code:e.substring(r.start,r.end),startLine:r.loc.start.line,endLine:r.loc.end.line,tips:"require variable is not allowed",msg:locales_1.default.config.NOT_ALLOWED_REQUIRE_VAR.format()}),NPM_RECORD.warn_require_var_num++)),"ExpressionStatement"===r.type&&r.expression&&"use strict"===r.expression.value&&o.push({start:r.start,end:r.end,adjustContent:""}),"ImportDeclaration"===r.type){const{source:e}=r,{specifiers:t}=r,a={start:r.start,end:r.end,adjustContent:""},i=[];e&&"Literal"===e.type&&(n.push(e.value),i.push(`var __TEMP__ = require('${e.value}');`)),t&&Array.isArray(t)&&t.forEach(e=>{if("ImportSpecifier"===e.type){const{local:t}=e,{imported:a}=e;"Identifier"===t.type&&"Identifier"===a.type&&i.push(`var ${t.name} = __TEMP__['${a.name}'];`)}else if("ImportDefaultSpecifier"===e.type){const{local:t}=e;"Identifier"===t.type&&i.push(`var ${t.name} = __REQUIRE_DEFAULT__(__TEMP__);`)}else if("ImportNamespaceSpecifier"===e.type){const{local:t}=e;"Identifier"===t.type&&i.push(`var ${t.name} = __REQUIRE_WILDCARD__(__TEMP__);`)}}),a.adjustContent=i.join(""),o.push(a)}if("ExportNamedDeclaration"===r.type){const{source:t}=r,{specifiers:a}=r,{declaration:i}=r;let s=!1;const p={start:r.start,end:r.end,adjustContent:""},c=['if (!exports.__esModule) Object.defineProperty(exports, "__esModule", { value: true });'];if(t&&"Literal"===t.type&&(n.push(t.value),c.push(`var __TEMP__ = require('${t.value}');`),s=!0),i){if("VariableDeclaration"===i.type){const{declarations:t}=i;t&&Array.isArray(t)&&t.forEach(t=>{if("VariableDeclarator"===t.type){const{id:a}=t,{init:n}=t;a&&"Identifier"===a.type&&(p.notAddLines=!0,c.push(`var ${a.name} = exports.${a.name} = ${n?e.substring(n.start,n.end):"undefined"};`))}})}else if("FunctionDeclaration"===i.type){const{id:t}=i;t&&"Identifier"===t.type&&(p.notAddLines=!0,c.push(`${e.substring(i.start,i.end)};exports.${t.name} = ${t.name}`))}else if("ClassDeclaration"===i.type){const{id:t}=i;t&&"Identifier"===t.type&&(p.notAddLines=!0,c.push(`${e.substring(i.start,i.end)};exports.${t.name} = ${t.name}`))}}else;a&&Array.isArray(a)&&a.forEach(e=>{if("ExportSpecifier"===e.type){const{local:t}=e,{exported:a}=e;"Identifier"===t.type&&"Identifier"===a.type&&c.push(`Object.defineProperty(exports, '${a.name}', { enumerable: true, configurable: true, get: function() { return ${s?"__TEMP__.":""}${t.name}; } });`)}}),p.adjustContent=c.join(""),o.push(p)}else if("ExportAllDeclaration"===r.type){const{source:e}=r,t={start:r.start,end:r.end,adjustContent:""},a=['if (!exports.__esModule) Object.defineProperty(exports, "__esModule", { value: true });'];e&&"Literal"===e.type&&(n.push(e.value),a.push(`var __TEMP__ = require('${e.value}');`)),a.push('Object.keys(__TEMP__).forEach(function(k) { if (k === "default" || k === "__esModule") return; Object.defineProperty(exports, k, { enumerable: true, configurable: true, get: function() { return __TEMP__[k]; } }); });'),t.adjustContent=a.join(""),o.push(t)}else if("ExportDefaultDeclaration"===r.type){const{declaration:t}=r,a={start:r.start,end:r.end,adjustContent:""},n=['if (!exports.__esModule) Object.defineProperty(exports, "__esModule", { value: true });'];if(t)if(a.notAddLines=!0,t.id){const{id:a}=t;n.push(`${e.substring(t.start,t.end)};exports.default = ${a.name}`)}else n.push(`exports.default = ${e.substring(t.start,t.end)};`);a.adjustContent=n.join(""),o.push(a)}const{expression:p}=r;"ExpressionStatement"===r.type&&p&&"AssignmentExpression"===p.type&&"Identifier"===p.right.type&&"require"===p.right.name&&(a.push({jsPath:t,code:e.substring(r.start,r.end),startLine:r.loc.start.line,endLine:r.loc.end.line,tips:"assign require function to a variable is not allowed",msg:locales_1.default.config.NOT_ALLOWED_REQUIRE_ASSIGN.format()}),NPM_RECORD.warn_require_rename_num++);const{declarations:c}=r;"VariableDeclaration"===r.type&&c.length>0&&c.forEach(n=>{const{init:o}=n;"VariableDeclarator"===n.type&&o&&"Identifier"===o.type&&"require"===o.name&&(a.push({jsPath:t,code:e.substring(r.start,r.end),startLine:r.loc.start.line,endLine:r.loc.end.line,tips:"assign require function to a variable is not allowed",msg:locales_1.default.config.NOT_ALLOWED_REQUIRE_ASSIGN.format()}),NPM_RECORD.warn_require_rename_num++)})}),o=o.sort((e,t)=>t.start-e.start),o.forEach(t=>{const a=e.substring(t.start,t.end),n=t.notAddLines?0:a.split("\n").length;e=e.substring(0,t.start)+t.adjustContent+new Array(n).join("\n")+e.substring(t.end)}),{deps:n,parsedContent:e}}async function parseJs(e,t,a,n,r,o){if(r[t=path_1.default.posix.normalize(t)])return r[t];const i=await readFileSync(t,"utf8"),s=getId(),p=path_1.default.posix.relative(e,t);if(t.endsWith(".json")){const e={id:s,name:p,content:"module.exports = "+i,deps:[],depsMap:{}};return r[t]=s,n.push(e),s}const{deps:c,parsedContent:_}=parseDeps(i,t,o),u={id:s,name:p,content:_,deps:c,depsMap:{}};r[t]=s,n.push(u);for(const i of c){let s,p=path_1.default.posix.join(path_1.default.posix.dirname(t),i);if(!p.endsWith(".js")&&!p.endsWith(".json")){const e=p+".js";try{await accessSync(e),p=e}catch(e){}}try{const e=await statSync(p);(null==e?void 0:e.isDirectory())&&(p=path_1.default.posix.join(p,"index.js"))}catch(e){}p.endsWith(".js")||p.endsWith(".json")||(p+=".js");try{await accessSync(p),s=await parseJs(e,p,a,n,r,o)}catch(e){}s&&(u.depsMap[i]=s)}return s}function addJsToMap(e,t,a,n){const r=t.split("\n").length;for(let o=1;o<=r;o++)e.addMapping({generated:{line:n+o,column:0},original:{line:o,column:0},source:a}),e.setSourceContent(a,t)}function findOutsideDeps(e){const t=new Set;return e.forEach(e=>{e.deps.forEach(a=>{Object.keys(e.depsMap).includes(a)||t.add(a)})}),Array.from(t)}async function packJs(e,t,a){try{const t=await statSync(e);(null==t?void 0:t.isDirectory())&&(e=path_1.default.posix.join(e,"index.js"))}catch(e){}e.endsWith(".js")||e.endsWith(".json")||(e+=".js");try{await accessSync(e)}catch(t){return a.push({jsPath:e,code:"",tips:"entry file is not found",msg:locales_1.default.config.NOT_FOUND_NPM_ENTRY.format()}),void NPM_RECORD.warn_not_found_num++}const n=new source_map_1.default.SourceMapGenerator({file:"index.js"}),r=[];await parseJs(path_1.default.posix.dirname(e),e,t,r,{},a);const o=findOutsideDeps(r),i=["module.exports = (function() {","var __MODS__ = {};","var __DEFINE__ = function(modId, func, req) { var m = { exports: {}, _tempexports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; };",'var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = __MODS__[modId].m; m._exports = m._tempexports; var desp = Object.getOwnPropertyDescriptor(m, "exports"); if (desp && desp.configurable) Object.defineProperty(m, "exports", { set: function (val) { if(typeof val === "object" && val !== m._exports) { m._exports.__proto__ = val.__proto__; Object.keys(val).forEach(function (k) { m._exports[k] = val[k]; }); } m._tempexports = val }, get: function () { return m._tempexports; } }); __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); } return __MODS__[modId].m.exports; };',"var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } };","var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; };"];if(r.length){const e=r.shift();i.push(`__DEFINE__(${e.id}, function(require, module, exports) {`),addJsToMap(n,e.content,e.name,i.length),i.push(e.content),i.push(`}, function(modId) {var map = ${JSON.stringify(e.depsMap)}; return __REQUIRE__(map[modId], modId); })`);for(const e of r)i.push(`__DEFINE__(${e.id}, function(require, module, exports) {`),addJsToMap(n,e.content,e.name,i.length),i.push(e.content),i.push(`}, function(modId) { var map = ${JSON.stringify(e.depsMap)}; return __REQUIRE__(map[modId], modId); })`);i.push(`return __REQUIRE__(${e.id});`)}return i.push("})()"),i.push("//miniprogram-npm-outsideDeps="+JSON.stringify(o)),i.push("//# sourceMappingURL=index.js.map"),{js:i.join("\n"),map:n.toString()}}async function checkIsMiniprogramPack(e,t){let a="miniprogram_dist";t.miniprogram&&"string"==typeof t.miniprogram&&(a=t.miniprogram);try{const t=path_1.default.posix.join(e,a);await accessSync(t);const n=await statSync(t);if(null==n?void 0:n.isDirectory())return t}catch(e){}return""}async function packNpm(e,t={}){const{projectPath:a}=e,n=e.type,r=await(0,projectconfig_1.getProjectConfigJSON)(e),o=r.pluginRoot||"",i=r.miniprogramRoot||"",s="miniProgramPlugin"===n||"miniGamePlugin"===n,{ignores:p,reporter:c}=t;if(!a)throw new error_1.CodeError(locales_1.default.config.SHOULD_NOT_BE_EMPTY.format("projectPath"),config_1.PARAM_ERROR);if("miniProgramPlugin"===n&&!o)throw new error_1.CodeError(locales_1.default.config.SHOULD_NOT_BE_EMPTY.format('project.config.json "pluginRoot"'),config_1.PARAM_ERROR);startRecord();const _=path_1.default.isAbsolute(a)?a:path_1.default.posix.join(process.cwd(),a),u=[{searchRoot:path_1.default.posix.join(_,i),paths:await globSync("**/package.json",{cwd:path_1.default.posix.join(_,i),nodir:!0,dot:!0,ignore:(p||[]).concat("**/node_modules/**")})}];s&&u.push({searchRoot:path_1.default.posix.join(_,o),paths:await globSync("**/package.json",{cwd:path_1.default.posix.join(_,o),nodir:!0,dot:!0,ignore:(p||[]).concat("**/node_modules/**")})});lodash_1.default.flattenDeep(u.map(e=>e.paths.map(t=>path_1.default.posix.join(e.searchRoot,path_1.default.dirname(t),"miniprogram_npm")))).forEach(e=>rimraf_1.default.sync(e));const l=[];for(const e of u)for(const t of e.paths){const a=path_1.default.dirname(path_1.default.posix.join(e.searchRoot,t)),n=lodash_1.default.xorWith(e.paths,[t]).map(e=>path_1.default.posix.join(path_1.default.posix.dirname(e),"/**")).filter(e=>"**"!==e);let r=await globSync("**/package.json",{cwd:a.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:(p||[]).concat(n).concat(["node_modules/@types/**"])});if(r=await(0,filterdeps_1.default)(a,r),r&&r.length)for(const e of r){const t=path_1.default.posix.join(a,e);let n=await readFileSync(t,"utf8");const r=path_1.default.dirname(t);let o=r.replace(/([\b/\\])node_modules([\b/\\])/g,(e,t,a)=>`${t}miniprogram_npm${a}`),i=path_1.default.basename(o);const s=i.split("@");s.length&&(i=s.pop()||""),o=o.replace(path_1.default.basename(o),i),n=JSON.parse(n);const p=path_1.default.posix.join(r,n.main||"index.js"),c=await checkIsMiniprogramPack(r,n);if(c){const e=await globSync("**/*",{cwd:c.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:"**/node_modules/**"});for(const t of e)await copyFile(path_1.default.posix.join(c,t),path_1.default.posix.join(o,t));NPM_RECORD.miniprogram_pack_num++}else{const e=await packJs(p,o,l);if(!e)continue;await writeFile(e.js,path_1.default.posix.join(o,"./index.js")),await writeFile(e.map,path_1.default.posix.join(o,"./index.js.map")),NPM_RECORD.other_pack_num++}}}if(endRecord(c),NPM_RECORD.miniprogram_pack_num+NPM_RECORD.other_pack_num<=0)throw new Error("__NO_NODE_MODULES__ "+locales_1.default.config.NOT_FOUND_NODE_MODULES.format());return"function"==typeof e.updateFileAndDirs&&e.updateFileAndDirs(),l}async function packNpmManually(e){let{packageJsonPath:t,miniprogramNpmDistDir:a}=e;const n=e.ignores||[],r={pack_time:0,miniprogram_pack_num:0,other_pack_num:0,warn_not_found_num:0,warn_require_var_num:0,warn_require_rename_num:0},o=[];if(!a)throw new Error("param miniprogramNpmDistDir is required");if(!t)throw new Error("param packageJsonPath is required");if(path_1.default.isAbsolute(a)||(a=path_1.default.join(process.cwd(),a)),path_1.default.isAbsolute(t)||(t=path_1.default.join(process.cwd(),t)),!fs_1.default.existsSync(t))throw new Error(`param packageJsonPath: ${t} file is not exited`);const i=path_1.default.dirname(t);let s=await globSync("**/package.json",{cwd:i.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:(n||[]).concat(["node_modules/@types/**"])});if(s=await(0,filterdeps_1.default)(i,s),!s||!s.length){const e={jsPath:i,code:"",tips:"",msg:"No miniprogram_npm package was found, please check package.json -> dependencies."};return log.warn(e.msg),o.push(e),{miniProgramPackNum:0,otherNpmPackNum:0,warnList:o}}s=s.filter(e=>e.startsWith("node_modules"));for(const e of s){const t=path_1.default.posix.join(i,e);let n=await readFileSync(t,"utf8");const s=path_1.default.dirname(t);let p=s.replace(/([\b/\\])node_modules([\b/\\])/g,(e,t,a)=>`${t}miniprogram_npm${a}`);p=path_1.default.posix.normalize(path_1.default.posix.join(a,"miniprogram_npm",p.split(/[/\\]miniprogram_npm[/\\]/)[1]));let c=path_1.default.basename(p);const _=c.split("@");_.length&&(c=_.pop()||""),p=p.replace(path_1.default.basename(p),c),n=JSON.parse(n);const u=path_1.default.posix.join(s,n.main||"index.js"),l=await checkIsMiniprogramPack(s,n);if(l){const e=await globSync("**/*",{cwd:l.replace(/\\/g,"/"),nodir:!0,dot:!0,ignore:"**/node_modules/**"});for(const t of e)await copyFile(path_1.default.posix.join(l,t),path_1.default.posix.join(p,t));r.miniprogram_pack_num++}else{const e=await packJs(u,p,o);if(!e)continue;await writeFile(e.js,path_1.default.posix.join(p,"./index.js")),await writeFile(e.map,path_1.default.posix.join(p,"./index.js.map")),r.other_pack_num++}}return{miniProgramPackNum:r.miniprogram_pack_num,otherNpmPackNum:r.other_pack_num,warnList:o}}exports.packNpm=packNpm,exports.packNpmManually=packNpmManually;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AppConf=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),baseconf_1=require("./baseconf"),original_1=require("../../original"),common_1=require("../../original/json/common"),locales_1=tslib_1.__importDefault(require("../../../../utils/locales/locales")),getPageJSON_1=require("../../original/json/page/getPageJSON"),util_1=require("./util"),taskmanager_1=tslib_1.__importDefault(require("../../../../utils/taskmanager"));class AppConf extends baseconf_1.MiniProgramBaseConf{constructor(){super(...arguments),this.packages=new Map,this.pages=new Map,this.comps=new Map,this.onFileChange=(t,o)=>{}}destroy(){}async getConf(t){return await this.build(t),{app:this.app,ext:this.ext,packages:Object.fromEntries(this.packages.entries()),pages:Object.fromEntries(this.pages.entries()),comps:Object.fromEntries(this.comps.entries()),sitemap:this.sitemap,theme:this.theme}}async buildPagesAndCompsForUpload(t,o=!1){const a={},e={};return await Promise.all(Array.from(this.pages.keys()).map(async t=>{const e=await(o?getPageJSON_1.getPageJSONWithDisableSpreading:original_1.getPageJSON)(this.proxyProject,{miniprogramRoot:this.root,pagePath:t});a[t+".json"]=JSON.stringify(e)})),await Promise.all(Array.from(this.comps.keys()).map(async t=>{const a=await(o?getPageJSON_1.getPageJSONWithDisableSpreading:original_1.getPageJSON)(this.proxyProject,{miniprogramRoot:this.root,pagePath:t});e[t+".json"]=JSON.stringify(a)})),{pageResults:a,componentResults:e}}async buildPagesAndCompsWithFileListForUpload(t,o,a=!1){const e={},s={},i=new taskmanager_1.default;for(const t of Array.from(this.pages.keys()))if(o.includes(t+".json")){const o=async t=>{const o=await(a?getPageJSON_1.getPageJSONWithDisableSpreading:original_1.getPageJSON)(this.proxyProject,{miniprogramRoot:this.root,pagePath:t});e[t+".json"]=JSON.stringify(o)};i.addTask(o,t)}for(const t of Array.from(this.comps.keys()))if(o.includes(t+".json")){const o=async t=>{const o=await(a?getPageJSON_1.getPageJSONWithDisableSpreading:original_1.getPageJSON)(this.proxyProject,{miniprogramRoot:this.root,pagePath:t});s[t+".json"]=JSON.stringify(o)};i.addTask(o,t)}return await i.runAllAsync(),{pageResults:e,componentResults:s}}async resetState(){this.app=void 0,this.ext=void 0,this.packages.clear(),this.pages.clear(),this.comps.clear(),this.sitemap=void 0,this.theme=void 0}async load(t){const o=await t.run(locales_1.default.config.SUMMER_COMPILE.format("app.json"),()=>(0,original_1.getAppJSON)(this.proxyProject));this.app=o;const a=await t.run(locales_1.default.config.SUMMER_COMPILE.format("ext.json"),()=>(0,original_1.getExtJSON)(this.proxyProject));this.ext=a;const e=new Set;for(const t of o.pages)e.add(t);const s=o.subPackages||[];for(const t of s){const o=t.root;this.packages.set(o,t);for(const a of t.pages)e.add(path_1.default.posix.join(o,a))}await t.run(locales_1.default.config.SUMMER_COMPILE_PAGE_JSON.format(e.size),async()=>{var t;for(const[t]of e.entries())(0,util_1.isPluginPath)(t)||await this.loadPage(t);for(const t of Object.values(o.usingComponents||{}))if(!t.startsWith("plugin://")&&!(0,util_1.isPluginPath)(t)){const o=(0,util_1.resolvePath)("app.json",t);await this.loadComp(o,t,"app.json")}if(null===(t=o.tabBar)||void 0===t?void 0:t.custom){const t=(0,util_1.resolvePath)("app.json","custom-tab-bar/index");this.proxyProject.stat(this.root,t+".json")&&await this.loadComp(t,"custom-tab-bar/index","app.json")}if(o.appBar){const t=(0,util_1.resolvePath)("app.json","app-bar/index");this.proxyProject.stat(this.root,t+".json")&&await this.loadComp(t,"app-bar/index","app.json")}if(o.plugins)for(const t of Object.values(o.plugins))t.genericsImplementation&&Object.values(t.genericsImplementation).forEach(t=>{Object.values(t).map(async t=>{const o=(0,util_1.resolvePath)("app.json",t);return await this.loadComp(o,t,"app.json")})})}),o.themeLocation&&await t.run(locales_1.default.config.SUMMER_COMPILE.format(o.themeLocation),()=>this.loadTheme(o.themeLocation)),o.accountCardPackage&&await t.run(locales_1.default.config.SUMMER_COMPILE.format(o.themeLocation),async()=>{for(const t of o.accountCardPackage.cardList){const a=path_1.default.posix.join(o.accountCardPackage.root,t.componentPath);await this.loadComp(a,a,"app.json")}})}async loadPage(t){const o=await(0,original_1.getPageJSON)(this.proxyProject,{miniprogramRoot:this.root,pagePath:t});this.pages.set(t,o);const a=async o=>{if((0,util_1.isPluginPath)(o))return;const a=(0,util_1.resolvePath)(t,o);await this.loadComp(a,o,t)};if(o.usingComponents)for(const t of Object.values(o.usingComponents))await a(t);if(o.componentGenerics)for(const t of Object.values(o.componentGenerics)){const o=t.default;o&&await a(o)}}async loadComp(t,o,a){if(await this.isExtendedLibComp(t,a))return;if(this.comps.has(t))return;if(!this.proxyProject.stat(this.root,t+".json"))throw new Error(`[summer-compiler] Couldn't found the '${o}.json' file relative to '${a}'`);const e=await(0,original_1.getPageJSON)(this.proxyProject,{miniprogramRoot:this.root,pagePath:t});this.comps.set(t,e);const s=async o=>{if((0,util_1.isPluginPath)(o))return;const a=(0,util_1.resolvePath)(t,o);await this.loadComp(a,o,t)};if(e.usingComponents)for(const t of Object.values(e.usingComponents))await s(t);if(e.componentGenerics)for(const t of Object.values(e.componentGenerics)){const o=t.default;o&&await s(o)}}async loadTheme(t){const o=await(0,original_1.checkThemeJSON)(this.proxyProject,{themeLocation:t});this.theme=o}async isExtendedLibComp(t,o){if(t.startsWith("miniprogram_npm/")){const a=(0,common_1.getUseExtendLib)(this.proxyProject,o);if(a.length>0){const o=a.map(t=>"miniprogram_npm/"+t);for(const a of o)if(t.startsWith(a))return!0}}return!1}}exports.AppConf=AppConf;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AppConf=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),baseconf_1=require("./baseconf"),original_1=require("../../original"),common_1=require("../../original/json/common"),locales_1=tslib_1.__importDefault(require("../../../../utils/locales/locales")),getPageJSON_1=require("../../original/json/page/getPageJSON"),util_1=require("./util"),taskmanager_1=tslib_1.__importDefault(require("../../../../utils/taskmanager"));class AppConf extends baseconf_1.MiniProgramBaseConf{constructor(){super(...arguments),this.packages=new Map,this.pages=new Map,this.comps=new Map,this.onFileChange=(t,o)=>{}}destroy(){}async getConf(t){return await this.build(t),{app:this.app,ext:this.ext,packages:Object.fromEntries(this.packages.entries()),pages:Object.fromEntries(this.pages.entries()),comps:Object.fromEntries(this.comps.entries()),sitemap:this.sitemap,theme:this.theme}}async buildPagesAndCompsForUpload(t,o=!1){const a={},e={};return await Promise.all(Array.from(this.pages.keys()).map(async t=>{const e=await(o?getPageJSON_1.getPageJSONWithDisableSpreading:original_1.getPageJSON)(this.proxyProject,{miniprogramRoot:this.root,pagePath:t});a[t+".json"]=JSON.stringify(e)})),await Promise.all(Array.from(this.comps.keys()).map(async t=>{const a=await(o?getPageJSON_1.getPageJSONWithDisableSpreading:original_1.getPageJSON)(this.proxyProject,{miniprogramRoot:this.root,pagePath:t});e[t+".json"]=JSON.stringify(a)})),{pageResults:a,componentResults:e}}async buildPagesAndCompsWithFileListForUpload(t,o,a=!1){const e={},s={},i=new taskmanager_1.default;for(const t of Array.from(this.pages.keys()))if(o.includes(t+".json")){const o=async t=>{const o=await(a?getPageJSON_1.getPageJSONWithDisableSpreading:original_1.getPageJSON)(this.proxyProject,{miniprogramRoot:this.root,pagePath:t});e[t+".json"]=JSON.stringify(o)};i.addTask(o,t)}for(const t of Array.from(this.comps.keys()))if(o.includes(t+".json")){const o=async t=>{const o=await(a?getPageJSON_1.getPageJSONWithDisableSpreading:original_1.getPageJSON)(this.proxyProject,{miniprogramRoot:this.root,pagePath:t});s[t+".json"]=JSON.stringify(o)};i.addTask(o,t)}return await i.runAllAsync(),{pageResults:e,componentResults:s}}async resetState(){this.app=void 0,this.ext=void 0,this.packages.clear(),this.pages.clear(),this.comps.clear(),this.sitemap=void 0,this.theme=void 0}async load(t){const o=await t.run(locales_1.default.config.SUMMER_COMPILE.format("app.json"),()=>(0,original_1.getAppJSON)(this.proxyProject));this.app=o;const a=await t.run(locales_1.default.config.SUMMER_COMPILE.format("ext.json"),()=>(0,original_1.getExtJSON)(this.proxyProject));this.ext=a;const{project:e}=this.proxyProject,s=new Set;for(const t of o.pages)s.add(t);for(const t of e.injectedPages)s.add((0,util_1.resolvePath)("app.json",t));const i=o.subPackages||[];for(const t of i){const o=t.root;this.packages.set(o,t);for(const a of t.pages)s.add(path_1.default.posix.join(o,a))}await t.run(locales_1.default.config.SUMMER_COMPILE_PAGE_JSON.format(s.size),async()=>{var t;for(const[t]of s.entries())(0,util_1.isPluginPath)(t)||await this.loadPage(t);for(const t of Object.values(o.usingComponents||{}))if(!t.startsWith("plugin://")&&!(0,util_1.isPluginPath)(t)){const o=(0,util_1.resolvePath)("app.json",t);await this.loadComp(o,t,"app.json")}if(null===(t=o.tabBar)||void 0===t?void 0:t.custom){const t=(0,util_1.resolvePath)("app.json","custom-tab-bar/index");this.proxyProject.stat(this.root,t+".json")&&await this.loadComp(t,"custom-tab-bar/index","app.json")}if(o.appBar){const t=(0,util_1.resolvePath)("app.json","app-bar/index");this.proxyProject.stat(this.root,t+".json")&&await this.loadComp(t,"app-bar/index","app.json")}if(o.plugins)for(const t of Object.values(o.plugins))t.genericsImplementation&&Object.values(t.genericsImplementation).forEach(t=>{Object.values(t).map(async t=>{const o=(0,util_1.resolvePath)("app.json",t);return await this.loadComp(o,t,"app.json")})})}),o.themeLocation&&await t.run(locales_1.default.config.SUMMER_COMPILE.format(o.themeLocation),()=>this.loadTheme(o.themeLocation)),o.accountCardPackage&&await t.run(locales_1.default.config.SUMMER_COMPILE.format(o.themeLocation),async()=>{for(const t of o.accountCardPackage.cardList){const a=path_1.default.posix.join(o.accountCardPackage.root,t.componentPath);await this.loadComp(a,a,"app.json")}})}async loadPage(t){const o=await(0,original_1.getPageJSON)(this.proxyProject,{miniprogramRoot:this.root,pagePath:t});this.pages.set(t,o);const a=async o=>{if((0,util_1.isPluginPath)(o))return;const a=(0,util_1.resolvePath)(t,o);await this.loadComp(a,o,t)};if(o.usingComponents)for(const t of Object.values(o.usingComponents))await a(t);if(o.componentGenerics)for(const t of Object.values(o.componentGenerics)){const o=t.default;o&&await a(o)}}async loadComp(t,o,a){if(await this.isExtendedLibComp(t,a))return;if(this.comps.has(t))return;if(!this.proxyProject.stat(this.root,t+".json"))throw new Error(`[summer-compiler] Couldn't found the '${o}.json' file relative to '${a}'`);const e=await(0,original_1.getPageJSON)(this.proxyProject,{miniprogramRoot:this.root,pagePath:t});this.comps.set(t,e);const s=async o=>{if((0,util_1.isPluginPath)(o))return;const a=(0,util_1.resolvePath)(t,o);await this.loadComp(a,o,t)};if(e.usingComponents)for(const t of Object.values(e.usingComponents))await s(t);if(e.componentGenerics)for(const t of Object.values(e.componentGenerics)){const o=t.default;o&&await s(o)}}async loadTheme(t){const o=await(0,original_1.checkThemeJSON)(this.proxyProject,{themeLocation:t});this.theme=o}async isExtendedLibComp(t,o){if(t.startsWith("miniprogram_npm/")){const a=(0,common_1.getUseExtendLib)(this.proxyProject,o);if(a.length>0){const o=a.map(t=>"miniprogram_npm/"+t);for(const a of o)if(t.startsWith(a))return!0}}return!1}}exports.AppConf=AppConf;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getSummerCompiler=exports.summerCompilerFactory=exports.SummerCompilerFactory=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),lodash_1=tslib_1.__importDefault(require("lodash")),config_1=require("../config/config"),ciProject_1=require("../project/ciProject"),tools_1=require("../utils/tools"),locales_1=tslib_1.__importDefault(require("../utils/locales/locales")),summerCompiler_1=require("./corecompiler/summerCompiler"),pluginconfig_1=require("./corecompiler/summer/pluginconfig"),WeappCompileCache="";class SummerCompilerFactory{constructor(){this.summerCompiler=null,this.project=null,this.createPromise=null,this.releaseCbs=[]}async getSummerCompiler(e,r){return this.shouldCreate(e)?(this.releaseLastCompiler(),this.project=e,this.summerCompiler=null,this.createPromise=this.createSummerCompiler(e,r),this.summerCompiler=await this.createPromise,this.summerCompiler.setLocale(locales_1.default.getLocale())):(this.summerCompiler||(this.summerCompiler=await this.createPromise),this.summerCompiler.updateOptions(this.getSummerOptions(e))),this.summerCompiler}shouldCreate(e){var r,i,t,o,s;if(!this.project)return!0;if(this.project.projectPath!==e.projectPath)return!0;if(!lodash_1.default.isEqual(this.project.packOptions,e.packOptions))return!0;const m=["es6","minified","postcss","uglifyFileName","compileWorklet","enhance","minifyWXML","minifyWXSS","disableUseStrict","swc","useCompilerPlugins","babelSetting","swcSetting","minifyWXMLSetting","condition","targetPlatform"],l=null!==(i=null===(r=this.project)||void 0===r?void 0:r.setting)&&void 0!==i?i:{},c=null!==(t=e.setting)&&void 0!==t?t:{};for(const e of m){const r=l[e],i=c[e];if(!lodash_1.default.isEqual(r,i))return console.info(`shouldCreate return true, project.setting.${e}, before: ${JSON.stringify(r)}, after: ${JSON.stringify(i)}`),!0}return(null===(o=this.project)||void 0===o?void 0:o.miniprogramRoot)!==e.miniprogramRoot||(null===(s=this.project)||void 0===s?void 0:s.pluginRoot)!==e.pluginRoot}async releaseLastCompiler(){const{releaseCbs:e}=this;if(this.releaseCbs=[],this.createPromise)try{(await this.createPromise).destroy(),e.forEach(e=>{try{e()}catch(e){console.error("[SummerCompilerFactory] releaseLastCompiler release cb execute error: "+e)}})}catch(e){console.error("[SummerCompilerFactory] releaseLastCompiler error: "+e)}}ensureCacheDir(){const e=path_1.default.join("",(0,tools_1.generateMD5)(this.project.projectPath+"|summer"));return(0,tools_1.mkdirSync)(e),e}async createSummerCompiler(e,r){const i=new ciProject_1.CIProject(e);await i.ready();const t=this.ensureCacheDir(),o=this.getSummerOptions(e),s=new summerCompiler_1.SummerCompiler(i,t,o,{showBuildLog:()=>{}},r);return await s.ready(),s}getSummerOptions(e){const r=(0,pluginconfig_1.getSummerPluginConfig)(e.setting),i={[config_1.compileTypeConfig.weapp]:"miniProgram",[config_1.compileTypeConfig.plugin]:"miniProgramPlugin",[config_1.compileTypeConfig.game]:"miniGame",[config_1.compileTypeConfig.gamePlugin]:"miniGamePlugin"}[e.compileType];return{appid:e.appid,attr:e.attr,projectArchitecture:e.projectArchitecture,miniprogramRoot:e.miniprogramRoot,pluginRoot:e.pluginRoot,compileType:i,summerPlugins:r,setting:Object.assign({},e.setting)}}}exports.SummerCompilerFactory=SummerCompilerFactory,exports.summerCompilerFactory=new SummerCompilerFactory,exports.getSummerCompiler=exports.summerCompilerFactory.getSummerCompiler.bind(exports.summerCompilerFactory);
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getSummerCompiler=exports.summerCompilerFactory=exports.SummerCompilerFactory=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),lodash_1=tslib_1.__importDefault(require("lodash")),config_1=require("../config/config"),ciProject_1=require("../project/ciProject"),tools_1=require("../utils/tools"),locales_1=tslib_1.__importDefault(require("../utils/locales/locales")),summerCompiler_1=require("./corecompiler/summerCompiler"),pluginconfig_1=require("./corecompiler/summer/pluginconfig"),WeappCompileCache="";class SummerCompilerFactory{constructor(){this.summerCompiler=null,this.project=null,this.createPromise=null,this.releaseCbs=[]}async getSummerCompiler(e,r){return this.shouldCreate(e)?(this.releaseLastCompiler(),this.project=e,this.summerCompiler=null,this.createPromise=this.createSummerCompiler(e,r),this.summerCompiler=await this.createPromise,this.summerCompiler.setLocale(locales_1.default.getLocale())):(this.summerCompiler||(this.summerCompiler=await this.createPromise),this.summerCompiler.updateOptions(this.getSummerOptions(e))),this.summerCompiler}shouldCreate(e){var r,i,t,o,s;if(!this.project)return!0;if(this.project.projectPath!==e.projectPath)return!0;if(!lodash_1.default.isEqual(this.project.packOptions,e.packOptions))return!0;const m=["es6","minified","postcss","uglifyFileName","compileWorklet","enhance","minifyWXML","minifyWXSS","disableUseStrict","swc","useCompilerPlugins","babelSetting","swcSetting","minifyWXMLSetting","condition","targetPlatform"],l=null!==(i=null===(r=this.project)||void 0===r?void 0:r.setting)&&void 0!==i?i:{},c=null!==(t=e.setting)&&void 0!==t?t:{};for(const e of m){const r=l[e],i=c[e];if(!lodash_1.default.isEqual(r,i))return console.info(`shouldCreate return true, project.setting.${e}, before: ${JSON.stringify(r)}, after: ${JSON.stringify(i)}`),!0}return(null===(o=this.project)||void 0===o?void 0:o.miniprogramRoot)!==e.miniprogramRoot||(null===(s=this.project)||void 0===s?void 0:s.pluginRoot)!==e.pluginRoot}async releaseLastCompiler(){const{releaseCbs:e}=this;if(this.releaseCbs=[],this.createPromise)try{(await this.createPromise).destroy(),e.forEach(e=>{try{e()}catch(e){console.error("[SummerCompilerFactory] releaseLastCompiler release cb execute error: "+e)}})}catch(e){console.error("[SummerCompilerFactory] releaseLastCompiler error: "+e)}}ensureCacheDir(){const e=path_1.default.join("",(0,tools_1.generateMD5)(this.project.projectPath+"|summer"));return(0,tools_1.mkdirSync)(e),e}async createSummerCompiler(e,r){const i=new ciProject_1.CIProject(e);await i.ready();const t=this.ensureCacheDir(),o=this.getSummerOptions(e),s=new summerCompiler_1.SummerCompiler(i,t,o,{showBuildLog:()=>{}},r);return await s.ready(),s}getSummerOptions(e){const r=(0,pluginconfig_1.getSummerPluginConfig)(e.setting),i={[config_1.compileTypeConfig.weapp]:"miniProgram",[config_1.compileTypeConfig.plugin]:"miniProgramPlugin",[config_1.compileTypeConfig.game]:"miniGame",[config_1.compileTypeConfig.gamePlugin]:"miniGamePlugin"}[e.compileType];return{appid:e.appid,attr:e.attr,projectArchitecture:e.projectArchitecture,miniprogramRoot:e.miniprogramRoot,pluginRoot:e.pluginRoot,compileType:i,summerPlugins:r,setting:Object.assign({},e.setting),injectedPages:[]}}}exports.SummerCompilerFactory=SummerCompilerFactory,exports.summerCompilerFactory=new SummerCompilerFactory,exports.getSummerCompiler=exports.summerCompilerFactory.getSummerCompiler.bind(exports.summerCompilerFactory);
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.remoteBuildProjectMaterialAbsoluteCacheDir=void 0;const tslib_1=require("tslib"),child_process=tslib_1.__importStar(require("child_process")),path_1=tslib_1.__importDefault(require("path")),fs_extra_1=tslib_1.__importDefault(require("fs-extra")),glob_1=tslib_1.__importDefault(require("glob")),env_1=require("../../../utils/env"),miniapp_builder_1=require("../../../utils/miniapp-builder"),codesign_1=require("../../../utils/codesign"),miniappJson_1=require("../../../utils/miniappJson"),lodash_1=require("lodash"),tools_1=require("../../../utils/tools"),uuidv4=require("uuid/v4"),sizeOf=require("image-size"),plist=require("simple-plist"),errorIOSSdkVersions=["1.0.19"],APPEX_PROFILES_MAPS_FILE="__appexProfilesCacheDir__/profilesMap.json",APPEX_PROFILES_MAPS_FOR_SHELL_FILE="__appexProfilesCacheDir__/profilesMapForShell.txt",defaultIconDirPath=path_1.default.join(__dirname,"../../../static/images/"),getDepReg=e=>new RegExp(`s.subspec '${e}'.*\n(?:.*\n)*?(?:.*sp.vendored_frameworks = \\[\n)((?:.*'.*?'.*\n)*?)(?:.*\\]\n)`,"m"),allowTheme=["Light","LightSpecial","Dark","DarkSpecial","Default"];exports.remoteBuildProjectMaterialAbsoluteCacheDir="__absoluteFile";const iconInfoMap={appStore1024:{size:[1024,1024],scale:1,idiom:"ios-marketing",required:!0},appStore1024Other:{size:[1024,1024],scale:1,idiom:"ios-marketing-other"},mainIcon120:{size:[60,60],scale:2,idiom:"iphone",required:!0},mainIcon180:{size:[60,60],scale:3,idiom:"iphone"},spotlightIcon80:{size:[40,40],scale:2,idiom:"iphone"},spotlightIcon120:{size:[40,40],scale:3,idiom:"iphone"},settingsIcon58:{size:[29,29],scale:2,idiom:"iphone"},settingsIcon87:{size:[29,29],scale:3,idiom:"iphone"},notificationIcon40:{size:[20,20],scale:2,idiom:"iphone"},notificationIcon60:{size:[20,20],scale:3,idiom:"iphone"},ipadMainIcon152:{size:[76,76],scale:2,idiom:"ipad"},ipadMainIcon167:{size:[83.5,83.5],scale:2,idiom:"ipad"},ipadSpotlightIcon40:{size:[40,40],scale:1,idiom:"ipad"},ipadSpotlightIcon80:{size:[40,40],scale:2,idiom:"ipad"},ipadSettingsIcon29:{size:[29,29],scale:1,idiom:"ipad"},ipadSpotlightIcon58:{size:[29,29],scale:2,idiom:"ipad"},ipadNotificationIcon20:{size:[20,20],scale:1,idiom:"ipad"},ipadNotificationIcon40:{size:[20,20],scale:2,idiom:"ipad"}};class buildCloudManager{generateTempDemoIpaPath(e){const i=path_1.default.join(e,"../.."),t=path_1.default.basename(i),n=path_1.default.dirname(i),a=path_1.default.join(n,t+"-operateDir");fs_extra_1.default.existsSync(a)&&fs_extra_1.default.removeSync(a),fs_extra_1.default.ensureDirSync(a);const s=path_1.default.join(a,"Payload/demo.app");return fs_extra_1.default.copySync(e,s),s}generateInfoPlistCFBundleURLTypesItem(e){const i={};return e.CFBundleURLName&&(i.CFBundleURLName=e.CFBundleURLName),e.CFBundleURLSchemes&&(i.CFBundleURLSchemes=[e.CFBundleURLSchemes]),e.CFBundleTypeRole&&(i.CFBundleTypeRole=e.CFBundleTypeRole),i}updatePrivacyBackgroundImage(e,i,t,n,a){t.message("doing","updatePrivacyBackgroundImage "+n);if(fs_extra_1.default.readdirSync(i).forEach(e=>{"privacy_"+n===path_1.default.basename(e,path_1.default.extname(e))&&fs_extra_1.default.removeSync(path_1.default.join(i,e))}),!a)return;path_1.default.isAbsolute(a)||(a=path_1.default.join(e,a)),a=this.getMaterialFilePath(e,a);const s=path_1.default.extname(a),o=path_1.default.join(i,`privacy_${n}${s}`);try{fs_extra_1.default.copyFileSync(a,o)}catch(e){throw t.message("error",`copy privacy image failed: ${n}, ${a} to ${o}`),e}}async updateIOSInfoPlistInfo(e,i,t,n,a,s){var o,r,l,d,p,u,c,f,_,h,g;a.progress("update app base info...");const{mobileapp_info:m={}}=i,y=m.mobileapp_id,I=path_1.default.join(t,"Info.plist"),S={},v=(e,i)=>{var t,n;if((null==i?void 0:i.startsWith("%"))&&(null==i?void 0:i.endsWith("%"))){const o=i.slice(1,-1);S[e]=o;const r=(null===(n=null===(t=null==s?void 0:s.base)||void 0===t?void 0:t.ios)||void 0===n?void 0:n[o])||"";return r||a.message("error",`未在国际化配置 base.json 中找到字段 ${o},请检查`),r}return i};v("UISplashScreenImageName",null===(o=null==n?void 0:n.splashscreen)||void 0===o?void 0:o.customImage),v("UILaunchStoryboardName",null===(r=null==n?void 0:n.splashscreen)||void 0===r?void 0:r.customImage);const x=plist.readFileSync(I);if(null===(l=null==n?void 0:n.useExtendedSdk)||void 0===l?void 0:l.WeAppGoogleLogin){if(!(null==n?void 0:n.googleLoginClientID)||!(null==n?void 0:n.googleLoginBundleUrlType))throw new Error("勾选了 Google Login 拓展模块但未填写 googleLoginClientID 或 googleLoginBundleUrlType 将导致拓展模块无法使用");x.GIDClientID=n.googleLoginClientID,x.CFBundleURLTypes=[{CFBundleURLSchemes:[n.googleLoginBundleUrlType]}]}if(x.CFBundleName=v("CFBundleName",n.name),x.CFBundleDisplayName=v("CFBundleDisplayName",n.name),x.CFBundleShortVersionString=n.version,"number"==typeof n.versionCode?x.CFBundleVersion=parseInt(n.versionCode.toString(),10).toString():x.CFBundleVersion=(parseInt(x.CFBundleVersion,10)+1).toString(),x.CFBundleIdentifier=this.getBundleIdentifier(m),Array.isArray(null==n?void 0:n.openMimeTypes)&&this.validateCFBundleDocumentTypes(n.openMimeTypes,a)&&(x.CFBundleDocumentTypes=n.openMimeTypes,a.message("doing","openMimeTypes 应用成功")),Array.isArray(x.CFBundleURLTypes)||(x.CFBundleURLTypes=[]),(null===(p=null===(d=x.CFBundleURLTypes)||void 0===d?void 0:d[0])||void 0===p?void 0:p.CFBundleURLSchemes)&&(x.CFBundleURLTypes[0].CFBundleURLSchemes=[y]),x.CFBundleURLTypes[0]&&(x.CFBundleURLTypes=[x.CFBundleURLTypes[0]]),Object.keys(miniappJson_1.iosPrivacyDescObj).forEach(e=>{var i,t;(null===(i=null==n?void 0:n.privateDescriptions)||void 0===i?void 0:i[e])?x[e]=v(e,null===(t=n.privateDescriptions)||void 0===t?void 0:t[e]):delete x[e]}),!0===(null===(u=null==n?void 0:n.infoPlist)||void 0===u?void 0:u.DisableAppUsesNonExemptEncryption)?x.ITSAppUsesNonExemptEncryption=!1:delete x.ITSAppUsesNonExemptEncryption,x.UIBackgroundModes=[],!0===(null===(c=null==n?void 0:n.infoPlist)||void 0===c?void 0:c.AudioInBackgroundMode)&&x.UIBackgroundModes.push("audio"),!0===(null===(f=null==n?void 0:n.infoPlist)||void 0===f?void 0:f.LocationInBackgroundMode)&&x.UIBackgroundModes.push("location"),!0===(null===(_=null==n?void 0:n.infoPlist)||void 0===_?void 0:_.requiresFullScreen)?x.UIRequiresFullScreen=!0:delete x.UIRequiresFullScreen,"object"==typeof(null===(h=null==n?void 0:n.infoPlist)||void 0===h?void 0:h.CFBundleURLTypes)){const e=this.generateInfoPlistCFBundleURLTypesItem(n.infoPlist.CFBundleURLTypes);x.CFBundleURLTypes.push(e);const{additionalCFBundleURLTypes:i}=n.infoPlist.CFBundleURLTypes;Array.isArray(i)&&i.forEach(e=>{if("object"==typeof e){const i=this.generateInfoPlistCFBundleURLTypesItem(e);x.CFBundleURLTypes.push(i)}})}if(!0===n.enableIpad&&((0,miniappJson_1.iOSAppJsonIsUsingIPadResizable)(e)?(x["UISupportedInterfaceOrientations~ipad"]=["UIInterfaceOrientationPortrait","UIInterfaceOrientationPortraitUpsideDown","UIInterfaceOrientationLandscapeLeft","UIInterfaceOrientationLandscapeRight"],a.progress("ipad is support Landscape")):(x["UISupportedInterfaceOrientations~ipad"]=["UIInterfaceOrientationPortrait","UIInterfaceOrientationPortraitUpsideDown"],a.progress("ipad is not support Landscape"))),null===(g=n.infoPlist)||void 0===g?void 0:g.LSApplicationQueriesSchemes){const e=n.infoPlist.LSApplicationQueriesSchemes.split(",");e.length&&x.LSApplicationQueriesSchemes.push(...e.filter(e=>e))}return plist.writeFileSync(I,x),await this.writeI18NInfoFile(t,s,S),x.CFBundleVersion}getBundleIdentifier(e){return e.ios_flag&&e.bundle_id||e.debug_ios_bundle_id}validateCFBundleDocumentTypes(e,i){const t=["Owner","Default"," Alternate","None"],n=["Editor","Viewer"," Shell","None"],a=new Set;for(const s of e){if(a.has(s.CFBundleTypeName))return i.message("error","openMimeTypes 应用失败,存在重复定义的 CFBundleTypeName: "+s.CFBundleTypeName),!1;if(a.add(s.CFBundleTypeName),!t.includes(s.LSHandlerRank))return i.message("error","openMimeTypes 应用失败,存在不合法的 LSHandlerRank: "+s.LSHandlerRank),!1;if(!n.includes(s.CFBundleTypeRole))return i.message("error","openMimeTypes 应用失败,存在不合法的 CFBundleTypeRole: "+s.CFBundleTypeRole),!1;if(!Array.isArray(s.LSItemContentTypes))return i.message("error","openMimeTypes 应用失败,LSItemContentTypes 类型不合法"),!1}return!0}useGDT(e){return(0,miniappJson_1.iOSMiniAppJsonIsUsingGDT)(e)}async updateIOSAppConfigPlistInfo(e,i,t,n,a,s,o,r="Dark",l){var d,p,u,c;o.progress("update app module info...");const{module_info:f={},cpa_info:_={},cpa_package_info:h={enable_remove_watermark:!1}}=i;if(!_.sdk_key||!_.sdk_key_secret)throw new Error("sdkKey and sdkSecret not found");const g=path_1.default.join(t,"MiniApp.bundle"),m=path_1.default.join(g,"AppConfig.plist"),y=plist.readFileSync(m);h.enable_remove_watermark?y.enableRemoveWatermark=!0:y.splashscreenTheme=r,y.miniModuleId=f.module_id,y.sdkKey=_.sdk_key,y.sdkSecret=_.sdk_key_secret;const{privacy:I={}}=n;y.privacy||(y.privacy={}),y.privacy.enable=!!I.enable;const S=path_1.default.posix.join(g,"configs/privacy.json"),{contentViewImage:v,cancelButtonImage:x,confirmButtonImage:b,template:F}=I;if(I.enable){let i=F||"";if(fs_extra_1.default.ensureDirSync(path_1.default.posix.join(g,"configs")),i.startsWith("%")&&i.endsWith("%")){const t=F.slice(1,-1);i=(null===(p=null===(d=null==l?void 0:l.base)||void 0===d?void 0:d.ios)||void 0===p?void 0:p[t])||"",i||o.message("error",`未在国际化配置 base.json 中找到字段 ${t},请检查`),Object.keys(l).forEach(i=>{var n,a;if("base"===i)return;let s=null===(a=null===(n=l[i])||void 0===n?void 0:n.ios)||void 0===a?void 0:a[t];if(s){s=this.getMaterialFilePath(e,s);const t=`configs/privacy-${i}.json`,n=path_1.default.posix.join(g,t);fs_extra_1.default.existsSync(s)?fs_extra_1.default.copyFileSync(s,n):o.message("error",`未找到隐私协议在国际化配置 ${i}.json 中配置的文件 ${s},请检查`)}})}i?(i=this.getMaterialFilePath(e,i),fs_extra_1.default.existsSync(i)?(fs_extra_1.default.copyFileSync(i,S),y.privacy.template="configs/privacy.json"):(o.message("error",`未找到隐私协议中配置的文件 ${i},请检查`),y.privacy.template="configs/defaultPrivacy.json")):y.privacy.template="configs/defaultPrivacy.json",!0===I.enableNativePlugin&&"string"==typeof I.nativePluginId&&I.nativePluginId.length>2&&(y.privacy.plugin={pluginId:I.nativePluginId,enable:!0})}else y.privacy.template="",fs_extra_1.default.removeSync(S);this.updatePrivacyBackgroundImage(e,t,o,"contentViewImage",v),this.updatePrivacyBackgroundImage(e,t,o,"confirmButtonImage",b),this.updatePrivacyBackgroundImage(e,t,o,"cancelButtonImage",x);const{appMenuEnable:P=!0}=n;y.appMenuEnable=P;const{enableVConsole:j="undefined"}=n;y.enableVConsole=j;const{tpush:B}=n;let C=!1;if("object"==typeof B){const e=path_1.default.posix.join(t,"PlugIns/TPNSService.appex"),i=path_1.default.posix.join(e,"AppConfig.plist");if(this.useTpush(n)){y.TPNSAccessID=B.accessID,y.TPNSAccessKey=B.accessKey,B.clusterDomainName?y.clusterDomainName=B.clusterDomainName:delete y.clusterDomainName;const t=s?"x86_64":"arm64",n=path_1.default.join(a,`appex/${t}/TPNSService.appex`);if(!fs_extra_1.default.existsSync(n))throw new Error("can not found extendsdk: "+n);try{fs_extra_1.default.copySync(n,e),plist.writeFileSync(i,y),C=!0}catch(e){throw new Error("copy TPNSService.appex to app failed: "+e)}}}if(!C)try{const e=path_1.default.posix.join(t,"PlugIns");fs_extra_1.default.existsSync(e)?(fs_extra_1.default.removeSync(e),o.progress("removed PlugIns folder...")):o.progress("no PlugIns folder...")}catch(e){throw new Error("remove TPNSService.appex from app failed: "+e)}if(null===(u=n.useExtendedSdk)||void 0===u?void 0:u.WeAppLBS){if(!n.qmapAPIKey)throw new Error("You need to provide the Tencent Location Service API Key when using LBS SDK.");y.qmapAPIKey=n.qmapAPIKey}const{gdt:L}=n,w=this.useGDT(n);if(y.GDTAd=w?{appid:L.appid,enable:!0,SplashAd:{placementId:L.splashAd_placementId,fetchDelay:L.splashAd_fetchDelay||3,defaultEnable:null===(c=L.splashAd_defaultEnable)||void 0===c||c}}:{appid:"",enable:!1,SplashAd:{placementId:"",fetchDelay:3}},n["mini-plugin"]&&Array.isArray(n["mini-plugin"].ios)){const e=n["mini-plugin"].ios.filter(e=>!!(e.open&&e.pluginId&&e.loadWhenStart)).map(e=>e.pluginId);y.plugins={loadWhenStart:e}}const{enableDebugLog:D=!1}=n;y.enableDebugLog=D;const{debugLogSizeLimit:A=10}=n;isNaN(Number(A))?o.message("error",`ios debugLogSizeLimit ${A} is NaN`):y.debugLogSizeLimit=Number(A);const{enableOpenUrlNavigate:$=!1}=n;y.enableOpenUrlNavigate=$,plist.writeFileSync(m,y)}async updateIOSAppexInfoPlistInfo(e,i,t,n,a){if(this.useTpush(t)){a.progress("update appex for notification base info...");const{mobileapp_info:s={}}=e,o=path_1.default.join(i,"PlugIns/TPNSService.appex"),r=path_1.default.join(o,"Info.plist"),l=plist.readFileSync(r);l.CFBundleShortVersionString=t.version,a.progress("update appex for CFBundleVersion: "+n),l.CFBundleVersion=n;const d=s.ios_flag&&s.bundle_id||s.debug_ios_bundle_id;l.CFBundleIdentifier=t.tpush.serviceBundleId||d+".service",a.progress("update appex bundle identifier for infoPlist : "+l.CFBundleIdentifier),plist.writeFileSync(r,l)}else a.progress("not using tpush...")}updateBundleIcons(e,i,t,n,a){const s=[],o=[],r=[];for(const l in t){if(!t[l])continue;const d=this.getMaterialFilePath(e,t[l]);if(!d)return void a.message("error","getMatrialFailed: "+t[l]);const p=iconInfoMap[l];try{const e=sizeOf(d),i=p.size[0]*p.scale,n=p.size[1]*p.scale;if(e.width!==i||e.height!==n){a.progress(`check ${l} size failed, require [${i}, ${n}] but [${e.width}, ${e.height}] ingore ${t[l]} `);continue}}catch(e){a.progress(`get ${l} info failed, ingore ${t[l]}(e: ${e.message})`);continue}const u=path_1.default.extname(d),c=1===p.scale?"":`@${p.scale}x`,f=`${p.size[0]}x${p.size[1]}`,_=l.startsWith("ipad"),h="appStore1024"===l||"appStore1024Other"===l,g="appStore1024Other"===l?n+"Other":n,m=path_1.default.join(i,`${g}${f}${c}${_?"~ipad":""}${u}`),y={from:d,to:m,filename:path_1.default.basename(m),size:f,scale:p.scale+"x",idiom:p.idiom,key:l};s.push(y),h||(_?r.includes(`${g}${f}`)||r.push(`${g}${f}${c}`):o.includes(`${g}${f}`)||o.push(`${g}${f}${c}`))}return{iphoneBundleIconFiles:o,ipadBundleIconFiles:r,addFiles:s}}async updateIOSIcons(e,i,t,n,a,s){s.progress("update app icons...");const{icons:o={}}=n,r=a&&!env_1.isWin&&!!t;s.progress("genAssetCar: "+r);const l=glob_1.default.sync("AppIcon*.+(png|jpg|jpeg|webp)",{nodir:!0,cwd:i}).map(e=>path_1.default.join(i,e)),d="AppIcon-"+uuidv4().slice(0,8),p=this.updateBundleIcons(e,i,o,d,s);if(!p)throw new Error("updateBundleIcons failed");const{iphoneBundleIconFiles:u=[],ipadBundleIconFiles:c=[],addFiles:f=[]}=p,_={};for(const e in iconInfoMap){if(!iconInfoMap[e].required||o[e])continue;const i=iconInfoMap[e].size[0]*iconInfoMap[e].scale,t=iconInfoMap[e].size[1]*iconInfoMap[e].scale;if(_[e]=path_1.default.join(defaultIconDirPath,`donut-icon${i}x${t}.png`),s.progress(`using default app icons when ${e} is not config...`),!fs_extra_1.default.existsSync(_[e]))throw new Error(`required ${e} but not default or set`)}const h=this.updateBundleIcons(e,i,_,d,s);if(!h)throw new Error("updateBundleIcons WithDefaultIcon failed");const{iphoneBundleIconFiles:g,ipadBundleIconFiles:m,addFiles:y}=h;if(u.push(...g),c.push(...m),f.push(...y),!u.length&&!c.length)return;l.forEach(e=>{fs_extra_1.default.existsSync(e)&&fs_extra_1.default.removeSync(e)});const I=path_1.default.join(t,"__assetCarOperateDir/assetsCar/"),S=path_1.default.join(I,`Assets.xcassets/${d}.appiconset/`);r&&(fs_extra_1.default.ensureDirSync(S),fs_extra_1.default.emptyDirSync(S));const v=[];let x=!1;if(f.forEach(e=>{fs_extra_1.default.existsSync(e.to)&&fs_extra_1.default.removeSync(e.to),fs_extra_1.default.copyFileSync(e.from,e.to),r&&(fs_extra_1.default.copySync(e.from,path_1.default.join(S,e.filename)),"ios-marketing-other"===e.idiom&&(x=!0),v.push({filename:e.filename,size:e.size,scale:e.scale,idiom:e.idiom}))}),r&&fs_extra_1.default.writeJsonSync(path_1.default.join(S,"Contents.json"),{images:v,info:{author:"xcode",version:1}},{spaces:"\t"}),r){const e=path_1.default.join(__dirname,"../../../static/scripts/assetsCar/"),t=path_1.default.join(I,"createAssetsCar");fs_extra_1.default.copySync(e,I);try{await(0,codesign_1.checkXcodeEnv)(s),child_process.execSync(`"${t}" ${d}`,{env:(0,env_1.getProcessEnv)()})}catch(e){s.progress("createAssetsCar failed "+(e.message||""))}const n=path_1.default.join(I,"build/Assets.car"),a=path_1.default.join(i,"Assets.car");fs_extra_1.default.copyFileSync(n,a)}else{const e=path_1.default.join(i,"Assets.car");fs_extra_1.default.removeSync(e)}const b=path_1.default.join(i,"Info.plist"),F=plist.readFileSync(b);if(!F.CFBundleIcons){const e={CFBundlePrimaryIcon:{}};F.CFBundleIcons=e}x&&(F.CFBundleIcons.CFBundleAlternateIcons={OtherAppStoreIcon:{CFBundleIconFiles:[d+"Other"],CFBundleIconName:"OtherAppStoreIcon"}}),F.CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconName=d,F.CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles=u,F["CFBundleIcons~ipad"]||(F["CFBundleIcons~ipad"]={CFBundlePrimaryIcon:{}}),F["CFBundleIcons~ipad"].CFBundlePrimaryIcon.CFBundleIconName=d,F["CFBundleIcons~ipad"].CFBundlePrimaryIcon.CFBundleIconFiles=c,F.NSAppTransportSecurity={NSAllowsArbitraryLoads:!0},plist.writeFileSync(b,F)}replaceLaunchScreenImage(e,i,t,n,a,s){const o=path_1.default.join(e,"01J-lp-oVM-view-Ze5-6b-2t3.nib");let r=fs_extra_1.default.readFileSync(o).toString("hex");if(!i.endsWith(".png"))return void n.message("error","IOS 启动页图片配置格式错误,必须为 PNG 格式, 错误配置:"+i);const l=this.getMaterialFilePath(a,i),d=t+".png",p="LaunchScreen-"+uuidv4().slice(0,12),u=p+".png",c=path_1.default.join(s,u);fs_extra_1.default.copyFileSync(l,c);const f=Buffer.from(d,"utf-8").toString("hex"),_=Buffer.from(u,"utf-8").toString("hex");return-1!==r.indexOf(f)?(r=r.replace(f,_),console.log("replace storyboard customImage success")):console.log("replace storyboard customImage fail"),fs_extra_1.default.writeFileSync(o,Buffer.from(r,"hex")),p}async updateSplashScreen(e,i,t,n,a="Dark",s){var o,r,l;let d;n.progress("update splashscreen image..."),allowTheme.includes(a)&&(d=path_1.default.join(i,`/Base.lproj/LaunchScreen${a}.storyboardc`)),d&&fs_extra_1.default.existsSync(d)&&fs_extra_1.default.copySync(d,path_1.default.join(i,"/Base.lproj/LaunchScreen.storyboardc")),allowTheme.forEach(e=>{const t=path_1.default.join(i,`/Base.lproj/LaunchScreen${e}.storyboardc`);fs_extra_1.default.existsSync(t)&&fs_extra_1.default.removeSync(t)});let p=null===(o=null==t?void 0:t.splashscreen)||void 0===o?void 0:o.customImage;if(!p)return;const u=path_1.default.join(i,"Info.plist"),c=plist.readFileSync(u),f=c.UISplashScreenImageName;if(glob_1.default.sync("LaunchScreen-*.+(png|jpg|jpeg|webp)",{nodir:!0,cwd:i}).forEach(e=>{const t=path_1.default.join(i,e);fs_extra_1.default.removeSync(t)}),p.startsWith("%")&&(null==p?void 0:p.endsWith("%"))){const t=p.slice(1,-1),a=(null===(l=null===(r=null==s?void 0:s.base)||void 0===r?void 0:r.ios)||void 0===l?void 0:l[t])||"";if(!a)return void n.message("error",`未在国际化配置 base.json 中找到字段 ${t},请检查,启动页国际化配置失败`);p=a,Object.keys(s).forEach(a=>{var o,r;if("base"===a)return;const l=null===(r=null===(o=s[a])||void 0===o?void 0:o.ios)||void 0===r?void 0:r[t];if(l){const t=path_1.default.join(i,`/${a}.lproj/LaunchScreen_${a}.storyboardc`);fs_extra_1.default.ensureDirSync(path_1.default.join(t,"..")),fs_extra_1.default.copySync(path_1.default.join(i,"/Base.lproj/LaunchScreen.storyboardc"),t);const s=this.replaceLaunchScreenImage(t,this.getMaterialFilePath(e,l),f,n,e,i);n.progress(`update ${a} splashscreen image...`);const o=fs_extra_1.default.readFileSync(path_1.default.join(i,a+".lproj/InfoPlist.strings"),"utf8");let r="";r=s?o.replace("__UISplashScreenImageName__",`UISplashScreenImageName = "${s}";\n`).replace("__UILaunchStoryboardName__",`UILaunchStoryboardName = "LaunchScreen_${a}";\n`):o.replace("__UISplashScreenImageName__","").replace("__UILaunchStoryboardName__",""),fs_extra_1.default.writeFileSync(path_1.default.join(i,a+".lproj/InfoPlist.strings"),r),n.progress(`update ${a} splashscreen image success`)}})}n.progress("update base splashscreen image...");const _=this.replaceLaunchScreenImage(path_1.default.join(i,"/Base.lproj/LaunchScreen.storyboardc"),this.getMaterialFilePath(e,p),f,n,e,i);n.progress("update base splashscreen image success"),_&&(c.UISplashScreenImageName=_,c.UILaunchStoryboardName="LaunchScreen",plist.writeFileSync(u,c))}genUseExtendedSdk(e,i){const t=Object.assign({},e.useExtendedSdk||{});for(const i in e)if("object"==typeof e[i])for(const n in e[i])if(n.startsWith("useExtendedLib_WeApp")&&!0===e[i][n]){t[n.slice("useExtendedLib_".length)]=!0}return!t.WeAppLBS||t.WeAppOpenFuns||t.WeAppOpenFuns_HasPay||(t.WeAppOpenFuns=!0),"RemoteDebug"===(null==i?void 0:i.debugType)&&(t.WeAppUSB=!0),t}async updateExtendedSdk(e,i,t,n,a,s,o){const r=path_1.default.join(i,"Frameworks");fs_extra_1.default.ensureDirSync(r),o.progress("update extendsdk...");const l=path_1.default.join(t,"WeAppSDK.podspec"),d=fs_extra_1.default.readFileSync(l,"utf-8"),p=this.genUseExtendedSdk(a,s);o.progress("useExtendedSdks: "+JSON.stringify(p));const{mobileapp_info:u={}}=e,c=this.getBundleIdentifier(u);if(p.WeAppOpenFuns&&p.WeAppOpenFuns_HasPay)throw new Error("OpenFuncs SDK 只可勾选使用一个,请按需勾选使用");const f={};for(const e in p){if(!p[e])continue;const i=getDepReg(e),a=d.match(i);if(!(null==a?void 0:a[1])){if("WeAppUSB"===e)continue;throw new Error(`拓展模块 ${e} 不存在或已被移除,请检查 project.miniapp.json -> 对应平台 -> useExtendedSdk 删除配置 ${e},版本配置差异请参考更新日志或 https://dev.weixin.qq.com/docs/framework/dev/sdk/difflog.html`)}const s=[];if(a[1].split("\n").forEach(e=>{const i=e.match(/.*'(.*?)',/);if(null==i?void 0:i[1]){const e=i[1].split("/").pop(),a=path_1.default.join(t,"Libs",n,e);if(!fs_extra_1.default.existsSync(a)){if("WeAppUSB.framework"===e)return;throw new Error(`拓展模块 ${e} 不存在或已被移除,请检查 project.miniapp.json -> 对应平台 -> useExtendedSdk 删除配置 ${e},版本配置差异请参考更新日志或 https://dev.weixin.qq.com/docs/framework/dev/sdk/difflog.html`)}const o=path_1.default.join(r,e);fs_extra_1.default.copySync(a,o),s.push(path_1.default.basename(e));const l=path_1.default.join(o,"info.plist");if(!fs_extra_1.default.existsSync(l))throw new Error("can not found extendsdk info.plist: "+e);this.changeExtendSDKInfoplistBundleId(l,c,e)}}),s.length){f[s.shift()]=s}}const _=path_1.default.join(i,"DyFrameworks.plist");fs_extra_1.default.existsSync(_)&&fs_extra_1.default.removeSync(_),plist.writeFileSync(_,f)}async updatePrivacyInfo(e,i,t){var n;const a=null===(n=null==i?void 0:i.privacy)||void 0===n?void 0:n.privacyInfo;a&&(a.endsWith("PrivacyInfo.xcprivacy")?fs_extra_1.default.existsSync(a)?(fs_extra_1.default.copySync(a,path_1.default.join(e,"/PrivacyInfo.xcprivacy")),t.progress("隐私清单文件替换成功")):t.message("error","隐私清单文件替换失败,文件不存在,将使用默认文件"):t.message("error","隐私清单文件替换失败,文件名必须为 PrivacyInfo.xcprivacy,将使用默认文件"))}async updatePlugin(e,i,t,n,a,s,o,r){const l={},d={},p=[];if(n["mini-plugin"]&&Array.isArray(n["mini-plugin"].ios)){n["mini-plugin"].ios.forEach(e=>{e.open&&e.pluginId?("string"==typeof e.resourcePath&&e.resourcePath.length>0&&(l[e.pluginId]=e.resourcePath),"object"==typeof e.resourceObjects&&Object.keys(e.resourceObjects).length>0&&(d[e.pluginId]=e.resourceObjects)):p.push(e.pluginId)})}if(p.length>0&&r.message("warn","下列插件未启用,请确认project.miniapp.json中的配置:"+p.join(", ")),!i.length)return;const u=path_1.default.join(e,"Frameworks"),c=path_1.default.join(e,"PlugIns");fs_extra_1.default.ensureDirSync(u),r.progress("update plugin...");const f=this.prepareAppexProfileConfig(i,n,t,a,s,o,n.version,r);if(!f)throw new Error("依赖的多端插件需要配置对应的profile");i.forEach(i=>{const{pluginId:n}=i,a=i.dir,s=n+".framework",o=path_1.default.join(u,s);if(-1!==a.indexOf("local-miniapp-plugin")){const e=fs_extra_1.default.statSync(a),{mtime:i}=e;r.progress(`${n}.framework 正在使用本地版本,修改时间为 ${i}`)}fs_extra_1.default.existsSync(o)&&fs_extra_1.default.removeSync(o);const p=path_1.default.join(a,s);if(fs_extra_1.default.existsSync(p)){fs_extra_1.default.copySync(p,o),this.copyResourcesToMainBundle(p,e),this.copyUserResourcePathIntoPlugins(n,t,l[n],d[n],path_1.default.join(o,"MiniPlugin.bundle"),r);fs_extra_1.default.readdirSync(a).forEach(i=>{if(i.endsWith(".appex")){const s=path_1.default.parse(i).name,o=f[s],p=path_1.default.join(c,i);if(!o||!0!==o.enable)return;r.progress(`${n} 插件使用 appex 中 : ${i}`),fs_extra_1.default.existsSync(p)&&fs_extra_1.default.removeSync(p),fs_extra_1.default.ensureDirSync(p);const u=path_1.default.join(a,i);fs_extra_1.default.copySync(u,p),(null==o?void 0:o.profilePath)&&fs_extra_1.default.copySync(o.profilePath,path_1.default.join(p,"embedded.mobileprovision")),this.copyResourcesToMainBundle(u,e),this.copyUserResourcePathIntoPlugins(n,t,l[n],d[n],path_1.default.join(p,"MiniPlugin.bundle"),r)}else if(i.endsWith("framework")&&i!==s){const e=path_1.default.join(u,i),t=path_1.default.join(a,i);fs_extra_1.default.existsSync(e)&&fs_extra_1.default.removeSync(e),fs_extra_1.default.copySync(t,e)}})}else fs_extra_1.default.copySync(a,o),this.copyResourcesToMainBundle(a,e),this.copyUserResourcePathIntoPlugins(n,t,l[n],d[n],path_1.default.join(o,"MiniPlugin.bundle"),r)})}copyUserResourcePathIntoPlugins(e,i,t,n,a,s){const o=a;if(t){const n=path_1.default.basename(t),a=this.getMaterialFilePath(i,t);if(a){s.progress(`${e}.framework 正在拷贝配置的资源:${t}`);const i=fs_extra_1.default.lstatSync(a);fs_extra_1.default.ensureDirSync(o),i.isDirectory()?fs_extra_1.default.copySync(a,o):i.isFile()&&fs_extra_1.default.copyFileSync(a,path_1.default.join(o,n))}}if(n){s.progress(e+".framework 正在写入配置的资源"),fs_extra_1.default.ensureDirSync(o);for(const e in n){const i=n[e],t=path_1.default.join(o,e);fs_extra_1.default.ensureDirSync(o),fs_extra_1.default.ensureFileSync(t),fs_extra_1.default.writeFileSync(t,i)}}}copyResourcesToMainBundle(e,i){const t=path_1.default.join(e,"MiniPlugin.bundle"),n=path_1.default.join(t,"PluginConfig.plist");if(fs_extra_1.default.existsSync(n)){const e=plist.readFileSync(n).CopyResourcesToMainBundle;(null==e?void 0:e.length)&&e.forEach(e=>{const n=path_1.default.join(t,e);fs_extra_1.default.existsSync(n)&&fs_extra_1.default.copySync(n,path_1.default.join(i,e))})}}prepareAppexProfileConfig(e,i,t,n,a,s,o,r){if(!n)return void r.message("doing","miniappCacheDirPath is missing");let l=!1;const d={};if(i["mini-plugin"]&&Array.isArray(i["mini-plugin"].ios)){i["mini-plugin"].ios.forEach(e=>{if(e.open&&e.pluginId&&"object"==typeof e.appexProfiles)for(const i in e.appexProfiles){r.message("doing",`检查插件 ${e.pluginId} ${i} appex 配置中 ...`);const n=e.appexProfiles[i];if(!0===n.enable){const s=`${e.pluginId}_${i}`;d[s]={enable:!0};let o=n.profilePath;if(a&&(o=n.distributeProfilePath),n.bundleID&&o){const a=path_1.default.join(t,o);fs_extra_1.default.existsSync(a)?(d[s].bundleID=n.bundleID,d[s].profilePath=path_1.default.join(t,o)):(l=!0,r.message("error",`${e.pluginId} 中 ${i} 的 profilePath 无法找到对应的文件:${a}(需要在小程序项目路径下,填入相对于项目根目录的路径)`))}else l=!0,r.message("error",`${e.pluginId}中${i} 是 无效的appexProfiles配置。需要配置 bundleID,profilePath,distributeProfilePath。profile 文件需要放置在小程序项目内,然后配置相对于小程序项目根目录的相对路径。分发证书构建的情况下, 一定需要配置distributeProfilePath。查看文档了解详情。`)}}})}if(e.forEach(e=>{fs_extra_1.default.readdirSync(e.dir).forEach(i=>{if(i.endsWith(".appex")){const t=path_1.default.parse(i).name,n=d[t];if(n&&!0===n.enable)if(n.bundleID&&n.profilePath){if(n.bundleID&&n.profilePath){const t=path_1.default.join(e.dir,i,"info.plist"),a=n.bundleID;this.changeInfoplistBundleId(t,a),this.changeInfoplistBundleVersion(t,s,o),r.message("doing",`${e.pluginId} ${i} ${a} ${t} 处理 appex bundle ID 中`)}}else l=!0,r.message("error",`${e.pluginId} 的 多端插件包含了${t.slice(e.pluginId.length+1)} 的 appex。开发者需要在project.miniapp.json 中 mini-plugin 配置下对应合理的 profile 文件。查看文档了解详情。`)}})}),l)return!1;if(!(0,lodash_1.isEmpty)(d)){const e=path_1.default.join(n,APPEX_PROFILES_MAPS_FILE);fs_extra_1.default.existsSync(e)&&fs_extra_1.default.removeSync(e),fs_extra_1.default.ensureFileSync(e);const i={};for(const e in d)i[e]={bundleID:d[e].bundleID,profilePath:d[e].profilePath};fs_extra_1.default.writeFileSync(e,JSON.stringify(i));const t=path_1.default.join(n,APPEX_PROFILES_MAPS_FOR_SHELL_FILE);fs_extra_1.default.existsSync(t)&&fs_extra_1.default.removeSync(t),fs_extra_1.default.ensureFileSync(t);const a=Object.keys(d).map(e=>{const i=d[e];return`pluginAppexName:${e};_;_;bundleID:${i.bundleID};_;_;profile:${i.profilePath}\n\n`}).join("");fs_extra_1.default.writeFileSync(t,a)}return d}changeExtendSDKInfoplistBundleId(e,i,t){const n=`${i}.${path_1.default.parse(t).name.replace(/_/g,"")}`;return this.changeInfoplistBundleId(e,n)}changeInfoplistBundleId(e,i){const t=plist.readFileSync(e);return t.CFBundleIdentifier=i,plist.writeFileSync(e,t),t.CFBundleIdentifier}changeInfoplistBundleVersion(e,i,t){const n=plist.readFileSync(e);return n.CFBundleVersion=i,n.CFBundleShortVersionString=t,plist.writeFileSync(e,n),n.CFBundleIdentifier}async getEntitlements(e,i,t,n){const{mobileapp_info:a={}}=e;let s=a.ios_universal_link||a.debug_ios_universal_link;if((s.startsWith("https://")||s.startsWith("http://"))&&(s=s.replace(/^http(s)?:\/\//g,"applinks:")),Array.isArray(t.__customAssociatedDomains)){const e=t.__customAssociatedDomains.filter(e=>"string"==typeof e&&e.length>0);if(e.length>0){e.splice(0,0,s);return{"com.apple.developer.associated-domains":e.join("_$_ULinK_$_")}}}return{"com.apple.developer.associated-domains":s}}useTpush(e){return(0,miniappJson_1.iOSMiniAppJsonIsUsingTpush)(e)}async buildCloud(e,i){const{projectPath:t,demoIpaPath:n,sdkPath:a,arch:s="arm64",bindingInfo:o,certificateInfo:r,output:l,miniappCacheDirPath:d,pluginDirList:p,inLandun:u,theme:c,i18nInfo:f,debugInfo:_,CILocalBuild:h}=e,g=this.generateTempDemoIpaPath(n),{selfCertificate:m={}}=r,y=(null==m?void 0:m.isPublish)||!1,I=(0,miniappJson_1.tryGetIOSMiniappJson)(t),S=this.useTpush(I);if((0,lodash_1.isEmpty)(I))throw new Error("获取project.miniapp.json失败");if(errorIOSSdkVersions.includes(I.sdkVersion))throw new Error("当前 mini-ios.sdkVersion 存在缺陷,请参考更新日志进行修改");let v=o;if(r.signType===miniapp_builder_1.miniappSinTypes.appleId.type){const{mobileapp_info:e={}}=v;v=Object.assign(Object.assign({},v),{mobileapp_info:Object.assign(Object.assign({},e),{bundle_id:miniapp_builder_1.DEFAULT_BUNDLE_ID,debug_ios_bundle_id:miniapp_builder_1.DEFAULT_BUNDLE_ID})})}const x=await this.updateIOSInfoPlistInfo(t,v,g,I,i,f);await this.updateIOSAppConfigPlistInfo(t,v,g,I,a,!1,i,c,f),await this.updateIOSAppexInfoPlistInfo(v,g,I,x,i),await this.updateIOSIcons(t,g,d,I,y,i),await this.updateSplashScreen(t,g,I,i,c,f),await this.updateExtendedSdk(v,g,a,s,I,_,i),await this.updatePlugin(g,p,t,I,d,y,x,i),await this.updatePrivacyInfo(g,I,i);const b=await this.getEntitlements(v,g,I,i),{mobileapp_info:F={}}=v;let P;P=r.signType===miniapp_builder_1.miniappSinTypes.appleId.type?miniapp_builder_1.DEFAULT_BUNDLE_ID:F.ios_flag&&F.bundle_id||F.debug_ios_bundle_id;const j={bundleId:P,output:l,entitlements:b};if(I.buildCloud&&(I.buildCloud.certificate&&"string"==typeof I.buildCloud.certificate&&(j.certificate=I.buildCloud.certificate),I.buildCloud.profile&&"string"==typeof I.buildCloud.profile&&(j.profile=path_1.default.join(t,I.buildCloud.profile)),S&&I.buildCloud.tpnsProfile&&"string"==typeof I.buildCloud.tpnsProfile&&(j.tpnsProfile=path_1.default.join(t,I.buildCloud.tpnsProfile))),h&&(j.profile=m.profilePath,j.certificate=m.certificateName),m.isPublish||h){const e=await(0,codesign_1.codesignAndExport)(t,g,d||"",j,i,S,!0===u);if(!0!==e.success)throw new Error("Build ipa failed:"+(e.errMsg||"codesignAndExport failed"))}return{projectPath:t,demoIpaPath:g,opts:j,iosMiniappJson:I,isPublish:y}}async writeI18NInfoFile(e,i,t){Object.keys(i).forEach(n=>{if("base"===n)return;let a="";Object.keys(t).forEach(e=>{var s,o,r,l;"UISplashScreenImageName"!==e?"UILaunchStoryboardName"!==e?(null===(o=null===(s=i[n])||void 0===s?void 0:s.ios)||void 0===o?void 0:o[t[e]])&&(a+=`${e} = "${null===(l=null===(r=i[n])||void 0===r?void 0:r.ios)||void 0===l?void 0:l[t[e]]}";\n`):a+="__UILaunchStoryboardName__\n":a+="__UISplashScreenImageName__\n"}),a&&(fs_extra_1.default.ensureDirSync(path_1.default.join(e,n+".lproj")),fs_extra_1.default.writeFileSync(path_1.default.join(e,n+".lproj/InfoPlist.strings"),a))})}getMaterialFilePath(e,i){if(!i)return"";let t=i;if(path_1.default.isAbsolute(i)||(t=path_1.default.join(e,i)),fs_extra_1.default.existsSync(t))return t;const n=(0,tools_1.generateMD5)(i),a=path_1.default.basename(i),s=path_1.default.join(e,exports.remoteBuildProjectMaterialAbsoluteCacheDir,`${n}_${a}`);return fs_extra_1.default.existsSync(s)?s:""}}exports.default=new buildCloudManager;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.remoteBuildProjectMaterialAbsoluteCacheDir=void 0;const tslib_1=require("tslib"),child_process=tslib_1.__importStar(require("child_process")),path_1=tslib_1.__importDefault(require("path")),fs_extra_1=tslib_1.__importDefault(require("fs-extra")),glob_1=tslib_1.__importDefault(require("glob")),env_1=require("../../../utils/env"),miniapp_builder_1=require("../../../utils/miniapp-builder"),codesign_1=require("../../../utils/codesign"),miniappJson_1=require("../../../utils/miniappJson"),lodash_1=require("lodash"),tools_1=require("../../../utils/tools"),uuidv4=require("uuid/v4"),sizeOf=require("image-size"),plist=require("simple-plist"),errorIOSSdkVersions=["1.0.19"],APPEX_PROFILES_MAPS_FILE="__appexProfilesCacheDir__/profilesMap.json",APPEX_PROFILES_MAPS_FOR_SHELL_FILE="__appexProfilesCacheDir__/profilesMapForShell.txt",defaultIconDirPath=path_1.default.join(__dirname,"../../../static/images/"),getDepReg=e=>new RegExp(`s.subspec '${e}'.*\n(?:.*\n)*?(?:.*sp.vendored_frameworks = \\[\n)((?:.*'.*?'.*\n)*?)(?:.*\\]\n)`,"m"),allowTheme=["Light","LightSpecial","Dark","DarkSpecial","Default"];exports.remoteBuildProjectMaterialAbsoluteCacheDir="__absoluteFile";const iconInfoMap={appStore1024:{size:[1024,1024],scale:1,idiom:"ios-marketing",required:!0},appStore1024Other:{size:[1024,1024],scale:1,idiom:"ios-marketing-other"},mainIcon120:{size:[60,60],scale:2,idiom:"iphone",required:!0},mainIcon180:{size:[60,60],scale:3,idiom:"iphone"},spotlightIcon80:{size:[40,40],scale:2,idiom:"iphone"},spotlightIcon120:{size:[40,40],scale:3,idiom:"iphone"},settingsIcon58:{size:[29,29],scale:2,idiom:"iphone"},settingsIcon87:{size:[29,29],scale:3,idiom:"iphone"},notificationIcon40:{size:[20,20],scale:2,idiom:"iphone"},notificationIcon60:{size:[20,20],scale:3,idiom:"iphone"},ipadMainIcon152:{size:[76,76],scale:2,idiom:"ipad"},ipadMainIcon167:{size:[83.5,83.5],scale:2,idiom:"ipad"},ipadSpotlightIcon40:{size:[40,40],scale:1,idiom:"ipad"},ipadSpotlightIcon80:{size:[40,40],scale:2,idiom:"ipad"},ipadSettingsIcon29:{size:[29,29],scale:1,idiom:"ipad"},ipadSpotlightIcon58:{size:[29,29],scale:2,idiom:"ipad"},ipadNotificationIcon20:{size:[20,20],scale:1,idiom:"ipad"},ipadNotificationIcon40:{size:[20,20],scale:2,idiom:"ipad"}};class buildCloudManager{generateTempDemoIpaPath(e){const i=path_1.default.join(e,"../.."),n=path_1.default.basename(i),t=path_1.default.dirname(i),a=path_1.default.join(t,n+"-operateDir");fs_extra_1.default.existsSync(a)&&fs_extra_1.default.removeSync(a),fs_extra_1.default.ensureDirSync(a);const s=path_1.default.join(a,"Payload/demo.app");return fs_extra_1.default.copySync(e,s),s}generateInfoPlistCFBundleURLTypesItem(e){const i={};return e.CFBundleURLName&&(i.CFBundleURLName=e.CFBundleURLName),e.CFBundleURLSchemes&&(i.CFBundleURLSchemes=[e.CFBundleURLSchemes]),e.CFBundleTypeRole&&(i.CFBundleTypeRole=e.CFBundleTypeRole),i}updatePrivacyBackgroundImage(e,i,n,t,a){n.message("doing","updatePrivacyBackgroundImage "+t);if(fs_extra_1.default.readdirSync(i).forEach(e=>{"privacy_"+t===path_1.default.basename(e,path_1.default.extname(e))&&fs_extra_1.default.removeSync(path_1.default.join(i,e))}),!a)return;path_1.default.isAbsolute(a)||(a=path_1.default.join(e,a)),a=this.getMaterialFilePath(e,a);const s=path_1.default.extname(a),o=path_1.default.join(i,`privacy_${t}${s}`);try{fs_extra_1.default.copyFileSync(a,o)}catch(e){throw n.message("error",`copy privacy image failed: ${t}, ${a} to ${o}`),e}}async updateIOSInfoPlistInfo(e,i,n,t,a,s){var o,r,l,d,p,u,c,f,_,h,g;a.progress("update app base info...");const{mobileapp_info:m={}}=i,y=m.mobileapp_id,I=path_1.default.join(n,"Info.plist"),S={},v=(e,i)=>{var n,t;if((null==i?void 0:i.startsWith("%"))&&(null==i?void 0:i.endsWith("%"))){const o=i.slice(1,-1);S[e]=o;const r=(null===(t=null===(n=null==s?void 0:s.base)||void 0===n?void 0:n.ios)||void 0===t?void 0:t[o])||"";return r||a.message("error",`未在国际化配置 base.json 中找到字段 ${o},请检查`),r}return i};v("UISplashScreenImageName",null===(o=null==t?void 0:t.splashscreen)||void 0===o?void 0:o.customImage),v("UILaunchStoryboardName",null===(r=null==t?void 0:t.splashscreen)||void 0===r?void 0:r.customImage);const x=plist.readFileSync(I);if(x.CFBundleName=v("CFBundleName",t.name),x.CFBundleDisplayName=v("CFBundleDisplayName",t.name),x.CFBundleShortVersionString=t.version,"number"==typeof t.versionCode?x.CFBundleVersion=parseInt(t.versionCode.toString(),10).toString():x.CFBundleVersion=(parseInt(x.CFBundleVersion,10)+1).toString(),x.CFBundleIdentifier=this.getBundleIdentifier(m),Array.isArray(null==t?void 0:t.openMimeTypes)&&this.validateCFBundleDocumentTypes(t.openMimeTypes,a)&&(x.CFBundleDocumentTypes=t.openMimeTypes,a.message("doing","openMimeTypes 应用成功")),Array.isArray(x.CFBundleURLTypes)||(x.CFBundleURLTypes=[]),(null===(d=null===(l=x.CFBundleURLTypes)||void 0===l?void 0:l[0])||void 0===d?void 0:d.CFBundleURLSchemes)&&(x.CFBundleURLTypes[0].CFBundleURLSchemes=[y]),x.CFBundleURLTypes[0]&&(x.CFBundleURLTypes=[x.CFBundleURLTypes[0]]),Object.keys(miniappJson_1.iosPrivacyDescObj).forEach(e=>{var i,n;(null===(i=null==t?void 0:t.privateDescriptions)||void 0===i?void 0:i[e])?x[e]=v(e,null===(n=t.privateDescriptions)||void 0===n?void 0:n[e]):delete x[e]}),!0===(null===(p=null==t?void 0:t.infoPlist)||void 0===p?void 0:p.DisableAppUsesNonExemptEncryption)?x.ITSAppUsesNonExemptEncryption=!1:delete x.ITSAppUsesNonExemptEncryption,x.UIBackgroundModes=[],!0===(null===(u=null==t?void 0:t.infoPlist)||void 0===u?void 0:u.AudioInBackgroundMode)&&x.UIBackgroundModes.push("audio"),!0===(null===(c=null==t?void 0:t.infoPlist)||void 0===c?void 0:c.LocationInBackgroundMode)&&x.UIBackgroundModes.push("location"),!0===(null===(f=null==t?void 0:t.infoPlist)||void 0===f?void 0:f.requiresFullScreen)?x.UIRequiresFullScreen=!0:delete x.UIRequiresFullScreen,"object"==typeof(null===(_=null==t?void 0:t.infoPlist)||void 0===_?void 0:_.CFBundleURLTypes)){const e=this.generateInfoPlistCFBundleURLTypesItem(t.infoPlist.CFBundleURLTypes);x.CFBundleURLTypes.push(e);const{additionalCFBundleURLTypes:i}=t.infoPlist.CFBundleURLTypes;Array.isArray(i)&&i.forEach(e=>{if("object"==typeof e){const i=this.generateInfoPlistCFBundleURLTypesItem(e);x.CFBundleURLTypes.push(i)}})}if(null===(h=null==t?void 0:t.useExtendedSdk)||void 0===h?void 0:h.WeAppGoogleLogin){if(!(null==t?void 0:t.googleLoginClientID)||!(null==t?void 0:t.googleLoginBundleUrlType))throw new Error("勾选了 Google Login 拓展模块但未填写 googleLoginClientID 或 googleLoginBundleUrlType 将导致拓展模块无法使用");x.GIDClientID=t.googleLoginClientID,Array.isArray(x.CFBundleURLTypes)?x.CFBundleURLTypes.push({CFBundleURLSchemes:[t.googleLoginBundleUrlType]}):x.CFBundleURLTypes=[{CFBundleURLSchemes:[t.googleLoginBundleUrlType]}]}if(!0===t.enableIpad&&((0,miniappJson_1.iOSAppJsonIsUsingIPadResizable)(e)?(x["UISupportedInterfaceOrientations~ipad"]=["UIInterfaceOrientationPortrait","UIInterfaceOrientationPortraitUpsideDown","UIInterfaceOrientationLandscapeLeft","UIInterfaceOrientationLandscapeRight"],a.progress("ipad is support Landscape")):(x["UISupportedInterfaceOrientations~ipad"]=["UIInterfaceOrientationPortrait","UIInterfaceOrientationPortraitUpsideDown"],a.progress("ipad is not support Landscape"))),null===(g=t.infoPlist)||void 0===g?void 0:g.LSApplicationQueriesSchemes){const e=t.infoPlist.LSApplicationQueriesSchemes.split(",");e.length&&x.LSApplicationQueriesSchemes.push(...e.filter(e=>e))}return plist.writeFileSync(I,x),await this.writeI18NInfoFile(n,s,S),x.CFBundleVersion}getBundleIdentifier(e){return e.ios_flag&&e.bundle_id||e.debug_ios_bundle_id}validateCFBundleDocumentTypes(e,i){const n=["Owner","Default"," Alternate","None"],t=["Editor","Viewer"," Shell","None"],a=new Set;for(const s of e){if(a.has(s.CFBundleTypeName))return i.message("error","openMimeTypes 应用失败,存在重复定义的 CFBundleTypeName: "+s.CFBundleTypeName),!1;if(a.add(s.CFBundleTypeName),!n.includes(s.LSHandlerRank))return i.message("error","openMimeTypes 应用失败,存在不合法的 LSHandlerRank: "+s.LSHandlerRank),!1;if(!t.includes(s.CFBundleTypeRole))return i.message("error","openMimeTypes 应用失败,存在不合法的 CFBundleTypeRole: "+s.CFBundleTypeRole),!1;if(!Array.isArray(s.LSItemContentTypes))return i.message("error","openMimeTypes 应用失败,LSItemContentTypes 类型不合法"),!1}return!0}useGDT(e){return(0,miniappJson_1.iOSMiniAppJsonIsUsingGDT)(e)}async updateIOSAppConfigPlistInfo(e,i,n,t,a,s,o,r="Dark",l){var d,p,u,c;o.progress("update app module info...");const{module_info:f={},cpa_info:_={},cpa_package_info:h={enable_remove_watermark:!1}}=i;if(!_.sdk_key||!_.sdk_key_secret)throw new Error("sdkKey and sdkSecret not found");const g=path_1.default.join(n,"MiniApp.bundle"),m=path_1.default.join(g,"AppConfig.plist"),y=plist.readFileSync(m);h.enable_remove_watermark?y.enableRemoveWatermark=!0:y.splashscreenTheme=r,y.miniModuleId=f.module_id,y.sdkKey=_.sdk_key,y.sdkSecret=_.sdk_key_secret;const{privacy:I={}}=t;y.privacy||(y.privacy={}),y.privacy.enable=!!I.enable;const S=path_1.default.posix.join(g,"configs/privacy.json"),{contentViewImage:v,cancelButtonImage:x,confirmButtonImage:b,template:F}=I;if(I.enable){let i=F||"";if(fs_extra_1.default.ensureDirSync(path_1.default.posix.join(g,"configs")),i.startsWith("%")&&i.endsWith("%")){const n=F.slice(1,-1);i=(null===(p=null===(d=null==l?void 0:l.base)||void 0===d?void 0:d.ios)||void 0===p?void 0:p[n])||"",i||o.message("error",`未在国际化配置 base.json 中找到字段 ${n},请检查`),Object.keys(l).forEach(i=>{var t,a;if("base"===i)return;let s=null===(a=null===(t=l[i])||void 0===t?void 0:t.ios)||void 0===a?void 0:a[n];if(s){s=this.getMaterialFilePath(e,s);const n=`configs/privacy-${i}.json`,t=path_1.default.posix.join(g,n);fs_extra_1.default.existsSync(s)?fs_extra_1.default.copyFileSync(s,t):o.message("error",`未找到隐私协议在国际化配置 ${i}.json 中配置的文件 ${s},请检查`)}})}i?(i=this.getMaterialFilePath(e,i),fs_extra_1.default.existsSync(i)?(fs_extra_1.default.copyFileSync(i,S),y.privacy.template="configs/privacy.json"):(o.message("error",`未找到隐私协议中配置的文件 ${i},请检查`),y.privacy.template="configs/defaultPrivacy.json")):y.privacy.template="configs/defaultPrivacy.json",!0===I.enableNativePlugin&&"string"==typeof I.nativePluginId&&I.nativePluginId.length>2&&(y.privacy.plugin={pluginId:I.nativePluginId,enable:!0})}else y.privacy.template="",fs_extra_1.default.removeSync(S);this.updatePrivacyBackgroundImage(e,n,o,"contentViewImage",v),this.updatePrivacyBackgroundImage(e,n,o,"confirmButtonImage",b),this.updatePrivacyBackgroundImage(e,n,o,"cancelButtonImage",x);const{appMenuEnable:P=!0}=t;y.appMenuEnable=P;const{enableVConsole:B="undefined"}=t;y.enableVConsole=B;const{tpush:j}=t;let C=!1;if("object"==typeof j){const e=path_1.default.posix.join(n,"PlugIns/TPNSService.appex"),i=path_1.default.posix.join(e,"AppConfig.plist");if(this.useTpush(t)){y.TPNSAccessID=j.accessID,y.TPNSAccessKey=j.accessKey,j.clusterDomainName?y.clusterDomainName=j.clusterDomainName:delete y.clusterDomainName;const n=s?"x86_64":"arm64",t=path_1.default.join(a,`appex/${n}/TPNSService.appex`);if(!fs_extra_1.default.existsSync(t))throw new Error("can not found extendsdk: "+t);try{fs_extra_1.default.copySync(t,e),plist.writeFileSync(i,y),C=!0}catch(e){throw new Error("copy TPNSService.appex to app failed: "+e)}}}if(!C)try{const e=path_1.default.posix.join(n,"PlugIns");fs_extra_1.default.existsSync(e)?(fs_extra_1.default.removeSync(e),o.progress("removed PlugIns folder...")):o.progress("no PlugIns folder...")}catch(e){throw new Error("remove TPNSService.appex from app failed: "+e)}if(null===(u=t.useExtendedSdk)||void 0===u?void 0:u.WeAppLBS){if(!t.qmapAPIKey)throw new Error("You need to provide the Tencent Location Service API Key when using LBS SDK.");y.qmapAPIKey=t.qmapAPIKey}const{gdt:L}=t,w=this.useGDT(t);if(y.GDTAd=w?{appid:L.appid,enable:!0,SplashAd:{placementId:L.splashAd_placementId,fetchDelay:L.splashAd_fetchDelay||3,defaultEnable:null===(c=L.splashAd_defaultEnable)||void 0===c||c}}:{appid:"",enable:!1,SplashAd:{placementId:"",fetchDelay:3}},t["mini-plugin"]&&Array.isArray(t["mini-plugin"].ios)){const e=t["mini-plugin"].ios.filter(e=>!!(e.open&&e.pluginId&&e.loadWhenStart)).map(e=>e.pluginId);y.plugins={loadWhenStart:e}}const{enableDebugLog:D=!1}=t;y.enableDebugLog=D;const{debugLogSizeLimit:A=10}=t;isNaN(Number(A))?o.message("error",`ios debugLogSizeLimit ${A} is NaN`):y.debugLogSizeLimit=Number(A);const{enableOpenUrlNavigate:$=!1}=t;y.enableOpenUrlNavigate=$,plist.writeFileSync(m,y)}async updateIOSAppexInfoPlistInfo(e,i,n,t,a){if(this.useTpush(n)){a.progress("update appex for notification base info...");const{mobileapp_info:s={}}=e,o=path_1.default.join(i,"PlugIns/TPNSService.appex"),r=path_1.default.join(o,"Info.plist"),l=plist.readFileSync(r);l.CFBundleShortVersionString=n.version,a.progress("update appex for CFBundleVersion: "+t),l.CFBundleVersion=t;const d=s.ios_flag&&s.bundle_id||s.debug_ios_bundle_id;l.CFBundleIdentifier=n.tpush.serviceBundleId||d+".service",a.progress("update appex bundle identifier for infoPlist : "+l.CFBundleIdentifier),plist.writeFileSync(r,l)}else a.progress("not using tpush...")}updateBundleIcons(e,i,n,t,a){const s=[],o=[],r=[];for(const l in n){if(!n[l])continue;const d=this.getMaterialFilePath(e,n[l]);if(!d)return void a.message("error","getMatrialFailed: "+n[l]);const p=iconInfoMap[l];try{const e=sizeOf(d),i=p.size[0]*p.scale,t=p.size[1]*p.scale;if(e.width!==i||e.height!==t){a.progress(`check ${l} size failed, require [${i}, ${t}] but [${e.width}, ${e.height}] ingore ${n[l]} `);continue}}catch(e){a.progress(`get ${l} info failed, ingore ${n[l]}(e: ${e.message})`);continue}const u=path_1.default.extname(d),c=1===p.scale?"":`@${p.scale}x`,f=`${p.size[0]}x${p.size[1]}`,_=l.startsWith("ipad"),h="appStore1024"===l||"appStore1024Other"===l,g="appStore1024Other"===l?t+"Other":t,m=path_1.default.join(i,`${g}${f}${c}${_?"~ipad":""}${u}`),y={from:d,to:m,filename:path_1.default.basename(m),size:f,scale:p.scale+"x",idiom:p.idiom,key:l};s.push(y),h||(_?r.includes(`${g}${f}`)||r.push(`${g}${f}${c}`):o.includes(`${g}${f}`)||o.push(`${g}${f}${c}`))}return{iphoneBundleIconFiles:o,ipadBundleIconFiles:r,addFiles:s}}async updateIOSIcons(e,i,n,t,a,s){s.progress("update app icons...");const{icons:o={}}=t,r=a&&!env_1.isWin&&!!n;s.progress("genAssetCar: "+r);const l=glob_1.default.sync("AppIcon*.+(png|jpg|jpeg|webp)",{nodir:!0,cwd:i}).map(e=>path_1.default.join(i,e)),d="AppIcon-"+uuidv4().slice(0,8),p=this.updateBundleIcons(e,i,o,d,s);if(!p)throw new Error("updateBundleIcons failed");const{iphoneBundleIconFiles:u=[],ipadBundleIconFiles:c=[],addFiles:f=[]}=p,_={};for(const e in iconInfoMap){if(!iconInfoMap[e].required||o[e])continue;const i=iconInfoMap[e].size[0]*iconInfoMap[e].scale,n=iconInfoMap[e].size[1]*iconInfoMap[e].scale;if(_[e]=path_1.default.join(defaultIconDirPath,`donut-icon${i}x${n}.png`),s.progress(`using default app icons when ${e} is not config...`),!fs_extra_1.default.existsSync(_[e]))throw new Error(`required ${e} but not default or set`)}const h=this.updateBundleIcons(e,i,_,d,s);if(!h)throw new Error("updateBundleIcons WithDefaultIcon failed");const{iphoneBundleIconFiles:g,ipadBundleIconFiles:m,addFiles:y}=h;if(u.push(...g),c.push(...m),f.push(...y),!u.length&&!c.length)return;l.forEach(e=>{fs_extra_1.default.existsSync(e)&&fs_extra_1.default.removeSync(e)});const I=path_1.default.join(n,"__assetCarOperateDir/assetsCar/"),S=path_1.default.join(I,`Assets.xcassets/${d}.appiconset/`);r&&(fs_extra_1.default.ensureDirSync(S),fs_extra_1.default.emptyDirSync(S));const v=[];let x=!1;if(f.forEach(e=>{fs_extra_1.default.existsSync(e.to)&&fs_extra_1.default.removeSync(e.to),fs_extra_1.default.copyFileSync(e.from,e.to),r&&(fs_extra_1.default.copySync(e.from,path_1.default.join(S,e.filename)),"ios-marketing-other"===e.idiom&&(x=!0),v.push({filename:e.filename,size:e.size,scale:e.scale,idiom:e.idiom}))}),r&&fs_extra_1.default.writeJsonSync(path_1.default.join(S,"Contents.json"),{images:v,info:{author:"xcode",version:1}},{spaces:"\t"}),r){const e=path_1.default.join(__dirname,"../../../static/scripts/assetsCar/"),n=path_1.default.join(I,"createAssetsCar");fs_extra_1.default.copySync(e,I);try{await(0,codesign_1.checkXcodeEnv)(s),child_process.execSync(`"${n}" ${d}`,{env:(0,env_1.getProcessEnv)()})}catch(e){s.progress("createAssetsCar failed "+(e.message||""))}const t=path_1.default.join(I,"build/Assets.car"),a=path_1.default.join(i,"Assets.car");fs_extra_1.default.copyFileSync(t,a)}else{const e=path_1.default.join(i,"Assets.car");fs_extra_1.default.removeSync(e)}const b=path_1.default.join(i,"Info.plist"),F=plist.readFileSync(b);if(!F.CFBundleIcons){const e={CFBundlePrimaryIcon:{}};F.CFBundleIcons=e}x&&(F.CFBundleIcons.CFBundleAlternateIcons={OtherAppStoreIcon:{CFBundleIconFiles:[d+"Other"],CFBundleIconName:"OtherAppStoreIcon"}}),F.CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconName=d,F.CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles=u,F["CFBundleIcons~ipad"]||(F["CFBundleIcons~ipad"]={CFBundlePrimaryIcon:{}}),F["CFBundleIcons~ipad"].CFBundlePrimaryIcon.CFBundleIconName=d,F["CFBundleIcons~ipad"].CFBundlePrimaryIcon.CFBundleIconFiles=c,F.NSAppTransportSecurity={NSAllowsArbitraryLoads:!0},plist.writeFileSync(b,F)}replaceLaunchScreenImage(e,i,n,t,a,s){const o=path_1.default.join(e,"01J-lp-oVM-view-Ze5-6b-2t3.nib");let r=fs_extra_1.default.readFileSync(o).toString("hex");if(!i.endsWith(".png"))return void t.message("error","IOS 启动页图片配置格式错误,必须为 PNG 格式, 错误配置:"+i);const l=this.getMaterialFilePath(a,i),d=n+".png",p="LaunchScreen-"+uuidv4().slice(0,12),u=p+".png",c=path_1.default.join(s,u);fs_extra_1.default.copyFileSync(l,c);const f=Buffer.from(d,"utf-8").toString("hex"),_=Buffer.from(u,"utf-8").toString("hex");return-1!==r.indexOf(f)?(r=r.replace(f,_),console.log("replace storyboard customImage success")):console.log("replace storyboard customImage fail"),fs_extra_1.default.writeFileSync(o,Buffer.from(r,"hex")),p}async updateSplashScreen(e,i,n,t,a="Dark",s){var o,r,l;let d;t.progress("update splashscreen image..."),allowTheme.includes(a)&&(d=path_1.default.join(i,`/Base.lproj/LaunchScreen${a}.storyboardc`)),d&&fs_extra_1.default.existsSync(d)&&fs_extra_1.default.copySync(d,path_1.default.join(i,"/Base.lproj/LaunchScreen.storyboardc")),allowTheme.forEach(e=>{const n=path_1.default.join(i,`/Base.lproj/LaunchScreen${e}.storyboardc`);fs_extra_1.default.existsSync(n)&&fs_extra_1.default.removeSync(n)});let p=null===(o=null==n?void 0:n.splashscreen)||void 0===o?void 0:o.customImage;if(!p)return;const u=path_1.default.join(i,"Info.plist"),c=plist.readFileSync(u),f=c.UISplashScreenImageName;if(glob_1.default.sync("LaunchScreen-*.+(png|jpg|jpeg|webp)",{nodir:!0,cwd:i}).forEach(e=>{const n=path_1.default.join(i,e);fs_extra_1.default.removeSync(n)}),p.startsWith("%")&&(null==p?void 0:p.endsWith("%"))){const n=p.slice(1,-1),a=(null===(l=null===(r=null==s?void 0:s.base)||void 0===r?void 0:r.ios)||void 0===l?void 0:l[n])||"";if(!a)return void t.message("error",`未在国际化配置 base.json 中找到字段 ${n},请检查,启动页国际化配置失败`);p=a,Object.keys(s).forEach(a=>{var o,r;if("base"===a)return;const l=null===(r=null===(o=s[a])||void 0===o?void 0:o.ios)||void 0===r?void 0:r[n];if(l){const n=path_1.default.join(i,`/${a}.lproj/LaunchScreen_${a}.storyboardc`);fs_extra_1.default.ensureDirSync(path_1.default.join(n,"..")),fs_extra_1.default.copySync(path_1.default.join(i,"/Base.lproj/LaunchScreen.storyboardc"),n);const s=this.replaceLaunchScreenImage(n,this.getMaterialFilePath(e,l),f,t,e,i);t.progress(`update ${a} splashscreen image...`);const o=fs_extra_1.default.readFileSync(path_1.default.join(i,a+".lproj/InfoPlist.strings"),"utf8");let r="";r=s?o.replace("__UISplashScreenImageName__",`UISplashScreenImageName = "${s}";\n`).replace("__UILaunchStoryboardName__",`UILaunchStoryboardName = "LaunchScreen_${a}";\n`):o.replace("__UISplashScreenImageName__","").replace("__UILaunchStoryboardName__",""),fs_extra_1.default.writeFileSync(path_1.default.join(i,a+".lproj/InfoPlist.strings"),r),t.progress(`update ${a} splashscreen image success`)}})}t.progress("update base splashscreen image...");const _=this.replaceLaunchScreenImage(path_1.default.join(i,"/Base.lproj/LaunchScreen.storyboardc"),this.getMaterialFilePath(e,p),f,t,e,i);t.progress("update base splashscreen image success"),_&&(c.UISplashScreenImageName=_,c.UILaunchStoryboardName="LaunchScreen",plist.writeFileSync(u,c))}genUseExtendedSdk(e,i){const n=Object.assign({},e.useExtendedSdk||{});for(const i in e)if("object"==typeof e[i])for(const t in e[i])if(t.startsWith("useExtendedLib_WeApp")&&!0===e[i][t]){n[t.slice("useExtendedLib_".length)]=!0}return!n.WeAppLBS||n.WeAppOpenFuns||n.WeAppOpenFuns_HasPay||(n.WeAppOpenFuns=!0),"RemoteDebug"===(null==i?void 0:i.debugType)&&(n.WeAppUSB=!0),n}async updateExtendedSdk(e,i,n,t,a,s,o){const r=path_1.default.join(i,"Frameworks");fs_extra_1.default.ensureDirSync(r),o.progress("update extendsdk...");const l=path_1.default.join(n,"WeAppSDK.podspec"),d=fs_extra_1.default.readFileSync(l,"utf-8"),p=this.genUseExtendedSdk(a,s);o.progress("useExtendedSdks: "+JSON.stringify(p));const{mobileapp_info:u={}}=e,c=this.getBundleIdentifier(u);if(p.WeAppOpenFuns&&p.WeAppOpenFuns_HasPay)throw new Error("OpenFuncs SDK 只可勾选使用一个,请按需勾选使用");const f={};for(const e in p){if(!p[e])continue;const i=getDepReg(e),a=d.match(i);if(!(null==a?void 0:a[1])){if("WeAppUSB"===e)continue;throw new Error(`拓展模块 ${e} 不存在或已被移除,请检查 project.miniapp.json -> 对应平台 -> useExtendedSdk 删除配置 ${e},版本配置差异请参考更新日志或 https://dev.weixin.qq.com/docs/framework/dev/sdk/difflog.html`)}const s=[];if(a[1].split("\n").forEach(e=>{const i=e.match(/.*'(.*?)',/);if(null==i?void 0:i[1]){const e=i[1].split("/").pop(),a=path_1.default.join(n,"Libs",t,e);if(!fs_extra_1.default.existsSync(a)){if("WeAppUSB.framework"===e)return;throw new Error(`拓展模块 ${e} 不存在或已被移除,请检查 project.miniapp.json -> 对应平台 -> useExtendedSdk 删除配置 ${e},版本配置差异请参考更新日志或 https://dev.weixin.qq.com/docs/framework/dev/sdk/difflog.html`)}const o=path_1.default.join(r,e);fs_extra_1.default.copySync(a,o),s.push(path_1.default.basename(e));const l=path_1.default.join(o,"info.plist");if(!fs_extra_1.default.existsSync(l))throw new Error("can not found extendsdk info.plist: "+e);this.changeExtendSDKInfoplistBundleId(l,c,e)}}),s.length){f[s.shift()]=s}}const _=path_1.default.join(i,"DyFrameworks.plist");fs_extra_1.default.existsSync(_)&&fs_extra_1.default.removeSync(_),plist.writeFileSync(_,f)}async updatePrivacyInfo(e,i,n){var t;const a=null===(t=null==i?void 0:i.privacy)||void 0===t?void 0:t.privacyInfo;a&&(a.endsWith("PrivacyInfo.xcprivacy")?fs_extra_1.default.existsSync(a)?(fs_extra_1.default.copySync(a,path_1.default.join(e,"/PrivacyInfo.xcprivacy")),n.progress("隐私清单文件替换成功")):n.message("error","隐私清单文件替换失败,文件不存在,将使用默认文件"):n.message("error","隐私清单文件替换失败,文件名必须为 PrivacyInfo.xcprivacy,将使用默认文件"))}async updatePlugin(e,i,n,t,a,s,o,r){const l={},d={},p=[];if(t["mini-plugin"]&&Array.isArray(t["mini-plugin"].ios)){t["mini-plugin"].ios.forEach(e=>{e.open&&e.pluginId?("string"==typeof e.resourcePath&&e.resourcePath.length>0&&(l[e.pluginId]=e.resourcePath),"object"==typeof e.resourceObjects&&Object.keys(e.resourceObjects).length>0&&(d[e.pluginId]=e.resourceObjects)):p.push(e.pluginId)})}if(p.length>0&&r.message("warn","下列插件未启用,请确认project.miniapp.json中的配置:"+p.join(", ")),!i.length)return;const u=path_1.default.join(e,"Frameworks"),c=path_1.default.join(e,"PlugIns");fs_extra_1.default.ensureDirSync(u),r.progress("update plugin...");const f=this.prepareAppexProfileConfig(i,t,n,a,s,o,t.version,r);if(!f)throw new Error("依赖的多端插件需要配置对应的profile");i.forEach(i=>{const{pluginId:t}=i,a=i.dir,s=t+".framework",o=path_1.default.join(u,s);if(-1!==a.indexOf("local-miniapp-plugin")){const e=fs_extra_1.default.statSync(a),{mtime:i}=e;r.progress(`${t}.framework 正在使用本地版本,修改时间为 ${i}`)}fs_extra_1.default.existsSync(o)&&fs_extra_1.default.removeSync(o);const p=path_1.default.join(a,s);if(fs_extra_1.default.existsSync(p)){fs_extra_1.default.copySync(p,o),this.copyResourcesToMainBundle(p,e),this.copyUserResourcePathIntoPlugins(t,n,l[t],d[t],path_1.default.join(o,"MiniPlugin.bundle"),r);fs_extra_1.default.readdirSync(a).forEach(i=>{if(i.endsWith(".appex")){const s=path_1.default.parse(i).name,o=f[s],p=path_1.default.join(c,i);if(!o||!0!==o.enable)return;r.progress(`${t} 插件使用 appex 中 : ${i}`),fs_extra_1.default.existsSync(p)&&fs_extra_1.default.removeSync(p),fs_extra_1.default.ensureDirSync(p);const u=path_1.default.join(a,i);fs_extra_1.default.copySync(u,p),(null==o?void 0:o.profilePath)&&fs_extra_1.default.copySync(o.profilePath,path_1.default.join(p,"embedded.mobileprovision")),this.copyResourcesToMainBundle(u,e),this.copyUserResourcePathIntoPlugins(t,n,l[t],d[t],path_1.default.join(p,"MiniPlugin.bundle"),r)}else if(i.endsWith("framework")&&i!==s){const e=path_1.default.join(u,i),n=path_1.default.join(a,i);fs_extra_1.default.existsSync(e)&&fs_extra_1.default.removeSync(e),fs_extra_1.default.copySync(n,e)}})}else fs_extra_1.default.copySync(a,o),this.copyResourcesToMainBundle(a,e),this.copyUserResourcePathIntoPlugins(t,n,l[t],d[t],path_1.default.join(o,"MiniPlugin.bundle"),r)})}copyUserResourcePathIntoPlugins(e,i,n,t,a,s){const o=a;if(n){const t=path_1.default.basename(n),a=this.getMaterialFilePath(i,n);if(a){s.progress(`${e}.framework 正在拷贝配置的资源:${n}`);const i=fs_extra_1.default.lstatSync(a);fs_extra_1.default.ensureDirSync(o),i.isDirectory()?fs_extra_1.default.copySync(a,o):i.isFile()&&fs_extra_1.default.copyFileSync(a,path_1.default.join(o,t))}}if(t){s.progress(e+".framework 正在写入配置的资源"),fs_extra_1.default.ensureDirSync(o);for(const e in t){const i=t[e],n=path_1.default.join(o,e);fs_extra_1.default.ensureDirSync(o),fs_extra_1.default.ensureFileSync(n),fs_extra_1.default.writeFileSync(n,i)}}}copyResourcesToMainBundle(e,i){const n=path_1.default.join(e,"MiniPlugin.bundle"),t=path_1.default.join(n,"PluginConfig.plist");if(fs_extra_1.default.existsSync(t)){const e=plist.readFileSync(t).CopyResourcesToMainBundle;(null==e?void 0:e.length)&&e.forEach(e=>{const t=path_1.default.join(n,e);fs_extra_1.default.existsSync(t)&&fs_extra_1.default.copySync(t,path_1.default.join(i,e))})}}prepareAppexProfileConfig(e,i,n,t,a,s,o,r){if(!t)return void r.message("doing","miniappCacheDirPath is missing");let l=!1;const d={};if(i["mini-plugin"]&&Array.isArray(i["mini-plugin"].ios)){i["mini-plugin"].ios.forEach(e=>{if(e.open&&e.pluginId&&"object"==typeof e.appexProfiles)for(const i in e.appexProfiles){r.message("doing",`检查插件 ${e.pluginId} ${i} appex 配置中 ...`);const t=e.appexProfiles[i];if(!0===t.enable){const s=`${e.pluginId}_${i}`;d[s]={enable:!0};let o=t.profilePath;if(a&&(o=t.distributeProfilePath),t.bundleID&&o){const a=path_1.default.join(n,o);fs_extra_1.default.existsSync(a)?(d[s].bundleID=t.bundleID,d[s].profilePath=path_1.default.join(n,o)):(l=!0,r.message("error",`${e.pluginId} 中 ${i} 的 profilePath 无法找到对应的文件:${a}(需要在小程序项目路径下,填入相对于项目根目录的路径)`))}else l=!0,r.message("error",`${e.pluginId}中${i} 是 无效的appexProfiles配置。需要配置 bundleID,profilePath,distributeProfilePath。profile 文件需要放置在小程序项目内,然后配置相对于小程序项目根目录的相对路径。分发证书构建的情况下, 一定需要配置distributeProfilePath。查看文档了解详情。`)}}})}if(e.forEach(e=>{fs_extra_1.default.readdirSync(e.dir).forEach(i=>{if(i.endsWith(".appex")){const n=path_1.default.parse(i).name,t=d[n];if(t&&!0===t.enable)if(t.bundleID&&t.profilePath){if(t.bundleID&&t.profilePath){const n=path_1.default.join(e.dir,i,"info.plist"),a=t.bundleID;this.changeInfoplistBundleId(n,a),this.changeInfoplistBundleVersion(n,s,o),r.message("doing",`${e.pluginId} ${i} ${a} ${n} 处理 appex bundle ID 中`)}}else l=!0,r.message("error",`${e.pluginId} 的 多端插件包含了${n.slice(e.pluginId.length+1)} 的 appex。开发者需要在project.miniapp.json 中 mini-plugin 配置下对应合理的 profile 文件。查看文档了解详情。`)}})}),l)return!1;if(!(0,lodash_1.isEmpty)(d)){const e=path_1.default.join(t,APPEX_PROFILES_MAPS_FILE);fs_extra_1.default.existsSync(e)&&fs_extra_1.default.removeSync(e),fs_extra_1.default.ensureFileSync(e);const i={};for(const e in d)i[e]={bundleID:d[e].bundleID,profilePath:d[e].profilePath};fs_extra_1.default.writeFileSync(e,JSON.stringify(i));const n=path_1.default.join(t,APPEX_PROFILES_MAPS_FOR_SHELL_FILE);fs_extra_1.default.existsSync(n)&&fs_extra_1.default.removeSync(n),fs_extra_1.default.ensureFileSync(n);const a=Object.keys(d).map(e=>{const i=d[e];return`pluginAppexName:${e};_;_;bundleID:${i.bundleID};_;_;profile:${i.profilePath}\n\n`}).join("");fs_extra_1.default.writeFileSync(n,a)}return d}changeExtendSDKInfoplistBundleId(e,i,n){const t=`${i}.${path_1.default.parse(n).name.replace(/_/g,"")}`;return this.changeInfoplistBundleId(e,t)}changeInfoplistBundleId(e,i){const n=plist.readFileSync(e);return n.CFBundleIdentifier=i,plist.writeFileSync(e,n),n.CFBundleIdentifier}changeInfoplistBundleVersion(e,i,n){const t=plist.readFileSync(e);return t.CFBundleVersion=i,t.CFBundleShortVersionString=n,plist.writeFileSync(e,t),t.CFBundleIdentifier}async getEntitlements(e,i,n,t){const{mobileapp_info:a={}}=e;let s=a.ios_universal_link||a.debug_ios_universal_link;if((s.startsWith("https://")||s.startsWith("http://"))&&(s=s.replace(/^http(s)?:\/\//g,"applinks:")),Array.isArray(n.__customAssociatedDomains)){const e=n.__customAssociatedDomains.filter(e=>"string"==typeof e&&e.length>0);if(e.length>0){e.splice(0,0,s);return{"com.apple.developer.associated-domains":e.join("_$_ULinK_$_")}}}return{"com.apple.developer.associated-domains":s}}useTpush(e){return(0,miniappJson_1.iOSMiniAppJsonIsUsingTpush)(e)}async buildCloud(e,i){const{projectPath:n,demoIpaPath:t,sdkPath:a,arch:s="arm64",bindingInfo:o,certificateInfo:r,output:l,miniappCacheDirPath:d,pluginDirList:p,inLandun:u,theme:c,i18nInfo:f,debugInfo:_,CILocalBuild:h}=e,g=this.generateTempDemoIpaPath(t),{selfCertificate:m={}}=r,y=(null==m?void 0:m.isPublish)||!1,I=(0,miniappJson_1.tryGetIOSMiniappJson)(n),S=this.useTpush(I);if((0,lodash_1.isEmpty)(I))throw new Error("获取project.miniapp.json失败");if(errorIOSSdkVersions.includes(I.sdkVersion))throw new Error("当前 mini-ios.sdkVersion 存在缺陷,请参考更新日志进行修改");let v=o;if(r.signType===miniapp_builder_1.miniappSinTypes.appleId.type){const{mobileapp_info:e={}}=v;v=Object.assign(Object.assign({},v),{mobileapp_info:Object.assign(Object.assign({},e),{bundle_id:miniapp_builder_1.DEFAULT_BUNDLE_ID,debug_ios_bundle_id:miniapp_builder_1.DEFAULT_BUNDLE_ID})})}const x=await this.updateIOSInfoPlistInfo(n,v,g,I,i,f);await this.updateIOSAppConfigPlistInfo(n,v,g,I,a,!1,i,c,f),await this.updateIOSAppexInfoPlistInfo(v,g,I,x,i),await this.updateIOSIcons(n,g,d,I,y,i),await this.updateSplashScreen(n,g,I,i,c,f),await this.updateExtendedSdk(v,g,a,s,I,_,i),await this.updatePlugin(g,p,n,I,d,y,x,i),await this.updatePrivacyInfo(g,I,i);const b=await this.getEntitlements(v,g,I,i),{mobileapp_info:F={}}=v;let P;P=r.signType===miniapp_builder_1.miniappSinTypes.appleId.type?miniapp_builder_1.DEFAULT_BUNDLE_ID:F.ios_flag&&F.bundle_id||F.debug_ios_bundle_id;const B={bundleId:P,output:l,entitlements:b};if(I.buildCloud&&(I.buildCloud.certificate&&"string"==typeof I.buildCloud.certificate&&(B.certificate=I.buildCloud.certificate),I.buildCloud.profile&&"string"==typeof I.buildCloud.profile&&(B.profile=path_1.default.join(n,I.buildCloud.profile)),S&&I.buildCloud.tpnsProfile&&"string"==typeof I.buildCloud.tpnsProfile&&(B.tpnsProfile=path_1.default.join(n,I.buildCloud.tpnsProfile))),h&&(B.profile=m.profilePath,B.certificate=m.certificateName),m.isPublish||h){const e=await(0,codesign_1.codesignAndExport)(n,g,d||"",B,i,S,!0===u);if(!0!==e.success)throw new Error("Build ipa failed:"+(e.errMsg||"codesignAndExport failed"))}return{projectPath:n,demoIpaPath:g,opts:B,iosMiniappJson:I,isPublish:y}}async writeI18NInfoFile(e,i,n){Object.keys(i).forEach(t=>{if("base"===t)return;let a="";Object.keys(n).forEach(e=>{var s,o,r,l;"UISplashScreenImageName"!==e?"UILaunchStoryboardName"!==e?(null===(o=null===(s=i[t])||void 0===s?void 0:s.ios)||void 0===o?void 0:o[n[e]])&&(a+=`${e} = "${null===(l=null===(r=i[t])||void 0===r?void 0:r.ios)||void 0===l?void 0:l[n[e]]}";\n`):a+="__UILaunchStoryboardName__\n":a+="__UISplashScreenImageName__\n"}),a&&(fs_extra_1.default.ensureDirSync(path_1.default.join(e,t+".lproj")),fs_extra_1.default.writeFileSync(path_1.default.join(e,t+".lproj/InfoPlist.strings"),a))})}getMaterialFilePath(e,i){if(!i)return"";let n=i;if(path_1.default.isAbsolute(i)||(n=path_1.default.join(e,i)),fs_extra_1.default.existsSync(n))return n;const t=(0,tools_1.generateMD5)(i),a=path_1.default.basename(i),s=path_1.default.join(e,exports.remoteBuildProjectMaterialAbsoluteCacheDir,`${t}_${a}`);return fs_extra_1.default.existsSync(s)?s:""}}exports.default=new buildCloudManager;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BaseProject=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),stream_1=require("stream"),fs_extra_1=tslib_1.__importDefault(require("fs-extra")),tools_1=require("../utils/tools"),waitable_1=tslib_1.__importDefault(require("../utils/waitable"));class BaseProject extends waitable_1.default{constructor(){super(...arguments),this._projectPath="",this._projectArchitecture="miniProgram",this._type="miniProgram",this._privateKey="",this.ignores=[],this.setting={},this._dirSet=new Set,this._fileSet=new Set,this.event=new stream_1.EventEmitter}get projectPath(){return this._projectPath}get projectArchitecture(){return this._projectArchitecture}get srcPath(){let t="";return"miniProgramPlugin"!==this._type&&"miniGamePlugin"!==this._type||(t=(0,tools_1.normalizePath)(path_1.default.join(this.projectPath,this.pluginRoot||""))),t=(0,tools_1.normalizePath)(path_1.default.join(this.projectPath,this.miniprogramRoot||"")),(this._projectPath.startsWith("//")||this._projectPath.startsWith("\\\\"))&&(t.startsWith("//")||(t="/"+t)),t}get pluginSrcPath(){return(0,tools_1.normalizePath)(path_1.default.join(this.projectPath,this.pluginRoot||""))}get type(){return this._type}set type(t){this._type=t}get appid(){return this._appid}set appid(t){this._appid=t}get privateKey(){return this._privateKey}set privateKey(t){this._privateKey=t}get miniprogramRoot(){return this._miniprogramRoot||""}set miniprogramRoot(t){this._miniprogramRoot=t}get pluginRoot(){return this._pluginRoot}set pluginRoot(t){this._pluginRoot=t}get nameMappingFromDevtools(){return this._nameMappingFromDevtools}set nameMappingFromDevtools(t){this._nameMappingFromDevtools=t}async attr(){return this._attr}async ready(){await this.wait()}getProjectType(t,e){let i="";return i=(null==t?void 0:t.gameApp)?"miniGamePlugin"===e?"miniGamePlugin":"miniGame":e,i}getProjectConfig(){let t={};const e=path_1.default.join(this.projectPath,"project.config.json");if(fs_extra_1.default.existsSync(e))try{t=fs_extra_1.default.readJsonSync(e)}catch(t){throw new Error("project.config.json not exist")}return t}async serialize(){const{files:t,dirs:e}=this.getFilesAndDirs();return{projectPath:this.projectPath,appid:this.appid,attr:await this.attr(),type:this.type,projectArchitecture:this.projectArchitecture,miniprogramRoot:this.miniprogramRoot,pluginRoot:this.pluginRoot,files:t,dirs:e,setting:this.setting}}updateFiles(){this.updateFileAndDirs(...arguments)}updateOptions(t){this._appid=t.appid,this._attr=t.attr,this._type=this.getProjectType(t.attr,t.compileType),this._miniprogramRoot=t.miniprogramRoot,this._pluginRoot=t.pluginRoot,this._projectArchitecture=t.projectArchitecture,this.packOptions=t.packOptions||{ignore:[],include:[]},this.event.emit("optionsChange",t)}cacheDirName(t,e){t.has(e)||(t.add(e),this.cacheDirName(t,path_1.default.posix.dirname(e)))}deleteDirOrFileOfSet(t,e,i){if(t.has(i)){t.delete(i);const r=i+"/",s=Array.from(t);for(const e of s)e.startsWith(r)&&t.delete(e);const a=Array.from(e);for(const t of a)t.startsWith(r)&&e.delete(t)}e.has(i)&&e.delete(i)}getTargetPath(t="",e=""){return(0,tools_1.normalizePath)((0,tools_1.joinPath)(t,e)).replace(/\/$/,"").replace(/^\//,"")}getFilesAndDirs(){return{files:Array.from(this._fileSet),dirs:Array.from(this._dirSet)}}exists(t="",e=""){const i=this.getTargetPath(t,e);if(!i.startsWith(t))return!1;if(this._fileSet.has(i)||this._dirSet.has(i))return!0;const r=(0,tools_1.normalizePath)((0,tools_1.joinPath)(this.projectPath,i));return fs_extra_1.default.existsSync(r)}stat(t="",e=""){if(!this.exists(t,e))return;const i=this.getTargetPath(t,e),r=path_1.default.join(this.projectPath,i);let s={};try{s=fs_extra_1.default.statSync(r)}catch(t){fs_extra_1.default.existsSync(r)||this.deleteDirOrFileOfSet(this._dirSet,this._fileSet,i)}if(this._fileSet.has(i)){return{isFile:!0,isDirectory:!1,size:this.getFileSize(t,e),mtimeMs:s.mtimeMs||""}}return this._dirSet.has(i)?{isFile:!1,isDirectory:!0,size:0,mtimeMs:s.mtimeMs}:void 0}getAllFileInfo(t=""){const e=this.getFileList(t),i={};return e.forEach(t=>{i[t]=this.stat("",t)||{}}),i}getFileList(t="",e=""){return Array.from(this._fileSet).filter(i=>(!e||path_1.default.posix.extname(i)===e)&&!(t&&!i.startsWith(t)))}getSrcFile(t,e){t=t||"";const i=this.getTargetPath(t,e),r=(0,tools_1.normalizePath)((0,tools_1.joinPath)(this.projectPath,i));return fs_extra_1.default.readFileSync(r,null)}getFile(t,e){return this.getSrcFile(t,e)}getJson(t="",e=""){const i=this.getFile(t,e).toString("utf-8");try{return JSON.parse(i)}catch(i){throw new Error("JSON parse failed: "+this.getTargetPath(t,e))}}getFileSize(t="",e=""){const i=this.getFile(t,e);return i?i.byteLength:0}getExtAppid(){throw new Error("Method not implemented.")}async onFileChange(t,e){e=(0,tools_1.normalizePath)(e).replace(/\/$/,"").replace(/^\//,""),"add"===t&&(this.cacheDirName(this._dirSet,path_1.default.posix.dirname(e)),this._fileSet.add(e)),"addDir"===t&&this.cacheDirName(this._dirSet,e),"unlink"===t&&this.deleteDirOrFileOfSet(this._dirSet,this._fileSet,e),"unlinkDir"===t&&this.deleteDirOrFileOfSet(this._dirSet,this._fileSet,e),"change"===t&&this._fileSet.has(e),this.event.emit("fileChange",t,e)}clearCache(){}}exports.BaseProject=BaseProject;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BaseProject=void 0;const tslib_1=require("tslib"),path_1=tslib_1.__importDefault(require("path")),stream_1=require("stream"),fs_extra_1=tslib_1.__importDefault(require("fs-extra")),tools_1=require("../utils/tools"),waitable_1=tslib_1.__importDefault(require("../utils/waitable"));class BaseProject extends waitable_1.default{constructor(){super(...arguments),this._projectPath="",this._injectedPages=[],this._projectArchitecture="miniProgram",this._type="miniProgram",this._privateKey="",this.ignores=[],this.setting={},this._dirSet=new Set,this._fileSet=new Set,this.event=new stream_1.EventEmitter}get projectPath(){return this._projectPath}get injectedPages(){return this._injectedPages}get projectArchitecture(){return this._projectArchitecture}get srcPath(){let t="";return"miniProgramPlugin"!==this._type&&"miniGamePlugin"!==this._type||(t=(0,tools_1.normalizePath)(path_1.default.join(this.projectPath,this.pluginRoot||""))),t=(0,tools_1.normalizePath)(path_1.default.join(this.projectPath,this.miniprogramRoot||"")),(this._projectPath.startsWith("//")||this._projectPath.startsWith("\\\\"))&&(t.startsWith("//")||(t="/"+t)),t}get pluginSrcPath(){return(0,tools_1.normalizePath)(path_1.default.join(this.projectPath,this.pluginRoot||""))}get type(){return this._type}set type(t){this._type=t}get appid(){return this._appid}set appid(t){this._appid=t}get privateKey(){return this._privateKey}set privateKey(t){this._privateKey=t}get miniprogramRoot(){return this._miniprogramRoot||""}set miniprogramRoot(t){this._miniprogramRoot=t}get pluginRoot(){return this._pluginRoot}set pluginRoot(t){this._pluginRoot=t}get nameMappingFromDevtools(){return this._nameMappingFromDevtools}set nameMappingFromDevtools(t){this._nameMappingFromDevtools=t}async attr(){return this._attr}async ready(){await this.wait()}getProjectType(t,e){let i="";return i=(null==t?void 0:t.gameApp)?"miniGamePlugin"===e?"miniGamePlugin":"miniGame":e,i}getProjectConfig(){let t={};const e=path_1.default.join(this.projectPath,"project.config.json");if(fs_extra_1.default.existsSync(e))try{t=fs_extra_1.default.readJsonSync(e)}catch(t){throw new Error("project.config.json not exist")}return t}async serialize(){const{files:t,dirs:e}=this.getFilesAndDirs();return{projectPath:this.projectPath,appid:this.appid,attr:await this.attr(),type:this.type,projectArchitecture:this.projectArchitecture,miniprogramRoot:this.miniprogramRoot,pluginRoot:this.pluginRoot,files:t,dirs:e,setting:this.setting}}updateFiles(){this.updateFileAndDirs(...arguments)}updateOptions(t){this._appid=t.appid,this._injectedPages=t.injectedPages||[],this._attr=t.attr,this._type=this.getProjectType(t.attr,t.compileType),this._miniprogramRoot=t.miniprogramRoot,this._pluginRoot=t.pluginRoot,this._projectArchitecture=t.projectArchitecture,this.packOptions=t.packOptions||{ignore:[],include:[]},this.event.emit("optionsChange",t)}cacheDirName(t,e){t.has(e)||(t.add(e),this.cacheDirName(t,path_1.default.posix.dirname(e)))}deleteDirOrFileOfSet(t,e,i){if(t.has(i)){t.delete(i);const r=i+"/",s=Array.from(t);for(const e of s)e.startsWith(r)&&t.delete(e);const a=Array.from(e);for(const t of a)t.startsWith(r)&&e.delete(t)}e.has(i)&&e.delete(i)}getTargetPath(t="",e=""){return(0,tools_1.normalizePath)((0,tools_1.joinPath)(t,e)).replace(/\/$/,"").replace(/^\//,"")}getFilesAndDirs(){return{files:Array.from(this._fileSet),dirs:Array.from(this._dirSet)}}exists(t="",e=""){const i=this.getTargetPath(t,e);if(!i.startsWith(t))return!1;if(this._fileSet.has(i)||this._dirSet.has(i))return!0;const r=(0,tools_1.normalizePath)((0,tools_1.joinPath)(this.projectPath,i));return fs_extra_1.default.existsSync(r)}stat(t="",e=""){if(!this.exists(t,e))return;const i=this.getTargetPath(t,e),r=path_1.default.join(this.projectPath,i);let s={};try{s=fs_extra_1.default.statSync(r)}catch(t){fs_extra_1.default.existsSync(r)||this.deleteDirOrFileOfSet(this._dirSet,this._fileSet,i)}if(this._fileSet.has(i)){return{isFile:!0,isDirectory:!1,size:this.getFileSize(t,e),mtimeMs:s.mtimeMs||""}}return this._dirSet.has(i)?{isFile:!1,isDirectory:!0,size:0,mtimeMs:s.mtimeMs}:void 0}getAllFileInfo(t=""){const e=this.getFileList(t),i={};return e.forEach(t=>{i[t]=this.stat("",t)||{}}),i}getFileList(t="",e=""){return Array.from(this._fileSet).filter(i=>(!e||path_1.default.posix.extname(i)===e)&&!(t&&!i.startsWith(t)))}getSrcFile(t,e){t=t||"";const i=this.getTargetPath(t,e),r=(0,tools_1.normalizePath)((0,tools_1.joinPath)(this.projectPath,i));return fs_extra_1.default.readFileSync(r,null)}getFile(t,e){return this.getSrcFile(t,e)}getJson(t="",e=""){const i=this.getFile(t,e).toString("utf-8");try{return JSON.parse(i)}catch(i){throw new Error("JSON parse failed: "+this.getTargetPath(t,e))}}getFileSize(t="",e=""){const i=this.getFile(t,e);return i?i.byteLength:0}getExtAppid(){throw new Error("Method not implemented.")}async onFileChange(t,e){e=(0,tools_1.normalizePath)(e).replace(/\/$/,"").replace(/^\//,""),"add"===t&&(this.cacheDirName(this._dirSet,path_1.default.posix.dirname(e)),this._fileSet.add(e)),"addDir"===t&&this.cacheDirName(this._dirSet,e),"unlink"===t&&this.deleteDirOrFileOfSet(this._dirSet,this._fileSet,e),"unlinkDir"===t&&this.deleteDirOrFileOfSet(this._dirSet,this._fileSet,e),"change"===t&&this._fileSet.has(e),this.event.emit("fileChange",t,e)}clearCache(){}}exports.BaseProject=BaseProject;
@@ -2017,6 +2017,7 @@ module.exports = {
2017
2017
  },
2018
2018
  "initialRenderingCache": {
2019
2019
  "enum": [
2020
+ "capture",
2020
2021
  "dynamic",
2021
2022
  "static"
2022
2023
  ],
@@ -2220,5 +2221,5 @@ module.exports = {
2220
2221
  }
2221
2222
  },
2222
2223
  "$schema": "http://json-schema.org/draft-07/schema#",
2223
- "$version": 1723702632103
2224
+ "$version": 1732792700523
2224
2225
  }
@@ -542,6 +542,7 @@ module.exports = {
542
542
  },
543
543
  "initialRenderingCache": {
544
544
  "enum": [
545
+ "capture",
545
546
  "dynamic",
546
547
  "static"
547
548
  ],
@@ -779,6 +780,7 @@ module.exports = {
779
780
  },
780
781
  "initialRenderingCache": {
781
782
  "enum": [
783
+ "capture",
782
784
  "dynamic",
783
785
  "static"
784
786
  ],
@@ -893,6 +895,7 @@ module.exports = {
893
895
  },
894
896
  "initialRenderingCache": {
895
897
  "enum": [
898
+ "capture",
896
899
  "dynamic",
897
900
  "static"
898
901
  ],
@@ -1087,5 +1090,5 @@ module.exports = {
1087
1090
  }
1088
1091
  },
1089
1092
  "$schema": "http://json-schema.org/draft-07/schema#",
1090
- "$version": 1693276416338
1093
+ "$version": 1724989414780
1091
1094
  }
@@ -207,5 +207,5 @@ module.exports = {
207
207
  }
208
208
  },
209
209
  "$schema": "http://json-schema.org/draft-07/schema#",
210
- "$version": 1693276416339
210
+ "$version": 1724989414780
211
211
  }
@@ -254,6 +254,7 @@ module.exports = {
254
254
  },
255
255
  "initialRenderingCache": {
256
256
  "enum": [
257
+ "capture",
257
258
  "dynamic",
258
259
  "static"
259
260
  ],
@@ -491,6 +492,7 @@ module.exports = {
491
492
  },
492
493
  "initialRenderingCache": {
493
494
  "enum": [
495
+ "capture",
494
496
  "dynamic",
495
497
  "static"
496
498
  ],
@@ -512,5 +514,5 @@ module.exports = {
512
514
  }
513
515
  },
514
516
  "$schema": "http://json-schema.org/draft-07/schema#",
515
- "$version": 1723702632104
517
+ "$version": 1724989414780
516
518
  }
@@ -49,5 +49,5 @@ module.exports = {
49
49
  },
50
50
  "additionalProperties": false,
51
51
  "$schema": "http://json-schema.org/draft-07/schema#",
52
- "$version": 1693798877514
52
+ "$version": 1724989414780
53
53
  }
@@ -10,5 +10,5 @@ module.exports = {
10
10
  },
11
11
  "additionalProperties": false,
12
12
  "$schema": "http://json-schema.org/draft-07/schema#",
13
- "$version": 1693276416340
13
+ "$version": 1724989414780
14
14
  }
@@ -690,5 +690,5 @@ module.exports = {
690
690
  }
691
691
  },
692
692
  "$schema": "http://json-schema.org/draft-07/schema#",
693
- "$version": 1723702681882
693
+ "$version": 1724989414780
694
694
  }
@@ -370,5 +370,5 @@ module.exports = {
370
370
  }
371
371
  },
372
372
  "$schema": "http://json-schema.org/draft-07/schema#",
373
- "$version": 1723702632105
373
+ "$version": 1724989414781
374
374
  }
@@ -49,5 +49,5 @@ module.exports = {
49
49
  "rules"
50
50
  ],
51
51
  "$schema": "http://json-schema.org/draft-07/schema#",
52
- "$version": 1693276416340
52
+ "$version": 1724989414781
53
53
  }
@@ -16,5 +16,5 @@ module.exports = {
16
16
  },
17
17
  "additionalProperties": false,
18
18
  "$schema": "http://json-schema.org/draft-07/schema#",
19
- "$version": 1693276416340
19
+ "$version": 1724989414781
20
20
  }
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.uploadToCosInCI=exports.uploadToCosCore=void 0;const COS=require("cos-js-sdk-v5"),COSForNode=require("cos-nodejs-sdk-v5"),fs=require("fs");function compareCache(e,o){const t=Object.keys(o);for(const r of Object.keys(e)){if(!t.includes(r))return!1;if(o[r]!=e[r])return!1}return!0}async function uploadToCosCore({uploadBuf:e,region:o,getUploadInfoFunc:t,getAuthFunc:r}){return new Promise((n,i)=>{t().then(t=>{let u=null;const c="undefined"==typeof Blob,s=new(c?COSForNode:COS)({getAuthorization(e,o){var n;if(1!=e.Scope.length)return void o("");const i=Object.assign({},t,{action:e.Scope[0].action});(null===(n=e.Query)||void 0===n?void 0:n.uploadId)&&(i.uploadId=e.Query.uploadId),null!==u&&compareCache(i,u)&&u.AuthExpireTime>Math.round(Date.now()/1e3)?o({Authorization:u.Authorization,SecurityToken:u.SecurityToken,SignFrom:"client"}):r(i).then(e=>{u=Object.assign({},i,{Authorization:e.Authorization,SecurityToken:e.SecurityToken,SignFrom:"client",AuthExpireTime:e.AuthExpireTime}),o({Authorization:e.Authorization,SecurityToken:e.SecurityToken,SignFrom:"client"})},()=>{o("")})}});let l=void 0,a={};if(c)try{const o=require("tmp");o.setGracefulCleanup(),a=o.fileSync({mode:420,prefix:"",postfix:""}),fs.writeSync(a.fd,e,0,e.length,null),fs.closeSync(a.fd)}catch(e){throw console.error("Error:",e),new Error("[upload Cos failed] write compileresult to tmp file failed: "+e.message)}else l=new Blob([e],{type:"application/octet-stream"});s.sliceUploadFile({Bucket:t.bucket,Region:o,Key:t.object,Body:l,FilePath:a.name,SliceSize:5242880,onProgress(){},AsyncLimit:1},(e,o)=>{e?i({err:e,data:o}):n({err:e,data:o})})},e=>{i({err:e})})})}function uploadToCosInCI(){}exports.uploadToCosCore=uploadToCosCore,exports.uploadToCosInCI=uploadToCosInCI;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.uploadToCosInCI=exports.uploadToCosCore=void 0;const COS=require("cos-js-sdk-v5"),COSForNode=require("cos-nodejs-sdk-v5"),fs=require("fs");function compareCache(e,o){const t=Object.keys(o);for(const r of Object.keys(e)){if(!t.includes(r))return!1;if(o[r]!=e[r])return!1}return!0}async function uploadToCosCore({uploadBuf:e,region:o,getUploadInfoFunc:t,getAuthFunc:r}){return new Promise((n,i)=>{t().then(t=>{let u=null;const s="undefined"==typeof Blob||"undefined"==typeof XMLHttpRequest,c=new(s?COSForNode:COS)({getAuthorization(e,o){var n;if(1!=e.Scope.length)return void o("");const i=Object.assign({},t,{action:e.Scope[0].action});(null===(n=e.Query)||void 0===n?void 0:n.uploadId)&&(i.uploadId=e.Query.uploadId),null!==u&&compareCache(i,u)&&u.AuthExpireTime>Math.round(Date.now()/1e3)?o({Authorization:u.Authorization,SecurityToken:u.SecurityToken,SignFrom:"client"}):r(i).then(e=>{u=Object.assign({},i,{Authorization:e.Authorization,SecurityToken:e.SecurityToken,SignFrom:"client",AuthExpireTime:e.AuthExpireTime}),o({Authorization:e.Authorization,SecurityToken:e.SecurityToken,SignFrom:"client"})},()=>{o("")})}});let l=void 0,a={};if(s)try{const o=require("tmp");o.setGracefulCleanup(),a=o.fileSync({mode:420,prefix:"",postfix:""}),fs.writeSync(a.fd,e,0,e.length,null),fs.closeSync(a.fd)}catch(e){throw console.error("Error:",e),new Error("[upload Cos failed] write compileresult to tmp file failed: "+e.message)}else l=new Blob([e],{type:"application/octet-stream"});c.sliceUploadFile({Bucket:t.bucket,Region:o,Key:t.object,Body:l,FilePath:a.name,SliceSize:5242880,onProgress(){},AsyncLimit:1},(e,o)=>{e?i({err:e,data:o}):n({err:e,data:o})})},e=>{i({err:e})})})}function uploadToCosInCI(){}exports.uploadToCosCore=uploadToCosCore,exports.uploadToCosInCI=uploadToCosInCI;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "miniprogram-ci",
3
- "version": "2.1.7",
3
+ "version": "2.1.8",
4
4
  "description": "Module that build miniprogram project for web or app extracted from WeChatDevtools.",
5
5
  "homepage": "https://developers.weixin.qq.com/community/homepage",
6
6
  "main": "dist/index.js",