picgo
Version:
A tool for picture uploading
1 lines • 364 kB
JavaScript
import e from"fs-extra";import t from"path";import{EventEmitter as n}from"events";import i,{homedir as r}from"os";import{Command as s}from"commander";import o from"inquirer";import{imageSize as a}from"image-size";import{URL as l}from"url";import c from"chalk";import u from"minimatch";import p from"globby";import E from"ejs";import g from"download-git-repo";import d from"rimraf";import _ from"dayjs";import I from"util";import m from"crypto";import C from"mime-types";import h from"qiniu";import P from"md5";import f from"resolve";import{merge as N,get as U,set as D,unset as L}from"lodash";import{spawn as S}from"child_process";import A from"is-wsl";import T from"axios";import O from"form-data";import B from"https";import y from"tunnel";import{JSONStore as b}from"@picgo/store";import R from"cross-spawn";import x from"js-yaml";import{ObjectAdapter as G,I18n as w}from"@picgo/i18n";const M={handle:e=>{const t=e.cmd;t.program.command("install <plugins...>").description("install picgo plugin").alias("add").option("-p, --proxy <proxy>","Add proxy for installing plugins").option("-r, --registry <registry>","Choose a registry for installing plugins").action(((t,n)=>{const{proxy:i,registry:r}=n,s={npmProxy:i,npmRegistry:r};e.pluginHandler.install(t,s).catch((t=>{e.log.error(t)}))})),t.program.command("uninstall <plugins...>").alias("rm").description("uninstall picgo plugin").action((t=>{e.pluginHandler.uninstall(t).catch((t=>{e.log.error(t)}))})),t.program.command("update <plugins...>").description("update picgo plugin").option("-p, --proxy <proxy>","Add proxy for installing plugins").option("-r, --registry <registry>","Choose a registry for installing plugins").action(((t,n)=>{const{proxy:i,registry:r}=n,s={npmProxy:i,npmRegistry:r};e.pluginHandler.update(t,s).catch((t=>{e.log.error(t)}))}))}},$={handle:e=>{e.cmd.program.option("-c, --config <path>","set config path")}},v=e=>e.startsWith("http://")||e.startsWith("https://"),H=e=>{e=e||"";try{return e!==decodeURI(e)}catch(e){return!1}},F=e=>(H(e)||(e=encodeURI(e)),e),k=e=>{try{const{width:t=0,height:n=0,type:i}=a(e);return{real:!0,width:t,height:n,extname:i?`.${i}`:".png"}}catch(e){return{real:!1,width:200,height:200,extname:".png"}}},q=async n=>{try{return{extname:t.extname(n),fileName:t.basename(n),buffer:await e.readFile(n),success:!0}}catch(e){return{reason:`read file ${n} error`,success:!1}}},K=async(e,n)=>{e=F(e);let i,r=!1,s="";const o=new Promise(((o,a)=>{(async()=>{var a;try{const a=await n.request({method:"get",url:e,resolveWithFullResponse:!0,responseType:"arraybuffer"}).then((e=>{const t=e.headers["content-type"];return(null==t?void 0:t.includes("image"))&&(r=!0,s=`.${t.split("image/")[1]}`),e.data}));if(clearTimeout(i),r){const n=new l(e).pathname,i=decodeURIComponent(t.basename(n));o({buffer:a,fileName:i,extname:s,success:!0})}else o({success:!1,reason:`${e} is not image`})}catch(t){clearTimeout(i),o({success:!1,reason:`request ${e} error, ${null!==(a=null==t?void 0:t.message)&&void 0!==a?a:""}`})}})().catch(a)})),a=new Promise((t=>{i=setTimeout((()=>{t({success:!1,reason:`request ${e} timeout`})}),1e4)}));return Promise.race([o,a])},Y=e=>/^@[^/]+\/picgo-plugin-/.test(e)?"scope":e.startsWith("picgo-plugin-")?"normal":j(e)?"simple":"unknown",j=n=>{if(t.isAbsolute(n))return!1;const i=t.join(process.cwd(),n);return!e.existsSync(i)&&(!n.includes("/")&&!n.includes("\\"))},Q=(e,t="")=>t?`@${t}/picgo-plugin-${e}`:`picgo-plugin-${e}`,W=(n,i=console)=>{switch(Y(n)){case"normal":case"scope":return n;case"simple":return Q(n);default:{let r=n;return t.isAbsolute(n)&&e.existsSync(n)?V(r):(r=t.join(process.cwd(),n),e.existsSync(r)?V(r):(i.warn(`Can't find plugin ${n}`),""))}}},z=(n,i=console)=>{var r;switch(Y(n)){case"normal":return J(n);case"scope":return J(n,!0);case"simple":return J(Q(n));default:{if(!e.existsSync(n))return i.warn(`Can't find plugin: ${n}`),"";const s=t.posix.join(n,"package.json");if(e.existsSync(s)){const t=e.readJSONSync(s)||{};return(null===(r=t.name)||void 0===r?void 0:r.includes("picgo-plugin-"))?t.name:(i.warn(`The plugin package.json's name filed is ${t.name||"empty"}, need to include the prefix: picgo-plugin-`),"")}return i.warn(`Can't find plugin: ${n}`),""}}},V=e=>e.split(t.sep).join("/"),J=(e,t=!1)=>{if(e.includes("@")){let n=/(.+\/)?(picgo-plugin-\w+)(@.+)*/;t&&(n=/(.+\/)?(^@[^/]+\/picgo-plugin-\w+)(@.+)*/);const i=e.match(n);return i?i[2]:(console.warn("can not remove plugin version"),e)}return e},X=[],Z=e=>X.some((t=>e.startsWith(t))),ee=e=>"object"==typeof e&&!Array.isArray(e)&&Object.keys(e).length>0;function te(e){try{return JSON.parse(e)}catch(t){return e}}const ne=(e=0)=>isNaN(Number(e))?0:Number(e),ie=()=>"development"===process.env.NODE_ENV;var re=Object.freeze({__proto__:null,isUrl:v,isUrlEncode:H,handleUrlEncode:F,getImageSize:k,getFSFile:q,getURLFile:K,getPluginNameType:Y,isSimpleName:j,handleStreamlinePluginName:e=>/^@[^/]+\/picgo-plugin-/.test(e)?e.replace(/^@[^/]+\/picgo-plugin-/,""):e.replace(/picgo-plugin-/,""),handleCompletePluginName:Q,getProcessPluginName:W,getNormalPluginName:z,handleUnixStylePath:V,removePluginVersion:J,configBlackList:X,isConfigKeyInBlackList:Z,isInputConfigValid:ee,safeParse:te,forceNumber:ne,isDev:ie,isProd:()=>"production"===process.env.NODE_ENV});const se={handle:n=>{n.cmd.program.command("upload").description("upload, go go go").arguments("[input...]").alias("u").action((i=>{(async()=>{const r=i.map((e=>v(e)?e:t.resolve(e))).filter((t=>{const i=e.existsSync(t)||v(t);return i||n.log.warn(`${t} does not exist.`),i}));await n.upload(r)})().catch((e=>{n.log.error(e)}))}))}},oe=async(e,t,n,i)=>{const r=await e.cmd.inquirer.prompt(t),s="uploader"===n?`picBed.${i}`:"transformer"===n?`transformer.${i}`:i;e.saveConfig({[s]:r}),"uploader"===n?e.saveConfig({"picBed.current":i,"picBed.uploader":i}):"transformer"===n&&e.saveConfig({"picBed.transformer":i})},ae={handle:e=>{e.cmd.program.command("set").alias("config").arguments("<module> [name]").description("configure config of picgo modules").action(((t,n)=>{(async()=>{var i,r;try{switch(t){case"uploader":case"transformer":if(n){const i=e.helper[t].get(n);if(!i)return e.log.error(`No ${t} named ${n}`);i.config&&await oe(e,i.config(e),t,n)}else{const n=[{type:"list",name:`${t}`,choices:e.helper[t].getIdList(),message:`Choose a(n) ${t}`}],i=await e.cmd.inquirer.prompt(n),r=e.helper[t].get(i[t]);(null==r?void 0:r.config)&&await oe(e,r.config(e),t,i[t])}break;case"plugin":if(n){if(n.includes("picgo-plugin-")||(n=`picgo-plugin-${n}`),!Object.keys(e.getConfig("picgoPlugins")).includes(n))return e.log.error(`No plugin named ${n}`);(null===(i=e.pluginLoader.getPlugin(n))||void 0===i?void 0:i.config)&&await oe(e,e.pluginLoader.getPlugin(n).config(e),"plugin",n)}else{const t=[{type:"list",name:"plugin",choices:e.pluginLoader.getFullList(),message:"Choose a plugin"}],n=await e.cmd.inquirer.prompt(t);(null===(r=e.pluginLoader.getPlugin(n.plugin))||void 0===r?void 0:r.config)&&await oe(e,e.pluginLoader.getPlugin(n.plugin).config(e),"plugin",n.plugin)}break;default:return e.log.warn(`No module named ${t}`),e.log.warn("Available modules are uploader|transformer|plugin")}e.log.success("Configure config successfully!"),"plugin"===t&&e.log.info("If you want to use this config, please run 'picgo use plugins'")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}})().catch((t=>{e.log.error(t)}))}))}},le={handle:async e=>{const t=e.cmd;t.program.command("use").arguments("[module]").description("use modules of picgo").action((n=>{(async()=>{try{let i=[];const r={uploader:{type:"list",name:"uploader",message:"Use an uploader",choices:e.helper.uploader.getIdList(),default:e.getConfig("picBed.uploader")||e.getConfig("picBed.current")||"smms"},transformer:{type:"list",name:"transformer",message:"Use a transformer",choices:e.helper.transformer.getIdList(),default:e.getConfig("picBed.transformer")||"path"},plugins:{type:"checkbox",name:"plugins",message:"Use plugins",choices:e.pluginLoader.getFullList(),default:Object.keys(e.getConfig("picgoPlugins")).filter((t=>e.getConfig(`picgoPlugins.${t}`)))}};if(n){if(!r[n])return e.log.warn(`No module named ${n}`),e.log.warn("Available modules are uploader|transformer|plugins");i.push(r[n])}else i=Object.keys(r).map((e=>r[e]));const s=await t.inquirer.prompt(i);if(s.plugins){const t=e.getConfig("picgoPlugins");Object.keys(t).map((e=>{s.plugins.includes(e)?t[e]=!0:t[e]=!1})),e.saveConfig({picgoPlugins:t})}e.saveConfig({"picBed.current":s.uploader||e.getConfig("picBed.current"),"picBed.uploader":s.uploader||e.getConfig("picBed.current"),"picBed.transformer":s.transformer||"path"}),e.log.success("Configure config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}})().catch((t=>{e.log.error(t)}))}))}},ce={handle:e=>{e.cmd.program.option("-p, --proxy <url>","set proxy for uploading",(t=>{e.setConfig({"picBed.proxy":t})}))}},ue=async(e,n)=>{try{const i=Ee(n.tmp),r=t.join(n.tmp,"template");let s={};i.prompts&&i.prompts.length>0&&(s=await e.cmd.inquirer.prompt(i.prompts));let o=await p(["**/*"],{cwd:r,dot:!0});if(o=o.filter((t=>{let n="";return Object.keys(i.filters).forEach((e=>{u(t,e,{dot:!0})&&(n=t)})),!n||pe(e,i.filters[n],s)})),0===o.length)return e.log.warn("Template files not found!");const a=ge(o,r,s);de(n.dest,a),"function"==typeof i.complete&&i.complete({answers:s,options:n,files:o,ctx:e}),i.completeMessage&&e.log.success(i.completeMessage),e.log.success("Done!")}catch(t){return e.log.error(t)}},pe=(e,t,n)=>{const i=new Function("data","with (data) { return "+t+"}");try{return i(n)}catch(n){return e.log.error(`Error when evaluating filter condition: ${JSON.stringify(t)}`),!1}},Ee=n=>{const i=t.join(n,"index.js");if(e.existsSync(i)){return require(i)}return{}},ge=(n,i,r)=>{const s={};return n.forEach((n=>{const o=e.readFileSync(t.join(i,n),"utf8"),a=E.render(o,r);(Buffer.isBuffer(a)||/[^\s]/.test(a))&&(s[n]=a)})),s},de=(n,i)=>{Object.keys(i).forEach((r=>{const s=t.join(n,r);e.ensureDirSync(t.dirname(s)),e.writeFileSync(s,i[r])}))},_e=(t,n)=>{n.offline?e.existsSync(n.template)?ue(t,n).catch((e=>{t.log.error(e)})):t.log.error(`Local template ${n.template} not found`):(n.template=n.hasSlash?n.template:"PicGo/picgo-template-"+n.template,Ie(t,n))},Ie=(t,n)=>{e.existsSync(n.tmp)&&d.sync(n.tmp),t.log.info("Template files are downloading..."),g(n.template,n.tmp,{clone:n.clone},(e=>{if(e)return t.log.error(e);t.log.success("Template files are downloaded!"),ue(t,n).catch((e=>{t.log.error(e)}))}))},me={handle:async n=>{n.cmd.program.command("init").arguments("<template> [project]").option("--clone","use git clone").option("--offline","use cached template").description("create picgo plugin's development templates").action(((i,s,o)=>{(async()=>{try{const a=i.includes("/"),l=!s||"."===s,c=t.resolve(s||"."),u=o.clone||!1,p=o.offline||!1,E=t.join(r(),".picgo/templates",i.replace(/[/:]/g,"-"));o.offline&&(i=E);const g={template:i,project:s,hasSlash:a,inPlace:l,dest:c,clone:u,tmp:E,offline:p};l||e.existsSync(c)?await n.cmd.inquirer.prompt([{type:"confirm",message:l?"Generate project in current directory?":"Target directory exists. Continue?",name:"ok"}]).then((e=>{e.ok&&_e(n,g)})):_e(n,g)}catch(e){if(n.log.error(e),process.argv.includes("--debug"))throw e}})().catch((e=>{n.log.error(e)}))})).on("--help",(()=>{console.log(),console.log("Examples:"),console.log(),console.log(c.gray(" # create a new project with an official template")),console.log(" $ picgo init plugin my-project"),console.log(),console.log(c.gray(" # create a new project straight from a github template")),console.log(" $ picgo init username/repo my-project"),console.log()}))}},Ce={handle:e=>{e.cmd.program.command("i18n").arguments("[lang]").description("change picgo language").action((async(t="")=>{const n=e.i18n.getLanguageList();if(!t){const t=[{type:"list",name:"i18n",choices:n,message:"Choose a language",default:e.getConfig("settings.language")||"zh-CN"}],i=await e.cmd.inquirer.prompt(t);return e.i18n.setLanguage(i.i18n),void e.log.success(`Language set to ${i.i18n}`)}if(!n.includes(t))return e.log.warn("No such language");e.i18n.setLanguage(t),e.log.success(`Language set to ${t}`)}))}};class he{constructor(e){this.name=e,this.list=new Map,this.pluginIdMap=new Map}register(e,t){var n;if(!e)throw new TypeError("id is required!");if("function"!=typeof t.handle)throw new TypeError("plugin.handle must be a function!");if(this.list.has(e))throw new TypeError(`${this.name} duplicate id: ${e}!`);this.list.set(e,t),he.currentPlugin&&(this.pluginIdMap.has(he.currentPlugin)?null===(n=this.pluginIdMap.get(he.currentPlugin))||void 0===n||n.push(e):this.pluginIdMap.set(he.currentPlugin,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);null==t||t.forEach((e=>{this.list.delete(e)}))}}getName(){return this.name}get(e){return this.list.get(e)}getList(){return[...this.list.values()]}getIdList(){return[...this.list.keys()]}}const Pe=(e=null)=>{he.currentPlugin=e};class fe{constructor(e){this.name="commander",this.list=new Map,this.pluginIdMap=new Map,this.program=new s,this.inquirer=o,this.ctx=e}getName(){return this.name}init(){var e;this.program.version("1.5.9","-v, --version").option("-d, --debug","debug mode",(()=>{this.ctx.setConfig({debug:!0})})).option("-s, --silent","silent mode",(()=>{this.ctx.setConfig({silent:!0})})).on("command:*",(()=>{this.ctx.log.error(`Invalid command: ${this.program.args.join(" ")}\nSee --help for a list of available commands.`),process.exit(1)})),(e=this.ctx).cmd.register("pluginHandler",M),e.cmd.register("config",$),e.cmd.register("setting",ae),e.cmd.register("upload",se),e.cmd.register("use",le),e.cmd.register("proxy",ce),e.cmd.register("init",me),e.cmd.register("i18n",Ce)}register(e,t){var n;if(!e)throw new TypeError("name is required!");if("function"!=typeof t.handle)throw new TypeError("plugin.handle must be a function!");if(this.list.has(e))throw new TypeError(`${this.name} plugin duplicate id: ${e}!`);this.list.set(e,t);const i=he.currentPlugin;null!==i&&(this.pluginIdMap.has(i)?null===(n=this.pluginIdMap.get(i))||void 0===n||n.push(e):this.pluginIdMap.set(i,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);null==t||t.forEach((e=>{this.list.delete(e)}))}}loadCommands(){this.getList().forEach((e=>{try{e.handle(this.ctx)}catch(e){this.ctx.log.error(e)}}))}get(e){return this.list.get(e)}getList(){return[...this.list.values()]}getIdList(){return[...this.list.keys()]}}var Ne,Ue,De;!function(e){e.success="success",e.info="info",e.warn="warn",e.error="error"}(Ne||(Ne={})),function(e){e.UPLOAD_PROGRESS="uploadProgress",e.FAILED="failed",e.BEFORE_TRANSFORM="beforeTransform",e.BEFORE_UPLOAD="beforeUpload",e.AFTER_UPLOAD="afterUpload",e.FINISHED="finished",e.INSTALL="install",e.UNINSTALL="uninstall",e.UPDATE="update",e.NOTIFICATION="notification"}(Ue||(Ue={})),function(e){e.CONFIG_CHANGE="CONFIG_CHANGE"}(De||(De={}));class Le{constructor(e){this.level={[Ne.success]:"green",[Ne.info]:"blue",[Ne.warn]:"yellow",[Ne.error]:"red"},this.ctx=e}handleLog(e,...n){if(this.logLevel=this.ctx.getConfig("settings.logLevel"),!this.ctx.getConfig("silent")&&this.checkLogLevel(e,this.logLevel)){const i=c[this.level[e]](`[PicGo ${e.toUpperCase()}]:`);console.log(i,...n),this.logPath=this.ctx.getConfig("settings.logPath")||t.join(this.ctx.baseDir,"./picgo.log"),setTimeout((()=>{try{const t=this.checkLogFileIsLarge(this.logPath);if(t.isLarge){const e=`Log file is too large (> ${t.logFileSizeLimit/1024/1024||"10"} MB), recreate log file`;console.log(c.yellow("[PicGo WARN]:"),e),this.recreateLogFile(this.logPath),n.unshift(e)}this.handleWriteLog(this.logPath,e,...n)}catch(e){console.error("[PicGo Error] on checking log file size",e)}}),0)}}checkLogFileIsLarge(t){if(e.existsSync(t)){const n=e.statSync(t).size,i=1024*ne(this.ctx.getConfig("settings.logFileSizeLimit")||10)*1024;return{isLarge:n>i,logFileSize:n,logFileSizeLimit:i}}return{isLarge:!1}}recreateLogFile(t){e.existsSync(t)&&(e.unlinkSync(t),e.createFileSync(t))}handleWriteLog(t,n,...i){try{let r=`${_().format("YYYY-MM-DD HH:mm:ss")} [PicGo ${n.toUpperCase()}] `;i.forEach((e=>{e instanceof Error&&"error"===n?r+=`\n------Error Stack Begin------\n${I.format(null==e?void 0:e.stack)}\n-------Error Stack End------- `:("object"==typeof e&&(e=JSON.stringify(e,null,2)),r+=`${e} `)})),r+="\n",e.appendFileSync(t,r)}catch(e){console.error("[PicGo Error] on writing log file",e)}}checkLogLevel(e,t){return void 0===t||"all"===t||(Array.isArray(t)?t.some((t=>t===e||"all"===t)):e===t)}success(...e){return this.handleLog(Ne.success,...e)}info(...e){return this.handleLog(Ne.info,...e)}error(...e){return this.handleLog(Ne.error,...e)}warn(...e){return this.handleLog(Ne.warn,...e)}debug(...e){ie()&&this.handleLog(Ne.info,...e)}}class Se extends n{constructor(e){super(),this.ctx=e}async start(e){const t=(e=>({configPath:e.configPath,baseDir:e.baseDir,log:e.log,cmd:e.cmd,output:[],input:[],pluginLoader:e.pluginLoader,pluginHandler:e.pluginHandler,Request:e.Request,helper:e.helper,VERSION:e.VERSION,GUI_VERSION:e.GUI_VERSION,request:e.request,i18n:e.i18n,getConfig:e.getConfig.bind(e),saveConfig:e.saveConfig.bind(e),removeConfig:e.removeConfig.bind(e),setConfig:e.setConfig.bind(e),unsetConfig:e.unsetConfig.bind(e),upload:e.upload.bind(e),addListener:e.addListener.bind(e),on:e.on.bind(e),once:e.once.bind(e),removeListener:e.removeListener.bind(e),off:e.off.bind(e),removeAllListeners:e.removeAllListeners.bind(e),setMaxListeners:e.setMaxListeners.bind(e),getMaxListeners:e.getMaxListeners.bind(e),listeners:e.listeners.bind(e),rawListeners:e.rawListeners.bind(e),emit:e.emit.bind(e),listenerCount:e.listenerCount.bind(e),prependListener:e.prependListener.bind(e),prependOnceListener:e.prependOnceListener.bind(e),eventNames:e.eventNames.bind(e)}))(this.ctx);try{if(!Array.isArray(e))throw new Error("Input must be an array.");return t.input=e,t.output=[],await this.beforeTransform(t),await this.doTransform(t),await this.beforeUpload(t),await this.doUpload(t),await this.afterUpload(t),t}catch(e){if(t.log.warn(Ue.FAILED),t.emit(Ue.UPLOAD_PROGRESS,-1),t.emit(Ue.FAILED,e),t.log.error(e),t.getConfig("debug"))throw e;return t}}async beforeTransform(e){return e.emit(Ue.UPLOAD_PROGRESS,0),e.emit(Ue.BEFORE_TRANSFORM,e),e.log.info("Before transform"),await this.handlePlugins(e.helper.beforeTransformPlugins,e),e}async doTransform(e){e.emit(Ue.UPLOAD_PROGRESS,30);const t=e.getConfig("picBed.transformer")||"path";let n=t,i=e.helper.transformer.get(t);return i||(i=e.helper.transformer.get("path"),n="path",e.log.warn(`Can't find transformer - ${t}, switch to default transformer - path`)),e.log.info(`Transforming... Current transformer is [${n}]`),await(null==i?void 0:i.handle(e)),e}async beforeUpload(e){return e.emit(Ue.UPLOAD_PROGRESS,60),e.log.info("Before upload"),e.emit(Ue.BEFORE_UPLOAD,e),await this.handlePlugins(e.helper.beforeUploadPlugins,e),e}async doUpload(e){let t=e.getConfig("picBed.uploader")||e.getConfig("picBed.current")||"smms",n=e.helper.uploader.get(t),i=t;n||(t="smms",i="smms",n=e.helper.uploader.get("smms"),e.log.warn(`Can't find uploader - ${t}, switch to default uploader - smms`)),e.log.info(`Uploading... Current uploader is [${i}]`),await(null==n?void 0:n.handle(e));for(const n of e.output)n.type=t;return e}async afterUpload(e){e.emit(Ue.AFTER_UPLOAD,e),e.emit(Ue.UPLOAD_PROGRESS,100),await this.handlePlugins(e.helper.afterUploadPlugins,e);let t="";const n=e.output.length,i=!0===e.getConfig("settings.encodeOutputURL");for(let r=0;r<n;r++)void 0!==e.output[r].imgUrl&&(t+=i?F(e.output[r].imgUrl):e.output[r].imgUrl,r!==n-1&&(t+="\n")),delete e.output[r].base64Image,delete e.output[r].buffer;return e.emit(Ue.FINISHED,e),e.log.success(`\n${t}`),e}async handlePlugins(e,t){const n=e.getList(),i=e.getIdList(),r=e.getName();return await Promise.all(n.map((async(e,n)=>{try{t.log.info(`${r}: ${i[n]} running`),await e.handle(t)}catch(e){throw t.log.error(`${r}: ${i[n]} error`),e}}))),t}}const Ae=(e,t,n,i="")=>({method:"POST",url:`https://${i||"sm.ms"}/api/v2/upload`,headers:{contentType:"multipart/form-data","User-Agent":"PicGo",Authorization:n},formData:{smfile:{value:t,options:{filename:e}},ssl:"true"}}),Te=async e=>{const t=e.getConfig("picBed.smms");if(!t)throw new Error("Can not find smms config!");const n=e.output;for(const i of n)if(i.fileName&&i.buffer){let n=i.buffer;!n&&i.base64Image&&(n=Buffer.from(i.base64Image,"base64"));const r=Ae(i.fileName,n,null==t?void 0:t.token,null==t?void 0:t.backupDomain);try{const t=await e.request(r),n=JSON.parse(t);if("success"===n.code)delete i.base64Image,delete i.buffer,i.imgUrl=n.data.url;else{if("image_repeated"!==n.code||"string"!=typeof n.images)throw e.emit(Ue.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:n.message}),new Error(n.message);delete i.base64Image,delete i.buffer,i.imgUrl=n.images}}catch(t){throw e.log.error(t),t}}return e},Oe=e=>{const t=e.getConfig("picBed.smms")||{};return[{name:"token",message:"api token",type:"password",get alias(){return e.i18n.translate("PICBED_SMMS_TOKEN")},default:t.token||"",required:!0},{name:"backupDomain",type:"input",get prefix(){return e.i18n.translate("PICBED_SMMS_BACKUP_DOMAIN")},get message(){return e.i18n.translate("PICBED_SMMS_MESSAGE_BACKUP_DOMAIN")},get alias(){return e.i18n.translate("PICBED_SMMS_BACKUP_DOMAIN")},default:t.backupDomain||"",required:!1}]};const Be=(e,t)=>{const n=e.secretId,i=e.secretKey,r=e.appId,s=e.bucket;let o,a="";if(e.version&&"v4"!==e.version){const n=Math.floor((new Date).getTime()/1e3);a=`${n};${n+86400}`;const r=m.createHmac("sha1",i).update(a).digest("hex"),s=e.endpoint?e.endpoint:`cos.${e.area}.myqcloud.com`,l=`put\n/${e.path}${t}\n\nhost=${e.bucket}.${s}\n`,c=`sha1\n${a}\n${m.createHash("sha1").update(l).digest("hex")}\n`;o=m.createHmac("sha1",r).update(c).digest("hex")}else{const e=Math.floor(1e10*Math.random()),t=Math.floor((new Date).getTime()/1e3)-1,a=`a=${r}&b=${s}&k=${n}&e=${t+3600}&t=${t}&r=${e}&f=`,l=m.createHmac("sha1",i).update(a).digest(),c=Buffer.concat([l,Buffer.from(a)]);o=Buffer.from(c).toString("base64")}return{signature:o,appId:r,bucket:s,signTime:a}},ye=(e,t,n,i,r)=>{const s=e.area,o=e.path;if(e.version&&"v4"!==e.version){const s=e.endpoint?e.endpoint:`cos.${e.area}.myqcloud.com`;return{method:"PUT",url:`http://${e.bucket}.${s}/${encodeURI(o)}${encodeURIComponent(t)}`,headers:{Host:`${e.bucket}.${s}`,Authorization:`q-sign-algorithm=sha1&q-ak=${e.secretId}&q-sign-time=${n.signTime}&q-key-time=${n.signTime}&q-header-list=host&q-url-param-list=&q-signature=${n.signature}`,contentType:C.lookup(t),"User-Agent":`PicGo;${r};null;null`},body:i,resolveWithFullResponse:!0}}return{method:"POST",url:`http://${s}.file.myqcloud.com/files/v2/${n.appId}/${n.bucket}/${encodeURI(o)}${t}`,headers:{Host:`${s}.file.myqcloud.com`,Authorization:n.signature,contentType:"multipart/form-data","User-Agent":`PicGo;${r};null;null`},formData:{op:"upload",filecontent:i},resolveWithFullResponse:!0}},be=async e=>{var t,n,i;const r=e.getConfig("picBed.tcyun");if(!r)throw new Error("Can't find tencent COS config");try{const s=e.output,o=r.customUrl,a=r.path,l=!r.version||"v4"===r.version;for(const c of s)if(c.fileName&&c.buffer){const s=Be(r,c.fileName);if(!s)return!1;let u=c.buffer;!u&&c.base64Image&&(u=Buffer.from(c.base64Image,"base64"));const p=ye(r,c.fileName,s,u,e.GUI_VERSION||e.VERSION),E=await e.request(p).then((e=>e)).catch((t=>({statusCode:400,body:{msg:e.i18n.translate("AUTH_FAILED"),err:t}})));let g;if(g=l&&"string"==typeof E?JSON.parse(E):E,400===g.statusCode)throw(null===(t=null==g?void 0:g.body)||void 0===t?void 0:t.err)?g.body.err:new Error((null===(n=null==g?void 0:g.body)||void 0===n?void 0:n.msg)||(null===(i=null==g?void 0:g.body)||void 0===i?void 0:i.message));const d=r.options||"",_=r.slim||"";if(l&&"SUCCESS"===g.message)delete c.base64Image,delete c.buffer,c.imgUrl=o?`${o}/${a}${c.fileName}`:`${g.data.source_url}${d}`;else{if(l||!g||200!==g.statusCode)throw new Error(E.body.msg);if(delete c.base64Image,delete c.buffer,o)c.imgUrl=`${o}/${encodeURI(a)}${encodeURIComponent(c.fileName)}${d}`;else{const e=r.endpoint?r.endpoint:`cos.${r.area}.myqcloud.com`;c.imgUrl=`https://${r.bucket}.${e}/${encodeURI(a)}${encodeURIComponent(c.fileName)}${d}`}}_&&(c.imgUrl+=d?"&imageSlim":"?imageSlim")}return e}catch(t){if(!r.version||"v4"===r.version)try{const n=JSON.parse(t.error);e.emit(Ue.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("UPLOAD_FAILED_REASON",{code:n.code}),text:"https://cloud.tencent.com/document/product/436/8432"})}catch(e){}throw t}},Re=e=>{const t=e.getConfig("picBed.tcyun")||{};return[{name:"version",type:"list",alias:e.i18n.translate("PICBED_TENCENTCLOUD_VERSION"),choices:["v4","v5"],default:"v5",required:!1},{name:"secretId",type:"input",get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_SECRETID")},default:t.secretId||"",required:!0},{name:"secretKey",type:"password",get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_SECRETKEY")},default:t.secretKey||"",required:!0},{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_BUCKET")},default:t.bucket||"",required:!0},{name:"appId",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_APPID")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_APPID")},default:t.appId||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_APPID")},required:!0},{name:"area",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_AREA")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_AREA")},default:t.area||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_AREA")},required:!0},{name:"endpoint",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_ENDPOINT")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_ENDPOINT")},default:t.endpoint||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT")},required:!1},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_PATH")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_PATH")},default:t.path||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_PATH")},required:!1},{name:"customUrl",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_CUSTOMURL")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_CUSTOMURL")},default:t.customUrl||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL")},required:!1},{name:"options",type:"input",default:t.options||"",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_OPTIONS")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_OPTIONS")},get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_OPTIONS")},required:!1},{name:"slim",type:"confirm",default:t.options||"",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM")},required:!1,get confirmText(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM_CONFIRM")},get cancelText(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM_CANCEL")},get tips(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM_TIP")}}]};const xe=(e,t,n)=>{const i=t.path||"",{token:r,repo:s}=t;return{method:"PUT",url:`https://api.github.com/repos/${s}/contents/${encodeURI(i)}${encodeURIComponent(e)}`,headers:{Authorization:`token ${r}`,"User-Agent":"PicGo","Content-Type":C.lookup(e)},body:n,json:!0}},Ge=async e=>{const t=e.getConfig("picBed.github");if(!t)throw new Error("Can't find github config");try{const n=e.output;for(const i of n)if(i.fileName&&i.buffer){const n=i.base64Image||Buffer.from(i.buffer).toString("base64"),r={message:"Upload by PicGo",branch:t.branch,content:n,path:t.path+encodeURI(i.fileName)},s=xe(i.fileName,t,r);try{const n=await e.request(s);if(!n)throw new Error("Server error, please try again");delete i.base64Image,delete i.buffer,t.customUrl?i.imgUrl=`${t.customUrl}/${encodeURI(t.path)}${encodeURIComponent(i.fileName)}`:i.imgUrl=n.content.download_url}catch(e){if(422!==e.statusCode)throw e;delete i.base64Image,delete i.buffer,t.customUrl?i.imgUrl=`${t.customUrl}/${encodeURI(t.path)}${encodeURIComponent(i.fileName)}`:i.imgUrl=`https://raw.githubusercontent.com/${t.repo}/${t.branch}/${encodeURI(t.path)}${encodeURIComponent(i.fileName)}`}}return e}catch(t){throw e.emit(Ue.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK")}),t}},we=e=>{const t=e.getConfig("picBed.github")||{};return[{name:"repo",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_REPO")},get alias(){return e.i18n.translate("PICBED_GITHUB_REPO")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_REPO")},default:t.repo||"",required:!0},{name:"branch",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_BRANCH")},get alias(){return e.i18n.translate("PICBED_GITHUB_BRANCH")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_BRANCH")},default:t.branch||"master",required:!0},{name:"token",type:"password",get alias(){return e.i18n.translate("PICBED_GITHUB_TOKEN")},default:t.token||"",required:!0},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_PATH")},get alias(){return e.i18n.translate("PICBED_GITHUB_PATH")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_PATH")},default:t.path||"",required:!1},{name:"customUrl",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_CUSTOMURL")},get alias(){return e.i18n.translate("PICBED_GITHUB_CUSTOMURL")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_CUSTOMURL")},default:t.customUrl||"",required:!1}]};function Me(e,t,n,i){const r=function(e){return"z0"===e?"":"-"+e}(e.area||"z0"),s=e.path||"";return{method:"POST",url:`http://upload${r}.qiniup.com/putb64/-1/key/${Buffer.from(s+t,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_")}`,headers:{Authorization:`UpToken ${n}`,"Content-Type":C.lookup(t)||"application/octet-stream"},body:i}}function $e(e){const t=e.accessKey,n=e.secretKey,i=new h.auth.digest.Mac(t,n),r={scope:e.bucket};return new h.rs.PutPolicy(r).uploadToken(i)}const ve=async e=>{const t=e.getConfig("picBed.qiniu");if(!t)throw new Error("Can't find qiniu config");try{const n=e.output;for(const i of n)if(i.fileName&&i.buffer){const n=i.base64Image||Buffer.from(i.buffer).toString("base64"),r=Me(t,i.fileName,$e(t),n),s=await e.request(r),o=JSON.parse(s);if(!(null==o?void 0:o.key))throw e.emit(Ue.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:o.msg}),e.log.error("qiniu error",o),new Error("Upload failed");{delete i.base64Image,delete i.buffer;const e=t.url,n=t.options;i.imgUrl=`${e}/${o.key}${n}`}}return e}catch(t){if("Upload failed"!==t.message&&t.response){const n=t.response.body;e.emit(Ue.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:n.error})}throw t}},He=e=>{const t=e.getConfig("picBed.qiniu")||{};return[{name:"accessKey",type:"input",get alias(){return e.i18n.translate("PICBED_QINIU_ACCESSKEY")},default:t.accessKey||"",required:!0},{name:"secretKey",type:"password",get alias(){return e.i18n.translate("PICBED_QINIU_SECRETKEY")},default:t.secretKey||"",required:!0},{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_QINIU_BUCKET")},default:t.bucket||"",required:!0},{name:"url",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_URL")},get alias(){return e.i18n.translate("PICBED_QINIU_URL")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_URL")},default:t.url||"",required:!0},{name:"area",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_AREA")},get alias(){return e.i18n.translate("PICBED_QINIU_AREA")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_AREA")},default:t.area||"",required:!0},{name:"options",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_OPTIONS")},get alias(){return e.i18n.translate("PICBED_QINIU_OPTIONS")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_OPTIONS")},default:t.options||"",required:!1},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_PATH")},get alias(){return e.i18n.translate("PICBED_QINIU_PATH")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_PATH")},default:t.path||"",required:!1}]};const Fe=(e,t,n)=>{const i={method:"POST",url:"https://api.imgur.com/3/image",headers:{Authorization:`Client-ID ${e.clientId}`,"content-type":"multipart/form-data",Host:"api.imgur.com","User-Agent":"PicGo"},formData:{image:n,type:"base64",name:t}};return e.proxy&&(i.proxy=e.proxy),i},ke=async e=>{var t;const n=e.getConfig("picBed.imgur");if(!n)throw new Error("Can't find imgur config");try{const t=e.output;for(const i of t)if(i.fileName&&i.buffer){const t=i.base64Image||Buffer.from(i.buffer).toString("base64"),r=Fe(n,i.fileName,t),s=await e.request(r),o="string"==typeof s?JSON.parse(s):s;if(!o.success)throw new Error("Server error, please try again");delete i.base64Image,delete i.buffer,i.imgUrl=o.data.link}return e}catch(n){throw e.emit(Ue.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK"),text:"http://docs.imgur.com/api/errno/"}),(null===(t=null==n?void 0:n.response)||void 0===t?void 0:t.data)||n}},qe=e=>{const t=e.getConfig("picBed.imgur")||{};return[{name:"clientId",type:"input",get alias(){return e.i18n.translate("PICBED_IMGUR_CLIENTID")},default:t.clientId||"",required:!0},{name:"proxy",type:"input",get prefix(){return e.i18n.translate("PICBED_IMGUR_PROXY")},get alias(){return e.i18n.translate("PICBED_IMGUR_PROXY")},get message(){return e.i18n.translate("PICBED_IMGUR_MESSAGE_PROXY")},default:t.proxy||"",required:!1}]};const Ke=(e,t)=>{const n=(new Date).toUTCString(),i=C.lookup(t);if(!i)throw Error(`No mime type found for file ${t}`);const r=`PUT\n\n${i}\n${n}\n/${e.bucket}/${e.path}${t}`,s=m.createHmac("sha1",e.accessKeySecret).update(r).digest("base64");return`OSS ${e.accessKeyId}:${s}`},Ye=(e,t,n,i)=>({method:"PUT",url:`https://${e.bucket}.${e.area}.aliyuncs.com/${encodeURI(e.path)}${encodeURIComponent(t)}`,headers:{Host:`${e.bucket}.${e.area}.aliyuncs.com`,Authorization:n,Date:(new Date).toUTCString(),"Content-Type":C.lookup(t)},body:i,resolveWithFullResponse:!0}),je=async e=>{const t=e.getConfig("picBed.aliyun");if(!t)throw new Error("Can't find aliYun OSS config");try{const n=e.output,i=t.customUrl,r=t.path;for(const s of n)if(s.fileName&&s.buffer){const n=Ke(t,s.fileName);let o=s.buffer;!o&&s.base64Image&&(o=Buffer.from(s.base64Image,"base64"));const a=Ye(t,s.fileName,n,o);if(200!==(await e.request(a)).statusCode)throw new Error("Upload failed");{delete s.base64Image,delete s.buffer;const e=t.options||"";s.imgUrl=i?`${i}/${encodeURI(r)}${encodeURIComponent(s.fileName)}${e}`:`https://${t.bucket}.${t.area}.aliyuncs.com/${encodeURI(r)}${encodeURIComponent(s.fileName)}${e}`}}return e}catch(t){throw e.emit(Ue.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")}),t}},Qe=e=>{const t=e.getConfig("picBed.aliyun")||{};return[{name:"accessKeyId",type:"input",get alias(){return e.i18n.translate("PICBED_ALICLOUD_ACCESSKEYID")},default:t.accessKeyId||"",required:!0},{name:"accessKeySecret",type:"password",get alias(){return e.i18n.translate("PICBED_ALICLOUD_ACCESSKEYSECRET")},default:t.accessKeySecret||"",required:!0},{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_ALICLOUD_BUCKET")},default:t.bucket||"",required:!0},{name:"area",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_AREA")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_AREA")},default:t.area||"",get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_AREA")},required:!0},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_PATH")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_PATH")},get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_PATH")},default:t.path||"",required:!1},{name:"customUrl",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_CUSTOMURL")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_CUSTOMURL")},get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_CUSTOMURL")},default:t.customUrl||"",required:!1},{name:"options",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_OPTIONS")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_OPTIONS")},get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_OPTIONS")},default:t.options||"",required:!1}]};const We=(e,t)=>{const n=e.path||"",i=e.operator,r=e.password,s=P(r),o=(new Date).toUTCString(),a=`PUT&${`/${e.bucket}/${encodeURI(n)}${encodeURIComponent(t)}`}&${o}`;return`UPYUN ${i}:${m.createHmac("sha1",s).update(a).digest("base64")}`},ze=(e,t,n,i)=>{const r=e.bucket,s=e.path||"";return{method:"PUT",url:`https://v0.api.upyun.com/${r}/${encodeURI(s)}${encodeURIComponent(t)}`,headers:{Authorization:n,Date:(new Date).toUTCString(),"Content-Type":C.lookup(t)||"application/octet-stream"},body:i,resolveWithFullResponse:!0}},Ve=async e=>{const t=e.getConfig("picBed.upyun");if(!t)throw new Error("Can't find upYun config");try{const n=e.output,i=t.path||"";for(const r of n)if(r.fileName&&r.buffer){let n=r.buffer;!n&&r.base64Image&&(n=Buffer.from(r.base64Image,"base64"));const s=We(t,r.fileName),o=ze(t,r.fileName,s,n);if(200!==(await e.request(o)).statusCode)throw new Error("Upload failed");delete r.base64Image,delete r.buffer,r.imgUrl=`${t.url}/${encodeURI(i)}${encodeURIComponent(r.fileName)}${t.options}`}return e}catch(t){if("Upload failed"===t.message)e.emit(Ue.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")});else{const n=te(t.error);e.emit(Ue.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("UPLOAD_FAILED_REASON",{code:"object"==typeof n?n.code:n}),text:"http://docs.upyun.com/api/errno/"})}throw t}},Je=e=>{const t=e.getConfig("picBed.upyun")||{};return[{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_UPYUN_BUCKET")},default:t.bucket||"",required:!0},{name:"operator",type:"input",get alias(){return e.i18n.translate("PICBED_UPYUN_OPERATOR")},get prefix(){return e.i18n.translate("PICBED_UPYUN_OPERATOR")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_OPERATOR")},default:t.operator||"",required:!0},{name:"password",type:"password",get prefix(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_PASSWORD")},get alias(){return e.i18n.translate("PICBED_UPYUN_PASSWORD")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_PASSWORD")},default:t.password||"",required:!0},{name:"url",type:"input",get alias(){return e.i18n.translate("PICBED_UPYUN_URL")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_URL")},default:t.url||"",required:!0},{name:"options",type:"input",get prefix(){return e.i18n.translate("PICBED_UPYUN_OPTIONS")},get alias(){return e.i18n.translate("PICBED_UPYUN_OPTIONS")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_OPTIONS")},default:t.options||"",required:!1},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_UPYUN_PATH")},get alias(){return e.i18n.translate("PICBED_UPYUN_PATH")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_PATH")},default:t.path||"",required:!1}]};const Xe=()=>({register(e){!function(e){e.helper.uploader.register("aliyun",{get name(){return e.i18n.translate("PICBED_ALICLOUD")},handle:je,config:Qe})}(e),function(e){e.helper.uploader.register("tcyun",{get name(){return e.i18n.translate("PICBED_TENCENTCLOUD")},handle:be,config:Re})}(e),function(e){e.helper.uploader.register("smms",{get name(){return e.i18n.translate("PICBED_SMMS")},handle:Te,config:Oe})}(e),function(e){e.helper.uploader.register("github",{get name(){return e.i18n.translate("PICBED_GITHUB")},handle:Ge,config:we})}(e),function(e){e.helper.uploader.register("qiniu",{get name(){return e.i18n.translate("PICBED_QINIU")},handle:ve,config:He})}(e),function(e){e.helper.uploader.register("imgur",{get name(){return e.i18n.translate("PICBED_IMGUR")},handle:ke,config:qe})}(e),function(e){e.helper.uploader.register("upyun",{get name(){return e.i18n.translate("PICBED_UPYUN")},handle:Ve,config:Je})}(e)}}),Ze=(e,t,n)=>{const i=k(t);return i.real||("string"==typeof n?e.log.warn(`can't get ${n}'s image size`):e.log.warn("can't get image size"),e.log.warn("fallback to 200 * 200")),i};var et={handle:async e=>{const t=e.output;return await Promise.all(e.input.map((async(n,i)=>{let r;if(r=Buffer.isBuffer(n)?{success:!0,buffer:n,fileName:"",extname:""}:v(n)?await K(n,e):await q(n),r.success&&r.buffer){const s=Ze(e,r.buffer,n),o=r.extname||s.extname||".png";t[i]={buffer:r.buffer,fileName:r.fileName||`${_().format("YYYYMMDDHHmmssSSS")}${o}}`,width:s.width,height:s.height,extname:o}}else e.log.error(r.reason)}))),e.output=t.filter((e=>e)),e}};var tt={handle:async e=>(e.output.push(...e.input),e)};class nt{constructor(e){this.list=[],this.fullList=new Set,this.pluginMap=new Map,this.ctx=e,this.init()}init(){const n=t.join(this.ctx.baseDir,"package.json");if(!e.existsSync(n)){const t={name:"picgo-plugins",description:"picgo-plugins",repository:"https://github.com/PicGo/PicGo-Core",license:"MIT"};e.writeFileSync(n,JSON.stringify(t),"utf8")}}resolvePlugin(e,n){try{return f.sync(n,{basedir:e.baseDir})}catch(i){return t.join(e.baseDir,"node_modules",n)}}load(){const n=t.join(this.ctx.baseDir,"package.json"),i=t.join(this.ctx.baseDir,"node_modules/");if(!e.existsSync(i))return!1;const r=e.readJSONSync(n),s=Object.keys(r.dependencies||{}),o=Object.keys(r.devDependencies||{}),a=s.concat(o).filter((t=>{if(!/^picgo-plugin-|^@[^/]+\/picgo-plugin-/.test(t))return!1;const n=this.resolvePlugin(this.ctx,t);return e.existsSync(n)}));for(const e of a)this.registerPlugin(e);return!0}registerPlugin(e,t){if(e&&"string"==typeof e){this.fullList.add(e);try{if(t){this.list.push(e),Pe(e);const n=t(this.ctx);this.pluginMap.set(e,n),n.register(this.ctx)}else if(!0===this.ctx.getConfig(`picgoPlugins.${e}`)||void 0===this.ctx.getConfig(`picgoPlugins.${e}`)){this.list.push(e),Pe(e),this.getPlugin(e).register(this.ctx);const t=`picgoPlugins[${e}]`;this.ctx.saveConfig({[t]:!0})}}catch(t){this.pluginMap.delete(e),this.list=this.list.filter((t=>t!==e)),this.fullList.delete(e),this.ctx.log.error(t),this.ctx.emit(Ue.NOTIFICATION,{title:`Plugin ${e} Load Error`,body:t})}}else this.ctx.log.warn("Please provide valid plugin")}unregisterPlugin(e){this.list=this.list.filter((t=>t!==e)),this.fullList.delete(e),this.pluginMap.delete(e),Pe(e),this.ctx.helper.uploader.unregister(e),this.ctx.helper.transformer.unregister(e),this.ctx.helper.beforeTransformPlugins.unregister(e),this.ctx.helper.beforeUploadPlugins.unregister(e),this.ctx.helper.afterUploadPlugins.unregister(e),this.ctx.cmd.unregister(e),this.ctx.removeConfig("picgoPlugins",e)}getPlugin(e){if(this.pluginMap.has(e))return this.pluginMap.get(e);const n=t.join(this.ctx.baseDir,"node_modules/"),i=require(n+e)(this.ctx);return this.pluginMap.set(e,i),i}getList(){return this.list}hasPlugin(e){return this.fullList.has(e)}getFullList(){return[...this.fullList]}}const it={darwin:'-- From https://github.com/mushanshitiancai/vscode-paste-image\nproperty fileTypes : {{«class PNGf», ".png"}}\n\non run argv\n\tif argv is {} then\n\t\treturn ""\n\tend if\n\n\tif ((clipboard info) as string) contains "«class furl»" then\n\t\treturn POSIX path of (the clipboard as «class furl»)\n\telse\n\t\tset imagePath to (item 1 of argv)\n\t\tset theType to getType()\n\n\t\tif theType is not missing value then\n\t\t\ttry\n\t\t\t\tset myFile to (open for access imagePath with write permission)\n\t\t\t\tset eof myFile to 0\n\t\t\t\twrite (the clipboard as (first item of theType)) to myFile\n\t\t\t\tclose access myFile\n\t\t\t\treturn (POSIX path of imagePath)\n\t\t\ton error\n\t\t\t\ttry\n\t\t\t\t\tclose access myFile\n\t\t\t\tend try\n\t\t\t\treturn "no image"\n\t\t\tend try\n\t\telse\n\t\t\treturn "no image"\n\t\tend if\n\tend if\nend run\n\non getType()\n\trepeat with aType in fileTypes\n\t\trepeat with theInfo in (clipboard info)\n\t\t\tif (first item of theInfo) is equal to (first item of aType) then return aType\n\t\tend repeat\n\tend repeat\n\treturn missing value\nend getType\n',win32:'\nparam($imagePath)\n\n# Adapted from https://github.com/octan3/img-clipboard-dump/blob/master/dump-clipboard-png.ps1\n\nAdd-Type -Assembly PresentationCore\n$img = [Windows.Clipboard]::GetImage()\n\nif ($img -eq $null) {\n "no image"\n Exit 1\n}\n\nif (-not $imagePath) {\n "no image"\n Exit 1\n}\n\n$fcb = new-object Windows.Media.Imaging.FormatConvertedBitmap($img, [Windows.Media.PixelFormats]::Rgb24, $null, 0)\n$stream = [IO.File]::Open($imagePath, "OpenOrCreate")\n$encoder = New-Object Windows.Media.Imaging.PngBitmapEncoder\n$encoder.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($fcb)) | out-null\n$encoder.Save($stream) | out-null\n$stream.Dispose() | out-null\n\n$imagePath\n',win10:'# Adapted from https://github.com/octan3/img-clipboard-dump/blob/master/dump-clipboard-png.ps1\nparam($imagePath)\n\n# https://github.com/PowerShell/PowerShell/issues/7233\n# fix the output encoding bug\n[console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding\n\nAdd-Type -Assembly PresentationCore\nfunction main {\n $img = [Windows.Clipboard]::GetImage()\n\n if ($img -eq $null) {\n "no image"\n Exit 1\n }\n\n if (-not $imagePath) {\n "no image"\n Exit 1\n }\n\n $fcb = new-object Windows.Media.Imaging.FormatConvertedBitmap($img, [Windows.Media.PixelFormats]::Rgb24, $null, 0)\n $stream = [IO.File]::Open($imagePath, "OpenOrCreate")\n $encoder = New-Object Windows.Media.Imaging.PngBitmapEncoder\n $encoder.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($fcb)) | out-null\n $encoder.Save($stream) | out-null\n $stream.Dispose() | out-null\n\n $imagePath\n # fix windows 10 native cmd crash bug when "picgo upload"\n # https://github.com/PicGo/PicGo-Core/issues/32\n Exit 1\n}\n\ntry {\n # For WIN10\n $file = Get-Clipboard -Format FileDropList\n if ($file -ne $null) {\n Convert-Path $file\n Exit 1\n }\n} catch {\n # For WIN7 WIN8 WIN10\n main\n}\n\nmain',linux:'#!/bin/sh\nif [ "$XDG_SESSION_TYPE" = "x11" ]; then\n # require xclip(see http://stackoverflow.com/questions/592620/check-if-a-program-exists-from-a-bash-script/677212#677212)\n command -v xclip >/dev/null 2>&1 || { echo >&1 "no xclip"; exit 1; }\n # write image in clipboard to file (see http://unix.stackexchange.com/questions/145131/copy-image-from-clipboard-to-file)\n filePath=`xclip -selection clipboard -o 2>/dev/null | grep ^file:// | cut -c8-`\n if [ ! -n "$filePath" ] ;then\n if\n xclip -selection clipboard -target image/png -o >/dev/null 2>&1\n then\n xclip -selection clipboard -target image/png -o >$1 2>/dev/null\n echo $1\n else\n echo "no image"\n fi\n else\n echo $filePath\n fi\nelif [ "$XDG_SESSION_TYPE" = "wayland" ]; then\n command -v wl-paste >/dev/null 2>&1 || { echo >&1 "no wl-clipboard"; exit 1; }\n isImage=`wl-paste --list-types | grep image`\n if [ -n "$isImage" ]; then\n wl-paste --type image/png > $1 2>/dev/null\n echo $1\n else\n echo "no image"\n exit 1\n fi\nfi\n',wsl:'#!/bin/sh\n# grab the paths\nscriptPath=$(echo $0 | awk \'{ print substr( $0, 1, length($0)-6 ) }\')"windows10.ps1"\nimagePath=$(echo $1 | awk \'{ print substr( $0, 1, length($0)-18 ) }\')\nimageName=$(echo $1 | awk \'{ print substr( $0, length($0)-17, length($0) ) }\')\n\n# run the powershell script\nres=$(powershell.exe -noprofile -noninteractive -nologo -sta -executionpolicy unrestricted -file $(wslpath -w $scriptPath) $(wslpath -w $imagePath)"\\\\"$imageName)\n\n# note that there is a return symbol in powershell result\nnoImage=$(echo "no image\\r")\n\n# check whether image exists\nif [ "$res" = "$noImage" ] ;then\n echo "no image"\nelse\n echo $(wslpath -u -a "${res}")\nfi\n'},rt={darwin:"mac.applescript",win32:"windows.ps1",win10:"windows10.ps1",linux:"linux.sh",wsl:"wsl.sh"};const st=async n=>{!function(n){const i=t.join(n.baseDir,"picgo-clipboard-images");e.existsSync(i)||e.mkdirSync(i)}(n);const r=t.join(n.baseDir,"picgo-clipboard-images",`${_().format("YYYYMMDDHHmmssSSS")}.png`);return await new Promise(((s,o)=>{const a=(()=>{const e=process.platform;if(A)return"wsl";if("win32"===e)return"10"===i.release().split(".")[0]?"win10":"win32";return"darwin"===e?"darwin":"linux"})(),l=t.join(n.baseDir,rt[a]);let c;e.existsSync(l)||e.writeFileSync(l,it[a],"utf8"),c="darwin"===a?S("osascript",[l,r]):"win32"===a||"win10"===a?S("powershell",["-noprofile","-noninteractive","-nologo","-sta","-executionpolicy","unrestricted","-file",l,r]):S("sh",[l,r]),c.stdout.on("data",(i=>{if("linux"===a&&"no xclip or wl-clipboard"===i.toString().trim())return n.emit(Ue.NOTIFICATION,{title:"xclip or wl-clipboard not found",body:"Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"}),o(new Error("Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"));const l=i.toString().trim();let c=!1;if(t.basename(l)!==t.basename(r)&&e.existsSync(l)&&(c=!0),"no image"!==l&&!e.existsSync(l))return o(new Error(`Can't find ${l}`));s({imgPath:l,shouldKeepAfterUploading:c})}))}))},ot=new n,at=new B.Agent({maxVersion:"TLSv1.2",minVersion:"TLSv1.2"});function lt(e,t,n){"object"==typeof n&&"value"in n&&"options"in n?e.append(t,n.value,n.options):e.append(t,n)}function ct(e){return Object.assign(Object.assign({},e),{statusCode:e.status,body:e.data})}function ut(e){var t,n,i,r,s,o,a;const l={method:(null===(n=null===(t=null==e?void 0:e.config)||void 0===t?void 0:t.method)||void 0===n?void 0:n.toUpperCase())||"",url:(null===(i=