xhs-mp-shared 1.11.0
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/config/cos.config.d.ts +9 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +1 -0
- package/dist/utils/logger.d.ts +11 -0
- package/dist/utils/reporter.d.ts +52 -0
- package/dist/utils/tracker/device.d.ts +4 -0
- package/dist/utils/tracker/index.d.ts +29 -0
- package/dist/utils/tracker/tracker.d.ts +22 -0
- package/dist/utils/uploader/cos-upload.d.ts +14 -0
- package/dist/utils/uploader/index.d.ts +5 -0
- package/dist/utils/uploader/interface/index.d.ts +46 -0
- package/dist/utils/uploader/uploader.d.ts +32 -0
- package/dist/utils/uploader/utils.d.ts +29 -0
- package/package.json +44 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export declare enum MP_UPLOAD_INFO {
|
|
2
|
+
SECRET_ID = "AKIDopc9PQM41h6VeVhqKRIsnRoy77sOe18z",
|
|
3
|
+
SECRET_KEY = "kEUTCdR0IOMuBONjlkUO4VgZiaCappql",
|
|
4
|
+
BUCKET_NAME = "fe-static",
|
|
5
|
+
APP_ID = "1251524319",
|
|
6
|
+
REGION = "ap-shanghai",
|
|
7
|
+
HOST = "eva-1251524319.cos.ap-shanghai.myqcloud.com",
|
|
8
|
+
FILE_KEY = "mp/red/map"
|
|
9
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e=require("chalk"),t=require("cos-nodejs-sdk-v5"),o=require("path"),r=require("fs"),s=require("uuid"),i=require("node-fetch"),n=require("child_process"),a=require("os"),c=require("crypto");function l(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(o){if("default"!==o){var r=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,r.get?r:{enumerable:!0,get:function(){return e[o]}})}})),t.default=e,Object.freeze(t)}var u=l(t);class p{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 d{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:d.formatDate(this.info.startTime),endTime:d.formatDate(Date.now()),tokenStartTime:d.formatDate(this.info.startTime),tokenEndTime:d.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=d.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 i=(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);i&&(Object.keys(r).forEach((e=>{"boolean"==typeof r[e]&&(r[e]=Number(r[e]))})),i({measurement_name:"infraUploader",measurement_data:r},"ApmXrayTracker"))}finally{return this}}static formatDate(e){return new Date(e).toISOString().replace(/T/," ").replace(/\..+/,"")}}var h;!function(e){e.SECRET_ID="AKIDopc9PQM41h6VeVhqKRIsnRoy77sOe18z",e.SECRET_KEY="kEUTCdR0IOMuBONjlkUO4VgZiaCappql",e.BUCKET_NAME="fe-static",e.APP_ID="1251524319",e.REGION="ap-shanghai",e.HOST="eva-1251524319.cos.ap-shanghai.myqcloud.com",e.FILE_KEY="mp/red/map"}(h||(h={}));const m=new t({SecretId:h.SECRET_ID,SecretKey:h.SECRET_KEY}),f=`${h.BUCKET_NAME}-${h.APP_ID}`,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 i=`${`${h.FILE_KEY}`}/${t}/${r}`;return{Bucket:f,Region:h.REGION,Key:i,FilePath:e}},v=async e=>{const t=e.map((({Key:e})=>({Key:e})));try{await m.deleteMultipleObject({Bucket:f,Region:h.REGION,Objects:t})}catch(e){console.log("===== 腾讯云中已存在同名文件,且删除时报错: =====",e)}};var w=Object.freeze({__proto__:null,Bucket:f,deleteExistingFiles:v,qcloudClient:m,upload2Qcloud:async(e,t)=>{if(!e||!e.length)throw new Error("上传地址不能为空!");const o=Array.isArray(e)?e.map((e=>g(e,t))):[g(e,t)];if(!o.every((e=>r.existsSync(e.FilePath))))throw new Error(`上传地址不合法: ${JSON.stringify(o,null,2)}`);return await v(o),await((e,t)=>new Promise(((t,o)=>{m.uploadFiles({files:e,SliceSize:1024,onProgress:e=>{Number(e.speed/1024/1024*100)}},((e,r)=>{e?o(e):t(r)}))})))(o)}});const y={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 b(e){return c.createHash("sha256").update(e).digest("hex")}function S(){var e,t;try{return"darwin"===process.platform?null===(e=n.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 x(){var e,t,o;const r=a.cpus(),s=null==r?void 0:r[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:Number(null===(o=1e3*(null==s?void 0:s.speed))||void 0===o?void 0:o.toFixed(0)),cpu_model:null==s?void 0:s.model,machine_memory:Math.round(a.totalmem()/1024/1024),os_version:S()}}const _=x(),T={context_nameTracker:"nodeT",context_platform:_.os_platform,context_appVersion:"",context_osVersion:_.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}`)}}(n.execSync(y[process.platform]).toString())}catch(e){}return JSON.stringify({...x(),login_user:b(a.userInfo().username||process.env.username),node_version:process.version})}(),context_package:"",context_networkType:"unknow",context_matchedPath:"cli",context_route:"xhsmp://cli",context_userAgent:[`Node/${process.version}`,`${_.os_platform}/${_.os_version} (${_.cpu_model}; ${_.cpu_speed}mhz; ${_.machine_memory}mb)`].join(" "),context_artifactName:"miniprogram",context_networkQuality:"UNKNOWN",context_artifactVersion:"UNKNOWN",context_userId:""},E="https://apm-fe.xiaohongshu.com/api/data";var I,k,N,O,C,D,z;exports.FeatureReporter=void 0,I=exports.FeatureReporter||(exports.FeatureReporter={}),(k=I.MODULE||(I.MODULE={})).appJSON="json-app",k.extJSON="json-ext",k.componentJSON="json-component",k.ml="ml",k.thirdFramework="third-framework",k.developMode="develop-mode",(N=I.AppExtJSON||(I.AppExtJSON={})).pages="pages",N.subpackages="subpackages",N.subPackages="subPackages",N.lazyCodeLoading="lazyCodeLoading",N.tabBar="tabBar",N.preloadRule="preloadRule",N.usingComponents="usingComponents",N.extPages="extPages",(O=I.JSONComponent||(I.JSONComponent={})).styleIsolation="styleIsolation",O.componentPlaceholder="componentPlaceholder",(C=I.ML||(I.ML={})).WebComponent="web-component",C.animation="animation",C.template="template",C.sjs="sjs",(D=I.ThirdFramework||(I.ThirdFramework={})).taroReact="taro-react",D.taroVue="taro-vue",D.taro="taro",D.uniapp3="uniapp3",D.uniapp2="uniapp2",D.weimeng="weimeng",(z=I.DevelopMode||(I.DevelopMode={})).customDevelopment="custom-development",z.templateDevelopment="template-development",exports.COS=u,exports.APM=class{constructor(e){this.reportQueue=[],this.allowReport=!1,this.eventSeq=1,this.context={...T},this.baseData={},this.logger=new p("[apm]: "),this.timer=null,this.context.context_appVersion=e}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"),i(E,{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()}),500))}},exports.Logger=p,exports.Uploader=class{constructor(e){this.useCache=!1,this.bizName=e.bizName,this.scene=e.scene,this.getToken=e.getToken,this.enableResume=e.enableResume}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,i=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&&i>t)throw new Error(`文件尺寸(${i/1048576} mb)超过最大尺寸(${t/1048576} mb)。`)}if(!(null==o?void 0:o.length))throw new Error("token 获取失败。");const[n]=o.sort(((e,t)=>t.qos-e.qos));return this.enableResume&&this.setCachePermit(e,t,n),n}))}post(e){const o=Date.now(),{fileFormat:r,onInstanceCreated:s,...i}=e,n=new d({info:{fileType:e.fileInfo.type,fileSize:e.fileInfo.size,startTime:o}});return this.getPermit(e.Body,e.fileInfo,r).then((r=>{n.setInfo({...n.info,tokenEndTime:Date.now()});const[a]=r.fileIds,c={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&&(c.AppId="1251524319");const l=new t(c);return s&&s(l),l.uploadFile({Bucket:r.bucket,Region:r.region,Key:a,...i}).then((t=>{var o,s;const c={...t,bizName:this.bizName,scene:this.scene,cloudType:r.cloudType,fileId:a,useCache:this.useCache};if(r.cdnDomain){const e=`${r.cdnDomain}/${a}`;c.cdnDomain=r.cdnDomain,c.url=e,c.previewUrl=e,c.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()));c[r]=null===(o=t.headers)||void 0===o?void 0:o[e]}}));const l={fileId:a,cloudType:r.cloudType,uploaderAddr:r.uploadAddr,sliceSize:i.SliceSize||1048576,isSlice:e.fileInfo.size>(i.SliceSize||1048576),tokenFail:!1};return(null===(o=null==t?void 0:t.headers)||void 0===o?void 0:o["x-tracer"])&&(l.tracerId=null===(s=t.headers)||void 0===s?void 0:s["x-tracer"]),this.setCachePermit(e.Body,e.fileInfo,null),n.setData(c).log(this,l)})).catch((t=>{var o;return 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),n.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:i.SliceSize||1048576,isSlice:e.fileInfo.size>(i.SliceSize||1048576),tokenFail:!1,serverFail:!0})}))})).catch((e=>n.fail().setInfo({...n.info,tokenEndTime:Date.now()}).setMsg(e.message).log(this,{tokenFail:!0})))}},exports.publicCos=w;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare class Logger {
|
|
2
|
+
prefix: string;
|
|
3
|
+
private verbose;
|
|
4
|
+
constructor(prefix: string);
|
|
5
|
+
setVerbose(verbose: any): void;
|
|
6
|
+
info(...args: any[]): void;
|
|
7
|
+
log(...args: any[]): void;
|
|
8
|
+
debug(...args: any[]): void;
|
|
9
|
+
warn(...args: any[]): void;
|
|
10
|
+
error(...args: any[]): void;
|
|
11
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
export declare namespace FeatureReporter {
|
|
2
|
+
enum MODULE {
|
|
3
|
+
appJSON = "json-app",
|
|
4
|
+
extJSON = "json-ext",
|
|
5
|
+
componentJSON = "json-component",
|
|
6
|
+
ml = "ml",
|
|
7
|
+
thirdFramework = "third-framework",
|
|
8
|
+
developMode = "develop-mode"
|
|
9
|
+
}
|
|
10
|
+
enum AppExtJSON {
|
|
11
|
+
pages = "pages",
|
|
12
|
+
subpackages = "subpackages",
|
|
13
|
+
subPackages = "subPackages",
|
|
14
|
+
lazyCodeLoading = "lazyCodeLoading",
|
|
15
|
+
tabBar = "tabBar",
|
|
16
|
+
preloadRule = "preloadRule",
|
|
17
|
+
usingComponents = "usingComponents",
|
|
18
|
+
extPages = "extPages"
|
|
19
|
+
}
|
|
20
|
+
enum JSONComponent {
|
|
21
|
+
styleIsolation = "styleIsolation",
|
|
22
|
+
componentPlaceholder = "componentPlaceholder"
|
|
23
|
+
}
|
|
24
|
+
enum ML {
|
|
25
|
+
WebComponent = "web-component",
|
|
26
|
+
animation = "animation",
|
|
27
|
+
template = "template",
|
|
28
|
+
sjs = "sjs"
|
|
29
|
+
}
|
|
30
|
+
enum ThirdFramework {
|
|
31
|
+
taroReact = "taro-react",
|
|
32
|
+
taroVue = "taro-vue",
|
|
33
|
+
taro = "taro",
|
|
34
|
+
uniapp3 = "uniapp3",
|
|
35
|
+
uniapp2 = "uniapp2",
|
|
36
|
+
weimeng = "weimeng"
|
|
37
|
+
}
|
|
38
|
+
enum DevelopMode {
|
|
39
|
+
customDevelopment = "custom-development",
|
|
40
|
+
templateDevelopment = "template-development"
|
|
41
|
+
}
|
|
42
|
+
interface IReporter {
|
|
43
|
+
reportThirdFramework: (a: ThirdFramework) => void;
|
|
44
|
+
reportMlFeature: (a: ML) => void;
|
|
45
|
+
reportMlWebComponent: (a: string) => void;
|
|
46
|
+
reportJSONComponent: (a: JSONComponent) => void;
|
|
47
|
+
reportStyleIsolation: (a: string) => void;
|
|
48
|
+
reportAppJSON: (a: AppExtJSON) => void;
|
|
49
|
+
reportExtJSON: (a: AppExtJSON) => void;
|
|
50
|
+
reportDevelopMode: (a: DevelopMode) => void;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { IBase } from './tracker';
|
|
2
|
+
interface ISequence {
|
|
3
|
+
context_sdkSeqId: number;
|
|
4
|
+
context_sdkSessionId: string;
|
|
5
|
+
context_pageSessionId: string;
|
|
6
|
+
clientTime: number;
|
|
7
|
+
}
|
|
8
|
+
interface IReqItem {
|
|
9
|
+
suquence: ISequence;
|
|
10
|
+
measurement_name: string;
|
|
11
|
+
measurement_data: Record<string, any>;
|
|
12
|
+
}
|
|
13
|
+
export declare class APM {
|
|
14
|
+
private reportQueue;
|
|
15
|
+
private allowReport;
|
|
16
|
+
private eventSeq;
|
|
17
|
+
private context;
|
|
18
|
+
private baseData;
|
|
19
|
+
private logger;
|
|
20
|
+
constructor(version: string);
|
|
21
|
+
setContext(userId: string, base?: IBase): void;
|
|
22
|
+
private startReport;
|
|
23
|
+
private getSequence;
|
|
24
|
+
private _request;
|
|
25
|
+
private bactchReport;
|
|
26
|
+
private timer;
|
|
27
|
+
report(measurement_name: string, measurement_data?: IReqItem['measurement_data']): void;
|
|
28
|
+
}
|
|
29
|
+
export {};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export interface IDeviceInfo {
|
|
2
|
+
os_platform: string;
|
|
3
|
+
os_arch: string;
|
|
4
|
+
cpu_speed: number;
|
|
5
|
+
cpu_model: string;
|
|
6
|
+
machine_memory: number;
|
|
7
|
+
os_version: string;
|
|
8
|
+
}
|
|
9
|
+
export interface IDeviceUA {
|
|
10
|
+
login_user?: string;
|
|
11
|
+
node_version: string;
|
|
12
|
+
}
|
|
13
|
+
export interface IBase {
|
|
14
|
+
app_id?: string;
|
|
15
|
+
app_name?: string;
|
|
16
|
+
third_name?: string;
|
|
17
|
+
page_key?: string;
|
|
18
|
+
base_version?: string;
|
|
19
|
+
app_env?: number;
|
|
20
|
+
app_type?: number;
|
|
21
|
+
bundle_version?: string;
|
|
22
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import COS, { UploadFilesResult } from 'cos-nodejs-sdk-v5';
|
|
2
|
+
import { MP_UPLOAD_INFO } from '../../config/cos.config';
|
|
3
|
+
type TFiles = ReturnType<typeof generFile>;
|
|
4
|
+
export declare const qcloudClient: COS;
|
|
5
|
+
export declare const Bucket = "fe-static-1251524319";
|
|
6
|
+
declare const generFile: (filePath: string, uuidKey: any) => {
|
|
7
|
+
Bucket: string;
|
|
8
|
+
Region: MP_UPLOAD_INFO;
|
|
9
|
+
Key: string;
|
|
10
|
+
FilePath: string;
|
|
11
|
+
};
|
|
12
|
+
export declare const deleteExistingFiles: (files: TFiles[]) => Promise<void>;
|
|
13
|
+
export declare const upload2Qcloud: (filePath: string | string[], uuidKey: any) => Promise<UploadFilesResult>;
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import COS from 'cos-nodejs-sdk-v5';
|
|
2
|
+
export interface UploadResponse extends COS.UploadFileResult {
|
|
3
|
+
bizName: string;
|
|
4
|
+
scene: string;
|
|
5
|
+
cloudType: number;
|
|
6
|
+
cdnDomain?: string;
|
|
7
|
+
fileId: string;
|
|
8
|
+
previewUrl?: string;
|
|
9
|
+
staticUrl?: string;
|
|
10
|
+
url?: string;
|
|
11
|
+
useCache?: boolean;
|
|
12
|
+
}
|
|
13
|
+
export interface UploadTempPermit {
|
|
14
|
+
secretId?: string;
|
|
15
|
+
secretKey?: string;
|
|
16
|
+
token: string;
|
|
17
|
+
uploadAddr: string;
|
|
18
|
+
expireTime: number;
|
|
19
|
+
qos: number;
|
|
20
|
+
cloudType: number;
|
|
21
|
+
bucket: string;
|
|
22
|
+
region: string;
|
|
23
|
+
fileIds: string[];
|
|
24
|
+
masterCloudId: number;
|
|
25
|
+
uploadId: number;
|
|
26
|
+
cdnDomain?: string;
|
|
27
|
+
}
|
|
28
|
+
export interface TokenRequest {
|
|
29
|
+
bizName: string;
|
|
30
|
+
scene: string;
|
|
31
|
+
fileCount: number;
|
|
32
|
+
fileFormat?: string;
|
|
33
|
+
persistentOps?: string;
|
|
34
|
+
persistentNotifyUrl?: string;
|
|
35
|
+
}
|
|
36
|
+
export interface InternalTokenRequest extends TokenRequest {
|
|
37
|
+
subsystem: string;
|
|
38
|
+
}
|
|
39
|
+
export interface TokenResponse {
|
|
40
|
+
uploadLimitPolicy?: {
|
|
41
|
+
fileTypes?: string[];
|
|
42
|
+
maxSize?: number;
|
|
43
|
+
};
|
|
44
|
+
uploadTempPermits: UploadTempPermit[];
|
|
45
|
+
}
|
|
46
|
+
export type GetToken = (request: TokenRequest | InternalTokenRequest) => Promise<TokenResponse>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import COS, { UploadBody } from 'cos-nodejs-sdk-v5';
|
|
2
|
+
import { Response } from './utils';
|
|
3
|
+
import { UploadResponse, GetToken } from './interface';
|
|
4
|
+
interface IFileInfo {
|
|
5
|
+
name: string;
|
|
6
|
+
size: number;
|
|
7
|
+
type: string;
|
|
8
|
+
}
|
|
9
|
+
export declare class Uploader {
|
|
10
|
+
bizName: string;
|
|
11
|
+
scene: string;
|
|
12
|
+
getToken: GetToken;
|
|
13
|
+
enableResume?: boolean;
|
|
14
|
+
constructor(args: {
|
|
15
|
+
bizName: string;
|
|
16
|
+
scene: string;
|
|
17
|
+
getToken: GetToken;
|
|
18
|
+
enableResume?: boolean;
|
|
19
|
+
});
|
|
20
|
+
private useCache;
|
|
21
|
+
get cacheKey(): string;
|
|
22
|
+
private getCachePermit;
|
|
23
|
+
private setCachePermit;
|
|
24
|
+
private getPermit;
|
|
25
|
+
post(options: Omit<COS.UploadFileParams, 'Bucket' | 'Region' | 'Key'> & {
|
|
26
|
+
Body: UploadBody;
|
|
27
|
+
fileInfo: IFileInfo;
|
|
28
|
+
fileFormat?: string;
|
|
29
|
+
onInstanceCreated?: (instance: COS) => void;
|
|
30
|
+
}): Promise<Response<UploadResponse>>;
|
|
31
|
+
}
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { Uploader } from './uploader';
|
|
2
|
+
interface Info {
|
|
3
|
+
fileType: string;
|
|
4
|
+
fileSize: number;
|
|
5
|
+
startTime: number;
|
|
6
|
+
tokenEndTime?: number;
|
|
7
|
+
}
|
|
8
|
+
export declare class Response<T = Record<string, any>> {
|
|
9
|
+
success: boolean;
|
|
10
|
+
code: number;
|
|
11
|
+
msg?: string;
|
|
12
|
+
data?: T;
|
|
13
|
+
info: Info;
|
|
14
|
+
static getLogger(): any;
|
|
15
|
+
constructor({ success, code, info, }: {
|
|
16
|
+
success?: boolean;
|
|
17
|
+
code?: number;
|
|
18
|
+
info: Info;
|
|
19
|
+
});
|
|
20
|
+
setCode(code: number): Response<T>;
|
|
21
|
+
setMsg(msg?: string): Response<T>;
|
|
22
|
+
setData(data?: T): Response<T>;
|
|
23
|
+
setInfo(info: Info): Response<T>;
|
|
24
|
+
fail(): Response<T>;
|
|
25
|
+
log(uploader: Uploader, metrics?: any): Response<T>;
|
|
26
|
+
static formatDate(timestamp: number): string;
|
|
27
|
+
}
|
|
28
|
+
export declare const toHump: (str: string) => string;
|
|
29
|
+
export {};
|
package/package.json
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "xhs-mp-shared",
|
|
3
|
+
"version": "1.11.0",
|
|
4
|
+
"description": "",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"registry": "https://registry.npmjs.org/",
|
|
9
|
+
"access": "public"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist"
|
|
13
|
+
],
|
|
14
|
+
"author": "",
|
|
15
|
+
"license": "ISC",
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"chalk": "^4.1.2",
|
|
18
|
+
"chokidar": "^3.6.0",
|
|
19
|
+
"cos-nodejs-sdk-v5": "^2.13.4",
|
|
20
|
+
"fs-extra": "^11.2.0",
|
|
21
|
+
"lodash": "^4.17.21",
|
|
22
|
+
"node-fetch": "^2",
|
|
23
|
+
"query-string": "^8.1.0",
|
|
24
|
+
"uuid": "^9.0.1"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@rollup/plugin-commonjs": "^25.0.7",
|
|
28
|
+
"@types/node": "14",
|
|
29
|
+
"rimraf": "^5.0.5",
|
|
30
|
+
"rollup": "^4.9.6",
|
|
31
|
+
"rollup-plugin-terser": "^7.0.2",
|
|
32
|
+
"rollup-plugin-typescript2": "^0.36.0",
|
|
33
|
+
"typescript": "^5.4.3"
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"clean": "rimraf -rf ./dist",
|
|
37
|
+
"watch": "npm run clean && rollup -c -w --sourcemap true",
|
|
38
|
+
"build": "npm run clean && rollup -c",
|
|
39
|
+
"lint": "eslint --cache --ext .js,.jsx,.ts,.tsx,.vue,svelte ./src",
|
|
40
|
+
"lint:fix": "npm run lint -- --quiet --fix",
|
|
41
|
+
"test": "echo \"todo\"",
|
|
42
|
+
"version:beta": "npm version prerelease --no-git-tag-version"
|
|
43
|
+
}
|
|
44
|
+
}
|