xhs-mp-shared 2.1.2 → 2.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("chalk"),t=require("cos-nodejs-sdk-v5"),o=require("path"),r=require("fs"),s=require("uuid"),n=require("node-fetch"),i=require("child_process"),a=require("os"),l=require("crypto");class c{constructor(e){this.prefix=e||"[@xhs-toolkit]",this.verbose=global.verbose}setVerbose(e){this.verbose=e}info(...t){console.info(e.blue(this.prefix),...t)}log(...t){console.log(e.blue(this.prefix),...t)}debug(...t){this.verbose&&console.debug(e.yellow(this.prefix),...t)}warn(...t){this.verbose&&console.warn(e.yellow(this.prefix),...t)}error(...t){console.error(e.red(this.prefix),...t)}}class u{static getLogger(){return window.eaglet.sendApm&&window.eaglet||global.eaglet}constructor({success:e=!0,code:t=0,info:o}){this.success=e,this.code=t,this.info=o}setCode(e){return this.code=e,this}setMsg(e){return this.msg=e,this}setData(e){return this.data=e,this}setInfo(e){return this.info=e,this}fail(){return this.success=!1,this.code=-1,this}log(e,t){var o;try{const r={bizName:e.bizName,scene:e.scene,customerHost:window.location.host,routePath:window.location.pathname,uploadSuccess:this.success,code:this.code,errorMsg:this.msg,successData:JSON.stringify(this.data),fileType:this.info.fileType,fileSize:this.info.fileSize,startTime:u.formatDate(this.info.startTime),endTime:u.formatDate(Date.now()),tokenStartTime:u.formatDate(this.info.startTime),tokenEndTime:u.formatDate(this.info.tokenEndTime||Date.now()),tokenTimestamp:(this.info.tokenEndTime||Date.now())-this.info.startTime,uploadTimestamp:Date.now()-this.info.startTime,...t};r.uploadSuccess&&0!==r.uploadTimestamp&&(r.uploadSpeed=r.fileSize/r.uploadTimestamp);const s=u.getLogger();if(s)s.push({type:"InfraUploader",value:r},"ApmJSONTracker");else{console.warn.bind(console)("[APM Warning]: eaglet is undefined, web app please install @xhs/launcher-plugin-eaglet, react-native app use eaglet plugin from asgard!")}const n=(null===(o=null===window||void 0===window?void 0:window.insight)||void 0===o?void 0:o.sendCustomPoint.bind(null===window||void 0===window?void 0:window.insight))||(null==s?void 0:s.flushApm);n&&(Object.keys(r).forEach((e=>{"boolean"==typeof r[e]&&(r[e]=Number(r[e]))})),n({measurement_name:"infraUploader",measurement_data:r},"ApmXrayTracker"))}finally{return this}}static formatDate(e){return new Date(e).toISOString().replace(/T/," ").replace(/\..+/,"")}}function p(e){return e.map((e=>String.fromCharCode(e))).join("")}function d(){return p([97,112,45,115,104,97,110,103,104,97,105])}function m(){return p([83,101,99,114,101,116,73,100])}function h(){return p([83,101,99,114,101,116,75,101,121])}const f=p([102,101,45,115,116,97,116,105,99,45,49,50,53,49,53,50,52,51,49,57]),g=(e,t)=>{const r=o.basename(e),s=o.extname(r);if(!s||"."===s)throw new Error(`fileName: '${e}' is not validata, please check extname`);const n=`${p([109,112,47,114,101,100,47,109,97,112])}/${t}/${r}`;return{Bucket:f,Region:d(),Key:n,FilePath:e}},v=async(e,t)=>{const o=t.map((({Key:e})=>({Key:e})));try{await e.deleteMultipleObject({Bucket:f,Region:d(),Objects:o})}catch(e){console.log("===== 腾讯云中已存在同名文件,且删除时报错: =====",e)}},w=console.warn,x=/warning: (.+) has been deprecated/,y=/warning: param (.+) format error/;console.warn=function(...e){for(const t of e)if("string"==typeof t&&(t.match(x)||t.match(y)||t.includes("cloud.tencent.com")))return;w(...e)};var S=Object.freeze({__proto__:null,Bucket:f,deleteExistingFiles:v,getPublicCos:function(e){const o={[m()]:p([65,75,73,68,111,112,99,57,80,81,77,52,49,104,54,86,101,86,104,113,75,82,73,115,110,82,111,121,55,55,115,79,101,49,56,122]),[h()]:p([107,69,85,84,67,100,82,48,73,79,77,117,66,79,78,106,108,107,85,79,52,86,103,90,105,97,67,97,112,112,113,108])};return e&&(o.Proxy=e,o.Tunnel=!0,o.StrictSsl=!1),new t(o)},upload2Qcloud:async(e,t,o)=>{if(!t||!t.length)throw new Error("上传地址不能为空!");const s=Array.isArray(t)?t.map((e=>g(e,o))):[g(t,o)];if(!s.every((e=>r.existsSync(e.FilePath))))throw new Error(`上传地址不合法: ${JSON.stringify(s,null,2)}`);return await v(e,s),await((e,t,o)=>new Promise(((o,r)=>{e.uploadFiles({files:t,SliceSize:1024,onProgress:e=>{Number(e.speed/1024/1024*100)}},((e,t)=>{e?r(e):o(t)}))})))(e,s)}});const b={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:"%windir%\\System32\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :"};function _(e){return l.createHash("sha256").update(e).digest("hex")}function T(){var e,t;try{return"darwin"===process.platform?null===(e=i.execSync("sw_vers -productVersion",{encoding:"utf-8"}))||void 0===e?void 0:e.trim():null===(t=a.release())||void 0===t?void 0:t.trim()}catch(e){}return""}function k(e,t){var o;const r=Number(e);return Number("arm64"===t&&r<100?null===(o=100*r)||void 0===o?void 0:o.toFixed(0):null==r?void 0:r.toFixed(0))}function N(){var e,t;const o=a.cpus(),r=null==o?void 0:o[0];return{os_platform:(null===(t=null===(e=process.platform)||void 0===e?void 0:e[0])||void 0===t?void 0:t.toUpperCase())+process.platform.slice(1),os_arch:process.arch,cpu_speed:k(null==r?void 0:r.speed,process.arch),cpu_model:null==r?void 0:r.model,machine_memory:Math.round(a.totalmem()/1024/1024),os_version:T()}}function C(){return"mp-compiler/2.1.2"}const E=N(),O={context_nameTracker:"nodeT",context_platform:E.os_platform,context_appVersion:"mp-compiler/2.1.2",context_osVersion:E.os_version,context_deviceModel:"",context_deviceId:function(){try{return function(e){switch(process.platform){case"darwin":return e.split("IOPlatformUUID")[1].split("\n")[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return e.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return e.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error(`Unsupported platform: ${process.platform}`)}}(i.execSync(b[process.platform]).toString())}catch(e){}return JSON.stringify({...N(),login_user:_(a.userInfo().username||process.env.username),node_version:process.version})}(),context_package:"",context_networkType:"unknow",context_matchedPath:"cli",context_route:"xhsmp://cli",context_userAgent:[void 0!==(null===(P=null===process||void 0===process?void 0:process.versions)||void 0===P?void 0:P.electron)?`Electron/${null===(I=null===process||void 0===process?void 0:process.versions)||void 0===I?void 0:I.electron}`:"",`Node/${process.version}`,`${E.os_platform}/${E.os_version}`,`CPU/${E.cpu_speed}mhz (${E.cpu_model}; ${E.os_arch})`,`Memory/${E.machine_memory}mb`,"mp-compiler/2.1.2"].map((e=>{var t;return null===(t=null==e?void 0:e.trim)||void 0===t?void 0:t.call(e)})).filter(Boolean).join(" ").trim(),context_artifactName:"miniprogram",context_networkQuality:"UNKNOWN",context_artifactVersion:"UNKNOWN",context_userId:""};var P,I;const z="https://apm-fe.xiaohongshu.com/api/data";var D,R,$,M,A,q,F;exports.FeatureReporter=void 0,D=exports.FeatureReporter||(exports.FeatureReporter={}),(R=D.MODULE||(D.MODULE={})).appJSON="json-app",R.extJSON="json-ext",R.componentJSON="json-component",R.pageJSON="json-page",R.ml="ml",R.thirdFramework="third-framework",R.developMode="develop-mode",($=D.AppExtJSON||(D.AppExtJSON={})).pages="pages",$.subpackages="subpackages",$.subPackages="subPackages",$.lazyCodeLoading="lazyCodeLoading",$.tabBar="tabBar",$.preloadRule="preloadRule",$.usingComponents="usingComponents",$.extPages="extPages",(M=D.ComponentJSON||(D.ComponentJSON={})).styleIsolation="styleIsolation",M.componentPlaceholder="componentPlaceholder",(D.PageJSON||(D.PageJSON={})).skeleton="skeleton",(A=D.ML||(D.ML={})).WebComponent="web-component",A.animation="animation",A.template="template",A.sjs="sjs",(q=D.ThirdFramework||(D.ThirdFramework={})).taroReact="taro-react",q.taroVue="taro-vue",q.taro="taro",q.uniapp3="uniapp3",q.uniapp2="uniapp2",q.weimeng="weimeng",(F=D.DevelopMode||(D.DevelopMode={})).customDevelopment="custom-development",F.templateDevelopment="template-development";exports.APM=class{constructor(){this.reportQueue=[],this.allowReport=!1,this.eventSeq=1,this.context={...O},this.baseData={},this.logger=new c("[apm]: "),this.timer=null}setContext(e,t={}){this.context={...this.context,context_userId:e},this.baseData=t,this.startReport()}startReport(){this.allowReport=!0,this.bactchReport()}getSequence(){return{context_sdkSeqId:this.eventSeq++,context_sdkSessionId:s.v4(),context_pageSessionId:s.v4(),clientTime:Date.now()}}_request(e,t=!0){var o;const r=(Array.isArray(e)?e:[e]).map((e=>({...this.context,...e.suquence,measurement_name:e.measurement_name,measurement_data:{...this.baseData,...e.measurement_data}})));return null===(o=this.logger)||void 0===o||o.debug("apm before send",`${JSON.stringify(r)}`,"warning"),n(z,{method:"POST",body:JSON.stringify(r),headers:{accept:"*/*","accept-language":"zh-CN,zh;q=0.9",batch:"true","biz-type":"apm_fe","cache-control":"no-cache","content-type":"application/json",pragma:"no-cache"}}).then((e=>e.json())).then((e=>{var t;if(!(null==e?void 0:e.success))throw new Error(null==e?void 0:e.msg);null===(t=this.logger)||void 0===t||t.debug("apm send success","")})).catch((e=>{var o;t&&setTimeout((()=>this._request(r,!1)),1e3),null===(o=this.logger)||void 0===o||o.log("apm send failed",`${(null==e?void 0:e.message)||null}`,"error")}))}bactchReport(){const e=[...this.reportQueue];for(this.reportQueue=[];e.length;)this._request(e.splice(0,5))}report(e,t={}){const o={suquence:this.getSequence(),measurement_name:e,measurement_data:t};this.reportQueue.push(o),clearTimeout(this.timer),this.allowReport&&(this.reportQueue.length>=10?this.bactchReport():this.timer=setTimeout((()=>{this.bactchReport()}),200))}},exports.CSS_REG=/(?<!\.skeleton)\.(wxss|css)$/,exports.Logger=c,exports.ML_COMMON_EXT=/\.(xhs|wx)ml$/,exports.ML_OPERATOR=/^(xhs|wx):/,exports.ML_REG=/(?<!\.skeleton)\.(xhs|wx)ml$/,exports.SKETCH_CSS_REG=/\.skeleton\.(wxss|css)$/,exports.SKETCH_ML_REG=/\.skeleton\.(xhs|wx)ml$/,exports.SKETCH_NAMESPACE="skeleton",exports.Uploader=class{constructor(e){this.useCache=!1,this.bizName=e.bizName,this.scene=e.scene,this.getToken=e.getToken,this.enableResume=e.enableResume,this.proxy=e.proxy}get cacheKey(){return`uploader-permit-${this.scene}-${this.bizName}`}getCachePermit(e,t){try{const o=`${t.name}-${t.size}`,r=localStorage.getItem(this.cacheKey);if(!r)return null;const s=JSON.parse(r)[o];return s?s.expireTime-12e4<Date.now()?(this.setCachePermit(e,t,null),null):s:null}catch(e){return localStorage.setItem(this.cacheKey,""),null}}setCachePermit(e,t,o){try{const e=`${t.name}-${t.size}`,r=localStorage.getItem(this.cacheKey),s=r?JSON.parse(r):{};s[e]=o,localStorage.setItem(this.cacheKey,JSON.stringify(s))}catch(e){}}getPermit(e,t,o,r,s){if(this.enableResume){const o=this.getCachePermit(e,t);if(o)return this.useCache=!0,Promise.resolve(o)}return this.useCache=!1,this.getToken({bizName:this.bizName,scene:this.scene,fileCount:1,fileFormat:o,persistentOps:r,persistentNotifyUrl:s}).then((({uploadTempPermits:o,uploadLimitPolicy:r})=>{const s=t.type,n=t.size;if(r){const{fileTypes:e,maxSize:t}=r;if((null==e?void 0:e.length)&&!e.reduce(((e,t)=>[...e,...t.split("/")]),[]).some((e=>s.endsWith(e))))throw new Error(`文件类型 ${s} 不在可上传的文件类型 ${e.join(", ")} 中。`);if(void 0!==t&&n>t)throw new Error(`文件尺寸(${n/1048576} mb)超过最大尺寸(${t/1048576} mb)。`)}if(!(null==o?void 0:o.length))throw new Error("token 获取失败。");const[i]=o.sort(((e,t)=>t.qos-e.qos));return this.enableResume&&this.setCachePermit(e,t,i),i}))}post(e){const o=Date.now(),{fileFormat:r,onInstanceCreated:s,...n}=e,i=new u({info:{fileType:e.fileInfo.type,fileSize:e.fileInfo.size,startTime:o}});return this.getPermit(e.Body,e.fileInfo,r).then((r=>{i.setInfo({...i.info,tokenEndTime:Date.now()});const[a]=r.fileIds,l={Domain:r.uploadAddr,getAuthorization(e,t){t({TmpSecretId:r.secretId||"null",TmpSecretKey:r.secretKey||"null",SecurityToken:r.token,StartTime:Math.floor(o/1e3),ExpiredTime:Math.floor(r.expireTime/1e3)})}};"unknown"===r.bucket&&(l.AppId="1251524319"),this.proxy&&(l.Proxy=this.proxy,l.Tunnel=!0,l.StrictSsl=!1);const c=new t(l);return s&&s(c),c.uploadFile({Bucket:r.bucket,Region:r.region,Key:a,...n}).then((t=>{var o,s;const l={...t,bizName:this.bizName,scene:this.scene,cloudType:r.cloudType,fileId:a,useCache:this.useCache};if(r.cdnDomain){const e=`${r.cdnDomain}/${a}`;l.cdnDomain=r.cdnDomain,l.url=e,l.previewUrl=e,l.staticUrl=e}(null==t?void 0:t.headers)&&Object.keys(t.headers).forEach((e=>{var o;if(e.startsWith("x-ros-")){const r=e.split("x-ros-")[1].replace(/\-(\w)/g,(e=>e[1].toUpperCase()));l[r]=null===(o=t.headers)||void 0===o?void 0:o[e]}}));const c={fileId:a,cloudType:r.cloudType,uploaderAddr:r.uploadAddr,sliceSize:n.SliceSize||1048576,isSlice:e.fileInfo.size>(n.SliceSize||1048576),tokenFail:!1};return(null===(o=null==t?void 0:t.headers)||void 0===o?void 0:o["x-tracer"])&&(c.tracerId=null===(s=t.headers)||void 0===s?void 0:s["x-tracer"]),this.setCachePermit(e.Body,e.fileInfo,null),i.setData(l).log(this,c)})).catch((t=>{var o;return console.log("cos uploadFile fail...",t),this.enableResume&&!(null===(o=null==t?void 0:t.message)||void 0===o?void 0:o.includes("network error"))&&this.setCachePermit(e.Body,e.fileInfo,null),i.fail().setCode(Number((null==t?void 0:t.code)||-1)).setMsg(null==t?void 0:t.message).log(this,{fileId:a,cloudType:r.cloudType,uploaderAddr:r.uploadAddr,sliceSize:n.SliceSize||1048576,isSlice:e.fileInfo.size>(n.SliceSize||1048576),tokenFail:!1,serverFail:!0})}))})).catch((e=>(console.log("getPermit error...",e),i.fail().setInfo({...i.info,tokenEndTime:Date.now()}).setMsg(e.message).log(this,{tokenFail:!0}))))}},exports.getBundleVersion=C,exports.getLegacyBundleVersion=function(){return"mp-compiler/2.1.2 @xhs/mp-ide/2.3.0"},exports.publicCos=S;
|
|
1
|
+
"use strict";var e=require("chalk"),t=require("cos-nodejs-sdk-v5"),o=require("path"),r=require("fs"),s=require("uuid"),n=require("node-fetch"),i=require("child_process"),a=require("os"),l=require("crypto");class c{constructor(e){this.prefix=e||"[@xhs-toolkit]",this.verbose=global.verbose}setVerbose(e){this.verbose=e}info(...t){console.info(e.blue(this.prefix),...t)}log(...t){console.log(e.blue(this.prefix),...t)}debug(...t){this.verbose&&console.debug(e.yellow(this.prefix),...t)}warn(...t){this.verbose&&console.warn(e.yellow(this.prefix),...t)}error(...t){console.error(e.red(this.prefix),...t)}}class u{static getLogger(){return window.eaglet.sendApm&&window.eaglet||global.eaglet}constructor({success:e=!0,code:t=0,info:o}){this.success=e,this.code=t,this.info=o}setCode(e){return this.code=e,this}setMsg(e){return this.msg=e,this}setData(e){return this.data=e,this}setInfo(e){return this.info=e,this}fail(){return this.success=!1,this.code=-1,this}log(e,t){var o;try{const r={bizName:e.bizName,scene:e.scene,customerHost:window.location.host,routePath:window.location.pathname,uploadSuccess:this.success,code:this.code,errorMsg:this.msg,successData:JSON.stringify(this.data),fileType:this.info.fileType,fileSize:this.info.fileSize,startTime:u.formatDate(this.info.startTime),endTime:u.formatDate(Date.now()),tokenStartTime:u.formatDate(this.info.startTime),tokenEndTime:u.formatDate(this.info.tokenEndTime||Date.now()),tokenTimestamp:(this.info.tokenEndTime||Date.now())-this.info.startTime,uploadTimestamp:Date.now()-this.info.startTime,...t};r.uploadSuccess&&0!==r.uploadTimestamp&&(r.uploadSpeed=r.fileSize/r.uploadTimestamp);const s=u.getLogger();if(s)s.push({type:"InfraUploader",value:r},"ApmJSONTracker");else{console.warn.bind(console)("[APM Warning]: eaglet is undefined, web app please install @xhs/launcher-plugin-eaglet, react-native app use eaglet plugin from asgard!")}const n=(null===(o=null===window||void 0===window?void 0:window.insight)||void 0===o?void 0:o.sendCustomPoint.bind(null===window||void 0===window?void 0:window.insight))||(null==s?void 0:s.flushApm);n&&(Object.keys(r).forEach((e=>{"boolean"==typeof r[e]&&(r[e]=Number(r[e]))})),n({measurement_name:"infraUploader",measurement_data:r},"ApmXrayTracker"))}finally{return this}}static formatDate(e){return new Date(e).toISOString().replace(/T/," ").replace(/\..+/,"")}}function p(e){return e.map((e=>String.fromCharCode(e))).join("")}function d(){return p([97,112,45,115,104,97,110,103,104,97,105])}function m(){return p([83,101,99,114,101,116,73,100])}function h(){return p([83,101,99,114,101,116,75,101,121])}const f=p([102,101,45,115,116,97,116,105,99,45,49,50,53,49,53,50,52,51,49,57]),g=(e,t)=>{const r=o.basename(e),s=o.extname(r);if(!s||"."===s)throw new Error(`fileName: '${e}' is not validata, please check extname`);const n=`${p([109,112,47,114,101,100,47,109,97,112])}/${t}/${r}`;return{Bucket:f,Region:d(),Key:n,FilePath:e}},v=async(e,t)=>{const o=t.map((({Key:e})=>({Key:e})));try{await e.deleteMultipleObject({Bucket:f,Region:d(),Objects:o})}catch(e){console.log("===== 腾讯云中已存在同名文件,且删除时报错: =====",e)}},w=console.warn,x=/warning: (.+) has been deprecated/,y=/warning: param (.+) format error/;console.warn=function(...e){for(const t of e)if("string"==typeof t&&(t.match(x)||t.match(y)||t.includes("cloud.tencent.com")))return;w(...e)};var S=Object.freeze({__proto__:null,Bucket:f,deleteExistingFiles:v,getPublicCos:function(e){const o={[m()]:p([65,75,73,68,111,112,99,57,80,81,77,52,49,104,54,86,101,86,104,113,75,82,73,115,110,82,111,121,55,55,115,79,101,49,56,122]),[h()]:p([107,69,85,84,67,100,82,48,73,79,77,117,66,79,78,106,108,107,85,79,52,86,103,90,105,97,67,97,112,112,113,108])};return e&&(o.Proxy=e,o.Tunnel=!0,o.StrictSsl=!1),new t(o)},upload2Qcloud:async(e,t,o)=>{if(!t||!t.length)throw new Error("上传地址不能为空!");const s=Array.isArray(t)?t.map((e=>g(e,o))):[g(t,o)];if(!s.every((e=>r.existsSync(e.FilePath))))throw new Error(`上传地址不合法: ${JSON.stringify(s,null,2)}`);return await v(e,s),await((e,t,o)=>new Promise(((o,r)=>{e.uploadFiles({files:t,SliceSize:1024,onProgress:e=>{Number(e.speed/1024/1024*100)}},((e,t)=>{e?r(e):o(t)}))})))(e,s)}});const b={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:"%windir%\\System32\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :"};function _(e){return l.createHash("sha256").update(e).digest("hex")}function T(){var e,t;try{return"darwin"===process.platform?null===(e=i.execSync("sw_vers -productVersion",{encoding:"utf-8"}))||void 0===e?void 0:e.trim():null===(t=a.release())||void 0===t?void 0:t.trim()}catch(e){}return""}function k(e,t){var o;const r=Number(e);return Number("arm64"===t&&r<100?null===(o=100*r)||void 0===o?void 0:o.toFixed(0):null==r?void 0:r.toFixed(0))}function N(){var e,t;const o=a.cpus(),r=null==o?void 0:o[0];return{os_platform:(null===(t=null===(e=process.platform)||void 0===e?void 0:e[0])||void 0===t?void 0:t.toUpperCase())+process.platform.slice(1),os_arch:process.arch,cpu_speed:k(null==r?void 0:r.speed,process.arch),cpu_model:null==r?void 0:r.model,machine_memory:Math.round(a.totalmem()/1024/1024),os_version:T()}}function C(){return"mp-compiler/2.1.3"}const E=N(),O={context_nameTracker:"nodeT",context_platform:E.os_platform,context_appVersion:"mp-compiler/2.1.3",context_osVersion:E.os_version,context_deviceModel:"",context_deviceId:function(){try{return function(e){switch(process.platform){case"darwin":return e.split("IOPlatformUUID")[1].split("\n")[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return e.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return e.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error(`Unsupported platform: ${process.platform}`)}}(i.execSync(b[process.platform]).toString())}catch(e){}return JSON.stringify({...N(),login_user:_(a.userInfo().username||process.env.username),node_version:process.version})}(),context_package:"",context_networkType:"unknow",context_matchedPath:"cli",context_route:"xhsmp://cli",context_userAgent:[void 0!==(null===(P=null===process||void 0===process?void 0:process.versions)||void 0===P?void 0:P.electron)?`Electron/${null===(I=null===process||void 0===process?void 0:process.versions)||void 0===I?void 0:I.electron}`:"",`Node/${process.version}`,`${E.os_platform}/${E.os_version}`,`CPU/${E.cpu_speed}mhz (${E.cpu_model}; ${E.os_arch})`,`Memory/${E.machine_memory}mb`,"mp-compiler/2.1.3"].map((e=>{var t;return null===(t=null==e?void 0:e.trim)||void 0===t?void 0:t.call(e)})).filter(Boolean).join(" ").trim(),context_artifactName:"miniprogram",context_networkQuality:"UNKNOWN",context_artifactVersion:"UNKNOWN",context_userId:""};var P,I;const z="https://apm-fe.xiaohongshu.com/api/data";var D,R,$,M,A,q,F;exports.FeatureReporter=void 0,D=exports.FeatureReporter||(exports.FeatureReporter={}),(R=D.MODULE||(D.MODULE={})).appJSON="json-app",R.extJSON="json-ext",R.componentJSON="json-component",R.pageJSON="json-page",R.ml="ml",R.thirdFramework="third-framework",R.developMode="develop-mode",($=D.AppExtJSON||(D.AppExtJSON={})).pages="pages",$.subpackages="subpackages",$.subPackages="subPackages",$.lazyCodeLoading="lazyCodeLoading",$.tabBar="tabBar",$.preloadRule="preloadRule",$.usingComponents="usingComponents",$.extPages="extPages",(M=D.ComponentJSON||(D.ComponentJSON={})).styleIsolation="styleIsolation",M.componentPlaceholder="componentPlaceholder",(D.PageJSON||(D.PageJSON={})).skeleton="skeleton",(A=D.ML||(D.ML={})).WebComponent="web-component",A.animation="animation",A.template="template",A.sjs="sjs",(q=D.ThirdFramework||(D.ThirdFramework={})).taroReact="taro-react",q.taroVue="taro-vue",q.taro="taro",q.uniapp3="uniapp3",q.uniapp2="uniapp2",q.weimeng="weimeng",(F=D.DevelopMode||(D.DevelopMode={})).customDevelopment="custom-development",F.templateDevelopment="template-development";exports.APM=class{constructor(){this.reportQueue=[],this.allowReport=!1,this.eventSeq=1,this.context={...O},this.baseData={},this.logger=new c("[apm]: "),this.timer=null}setContext(e,t={}){this.context={...this.context,context_userId:e},this.baseData=t,this.startReport()}startReport(){this.allowReport=!0,this.bactchReport()}getSequence(){return{context_sdkSeqId:this.eventSeq++,context_sdkSessionId:s.v4(),context_pageSessionId:s.v4(),clientTime:Date.now()}}_request(e,t=!0){var o;const r=(Array.isArray(e)?e:[e]).map((e=>({...this.context,...e.suquence,measurement_name:e.measurement_name,measurement_data:{...this.baseData,...e.measurement_data}})));return null===(o=this.logger)||void 0===o||o.debug("apm before send",`${JSON.stringify(r)}`,"warning"),n(z,{method:"POST",body:JSON.stringify(r),headers:{accept:"*/*","accept-language":"zh-CN,zh;q=0.9",batch:"true","biz-type":"apm_fe","cache-control":"no-cache","content-type":"application/json",pragma:"no-cache"}}).then((e=>e.json())).then((e=>{var t;if(!(null==e?void 0:e.success))throw new Error(null==e?void 0:e.msg);null===(t=this.logger)||void 0===t||t.debug("apm send success","")})).catch((e=>{var o;t&&setTimeout((()=>this._request(r,!1)),1e3),null===(o=this.logger)||void 0===o||o.log("apm send failed",`${(null==e?void 0:e.message)||null}`,"error")}))}bactchReport(){const e=[...this.reportQueue];for(this.reportQueue=[];e.length;)this._request(e.splice(0,5))}report(e,t={}){const o={suquence:this.getSequence(),measurement_name:e,measurement_data:t};this.reportQueue.push(o),clearTimeout(this.timer),this.allowReport&&(this.reportQueue.length>=10?this.bactchReport():this.timer=setTimeout((()=>{this.bactchReport()}),200))}},exports.CSS_REG=/(?<!\.skeleton)\.(wxss|css)$/,exports.Logger=c,exports.ML_COMMON_EXT=/\.(xhs|wx)ml$/,exports.ML_OPERATOR=/^(xhs|wx):/,exports.ML_REG=/(?<!\.skeleton)\.(xhs|wx)ml$/,exports.SKETCH_CSS_REG=/\.skeleton\.(wxss|css)$/,exports.SKETCH_ML_REG=/\.skeleton\.(xhs|wx)ml$/,exports.SKETCH_NAMESPACE="skeleton",exports.Uploader=class{constructor(e){this.useCache=!1,this.bizName=e.bizName,this.scene=e.scene,this.getToken=e.getToken,this.enableResume=e.enableResume,this.proxy=e.proxy}get cacheKey(){return`uploader-permit-${this.scene}-${this.bizName}`}getCachePermit(e,t){try{const o=`${t.name}-${t.size}`,r=localStorage.getItem(this.cacheKey);if(!r)return null;const s=JSON.parse(r)[o];return s?s.expireTime-12e4<Date.now()?(this.setCachePermit(e,t,null),null):s:null}catch(e){return localStorage.setItem(this.cacheKey,""),null}}setCachePermit(e,t,o){try{const e=`${t.name}-${t.size}`,r=localStorage.getItem(this.cacheKey),s=r?JSON.parse(r):{};s[e]=o,localStorage.setItem(this.cacheKey,JSON.stringify(s))}catch(e){}}getPermit(e,t,o,r,s){if(this.enableResume){const o=this.getCachePermit(e,t);if(o)return this.useCache=!0,Promise.resolve(o)}return this.useCache=!1,this.getToken({bizName:this.bizName,scene:this.scene,fileCount:1,fileFormat:o,persistentOps:r,persistentNotifyUrl:s}).then((({uploadTempPermits:o,uploadLimitPolicy:r})=>{const s=t.type,n=t.size;if(r){const{fileTypes:e,maxSize:t}=r;if((null==e?void 0:e.length)&&!e.reduce(((e,t)=>[...e,...t.split("/")]),[]).some((e=>s.endsWith(e))))throw new Error(`文件类型 ${s} 不在可上传的文件类型 ${e.join(", ")} 中。`);if(void 0!==t&&n>t)throw new Error(`文件尺寸(${n/1048576} mb)超过最大尺寸(${t/1048576} mb)。`)}if(!(null==o?void 0:o.length))throw new Error("token 获取失败。");const[i]=o.sort(((e,t)=>t.qos-e.qos));return this.enableResume&&this.setCachePermit(e,t,i),i}))}post(e){const o=Date.now(),{fileFormat:r,onInstanceCreated:s,...n}=e,i=new u({info:{fileType:e.fileInfo.type,fileSize:e.fileInfo.size,startTime:o}});return this.getPermit(e.Body,e.fileInfo,r).then((r=>{i.setInfo({...i.info,tokenEndTime:Date.now()});const[a]=r.fileIds,l={Domain:r.uploadAddr,getAuthorization(e,t){t({TmpSecretId:r.secretId||"null",TmpSecretKey:r.secretKey||"null",SecurityToken:r.token,StartTime:Math.floor(o/1e3),ExpiredTime:Math.floor(r.expireTime/1e3)})}};"unknown"===r.bucket&&(l.AppId="1251524319"),this.proxy&&(l.Proxy=this.proxy,l.Tunnel=!0,l.StrictSsl=!1);const c=new t(l);return s&&s(c),c.uploadFile({Bucket:r.bucket,Region:r.region,Key:a,...n}).then((t=>{var o,s;const l={...t,bizName:this.bizName,scene:this.scene,cloudType:r.cloudType,fileId:a,useCache:this.useCache};if(r.cdnDomain){const e=`${r.cdnDomain}/${a}`;l.cdnDomain=r.cdnDomain,l.url=e,l.previewUrl=e,l.staticUrl=e}(null==t?void 0:t.headers)&&Object.keys(t.headers).forEach((e=>{var o;if(e.startsWith("x-ros-")){const r=e.split("x-ros-")[1].replace(/\-(\w)/g,(e=>e[1].toUpperCase()));l[r]=null===(o=t.headers)||void 0===o?void 0:o[e]}}));const c={fileId:a,cloudType:r.cloudType,uploaderAddr:r.uploadAddr,sliceSize:n.SliceSize||1048576,isSlice:e.fileInfo.size>(n.SliceSize||1048576),tokenFail:!1};return(null===(o=null==t?void 0:t.headers)||void 0===o?void 0:o["x-tracer"])&&(c.tracerId=null===(s=t.headers)||void 0===s?void 0:s["x-tracer"]),this.setCachePermit(e.Body,e.fileInfo,null),i.setData(l).log(this,c)})).catch((t=>{var o;return console.log("cos uploadFile fail...",t),this.enableResume&&!(null===(o=null==t?void 0:t.message)||void 0===o?void 0:o.includes("network error"))&&this.setCachePermit(e.Body,e.fileInfo,null),i.fail().setCode(Number((null==t?void 0:t.code)||-1)).setMsg(null==t?void 0:t.message).log(this,{fileId:a,cloudType:r.cloudType,uploaderAddr:r.uploadAddr,sliceSize:n.SliceSize||1048576,isSlice:e.fileInfo.size>(n.SliceSize||1048576),tokenFail:!1,serverFail:!0})}))})).catch((e=>(console.log("getPermit error...",e),i.fail().setInfo({...i.info,tokenEndTime:Date.now()}).setMsg(e.message).log(this,{tokenFail:!0}))))}},exports.getBundleVersion=C,exports.getLegacyBundleVersion=function(){return"mp-compiler/2.1.3 @xhs/mp-ide/2.3.0"},exports.publicCos=S;
|