picgo 1.6.1 → 1.6.2
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.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/types/index.d.ts +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var e=require("fs-extra"),t=require("path"),n=require("events"),r=require("os"),i=require("commander"),s=require("inquirer"),a=require("image-size"),o=require("url"),l=require("chalk"),c=require("minimatch"),u=require("globby"),p=require("ejs"),E=require("download-git-repo"),g=require("rimraf"),I=require("dayjs"),d=require("util"),_=require("crypto"),h=require("mime-types"),m=require("qiniu"),C=require("md5"),P=require("resolve"),f=require("lodash"),N=require("child_process"),U=require("is-wsl"),D=require("axios"),L=require("form-data"),S=require("https"),A=require("tunnel"),T=require("@picgo/store"),B=require("cross-spawn"),O=require("js-yaml"),y=require("@picgo/i18n");const x={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:r,registry:i}=n,s={npmProxy:r,npmRegistry:i};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:r,registry:i}=n,s={npmProxy:r,npmRegistry:i};e.pluginHandler.update(t,s).catch(t=>{e.log.error(t)})})}},b={handle:e=>{e.cmd.program.option("-c, --config <path>","set config path")}},R=e=>e.startsWith("http://")||e.startsWith("https://"),G=e=>{e=e||"";try{return e!==decodeURI(e)}catch(e){return!1}},w=e=>(G(e)||(e=encodeURI(e)),e),M=(...e)=>e.join("").replace(/\/{2,}/g,"/").split("/").map(e=>encodeURIComponent(e)).join("/"),$=e=>{try{const{width:t=0,height:n=0,type:r}=a.imageSize(e);return{real:!0,width:t,height:n,extname:r?`.${r}`:".png"}}catch(e){return{real:!1,width:200,height:200,extname:".png"}}},H=async n=>{try{return{extname:t.extname(n),fileName:t.basename(n),filePath:n,buffer:await e.readFile(n),success:!0}}catch{return{reason:`read file ${n} error`,success:!1}}},v=async(e,n)=>{e=w(e);let r,i=!1,s="";const a=new Promise((a,l)=>{(async()=>{try{const l=await n.request({method:"get",url:e,resolveWithFullResponse:!0,responseType:"arraybuffer"}).then(e=>{const t=e.headers["content-type"];return t?.includes("image")&&(i=!0,s=`.${t.split("image/")[1]}`),e.data});if(clearTimeout(r),i){const n=new o.URL(e).pathname,r=decodeURIComponent(t.basename(n));a({buffer:l,fileName:r,extname:s,success:!0})}else a({success:!1,reason:`${e} is not image`})}catch(t){clearTimeout(r),a({success:!1,reason:`request ${e} error, ${t?.message??""}`})}})().catch(l)}),l=new Promise(t=>{r=setTimeout(()=>{t({success:!1,reason:`request ${e} timeout`})},1e4)});return Promise.race([a,l])},F=e=>/^@[^/]+\/picgo-plugin-/.test(e)?"scope":e.startsWith("picgo-plugin-")?"normal":q(e)?"simple":"unknown",q=n=>{if(t.isAbsolute(n))return!1;const r=t.join(process.cwd(),n);return!e.existsSync(r)&&(!n.includes("/")&&!n.includes("\\"))},k=(e,t="")=>t?`@${t}/picgo-plugin-${e}`:`picgo-plugin-${e}`,K=(n,r=console)=>{switch(F(n)){case"normal":case"scope":return n;case"simple":return k(n);default:{let i=n;return t.isAbsolute(n)&&e.existsSync(n)?j(i):(i=t.join(process.cwd(),n),e.existsSync(i)?j(i):(r.warn(`Can't find plugin ${n}`),""))}}},Y=(n,r=console)=>{switch(F(n)){case"normal":return Q(n);case"scope":return Q(n,!0);case"simple":return Q(k(n));default:{if(!e.existsSync(n))return r.warn(`Can't find plugin: ${n}`),"";const i=t.posix.join(n,"package.json");if(e.existsSync(i)){const t=e.readJSONSync(i)||{};return t.name?.includes("picgo-plugin-")?t.name:(r.warn(`The plugin package.json's name filed is ${t.name||"empty"}, need to include the prefix: picgo-plugin-`),"")}return r.warn(`Can't find plugin: ${n}`),""}}},j=e=>e.split(t.sep).join("/"),Q=(e,t=!1)=>{if(e.includes("@")){let n=/(.+\/)?(picgo-plugin-\w+)(@.+)*/;t&&(n=/(.+\/)?(^@[^/]+\/picgo-plugin-\w+)(@.+)*/);const r=e.match(n);return r?r[2]:(console.warn("can not remove plugin version"),e)}return e},W=[],z=e=>W.some(t=>e.startsWith(t)),V=e=>"object"==typeof e&&!Array.isArray(e)&&Object.keys(e).length>0;function J(e){try{return JSON.parse(e)}catch(t){return e}}const X=(e=0)=>isNaN(Number(e))?0:Number(e),Z=()=>"development"===process.env.NODE_ENV;var ee=Object.freeze({__proto__:null,configBlackList:W,forceNumber:X,getFSFile:H,getImageSize:$,getNormalPluginName:Y,getPluginNameType:F,getProcessPluginName:K,getURLFile:v,handleCompletePluginName:k,handleStreamlinePluginName:e=>/^@[^/]+\/picgo-plugin-/.test(e)?e.replace(/^@[^/]+\/picgo-plugin-/,""):e.replace(/picgo-plugin-/,""),handleUnixStylePath:j,handleUrlEncode:w,handleUrlPathSafeEncode:M,isConfigKeyInBlackList:z,isDev:Z,isInputConfigValid:V,isProd:()=>"production"===process.env.NODE_ENV,isSimpleName:q,isUrl:R,isUrlEncode:G,removePluginVersion:Q,safeParse:J});const te={handle:n=>{n.cmd.program.command("upload").description("upload, go go go").arguments("[input...]").alias("u").action(r=>{(async()=>{const i=r.map(e=>R(e)?e:t.resolve(e)).filter(t=>{const r=e.existsSync(t)||R(t);return r||n.log.warn(`${t} does not exist.`),r});await n.upload(i)})().catch(e=>{n.log.error(e)})})}},ne=async(e,t,n,r)=>{const i=await e.cmd.inquirer.prompt(t),s="uploader"===n?`picBed.${r}`:"transformer"===n?`transformer.${r}`:r;e.saveConfig({[s]:i}),"uploader"===n?e.saveConfig({"picBed.current":r,"picBed.uploader":r}):"transformer"===n&&e.saveConfig({"picBed.transformer":r})},re={handle:e=>{e.cmd.program.command("set").alias("config").arguments("<module> [name]").description("configure config of picgo modules").action((t,n)=>{(async()=>{try{switch(t){case"uploader":case"transformer":if(n){const r=e.helper[t].get(n);if(!r)return e.log.error(`No ${t} named ${n}`);r.config&&await ne(e,r.config(e),t,n)}else{const n=[{type:"list",name:`${t}`,choices:e.helper[t].getIdList(),message:`Choose a(n) ${t}`}],r=await e.cmd.inquirer.prompt(n),i=e.helper[t].get(r[t]);i?.config&&await ne(e,i.config(e),t,r[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}`);e.pluginLoader.getPlugin(n)?.config&&await ne(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);e.pluginLoader.getPlugin(n.plugin)?.config&&await ne(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)})})}},ie={handle:async e=>{const t=e.cmd;t.program.command("use").arguments("[module]").description("use modules of picgo").action(n=>{(async()=>{try{let r=[];const i={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(!i[n])return e.log.warn(`No module named ${n}`),e.log.warn("Available modules are uploader|transformer|plugins");r.push(i[n])}else r=Object.keys(i).map(e=>i[e]);const s=await t.inquirer.prompt(r);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)})})}},se={handle:e=>{e.cmd.program.option("-p, --proxy <url>","set proxy for uploading",t=>{e.setConfig({"picBed.proxy":t})})}},ae=async(e,n)=>{try{const r=le(n.tmp),i=t.join(n.tmp,"template");let s={};r.prompts&&r.prompts.length>0&&(s=await e.cmd.inquirer.prompt(r.prompts));let a=await u(["**/*"],{cwd:i,dot:!0});const o=Object.keys(r.filters||{});if(o.length>0&&(a=a.filter(t=>{let n="";for(const e of o)if(c(t,e,{dot:!0})){n=t;break}return!n||oe(e,r.filters[n],s)})),0===a.length)return e.log.warn("Template files not found!");const l=ce(a,i,s);ue(n.dest,l),"function"==typeof r.complete&&r.complete({answers:s,options:n,files:a,ctx:e}),r.completeMessage&&e.log.success(r.completeMessage),e.log.success("Done!")}catch(t){return e.log.error(t)}},oe=(e,t,n)=>{const r=new Function("data","with (data) { return "+t+"}");try{return r(n)}catch(n){return e.log.error(`Error when evaluating filter condition: ${JSON.stringify(t)}`),!1}},le=n=>{const r=t.join(n,"index.js");if(e.existsSync(r)){return require(r)}return{}},ce=(n,r,i)=>{const s={};return n.forEach(n=>{const a=e.readFileSync(t.join(r,n),"utf8"),o=p.render(a,i);(Buffer.isBuffer(o)||/[^\s]/.test(o))&&(s[n]=o)}),s},ue=(n,r)=>{Object.keys(r).forEach(i=>{const s=t.join(n,i);e.ensureDirSync(t.dirname(s)),e.writeFileSync(s,r[i])})},pe=(t,n)=>{n.offline?e.existsSync(n.template)?ae(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,Ee(t,n))},Ee=(t,n)=>{e.existsSync(n.tmp)&&g.rimrafSync(n.tmp),t.log.info("Template files are downloading..."),E(n.template,n.tmp,{clone:n.clone},e=>{if(e)return t.log.error(e);t.log.success("Template files are downloaded!"),ae(t,n).catch(e=>{t.log.error(e)})})},ge={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,a)=>{(async()=>{try{const o=i.includes("/"),l=!s||"."===s,c=t.resolve(s||"."),u=a.clone||!1,p=a.offline||!1,E=t.join(r.homedir(),".picgo/templates",i.replace(/[/:]/g,"-"));a.offline&&(i=E);const g={template:i,project:s,hasSlash:o,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&&pe(n,g)}):pe(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(l.gray(" # create a new project with an official template")),console.log(" $ picgo init plugin my-project"),console.log(),console.log(l.gray(" # create a new project straight from a github template")),console.log(" $ picgo init username/repo my-project"),console.log()})}},Ie={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"}],r=await e.cmd.inquirer.prompt(t);return e.i18n.setLanguage(r.i18n),void e.log.success(`Language set to ${r.i18n}`)}if(!n.includes(t))return e.log.warn("No such language");e.i18n.setLanguage(t),e.log.success(`Language set to ${t}`)})}};class de{static currentPlugin;list;pluginIdMap;name;constructor(e){this.name=e,this.list=new Map,this.pluginIdMap=new Map}register(e,t){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),de.currentPlugin&&(this.pluginIdMap.has(de.currentPlugin)?this.pluginIdMap.get(de.currentPlugin)?.push(e):this.pluginIdMap.set(de.currentPlugin,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);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 _e=(e=null)=>{de.currentPlugin=e};class he{name="commander";static currentPlugin;list=new Map;pluginIdMap=new Map;ctx;program;inquirer;constructor(e){this.program=new i.Command,this.inquirer=s,this.ctx=e}getName(){return this.name}init(){var e;this.program.version("1.6.1","-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",x),e.cmd.register("config",b),e.cmd.register("setting",re),e.cmd.register("upload",te),e.cmd.register("use",ie),e.cmd.register("proxy",se),e.cmd.register("init",ge),e.cmd.register("i18n",Ie)}register(e,t){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 n=de.currentPlugin;null!==n&&(this.pluginIdMap.has(n)?this.pluginIdMap.get(n)?.push(e):this.pluginIdMap.set(n,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);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 me,Ce;exports.ILogType=void 0,(me=exports.ILogType||(exports.ILogType={})).success="success",me.info="info",me.warn="warn",me.error="error",exports.IBuildInEvent=void 0,(Ce=exports.IBuildInEvent||(exports.IBuildInEvent={})).UPLOAD_PROGRESS="uploadProgress",Ce.FAILED="failed",Ce.BEFORE_TRANSFORM="beforeTransform",Ce.BEFORE_UPLOAD="beforeUpload",Ce.AFTER_UPLOAD="afterUpload",Ce.FINISHED="finished",Ce.INSTALL="install",Ce.UNINSTALL="uninstall",Ce.UPDATE="update",Ce.NOTIFICATION="notification",exports.IBusEvent=void 0,(exports.IBusEvent||(exports.IBusEvent={})).CONFIG_CHANGE="CONFIG_CHANGE";class Pe{level={[exports.ILogType.success]:"green",[exports.ILogType.info]:"blue",[exports.ILogType.warn]:"yellow",[exports.ILogType.error]:"red"};ctx;logLevel;logPath;constructor(e){this.ctx=e}handleLog(e,...n){if(this.logLevel=this.ctx.getConfig("settings.logLevel"),!this.ctx.getConfig("silent")&&this.checkLogLevel(e,this.logLevel)){const r=l[this.level[e]](`[PicGo ${e.toUpperCase()}]:`);console.log(r,...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(l.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,r=1024*X(this.ctx.getConfig("settings.logFileSizeLimit")||10)*1024;return{isLarge:n>r,logFileSize:n,logFileSizeLimit:r}}return{isLarge:!1}}recreateLogFile(t){e.existsSync(t)&&(e.unlinkSync(t),e.createFileSync(t))}handleWriteLog(t,n,...r){try{let i=`${I().format("YYYY-MM-DD HH:mm:ss")} [PicGo ${n.toUpperCase()}] `;r.forEach(e=>{e instanceof Error&&"error"===n?i+=`\n------Error Stack Begin------\n${d.format(e?.stack)}\n-------Error Stack End------- `:("object"==typeof e&&(e=JSON.stringify(e,null,2)),i+=`${e} `)}),i+="\n",e.appendFileSync(t,i)}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(exports.ILogType.success,...e)}info(...e){return this.handleLog(exports.ILogType.info,...e)}error(...e){return this.handleLog(exports.ILogType.error,...e)}warn(...e){return this.handleLog(exports.ILogType.warn,...e)}debug(...e){Z()&&this.handleLog(exports.ILogType.info,...e)}}class fe extends n.EventEmitter{ctx;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(exports.IBuildInEvent.FAILED),t.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,-1),t.emit(exports.IBuildInEvent.FAILED,e),t.log.error(e),t.getConfig("debug"))throw e;return t}}async beforeTransform(e){return e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,0),e.emit(exports.IBuildInEvent.BEFORE_TRANSFORM,e),e.log.info("Before transform"),await this.handlePlugins(e.helper.beforeTransformPlugins,e),e}async doTransform(e){e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,30);const t=e.getConfig("picBed.transformer")||"path";let n=t,r=e.helper.transformer.get(t);return r||(r=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(r?.handle(e)),e}async beforeUpload(e){return e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,60),e.log.info("Before upload"),e.emit(exports.IBuildInEvent.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),r=t;n||(t="smms",r="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 [${r}]`),await(n?.handle(e));for(const n of e.output)n.type=t;return e}async afterUpload(e){e.emit(exports.IBuildInEvent.AFTER_UPLOAD,e),e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,100),await this.handlePlugins(e.helper.afterUploadPlugins,e);let t="";const n=e.output.length,r=!0===e.getConfig("settings.encodeOutputURL");for(let i=0;i<n;i++)void 0!==e.output[i].imgUrl&&(t+=r?w(e.output[i].imgUrl):e.output[i].imgUrl,i!==n-1&&(t+="\n")),delete e.output[i].base64Image,delete e.output[i].buffer;return e.emit(exports.IBuildInEvent.FINISHED,e),e.log.success(`\n${t}`),e}async handlePlugins(e,t){const n=e.getList(),r=e.getIdList(),i=e.getName();return await Promise.all(n.map(async(e,n)=>{try{t.log.info(`${i}: ${r[n]} running`),await e.handle(t)}catch(e){throw t.log.error(`${i}: ${r[n]} error`),e}})),t}}const Ne=(e,t,n,r="")=>({method:"POST",url:`https://${r||"sm.ms"}/api/v2/upload`,headers:{contentType:"multipart/form-data","User-Agent":"PicGo",Authorization:n},formData:{smfile:{value:t,options:{filename:e}},ssl:"true"}}),Ue=async e=>{const t=e.getConfig("picBed.smms");if(!t)throw new Error("Can not find smms config!");const n=e.output;for(const r of n)if(r.fileName&&r.buffer){let n=r.buffer;!n&&r.base64Image&&(n=Buffer.from(r.base64Image,"base64"));const i=Ne(r.fileName,n,t?.token,t?.backupDomain);try{const t=await e.request(i),n=JSON.parse(t);if("success"===n.code)delete r.base64Image,delete r.buffer,r.imgUrl=n.data.url;else{if("image_repeated"!==n.code||"string"!=typeof n.images)throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:n.message}),new Error(n.message);delete r.base64Image,delete r.buffer,r.imgUrl=n.images}}catch(t){throw e.log.error(t),t}}return e},De=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 Le=e=>h.lookup(e)||"application/octet-stream",Se=(e,t,n,r)=>{const i=e.secretId,s=e.secretKey,a=e.appId,o=e.bucket;let l,c="";if(e.version&&"v4"!==e.version){const i=Math.floor((new Date).getTime()/1e3);c=`${i};${i+86400}`;const a=_.createHmac("sha1",s).update(c).digest("hex"),o=e.endpoint?e.endpoint:`cos.${e.area}.myqcloud.com`,p=`put\n/${e.path}${t}\n\ncontent-length=${r}&content-type=${u=n,encodeURIComponent(u).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A")}&host=${e.bucket}.${o}\n`,E=`sha1\n${c}\n${_.createHash("sha1").update(p).digest("hex")}\n`;l=_.createHmac("sha1",a).update(E).digest("hex")}else{const e=Math.floor(1e10*Math.random()),t=Math.floor((new Date).getTime()/1e3)-1,n=`a=${a}&b=${o}&k=${i}&e=${t+3600}&t=${t}&r=${e}&f=`,r=_.createHmac("sha1",s).update(n).digest(),c=Buffer.concat([r,Buffer.from(n)]);l=Buffer.from(c).toString("base64")}var u;return{signature:l,appId:a,bucket:o,signTime:c}},Ae=(e,t,n,r,i)=>{const s=e.area,a=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}/${M(a,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=content-length;content-type;host&q-url-param-list=&q-signature=${n.signature}`,contentType:Le(t),contentLength:r.byteLength,"User-Agent":`PicGo;${i};null;null`},body:r,resolveWithFullResponse:!0}}return{method:"POST",url:`http://${s}.file.myqcloud.com/files/v2/${n.appId}/${n.bucket}/${M(a,t)}`,headers:{Host:`${s}.file.myqcloud.com`,Authorization:n.signature,contentType:"multipart/form-data","User-Agent":`PicGo;${i};null;null`},formData:{op:"upload",filecontent:r},resolveWithFullResponse:!0}},Te=async e=>{const t=e.getConfig("picBed.tcyun");if(!t)throw new Error("Can't find tencent COS config");try{const n=e.output,r=t.customUrl,i=t.path,s=!t.version||"v4"===t.version;for(const a of n)if(a.fileName&&a.buffer){let n=a.buffer;!n&&a.base64Image&&(n=Buffer.from(a.base64Image,"base64"));const o=Se(t,a.fileName,Le(a.fileName),n.byteLength);if(!o)return!1;const l=Ae(t,a.fileName,o,n,e.GUI_VERSION||e.VERSION),c=await e.request(l).then(e=>e).catch(t=>({statusCode:400,body:{msg:e.i18n.translate("AUTH_FAILED"),err:t}}));let u;if(u=s&&"string"==typeof c?JSON.parse(c):c,400===u.statusCode)throw u?.body?.err?u.body.err:new Error(u?.body?.msg||u?.body?.message);const p=t.options||"",E=t.slim||"";if(s&&"SUCCESS"===u.message)delete a.base64Image,delete a.buffer,a.imgUrl=r?`${r}/${i}${a.fileName}`:`${u.data.source_url}${p}`;else{if(s||!u||200!==u.statusCode)throw new Error(c.body.msg);if(delete a.base64Image,delete a.buffer,r)a.imgUrl=`${r}/${encodeURI(i)}${M(a.fileName)}${p}`;else{const e=t.endpoint?t.endpoint:`cos.${t.area}.myqcloud.com`;a.imgUrl=`https://${t.bucket}.${e}/${encodeURI(i)}${M(a.fileName)}${p}`}}E&&(a.imgUrl+=p?"&imageSlim":"?imageSlim")}return e}catch(n){if(!t.version||"v4"===t.version)try{const t=JSON.parse(n.error);e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("UPLOAD_FAILED_REASON",{code:t.code}),text:"https://cloud.tencent.com/document/product/436/8432"})}catch(e){}throw n}},Be=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 Oe=(e,t,n)=>{const r=t.path||"",{token:i,repo:s}=t;return{method:"PUT",url:`https://api.github.com/repos/${s}/contents/${M(r,e)}`,headers:{Authorization:`token ${i}`,"User-Agent":"PicGo","Content-Type":h.lookup(e)},body:n,json:!0}},ye=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 r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i={message:"Upload by PicGo",branch:t.branch,content:n,path:t.path+encodeURI(r.fileName)},s=Oe(r.fileName,t,i);try{const n=await e.request(s);if(!n)throw new Error("Server error, please try again");delete r.base64Image,delete r.buffer,t.customUrl?r.imgUrl=`${t.customUrl}/${M(t.path||"",r.fileName)}`:r.imgUrl=n.content.download_url}catch(e){if(422!==e.statusCode)throw e;delete r.base64Image,delete r.buffer,t.customUrl?r.imgUrl=`${t.customUrl}/${M(t.path||"",r.fileName)}`:r.imgUrl=`https://raw.githubusercontent.com/${t.repo}/${t.branch}/${M(t.path||"",r.fileName)}`}}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK")}),t}},xe=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 be(e,t,n,r){const i=function(e){return"z0"===e?"":"-"+e}(e.area||"z0"),s=e.path||"";return{method:"POST",url:`http://upload${i}.qiniup.com/putb64/-1/key/${Buffer.from(s+t,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_")}`,headers:{Authorization:`UpToken ${n}`,"Content-Type":h.lookup(t)||"application/octet-stream"},body:r}}function Re(e){const t=e.accessKey,n=e.secretKey,r=new m.auth.digest.Mac(t,n),i={scope:e.bucket};return new m.rs.PutPolicy(i).uploadToken(r)}const Ge=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 r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i=be(t,r.fileName,Re(t),n),s=await e.request(i),a=JSON.parse(s);if(!a?.key)throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:a.msg}),e.log.error("qiniu error",a),new Error("Upload failed");{delete r.base64Image,delete r.buffer;const e=t.url,n=t.options;r.imgUrl=`${e}/${a.key}${n}`}}return e}catch(t){if("Upload failed"!==t.message&&t.response){const n=t.response.body;e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:n.error})}throw t}},we=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 Me=(e,t,n)=>{const r={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&&(r.proxy=e.proxy),r},$e=async e=>{const t=e.getConfig("picBed.imgur");if(!t)throw new Error("Can't find imgur config");try{const n=e.output;for(const r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i=Me(t,r.fileName,n),s=await e.request(i),a="string"==typeof s?JSON.parse(s):s;if(!a.success)throw new Error("Server error, please try again");delete r.base64Image,delete r.buffer,r.imgUrl=a.data.link}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK"),text:"http://docs.imgur.com/api/errno/"}),t?.response?.data||t}},He=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 ve=(e,t)=>{const n=(new Date).toUTCString(),r=h.lookup(t);if(!r)throw Error(`No mime type found for file ${t}`);const i=`PUT\n\n${r}\n${n}\n/${e.bucket}/${e.path}${t}`,s=_.createHmac("sha1",e.accessKeySecret).update(i).digest("base64");return`OSS ${e.accessKeyId}:${s}`},Fe=(e,t,n,r)=>{const i=e.path||"";return{method:"PUT",url:`https://${e.bucket}.${e.area}.aliyuncs.com/${M(i,t)}`,headers:{Host:`${e.bucket}.${e.area}.aliyuncs.com`,Authorization:n,Date:(new Date).toUTCString(),"Content-Type":h.lookup(t)},body:r,resolveWithFullResponse:!0}},qe=async e=>{const t=e.getConfig("picBed.aliyun");if(!t)throw new Error("Can't find aliYun OSS config");try{const n=e.output,r=t.customUrl,i=t.path||"";for(const s of n)if(s.fileName&&s.buffer){const n=ve(t,s.fileName);let a=s.buffer;!a&&s.base64Image&&(a=Buffer.from(s.base64Image,"base64"));const o=Fe(t,s.fileName,n,a);if(200!==(await e.request(o)).statusCode)throw new Error("Upload failed");{delete s.base64Image,delete s.buffer;const e=t.options||"";s.imgUrl=r?`${r}/${M(i,s.fileName)}${e}`:`https://${t.bucket}.${t.area}.aliyuncs.com/${M(i,s.fileName)}${e}`}}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")}),t}},ke=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 Ke=(e,t)=>{const n=e.path||"",r=e.operator,i=e.password,s=C(i),a=(new Date).toUTCString(),o=`PUT&${`/${e.bucket}/${M(n,t)}`}&${a}`;return`UPYUN ${r}:${_.createHmac("sha1",s).update(o).digest("base64")}`},Ye=(e,t,n,r)=>{const i=e.bucket,s=e.path||"";return{method:"PUT",url:`https://v0.api.upyun.com/${i}/${M(s,t)}`,headers:{Authorization:n,Date:(new Date).toUTCString(),"Content-Type":h.lookup(t)||"application/octet-stream"},body:r,resolveWithFullResponse:!0}},je=async e=>{const t=e.getConfig("picBed.upyun");if(!t)throw new Error("Can't find upYun config");try{const n=e.output,r=t.path||"";for(const i of n)if(i.fileName&&i.buffer){let n=i.buffer;!n&&i.base64Image&&(n=Buffer.from(i.base64Image,"base64"));const s=Ke(t,i.fileName),a=Ye(t,i.fileName,s,n);if(200!==(await e.request(a)).statusCode)throw new Error("Upload failed");delete i.base64Image,delete i.buffer,i.imgUrl=`${t.url}/${M(r,i.fileName)}${t.options}`}return e}catch(t){if("Upload failed"===t.message)e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")});else{const n=J(t.error);e.emit(exports.IBuildInEvent.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}},Qe=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 We=()=>({register(e){!function(e){e.helper.uploader.register("aliyun",{get name(){return e.i18n.translate("PICBED_ALICLOUD")},handle:qe,config:ke})}(e),function(e){e.helper.uploader.register("tcyun",{get name(){return e.i18n.translate("PICBED_TENCENTCLOUD")},handle:Te,config:Be})}(e),function(e){e.helper.uploader.register("smms",{get name(){return e.i18n.translate("PICBED_SMMS")},handle:Ue,config:De})}(e),function(e){e.helper.uploader.register("github",{get name(){return e.i18n.translate("PICBED_GITHUB")},handle:ye,config:xe})}(e),function(e){e.helper.uploader.register("qiniu",{get name(){return e.i18n.translate("PICBED_QINIU")},handle:Ge,config:we})}(e),function(e){e.helper.uploader.register("imgur",{get name(){return e.i18n.translate("PICBED_IMGUR")},handle:$e,config:He})}(e),function(e){e.helper.uploader.register("upyun",{get name(){return e.i18n.translate("PICBED_UPYUN")},handle:je,config:Qe})}(e)}}),ze=(e,t,n)=>{const r=$(t);return r.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")),r};var Ve={handle:async e=>{const t=e.output;return await Promise.all(e.input.map(async(n,r)=>{let i;if(i=Buffer.isBuffer(n)?{success:!0,buffer:n,fileName:"",extname:""}:R(n)?await v(n,e):await H(n),i.success&&i.buffer){const s=ze(e,i.buffer,n),a=i.extname||s.extname||".png";t[r]={buffer:i.buffer,fileName:i.fileName||`${I().format("YYYYMMDDHHmmssSSS")}${a}}`,width:s.width,height:s.height,filePath:i.filePath,extname:a,mimeType:h.lookup(a)||"application/octet-stream"}}else e.log.error(i.reason)})),e.output=t.filter(e=>e),e}};var Je={handle:async e=>(e.output.push(...e.input),e)};class Xe{ctx;list=[];fullList=new Set;pluginMap=new Map;constructor(e){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 P.sync(n,{basedir:e.baseDir})}catch(r){return t.join(e.baseDir,"node_modules",n)}}load(){const n=t.join(this.ctx.baseDir,"package.json"),r=t.join(this.ctx.baseDir,"node_modules/");if(!e.existsSync(r))return!1;const i=e.readJSONSync(n),s=Object.keys(i.dependencies||{}),a=Object.keys(i.devDependencies||{}),o=s.concat(a).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 o)this.registerPlugin(e);return!0}registerPlugin(e,t){if(e&&"string"==typeof e){this.fullList.add(e);try{if(t){this.list.push(e),_e(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),_e(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(exports.IBuildInEvent.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),_e(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/"),r=require(n+e)(this.ctx);return this.pluginMap.set(e,r),r}getList(){return this.list}hasPlugin(e){return this.fullList.has(e)}getFullList(){return[...this.fullList]}}const Ze="picgo-clipboard-images",et={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\nelse\n # fallback for unsupported session types\n echo >&2 "Error: Unsupported session type \'$XDG_SESSION_TYPE\'."\n echo >&2 "Solution: The variable of XDG_SESSION_TYPE must set as \'x11\' or \'wayland\'."\n exit 1\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'},tt={darwin:"mac.applescript",win32:"windows.ps1",win10:"windows10.ps1",linux:"linux.sh",wsl:"wsl.sh"};const nt=async n=>{!function(n){const r=t.join(n.baseDir,Ze);e.existsSync(r)||e.mkdirSync(r)}(n);const i=t.join(n.baseDir,Ze,`${I().format("YYYYMMDDHHmmssSSS")}.png`);return await new Promise((s,a)=>{const o=(()=>{const e=process.platform;if(U)return"wsl";if("win32"===e)return"10"===r.release().split(".")[0]?"win10":"win32";return"darwin"===e?"darwin":"linux"})(),l=t.join(n.baseDir,tt[o]);let c;e.existsSync(l)||e.writeFileSync(l,et[o],"utf8"),c="darwin"===o?N.spawn("osascript",[l,i]):"win32"===o||"win10"===o?N.spawn("powershell",["-noprofile","-noninteractive","-nologo","-sta","-executionpolicy","unrestricted","-file",l,i]):N.spawn("sh",[l,i]),c.stdout.on("data",r=>{if("linux"===o&&"no xclip or wl-clipboard"===r.toString().trim())return n.emit(exports.IBuildInEvent.NOTIFICATION,{title:"xclip or wl-clipboard not found",body:"Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"}),a(new Error("Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"));const l=r.toString().trim();let c=!1;if(t.basename(l)!==t.basename(i)&&e.existsSync(l)&&(c=!0),"no image"!==l&&!e.existsSync(l))return a(new Error(`Can't find ${l}`));s({imgPath:l,shouldKeepAfterUploading:c})})})},rt=new n.EventEmitter,it=new S.Agent({maxVersion:"TLSv1.2",minVersion:"TLSv1.2"});function st(e,t,n){"object"==typeof n&&"value"in n&&"options"in n?e.append(t,n.value,n.options):e.append(t,n)}function at(e){return{...e,statusCode:e.status,body:e.data}}function ot(e){const t={method:e?.config?.method?.toUpperCase()||"",url:e?.config?.url||"",statusCode:e?.response?.status||0,message:e?.message||"",stack:e?.stack||{},response:{status:e?.response?.status||0,statusCode:e?.response?.status||0,body:e?.response?.data||""}};return Promise.reject(t)}class lt{ctx;proxy="";options={};constructor(e){this.ctx=e,this.init(),rt.on(exports.IBusEvent.CONFIG_CHANGE,e=>{switch(e.configName){case"picBed":e.value?.proxy&&(this.proxy=e.value.proxy);break;case"picBed.proxy":this.proxy=e.value}})}init(){const e=this.ctx.getConfig("picBed.proxy");e&&(this.proxy=e)}handleProxy(){if(this.proxy)try{const e=new o.URL(this.proxy);return{host:e.hostname,port:parseInt(e.port||"0",10),protocol:e.protocol}}catch(e){}return!1}request(e){this.options.proxy=this.handleProxy(),this.options.headers=e.headers||{},this.options.maxBodyLength=1/0,this.options.maxContentLength=1/0,this.options.proxy&&e.url?.startsWith("https://")?(this.options.httpsAgent=A.httpsOverHttp({proxy:{host:this.options.proxy.host,port:this.options.proxy.port}}),this.options.proxy=!1):this.options.httpsAgent=it;const t=D.create(this.options);t.interceptors.response.use(at,ot);const n=function(e){let t=!1;const n={...e,url:e.url||"",headers:e.headers||{}};if(e.proxy){let r=e.proxy;if("string"==typeof r){try{r=new o.URL(e.proxy)}catch(e){r=!1,n.proxy=!1,console.error(e)}t=!0}r&&(e.url?.startsWith("https://")?(n.proxy=!1,n.httpsAgent=A.httpsOverHttp({proxy:{host:r?.hostname,port:parseInt(r?.port,10)}})):n.proxy={host:r.hostname,port:parseInt(r.port,10),protocol:"http"})}if("formData"in e){const r=new L;for(const t in e.formData)st(r,t,e.formData[t]);n.data=r,n.headers=Object.assign(n.headers||{},r.getHeaders()),t=!0,delete n.formData}return"body"in e&&(n.data=e.body,t=!0,delete n.body),"qs"in e&&(n.params=e.qs,t=!0),n.__isOldOptions=t,n}(e);return t.interceptors.request.use(function(e){let t="";return e?.headers?.contentType?(t=e.headers.contentType,delete e.headers.contentType):e?.headers?.ContentType?(t=e.headers.ContentType,delete e.headers.ContentType):e?.headers?.["content-type"]&&(t=e.headers["content-type"],delete e.headers["content-type"]),""!==t&&e.headers&&(e.headers["Content-Type"]=t),e}),"resolveWithFullResponse"in e&&e.resolveWithFullResponse?t.request(n):t.request(n).then(t=>n.__isOldOptions?"json"in e?e.json?t.data:void 0:JSON.stringify(t.data):t.data)}}class ct{ctx;db;constructor(e){if(this.ctx=e,this.db=new T.JSONStore(this.ctx.configPath),!this.db.has("picBed"))try{this.db.set("picBed",{uploader:"smms",current:"smms"})}catch(e){throw this.ctx.log.error(e),e}if(!this.db.has("picgoPlugins"))try{this.db.set("picgoPlugins",{})}catch(e){throw this.ctx.log.error(e),e}}read(e){return this.db.read(e)}get(e=""){return this.read(!0),this.db.get(e)}set(e,t){return this.read(!0),this.db.set(e,t)}has(e){return this.read(!0),this.db.has(e)}unset(e,t){return this.read(!0),this.db.unset(e,t)}saveConfig(e){Object.keys(e).forEach(t=>{this.set(t,e[t])})}removeConfig(e){Object.keys(e).forEach(t=>{this.unset(t,e[t])})}}class ut{ctx;constructor(e){this.ctx=e}async install(e,t={},n){const r=[],i=e.map(e=>pt(this.ctx,e)).filter(e=>this.ctx.pluginLoader.hasPlugin(e.pkgName)?(r.push(e.pkgName),this.ctx.log.success(`PicGo has already installed ${e.pkgName}`),!1):!!e.success),s=i.map(e=>e.fullName),a=i.map(e=>e.pkgName);if(s.length>0){const e=await this.execCommand("install",s,this.ctx.baseDir,t,n);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("installFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED"),body:t});return{success:!1,body:t}}a.forEach(e=>{this.ctx.pluginLoader.registerPlugin(e)}),this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS")),this.ctx.emit("installSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS"),body:[...a,...r]});return{success:!0,body:[...a,...r]}}if(0===r.length){const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("installFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED"),body:e});return{success:!1,body:e}}this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS")),this.ctx.emit("installSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS"),body:[...a,...r]});return{success:!0,body:[...a,...r]}}async uninstall(e){const t=e.map(e=>pt(this.ctx,e)).filter(e=>e.success).map(e=>e.pkgName);if(t.length>0){const e=await this.execCommand("uninstall",t,this.ctx.baseDir);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("uninstallFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED"),body:t});return{success:!1,body:t}}t.forEach(e=>{this.ctx.pluginLoader.unregisterPlugin(e)}),this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS")),this.ctx.emit("uninstallSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS"),body:t});return{success:!0,body:t}}{const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("uninstallFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED"),body:e});return{success:!1,body:e}}}async update(e,t={},n){const r=e.map(e=>pt(this.ctx,e)).filter(e=>e.success).map(e=>e.pkgName);if(r.length>0){const e=await this.execCommand("update",r,this.ctx.baseDir,t,n);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("updateFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED"),body:t});return{success:!1,body:t}}this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS")),this.ctx.emit("updateSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS"),body:r});return{success:!0,body:r}}{const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("updateFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED"),body:e});return{success:!1,body:e}}}async execCommand(e,t,n,r={},i={}){const s=r.npmRegistry||this.ctx.getConfig("settings.npmRegistry"),a=r.npmProxy||this.ctx.getConfig("settings.npmProxy");return await new Promise(r=>{let o=[e].concat(t).concat("--color=always").concat("--save");s&&(o=o.concat(`--registry=${s}`)),a&&(o=o.concat(`--proxy=${a}`));try{const e=B("npm",o,{cwd:n,env:Object.assign({},process.env,i)});let t="";e.stdout?.on("data",e=>{t+=e}).pipe(process.stdout),e.stderr?.on("data",e=>{t+=e}).pipe(process.stderr),e.on("close",e=>{r(e?{code:e,data:t}:{code:0,data:t})}),e.on("error",e=>{this.ctx.log.error(e),this.ctx.log.error("NPM is not installed"),this.ctx.emit(exports.IBuildInEvent.FAILED,"NPM is not installed")})}catch(e){this.ctx.log.error(e),this.ctx.emit(exports.IBuildInEvent.FAILED,e)}})}}const pt=(e,t)=>{const n={success:!1,fullName:"",pkgName:""},r=K(t,e.log);if(!r)return n;const i=Y(r,e.log);return i?{success:!0,fullName:r,pkgName:i}:n},Et={"zh-CN":{UPLOAD_FAILED:"上传失败",CHECK_SETTINGS:"请检查你的配置项是否正确",CHECK_SETTINGS_AND_NETWORK:"请检查你的配置项以及网络",UPLOAD_FAILED_REASON:"错误码:${code},请打开浏览器粘贴地址查看相关原因",SERVER_ERROR:"服务端出错,请重试",AUTH_FAILED:"认证失败",PICBED_SMMS:"SM.MS",PICBED_SMMS_TOKEN:"设定Token",PICBED_SMMS_BACKUP_DOMAIN:"备用上传域名",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例如 smms.app",PICBED_ALICLOUD:"阿里云OSS",PICBED_ALICLOUD_ACCESSKEYID:"设定KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"设定KeySecret",PICBED_ALICLOUD_BUCKET:"设定Bucket",PICBED_ALICLOUD_AREA:"设定存储区域",PICBED_ALICLOUD_PATH:"设定存储路径",PICBED_ALICLOUD_CUSTOMURL:"设定自定义域名",PICBED_ALICLOUD_OPTIONS:"设定网址后缀",PICBED_ALICLOUD_MESSAGE_AREA:"例如:oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例如:test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例如:?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD:"腾讯云COS",PICBED_TENCENTCLOUD_VERSION:"COS版本",PICBED_TENCENTCLOUD_SECRETID:"设定SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"设定SecretKey",PICBED_TENCENTCLOUD_APPID:"设定AppId",PICBED_TENCENTCLOUD_BUCKET:"设定Bucket",PICBED_TENCENTCLOUD_AREA:"设定存储区域",PICBED_TENCENTCLOUD_ENDPOINT:"设定Endpoint",PICBED_TENCENTCLOUD_PATH:"设定存储路径",PICBED_TENCENTCLOUD_OPTIONS:"设定网址后缀",PICBED_TENCENTCLOUD_CUSTOMURL:"设定自定义域名",PICBED_TENCENTCLOUD_SLIM:"极智压缩",PICBED_TENCENTCLOUD_SLIM_TIP:"图片极智压缩,详情请参考[文档说明](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"开启",PICBED_TENCENTCLOUD_SLIM_CANCEL:"关闭",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例如:1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例如:ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例如:cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例如:test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例如:?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"设定Token",PICBED_GITHUB_REPO:"设定仓库名",PICBED_GITHUB_PATH:"设定存储路径",PICBED_GITHUB_BRANCH:"设定分支名",PICBED_GITHUB_CUSTOMURL:"设定自定义域名",PICBED_GITHUB_MESSAGE_REPO:"格式:username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例如:main",PICBED_GITHUB_MESSAGE_PATH:"例如:test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_QINIU:"七牛云",PICBED_QINIU_ACCESSKEY:"设定AccessKey",PICBED_QINIU_SECRETKEY:"设定SecretKey",PICBED_QINIU_BUCKET:"设定Bucket",PICBED_QINIU_PATH:"设定存储路径",PICBED_QINIU_URL:"设定访问网址",PICBED_QINIU_OPTIONS:"设定网址后缀",PICBED_QINIU_AREA:"设定存储区域",PICBED_QINIU_MESSAGE_PATH:"例如:test/",PICBED_QINIU_MESSAGE_AREA:"例如:z0",PICBED_QINIU_MESSAGE_OPTIONS:"例如:?imageslim",PICBED_QINIU_MESSAGE_URL:"例如:https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"设定ClientId",PICBED_IMGUR_PROXY:"设定代理",PICBED_IMGUR_MESSAGE_PROXY:"例如:http://127.0.0.1:1080",PICBED_UPYUN:"又拍云",PICBED_UPYUN_BUCKET:"设定Bucket",PICBED_UPYUN_OPERATOR:"设定操作员",PICBED_UPYUN_PASSWORD:"设定操作员密码",PICBED_UPYUN_PATH:"设定存储路径",PICBED_UPYUN_URL:"设定加速域名",PICBED_UPYUN_OPTIONS:"设定网址后缀",PICBED_UPYUN_MESSAGE_OPERATOR:"例如:me",PICBED_UPYUN_MESSAGE_PASSWORD:"输入操作员密码",PICBED_UPYUN_MESSAGE_URL:"例如:http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例如:!imgslim",PICBED_UPYUN_MESSAGE_PATH:"例如:test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"插件安装成功",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"插件安装失败",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"插件安装失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"插件安装失败,请输入合法插件名或合法安装路径",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"插件卸载成功",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"插件卸载失败",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"插件卸载失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"插件卸载失败,请输入合法插件名",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"插件更新成功",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"插件更新失败",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"插件更新失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"插件更新失败,请输入合法插件名"},"zh-TW":{UPLOAD_FAILED:"上傳失敗",CHECK_SETTINGS:"請檢查你的設定是否正確",CHECK_SETTINGS_AND_NETWORK:"請檢查你的設定及網路",UPLOAD_FAILED_REASON:"錯誤碼:${code},請打開瀏覽器貼上地址查看相關原因",SERVER_ERROR:"伺服器出錯,請重試",AUTH_FAILED:"認證失敗",PICBED_SMMS:"SM.MS",PICBED_SMMS_TOKEN:"設定Token",PICBED_SMMS_BACKUP_DOMAIN:"備用上傳網址",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例如 smms.app",PICBED_ALICLOUD:"阿里云OSS",PICBED_ALICLOUD_ACCESSKEYID:"設定KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"設定KeySecret",PICBED_ALICLOUD_BUCKET:"設定Bucket",PICBED_ALICLOUD_AREA:"設定儲存區域",PICBED_ALICLOUD_PATH:"設定儲存路徑",PICBED_ALICLOUD_CUSTOMURL:"設定自訂網址",PICBED_ALICLOUD_OPTIONS:"設定網址後綴",PICBED_ALICLOUD_MESSAGE_AREA:"例如:oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例如:test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例如:?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD:"騰訊云COS",PICBED_TENCENTCLOUD_VERSION:"COS版本",PICBED_TENCENTCLOUD_SECRETID:"設定SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"設定SecretKey",PICBED_TENCENTCLOUD_APPID:"設定AppId",PICBED_TENCENTCLOUD_BUCKET:"設定Bucket",PICBED_TENCENTCLOUD_AREA:"設定儲存區域",PICBED_TENCENTCLOUD_ENDPOINT:"設定Endpoint",PICBED_TENCENTCLOUD_PATH:"設定儲存路徑",PICBED_TENCENTCLOUD_OPTIONS:"設定網址後綴",PICBED_TENCENTCLOUD_SLIM:"極智壓縮",PICBED_TENCENTCLOUD_SLIM_CANCEL:"關閉",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"開啓",PICBED_TENCENTCLOUD_SLIM_TIP:"圖片極智壓縮,詳情請參考[文檔說明](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_CUSTOMURL:"設定自訂網址",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例如:1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例如:ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例如:cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例如:test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例如:?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"設定Token",PICBED_GITHUB_REPO:"設定倉庫名稱",PICBED_GITHUB_PATH:"設定儲存路徑",PICBED_GITHUB_BRANCH:"設定分支名稱",PICBED_GITHUB_CUSTOMURL:"設定自訂網址",PICBED_GITHUB_MESSAGE_REPO:"格式:username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例如:main",PICBED_GITHUB_MESSAGE_PATH:"例如:test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_QINIU:"七牛云",PICBED_QINIU_ACCESSKEY:"設定AccessKey",PICBED_QINIU_SECRETKEY:"設定SecretKey",PICBED_QINIU_BUCKET:"設定Bucket",PICBED_QINIU_PATH:"設定儲存路徑",PICBED_QINIU_URL:"設定訪問網址",PICBED_QINIU_OPTIONS:"設定網址後綴",PICBED_QINIU_AREA:"設定儲存區域",PICBED_QINIU_MESSAGE_PATH:"例如:test/",PICBED_QINIU_MESSAGE_AREA:"例如:z0",PICBED_QINIU_MESSAGE_OPTIONS:"例如:?imageslim",PICBED_QINIU_MESSAGE_URL:"例如:https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"設定ClientId",PICBED_IMGUR_PROXY:"設定PROXY",PICBED_IMGUR_MESSAGE_PROXY:"例如:http://127.0.0.1:1080",PICBED_UPYUN:"又拍云",PICBED_UPYUN_BUCKET:"設定Bucket",PICBED_UPYUN_OPERATOR:"設定操作員",PICBED_UPYUN_PASSWORD:"設定操作員密碼",PICBED_UPYUN_PATH:"設定儲存路徑",PICBED_UPYUN_URL:"設定加速網址",PICBED_UPYUN_OPTIONS:"設定網址後綴",PICBED_UPYUN_MESSAGE_OPERATOR:"例如:me",PICBED_UPYUN_MESSAGE_PASSWORD:"輸入操作員密碼",PICBED_UPYUN_MESSAGE_URL:"例如:http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例如:!imgslim",PICBED_UPYUN_MESSAGE_PATH:"例如:test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"插件安裝成功",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"插件安裝失敗",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"插件安裝失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"插件安裝失敗,請輸入正確的插件名稱或正確的安裝路徑",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"插件卸載成功",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"插件卸載失敗",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"插件卸載失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"插件卸載失敗,請輸入正確的插件名稱",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"插件更新成功",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"插件更新失敗",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"插件更新失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"插件更新失敗,請輸入正確的插件名稱"},en:{UPLOAD_FAILED:"Upload failed",CHECK_SETTINGS:"Please check your settings",CHECK_SETTINGS_AND_NETWORK:"Please check your settings and network",UPLOAD_FAILED_REASON:"Error code: ${code}, please open the browser and paste the address to see the reason",SERVER_ERROR:"Server error, please try again later",AUTH_FAILED:"Authentication failed",PICBED_SMMS:"SM.MS",PICBED_SMMS_TOKEN:"Set Token",PICBED_SMMS_BACKUP_DOMAIN:"Set Backup Upload Domain",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"Ex. smms.app",PICBED_ALICLOUD:"Ali Cloud",PICBED_ALICLOUD_ACCESSKEYID:"Set KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"Set KeySecret",PICBED_ALICLOUD_BUCKET:"Set Bucket",PICBED_ALICLOUD_AREA:"Set Area",PICBED_ALICLOUD_PATH:"Set Path",PICBED_ALICLOUD_CUSTOMURL:"Set Custom URL",PICBED_ALICLOUD_OPTIONS:"Set URL Suffix",PICBED_ALICLOUD_MESSAGE_AREA:"Ex. oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"Ex. test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"Ex. ?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"Ex. https://test.com",PICBED_TENCENTCLOUD:"Tencent Cloud",PICBED_TENCENTCLOUD_VERSION:"Choose COS version",PICBED_TENCENTCLOUD_SECRETID:"Set SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"Set SecretKey",PICBED_TENCENTCLOUD_APPID:"Set AppId",PICBED_TENCENTCLOUD_BUCKET:"Set Bucket",PICBED_TENCENTCLOUD_AREA:"Set Area",PICBED_TENCENTCLOUD_ENDPOINT:"Set Endpoint",PICBED_TENCENTCLOUD_PATH:"Set Path",PICBED_TENCENTCLOUD_OPTIONS:"Set URL Suffix",PICBED_TENCENTCLOUD_SLIM:"Set ImageSlim",PICBED_TENCENTCLOUD_SLIM_TIP:"Image extremely intelligent compression, please refer to the [document description](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"OPEN",PICBED_TENCENTCLOUD_SLIM_CANCEL:"CLOSE",PICBED_TENCENTCLOUD_CUSTOMURL:"Set Custom URL",PICBED_TENCENTCLOUD_MESSAGE_APPID:"Ex. 1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"Ex. ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"Ex. cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"Ex. test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"Ex. http://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"Ex. ?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"Set Token",PICBED_GITHUB_REPO:"Set Repo Name",PICBED_GITHUB_PATH:"Set Path",PICBED_GITHUB_BRANCH:"Set Branch",PICBED_GITHUB_CUSTOMURL:"Set Custom URL",PICBED_GITHUB_MESSAGE_REPO:"Ex. username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"Ex. main",PICBED_GITHUB_MESSAGE_PATH:"Ex. test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"Ex. https://test.com",PICBED_QINIU:"Qiniu",PICBED_QINIU_ACCESSKEY:"Set AccessKey",PICBED_QINIU_SECRETKEY:"Set SecretKey",PICBED_QINIU_BUCKET:"Set Bucket",PICBED_QINIU_PATH:"Set Path",PICBED_QINIU_URL:"Set URL",PICBED_QINIU_OPTIONS:"Set URL Suffix",PICBED_QINIU_AREA:"Set Area",PICBED_QINIU_MESSAGE_PATH:"Ex. test/",PICBED_QINIU_MESSAGE_AREA:"Ex. z0",PICBED_QINIU_MESSAGE_OPTIONS:"Ex. ?imageslim",PICBED_QINIU_MESSAGE_URL:"Ex. https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"Set ClientId",PICBED_IMGUR_PROXY:"Set Proxy",PICBED_IMGUR_MESSAGE_PROXY:"Ex. http://127.0.0.1:1080",PICBED_UPYUN:"Upyun",PICBED_UPYUN_BUCKET:"Set Bucket",PICBED_UPYUN_OPERATOR:"Set Operator",PICBED_UPYUN_PASSWORD:"Set Operator Password",PICBED_UPYUN_PATH:"Set Path",PICBED_UPYUN_URL:"Set URL",PICBED_UPYUN_OPTIONS:"Set URL Suffix",PICBED_UPYUN_MESSAGE_OPERATOR:"Ex. me",PICBED_UPYUN_MESSAGE_PASSWORD:"Please type the operator password",PICBED_UPYUN_MESSAGE_URL:"Ex. http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"Ex. !imgslim",PICBED_UPYUN_MESSAGE_PATH:"Ex. test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"Plugin installed successfully",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"Plugin installation failed",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"Plugin installation failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"Plugin installation failed, please enter a valid plugin name or valid installation path",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"Plugin uninstalled successfully",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"Plugin uninstall failed",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"Plugin uninstall failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"Plugin uninstall failed, please enter a valid plugin name",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"Plugin updated successfully",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"Plugin update failed",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"Plugin update failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"Plugin update failed, please enter a valid plugin name"}};class gt{i18n;objectAdapter;ctx;constructor(e){this.ctx=e,this.objectAdapter=new y.ObjectAdapter(Et);let t=this.ctx.getConfig("settings.language")||"zh-CN";Et[t]||(t="zh-CN"),this.i18n=new y.I18n({adapter:this.objectAdapter,defaultLanguage:t}),this.loadOutterI18n()}loadOutterI18n(){const n=this.getOutterI18nFolder();e.readdirSync(n,{withFileTypes:!0}).forEach(r=>{if(r.isFile()&&r.name.endsWith(".yml")){const i=t.join(n,r.name),s=e.readFileSync(i,"utf8");try{const e=O.load(s);Et[r.name.replace(/\.yml$/,"")]=e}catch(e){console.error(e)}}})}getOutterI18nFolder(){const n=t.join(this.ctx.baseDir,"i18n-cli");return e.pathExistsSync(n)||e.ensureDirSync(n),n}translate(e,t){return this.i18n.translate(e,t)||e}setLanguage(e){this.i18n.setLanguage(e),this.ctx.saveConfig({"settings.language":e})}addLocale(e,t){const n=this.objectAdapter.getLocale(e);if(!n)return!1;const r=f.merge(n,t);return this.objectAdapter.setLocale(e,r),!0}addLanguage(e,t){return!this.objectAdapter.getLocale(e)&&(this.objectAdapter.setLocale(e,t),Et[e]=t,!0)}getLanguageList(){return Object.keys(Et)}}class It extends n.EventEmitter{_config;lifecycle;db;_pluginLoader;configPath;baseDir;helper;log;cmd;output;input;pluginHandler;Request;i18n;VERSION="1.6.1";GUI_VERSION;get pluginLoader(){return this._pluginLoader}constructor(e=""){super(),this.configPath=e,this.output=[],this.input=[],this.helper={transformer:new de("transformer"),uploader:new de("uploader"),beforeTransformPlugins:new de("beforeTransformPlugins"),beforeUploadPlugins:new de("beforeUploadPlugins"),afterUploadPlugins:new de("afterUploadPlugins")},this.initConfigPath(),this.log=new Pe(this),this.cmd=new he(this),this.pluginHandler=new ut(this),this.initConfig(),this.init()}initConfigPath(){if(""===this.configPath&&(this.configPath=r.homedir()+"/.picgo/config.json"),".JSON"!==t.extname(this.configPath).toUpperCase())throw this.configPath="",Error("The configuration file only supports JSON format.");this.baseDir=t.dirname(this.configPath);e.pathExistsSync(this.configPath)||e.ensureFileSync(`${this.configPath}`)}initConfig(){this.db=new ct(this),this._config=this.db.read(!0)}init(){try{this.i18n=new gt(this),this.Request=new lt(this),this._pluginLoader=new Xe(this),_e("picgo"),We().register(this),{register(e){e.helper.transformer.register("path",Ve),e.helper.transformer.register("base64",Je)}}.register(this),_e(""),this._pluginLoader.load(),this.lifecycle=new fe(this)}catch(e){throw this.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,-1),this.log.error(e),e}}use(e,t){if(t)return this.pluginLoader.registerPlugin(t,e),this.pluginLoader.getPlugin(t);return e(this)}registerCommands(){""!==this.configPath&&(this.cmd.init(),this.cmd.loadCommands())}getConfig(e){return e?f.get(this._config,e):this._config}saveConfig(e){V(e)?(this.setConfig(e),this.db.saveConfig(e)):this.log.warn("the format of config is invalid, please provide object")}removeConfig(e,t){e&&t&&(z(e)?this.log.warn(`the config.${e} can't be removed`):(this.unsetConfig(e,t),this.db.unset(e,t)))}setConfig(e){V(e)?Object.keys(e).forEach(t=>{z(t)&&(this.log.warn(`the config.${t} can't be modified`),delete e[t]),f.set(this._config,t,e[t]),rt.emit(exports.IBusEvent.CONFIG_CHANGE,{configName:t,value:e[t]})}):this.log.warn("the format of config is invalid, please provide object")}unsetConfig(e,t){e&&t&&(z(e)?this.log.warn(`the config.${e} can't be unset`):f.unset(this.getConfig(e),t))}get request(){return this.Request.request.bind(this.Request)}async upload(t){if(""===this.configPath)return this.log.error("The configuration file only supports JSON format."),[];if(void 0!==t&&0!==t.length){const{output:e}=await this.lifecycle.start(t);return e}try{const{imgPath:t,shouldKeepAfterUploading:n}=await nt(this);if("no image"===t)throw new Error("image not found in clipboard");{this.once(exports.IBuildInEvent.FAILED,()=>{n||e.remove(t).catch(e=>{this.log.error(e)})}),this.once("finished",()=>{n||e.remove(t).catch(e=>{this.log.error(e)})});const{output:r}=await this.lifecycle.start([t]);return r}}catch(e){throw this.emit(exports.IBuildInEvent.FAILED,e),e}}}exports.Commander=he,exports.Lifecycle=fe,exports.LifecyclePlugins=de,exports.Logger=Pe,exports.PicGo=It,exports.PicGoUtils=ee,exports.PluginHandler=ut,exports.PluginLoader=Xe,exports.Request=lt;
|
|
1
|
+
"use strict";var e=require("fs-extra"),t=require("path"),n=require("events"),r=require("os"),i=require("commander"),s=require("inquirer"),a=require("image-size"),o=require("url"),l=require("chalk"),c=require("minimatch"),u=require("globby"),p=require("ejs"),E=require("download-git-repo"),g=require("rimraf"),I=require("dayjs"),d=require("util"),_=require("crypto"),h=require("mime-types"),m=require("qiniu"),C=require("md5"),P=require("resolve"),f=require("lodash"),N=require("child_process"),U=require("is-wsl"),D=require("axios"),L=require("form-data"),S=require("https"),A=require("tunnel"),T=require("@picgo/store"),B=require("cross-spawn"),O=require("js-yaml"),y=require("@picgo/i18n");const x={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:r,registry:i}=n,s={npmProxy:r,npmRegistry:i};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:r,registry:i}=n,s={npmProxy:r,npmRegistry:i};e.pluginHandler.update(t,s).catch(t=>{e.log.error(t)})})}},b={handle:e=>{e.cmd.program.option("-c, --config <path>","set config path")}},R=e=>e.startsWith("http://")||e.startsWith("https://"),G=e=>{e=e||"";try{return e!==decodeURI(e)}catch(e){return!1}},w=e=>(G(e)||(e=encodeURI(e)),e),M=(...e)=>e.join("").replace(/\/{2,}/g,"/").split("/").map(e=>encodeURIComponent(e)).join("/"),$=e=>{try{const{width:t=0,height:n=0,type:r}=a.imageSize(e);return{real:!0,width:t,height:n,extname:r?`.${r}`:".png"}}catch(e){return{real:!1,width:200,height:200,extname:".png"}}},H=async n=>{try{return{extname:t.extname(n),fileName:t.basename(n),filePath:n,buffer:await e.readFile(n),success:!0}}catch{return{reason:`read file ${n} error`,success:!1}}},v=async(e,n)=>{e=w(e);let r,i=!1,s="";const a=new Promise((a,l)=>{(async()=>{try{const l=await n.request({method:"get",url:e,resolveWithFullResponse:!0,responseType:"arraybuffer"}).then(e=>{const t=e.headers["content-type"];return t?.includes("image")&&(i=!0,s=`.${t.split("image/")[1]}`),e.data});if(clearTimeout(r),i){const n=new o.URL(e).pathname,r=decodeURIComponent(t.basename(n));a({buffer:l,fileName:r,extname:s,success:!0})}else a({success:!1,reason:`${e} is not image`})}catch(t){clearTimeout(r),a({success:!1,reason:`request ${e} error, ${t?.message??""}`})}})().catch(l)}),l=new Promise(t=>{r=setTimeout(()=>{t({success:!1,reason:`request ${e} timeout`})},1e4)});return Promise.race([a,l])},F=e=>/^@[^/]+\/picgo-plugin-/.test(e)?"scope":e.startsWith("picgo-plugin-")?"normal":q(e)?"simple":"unknown",q=n=>{if(t.isAbsolute(n))return!1;const r=t.join(process.cwd(),n);return!e.existsSync(r)&&(!n.includes("/")&&!n.includes("\\"))},k=(e,t="")=>t?`@${t}/picgo-plugin-${e}`:`picgo-plugin-${e}`,K=(n,r=console)=>{switch(F(n)){case"normal":case"scope":return n;case"simple":return k(n);default:{let i=n;return t.isAbsolute(n)&&e.existsSync(n)?j(i):(i=t.join(process.cwd(),n),e.existsSync(i)?j(i):(r.warn(`Can't find plugin ${n}`),""))}}},Y=(n,r=console)=>{switch(F(n)){case"normal":return Q(n);case"scope":return Q(n,!0);case"simple":return Q(k(n));default:{if(!e.existsSync(n))return r.warn(`Can't find plugin: ${n}`),"";const i=t.posix.join(n,"package.json");if(e.existsSync(i)){const t=e.readJSONSync(i)||{};return t.name?.includes("picgo-plugin-")?t.name:(r.warn(`The plugin package.json's name filed is ${t.name||"empty"}, need to include the prefix: picgo-plugin-`),"")}return r.warn(`Can't find plugin: ${n}`),""}}},j=e=>e.split(t.sep).join("/"),Q=(e,t=!1)=>{if(e.includes("@")){let n=/(.+\/)?(picgo-plugin-\w+)(@.+)*/;t&&(n=/(.+\/)?(^@[^/]+\/picgo-plugin-\w+)(@.+)*/);const r=e.match(n);return r?r[2]:(console.warn("can not remove plugin version"),e)}return e},W=[],z=e=>W.some(t=>e.startsWith(t)),V=e=>"object"==typeof e&&!Array.isArray(e)&&Object.keys(e).length>0;function J(e){try{return JSON.parse(e)}catch(t){return e}}const X=(e=0)=>isNaN(Number(e))?0:Number(e),Z=()=>"development"===process.env.NODE_ENV;var ee=Object.freeze({__proto__:null,configBlackList:W,forceNumber:X,getFSFile:H,getImageSize:$,getNormalPluginName:Y,getPluginNameType:F,getProcessPluginName:K,getURLFile:v,handleCompletePluginName:k,handleStreamlinePluginName:e=>/^@[^/]+\/picgo-plugin-/.test(e)?e.replace(/^@[^/]+\/picgo-plugin-/,""):e.replace(/picgo-plugin-/,""),handleUnixStylePath:j,handleUrlEncode:w,handleUrlPathSafeEncode:M,isConfigKeyInBlackList:z,isDev:Z,isInputConfigValid:V,isProd:()=>"production"===process.env.NODE_ENV,isSimpleName:q,isUrl:R,isUrlEncode:G,removePluginVersion:Q,safeParse:J});const te={handle:n=>{n.cmd.program.command("upload").description("upload, go go go").arguments("[input...]").alias("u").action(r=>{(async()=>{const i=r.map(e=>R(e)?e:t.resolve(e)).filter(t=>{const r=e.existsSync(t)||R(t);return r||n.log.warn(`${t} does not exist.`),r});await n.upload(i)})().catch(e=>{n.log.error(e)})})}},ne=async(e,t,n,r)=>{const i=await e.cmd.inquirer.prompt(t),s="uploader"===n?`picBed.${r}`:"transformer"===n?`transformer.${r}`:r;e.saveConfig({[s]:i}),"uploader"===n?e.saveConfig({"picBed.current":r,"picBed.uploader":r}):"transformer"===n&&e.saveConfig({"picBed.transformer":r})},re={handle:e=>{e.cmd.program.command("set").alias("config").arguments("<module> [name]").description("configure config of picgo modules").action((t,n)=>{(async()=>{try{switch(t){case"uploader":case"transformer":if(n){const r=e.helper[t].get(n);if(!r)return e.log.error(`No ${t} named ${n}`);r.config&&await ne(e,r.config(e),t,n)}else{const n=[{type:"list",name:`${t}`,choices:e.helper[t].getIdList(),message:`Choose a(n) ${t}`}],r=await e.cmd.inquirer.prompt(n),i=e.helper[t].get(r[t]);i?.config&&await ne(e,i.config(e),t,r[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}`);e.pluginLoader.getPlugin(n)?.config&&await ne(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);e.pluginLoader.getPlugin(n.plugin)?.config&&await ne(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)})})}},ie={handle:async e=>{const t=e.cmd;t.program.command("use").arguments("[module]").description("use modules of picgo").action(n=>{(async()=>{try{let r=[];const i={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(!i[n])return e.log.warn(`No module named ${n}`),e.log.warn("Available modules are uploader|transformer|plugins");r.push(i[n])}else r=Object.keys(i).map(e=>i[e]);const s=await t.inquirer.prompt(r);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)})})}},se={handle:e=>{e.cmd.program.option("-p, --proxy <url>","set proxy for uploading",t=>{e.setConfig({"picBed.proxy":t})})}},ae=async(e,n)=>{try{const r=le(n.tmp),i=t.join(n.tmp,"template");let s={};r.prompts&&r.prompts.length>0&&(s=await e.cmd.inquirer.prompt(r.prompts));let a=await u(["**/*"],{cwd:i,dot:!0});const o=Object.keys(r.filters||{});if(o.length>0&&(a=a.filter(t=>{let n="";for(const e of o)if(c(t,e,{dot:!0})){n=t;break}return!n||oe(e,r.filters[n],s)})),0===a.length)return e.log.warn("Template files not found!");const l=ce(a,i,s);ue(n.dest,l),"function"==typeof r.complete&&r.complete({answers:s,options:n,files:a,ctx:e}),r.completeMessage&&e.log.success(r.completeMessage),e.log.success("Done!")}catch(t){return e.log.error(t)}},oe=(e,t,n)=>{const r=new Function("data","with (data) { return "+t+"}");try{return r(n)}catch(n){return e.log.error(`Error when evaluating filter condition: ${JSON.stringify(t)}`),!1}},le=n=>{const r=t.join(n,"index.js");if(e.existsSync(r)){return require(r)}return{}},ce=(n,r,i)=>{const s={};return n.forEach(n=>{const a=e.readFileSync(t.join(r,n),"utf8"),o=p.render(a,i);(Buffer.isBuffer(o)||/[^\s]/.test(o))&&(s[n]=o)}),s},ue=(n,r)=>{Object.keys(r).forEach(i=>{const s=t.join(n,i);e.ensureDirSync(t.dirname(s)),e.writeFileSync(s,r[i])})},pe=(t,n)=>{n.offline?e.existsSync(n.template)?ae(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,Ee(t,n))},Ee=(t,n)=>{e.existsSync(n.tmp)&&g.rimrafSync(n.tmp),t.log.info("Template files are downloading..."),E(n.template,n.tmp,{clone:n.clone},e=>{if(e)return t.log.error(e);t.log.success("Template files are downloaded!"),ae(t,n).catch(e=>{t.log.error(e)})})},ge={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,a)=>{(async()=>{try{const o=i.includes("/"),l=!s||"."===s,c=t.resolve(s||"."),u=a.clone||!1,p=a.offline||!1,E=t.join(r.homedir(),".picgo/templates",i.replace(/[/:]/g,"-"));a.offline&&(i=E);const g={template:i,project:s,hasSlash:o,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&&pe(n,g)}):pe(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(l.gray(" # create a new project with an official template")),console.log(" $ picgo init plugin my-project"),console.log(),console.log(l.gray(" # create a new project straight from a github template")),console.log(" $ picgo init username/repo my-project"),console.log()})}},Ie={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"}],r=await e.cmd.inquirer.prompt(t);return e.i18n.setLanguage(r.i18n),void e.log.success(`Language set to ${r.i18n}`)}if(!n.includes(t))return e.log.warn("No such language");e.i18n.setLanguage(t),e.log.success(`Language set to ${t}`)})}};class de{static currentPlugin;list;pluginIdMap;name;constructor(e){this.name=e,this.list=new Map,this.pluginIdMap=new Map}register(e,t){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),de.currentPlugin&&(this.pluginIdMap.has(de.currentPlugin)?this.pluginIdMap.get(de.currentPlugin)?.push(e):this.pluginIdMap.set(de.currentPlugin,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);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 _e=(e=null)=>{de.currentPlugin=e};class he{name="commander";static currentPlugin;list=new Map;pluginIdMap=new Map;ctx;program;inquirer;constructor(e){this.program=new i.Command,this.inquirer=s,this.ctx=e}getName(){return this.name}init(){var e;this.program.version("1.6.2","-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",x),e.cmd.register("config",b),e.cmd.register("setting",re),e.cmd.register("upload",te),e.cmd.register("use",ie),e.cmd.register("proxy",se),e.cmd.register("init",ge),e.cmd.register("i18n",Ie)}register(e,t){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 n=de.currentPlugin;null!==n&&(this.pluginIdMap.has(n)?this.pluginIdMap.get(n)?.push(e):this.pluginIdMap.set(n,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);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 me,Ce;exports.ILogType=void 0,(me=exports.ILogType||(exports.ILogType={})).success="success",me.info="info",me.warn="warn",me.error="error",exports.IBuildInEvent=void 0,(Ce=exports.IBuildInEvent||(exports.IBuildInEvent={})).UPLOAD_PROGRESS="uploadProgress",Ce.FAILED="failed",Ce.BEFORE_TRANSFORM="beforeTransform",Ce.BEFORE_UPLOAD="beforeUpload",Ce.AFTER_UPLOAD="afterUpload",Ce.FINISHED="finished",Ce.INSTALL="install",Ce.UNINSTALL="uninstall",Ce.UPDATE="update",Ce.NOTIFICATION="notification",exports.IBusEvent=void 0,(exports.IBusEvent||(exports.IBusEvent={})).CONFIG_CHANGE="CONFIG_CHANGE";class Pe{level={[exports.ILogType.success]:"green",[exports.ILogType.info]:"blue",[exports.ILogType.warn]:"yellow",[exports.ILogType.error]:"red"};ctx;logLevel;logPath;constructor(e){this.ctx=e}handleLog(e,...n){if(this.logLevel=this.ctx.getConfig("settings.logLevel"),!this.ctx.getConfig("silent")&&this.checkLogLevel(e,this.logLevel)){const r=l[this.level[e]](`[PicGo ${e.toUpperCase()}]:`);console.log(r,...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(l.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,r=1024*X(this.ctx.getConfig("settings.logFileSizeLimit")||10)*1024;return{isLarge:n>r,logFileSize:n,logFileSizeLimit:r}}return{isLarge:!1}}recreateLogFile(t){e.existsSync(t)&&(e.unlinkSync(t),e.createFileSync(t))}handleWriteLog(t,n,...r){try{let i=`${I().format("YYYY-MM-DD HH:mm:ss")} [PicGo ${n.toUpperCase()}] `;r.forEach(e=>{e instanceof Error&&"error"===n?i+=`\n------Error Stack Begin------\n${d.format(e?.stack)}\n-------Error Stack End------- `:("object"==typeof e&&(e=JSON.stringify(e,null,2)),i+=`${e} `)}),i+="\n",e.appendFileSync(t,i)}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(exports.ILogType.success,...e)}info(...e){return this.handleLog(exports.ILogType.info,...e)}error(...e){return this.handleLog(exports.ILogType.error,...e)}warn(...e){return this.handleLog(exports.ILogType.warn,...e)}debug(...e){Z()&&this.handleLog(exports.ILogType.info,...e)}}class fe extends n.EventEmitter{ctx;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(exports.IBuildInEvent.FAILED),t.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,-1),t.emit(exports.IBuildInEvent.FAILED,e),t.log.error(e),t.getConfig("debug"))throw e;return t}}async beforeTransform(e){return e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,0),e.emit(exports.IBuildInEvent.BEFORE_TRANSFORM,e),e.log.info("Before transform"),await this.handlePlugins(e.helper.beforeTransformPlugins,e),e}async doTransform(e){e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,30);const t=e.getConfig("picBed.transformer")||"path";let n=t,r=e.helper.transformer.get(t);return r||(r=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(r?.handle(e)),e}async beforeUpload(e){return e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,60),e.log.info("Before upload"),e.emit(exports.IBuildInEvent.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),r=t;n||(t="smms",r="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 [${r}]`),await(n?.handle(e));for(const n of e.output)n.type=t;return e}async afterUpload(e){e.emit(exports.IBuildInEvent.AFTER_UPLOAD,e),e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,100),await this.handlePlugins(e.helper.afterUploadPlugins,e);let t="";const n=e.output.length,r=!0===e.getConfig("settings.encodeOutputURL");for(let i=0;i<n;i++)void 0!==e.output[i].imgUrl&&(t+=r?w(e.output[i].imgUrl):e.output[i].imgUrl,i!==n-1&&(t+="\n")),delete e.output[i].base64Image,delete e.output[i].buffer;return e.emit(exports.IBuildInEvent.FINISHED,e),e.log.success(`\n${t}`),e}async handlePlugins(e,t){const n=e.getList(),r=e.getIdList(),i=e.getName();return await Promise.all(n.map(async(e,n)=>{try{t.log.info(`${i}: ${r[n]} running`),await e.handle(t)}catch(e){throw t.log.error(`${i}: ${r[n]} error`),e}})),t}}const Ne=(e,t,n,r="")=>({method:"POST",url:`https://${r||"sm.ms"}/api/v2/upload`,headers:{contentType:"multipart/form-data","User-Agent":"PicGo",Authorization:n},formData:{smfile:{value:t,options:{filename:e}},ssl:"true"}}),Ue=async e=>{const t=e.getConfig("picBed.smms");if(!t)throw new Error("Can not find smms config!");const n=e.output;for(const r of n)if(r.fileName&&r.buffer){let n=r.buffer;!n&&r.base64Image&&(n=Buffer.from(r.base64Image,"base64"));const i=Ne(r.fileName,n,t?.token,t?.backupDomain);try{const t=await e.request(i),n=JSON.parse(t);if("success"===n.code)delete r.base64Image,delete r.buffer,r.imgUrl=n.data.url;else{if("image_repeated"!==n.code||"string"!=typeof n.images)throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:n.message}),new Error(n.message);delete r.base64Image,delete r.buffer,r.imgUrl=n.images}}catch(t){throw e.log.error(t),t}}return e},De=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 Le=e=>h.lookup(e)||"application/octet-stream",Se=(e,t,n,r)=>{const i=e.secretId,s=e.secretKey,a=e.appId,o=e.bucket;let l,c="";if(e.version&&"v4"!==e.version){const i=Math.floor((new Date).getTime()/1e3);c=`${i};${i+86400}`;const a=_.createHmac("sha1",s).update(c).digest("hex"),o=e.endpoint?e.endpoint:`cos.${e.area}.myqcloud.com`,p=`put\n/${e.path}${t}\n\ncontent-length=${r}&content-type=${u=n,encodeURIComponent(u).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A")}&host=${e.bucket}.${o}\n`,E=`sha1\n${c}\n${_.createHash("sha1").update(p).digest("hex")}\n`;l=_.createHmac("sha1",a).update(E).digest("hex")}else{const e=Math.floor(1e10*Math.random()),t=Math.floor((new Date).getTime()/1e3)-1,n=`a=${a}&b=${o}&k=${i}&e=${t+3600}&t=${t}&r=${e}&f=`,r=_.createHmac("sha1",s).update(n).digest(),c=Buffer.concat([r,Buffer.from(n)]);l=Buffer.from(c).toString("base64")}var u;return{signature:l,appId:a,bucket:o,signTime:c}},Ae=(e,t,n,r,i)=>{const s=e.area,a=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}/${M(a,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=content-length;content-type;host&q-url-param-list=&q-signature=${n.signature}`,contentType:Le(t),contentLength:r.byteLength,"User-Agent":`PicGo;${i};null;null`},body:r,resolveWithFullResponse:!0}}return{method:"POST",url:`http://${s}.file.myqcloud.com/files/v2/${n.appId}/${n.bucket}/${M(a,t)}`,headers:{Host:`${s}.file.myqcloud.com`,Authorization:n.signature,contentType:"multipart/form-data","User-Agent":`PicGo;${i};null;null`},formData:{op:"upload",filecontent:r},resolveWithFullResponse:!0}},Te=async e=>{const t=e.getConfig("picBed.tcyun");if(!t)throw new Error("Can't find tencent COS config");try{const n=e.output,r=t.customUrl,i=t.path,s=!t.version||"v4"===t.version;for(const a of n)if(a.fileName&&a.buffer){let n=a.buffer;!n&&a.base64Image&&(n=Buffer.from(a.base64Image,"base64"));const o=Se(t,a.fileName,Le(a.fileName),n.byteLength);if(!o)return!1;const l=Ae(t,a.fileName,o,n,e.GUI_VERSION||e.VERSION),c=await e.request(l).then(e=>e).catch(t=>({statusCode:400,body:{msg:e.i18n.translate("AUTH_FAILED"),err:t}}));let u;if(u=s&&"string"==typeof c?JSON.parse(c):c,400===u.statusCode)throw u?.body?.err?u.body.err:new Error(u?.body?.msg||u?.body?.message);const p=t.options||"",E=t.slim||"";if(s&&"SUCCESS"===u.message)delete a.base64Image,delete a.buffer,a.imgUrl=r?`${r}/${i}${a.fileName}`:`${u.data.source_url}${p}`;else{if(s||!u||200!==u.statusCode)throw new Error(c.body.msg);if(delete a.base64Image,delete a.buffer,r)a.imgUrl=`${r}/${encodeURI(i)}${M(a.fileName)}${p}`;else{const e=t.endpoint?t.endpoint:`cos.${t.area}.myqcloud.com`;a.imgUrl=`https://${t.bucket}.${e}/${encodeURI(i)}${M(a.fileName)}${p}`}}E&&(a.imgUrl+=p?"&imageSlim":"?imageSlim")}return e}catch(n){if(!t.version||"v4"===t.version)try{const t=JSON.parse(n.error);e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("UPLOAD_FAILED_REASON",{code:t.code}),text:"https://cloud.tencent.com/document/product/436/8432"})}catch(e){}throw n}},Be=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 Oe=(e,t,n)=>{const r=t.path||"",{token:i,repo:s}=t;return{method:"PUT",url:`https://api.github.com/repos/${s}/contents/${M(r,e)}`,headers:{Authorization:`token ${i}`,"User-Agent":"PicGo","Content-Type":h.lookup(e)},body:n,json:!0}},ye=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 r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i={message:"Upload by PicGo",branch:t.branch,content:n,path:t.path+encodeURI(r.fileName)},s=Oe(r.fileName,t,i);try{const n=await e.request(s);if(!n)throw new Error("Server error, please try again");delete r.base64Image,delete r.buffer,t.customUrl?r.imgUrl=`${t.customUrl}/${M(t.path||"",r.fileName)}`:r.imgUrl=n.content.download_url}catch(e){if(422!==e.statusCode)throw e;delete r.base64Image,delete r.buffer,t.customUrl?r.imgUrl=`${t.customUrl}/${M(t.path||"",r.fileName)}`:r.imgUrl=`https://raw.githubusercontent.com/${t.repo}/${t.branch}/${M(t.path||"",r.fileName)}`}}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK")}),t}},xe=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 be(e,t,n,r){const i=function(e){return"z0"===e?"":"-"+e}(e.area||"z0"),s=e.path||"";return{method:"POST",url:`http://upload${i}.qiniup.com/putb64/-1/key/${Buffer.from(s+t,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_")}`,headers:{Authorization:`UpToken ${n}`,"Content-Type":h.lookup(t)||"application/octet-stream"},body:r}}function Re(e){const t=e.accessKey,n=e.secretKey,r=new m.auth.digest.Mac(t,n),i={scope:e.bucket};return new m.rs.PutPolicy(i).uploadToken(r)}const Ge=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 r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i=be(t,r.fileName,Re(t),n),s=await e.request(i),a=JSON.parse(s);if(!a?.key)throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:a.msg}),e.log.error("qiniu error",a),new Error("Upload failed");{delete r.base64Image,delete r.buffer;const e=t.url,n=t.options;r.imgUrl=`${e}/${a.key}${n}`}}return e}catch(t){if("Upload failed"!==t.message&&t.response){const n=t.response.body;e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:n.error})}throw t}},we=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 Me=(e,t,n)=>{const r={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&&(r.proxy=e.proxy),r},$e=async e=>{const t=e.getConfig("picBed.imgur");if(!t)throw new Error("Can't find imgur config");try{const n=e.output;for(const r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i=Me(t,r.fileName,n),s=await e.request(i),a="string"==typeof s?JSON.parse(s):s;if(!a.success)throw new Error("Server error, please try again");delete r.base64Image,delete r.buffer,r.imgUrl=a.data.link}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK"),text:"http://docs.imgur.com/api/errno/"}),t?.response?.data||t}},He=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 ve=(e,t)=>{const n=(new Date).toUTCString(),r=h.lookup(t);if(!r)throw Error(`No mime type found for file ${t}`);const i=`PUT\n\n${r}\n${n}\n/${e.bucket}/${e.path}${t}`,s=_.createHmac("sha1",e.accessKeySecret).update(i).digest("base64");return`OSS ${e.accessKeyId}:${s}`},Fe=(e,t,n,r)=>{const i=e.path||"";return{method:"PUT",url:`https://${e.bucket}.${e.area}.aliyuncs.com/${M(i,t)}`,headers:{Host:`${e.bucket}.${e.area}.aliyuncs.com`,Authorization:n,Date:(new Date).toUTCString(),"Content-Type":h.lookup(t)},body:r,resolveWithFullResponse:!0}},qe=async e=>{const t=e.getConfig("picBed.aliyun");if(!t)throw new Error("Can't find aliYun OSS config");try{const n=e.output,r=t.customUrl,i=t.path||"";for(const s of n)if(s.fileName&&s.buffer){const n=ve(t,s.fileName);let a=s.buffer;!a&&s.base64Image&&(a=Buffer.from(s.base64Image,"base64"));const o=Fe(t,s.fileName,n,a);if(200!==(await e.request(o)).statusCode)throw new Error("Upload failed");{delete s.base64Image,delete s.buffer;const e=t.options||"";s.imgUrl=r?`${r}/${M(i,s.fileName)}${e}`:`https://${t.bucket}.${t.area}.aliyuncs.com/${M(i,s.fileName)}${e}`}}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")}),t}},ke=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 Ke=(e,t)=>{const n=e.path||"",r=e.operator,i=e.password,s=C(i),a=(new Date).toUTCString(),o=`PUT&${`/${e.bucket}/${M(n,t)}`}&${a}`;return`UPYUN ${r}:${_.createHmac("sha1",s).update(o).digest("base64")}`},Ye=(e,t,n,r)=>{const i=e.bucket,s=e.path||"";return{method:"PUT",url:`https://v0.api.upyun.com/${i}/${M(s,t)}`,headers:{Authorization:n,Date:(new Date).toUTCString(),"Content-Type":h.lookup(t)||"application/octet-stream"},body:r,resolveWithFullResponse:!0}},je=async e=>{const t=e.getConfig("picBed.upyun");if(!t)throw new Error("Can't find upYun config");try{const n=e.output,r=t.path||"";for(const i of n)if(i.fileName&&i.buffer){let n=i.buffer;!n&&i.base64Image&&(n=Buffer.from(i.base64Image,"base64"));const s=Ke(t,i.fileName),a=Ye(t,i.fileName,s,n);if(200!==(await e.request(a)).statusCode)throw new Error("Upload failed");delete i.base64Image,delete i.buffer,i.imgUrl=`${t.url}/${M(r,i.fileName)}${t.options}`}return e}catch(t){if("Upload failed"===t.message)e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")});else{const n=J(t.error);e.emit(exports.IBuildInEvent.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}},Qe=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 We=()=>({register(e){!function(e){e.helper.uploader.register("aliyun",{get name(){return e.i18n.translate("PICBED_ALICLOUD")},handle:qe,config:ke})}(e),function(e){e.helper.uploader.register("tcyun",{get name(){return e.i18n.translate("PICBED_TENCENTCLOUD")},handle:Te,config:Be})}(e),function(e){e.helper.uploader.register("smms",{get name(){return e.i18n.translate("PICBED_SMMS")},handle:Ue,config:De})}(e),function(e){e.helper.uploader.register("github",{get name(){return e.i18n.translate("PICBED_GITHUB")},handle:ye,config:xe})}(e),function(e){e.helper.uploader.register("qiniu",{get name(){return e.i18n.translate("PICBED_QINIU")},handle:Ge,config:we})}(e),function(e){e.helper.uploader.register("imgur",{get name(){return e.i18n.translate("PICBED_IMGUR")},handle:$e,config:He})}(e),function(e){e.helper.uploader.register("upyun",{get name(){return e.i18n.translate("PICBED_UPYUN")},handle:je,config:Qe})}(e)}}),ze=(e,t,n)=>{const r=$(t);return r.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")),r};var Ve={handle:async e=>{const t=e.output;return await Promise.all(e.input.map(async(n,r)=>{let i;if(i=Buffer.isBuffer(n)?{success:!0,buffer:n,fileName:"",extname:""}:R(n)?await v(n,e):await H(n),i.success&&i.buffer){const s=ze(e,i.buffer,n),a=i.extname||s.extname||".png";t[r]={buffer:i.buffer,fileName:i.fileName||`${I().format("YYYYMMDDHHmmssSSS")}${a}}`,width:s.width,height:s.height,filePath:i.filePath,extname:a,mimeType:h.lookup(a)||"application/octet-stream"}}else e.log.error(i.reason)})),e.output=t.filter(e=>e),e}};var Je={handle:async e=>(e.output.push(...e.input),e)};class Xe{ctx;list=[];fullList=new Set;pluginMap=new Map;constructor(e){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 P.sync(n,{basedir:e.baseDir})}catch(r){return t.join(e.baseDir,"node_modules",n)}}load(){const n=t.join(this.ctx.baseDir,"package.json"),r=t.join(this.ctx.baseDir,"node_modules/");if(!e.existsSync(r))return!1;const i=e.readJSONSync(n),s=Object.keys(i.dependencies||{}),a=Object.keys(i.devDependencies||{}),o=s.concat(a).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 o)this.registerPlugin(e);return!0}registerPlugin(e,t){if(e&&"string"==typeof e){this.fullList.add(e);try{if(t){this.list.push(e),_e(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),_e(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(exports.IBuildInEvent.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),_e(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/"),r=require(n+e)(this.ctx);return this.pluginMap.set(e,r),r}getList(){return this.list}hasPlugin(e){return this.fullList.has(e)}getFullList(){return[...this.fullList]}}const Ze="picgo-clipboard-images",et={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\nelse\n # fallback for unsupported session types\n echo >&2 "Error: Unsupported session type \'$XDG_SESSION_TYPE\'."\n echo >&2 "Solution: The variable of XDG_SESSION_TYPE must set as \'x11\' or \'wayland\'."\n exit 1\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'},tt={darwin:"mac.applescript",win32:"windows.ps1",win10:"windows10.ps1",linux:"linux.sh",wsl:"wsl.sh"};const nt=async n=>{!function(n){const r=t.join(n.baseDir,Ze);e.existsSync(r)||e.mkdirSync(r)}(n);const i=t.join(n.baseDir,Ze,`${I().format("YYYYMMDDHHmmssSSS")}.png`);return await new Promise((s,a)=>{const o=(()=>{const e=process.platform;if(U)return"wsl";if("win32"===e)return"10"===r.release().split(".")[0]?"win10":"win32";return"darwin"===e?"darwin":"linux"})(),l=t.join(n.baseDir,tt[o]);let c;e.existsSync(l)||e.writeFileSync(l,et[o],"utf8"),c="darwin"===o?N.spawn("osascript",[l,i]):"win32"===o||"win10"===o?N.spawn("powershell",["-noprofile","-noninteractive","-nologo","-sta","-executionpolicy","unrestricted","-file",l,i]):N.spawn("sh",[l,i]),c.stdout.on("data",r=>{if("linux"===o&&"no xclip or wl-clipboard"===r.toString().trim())return n.emit(exports.IBuildInEvent.NOTIFICATION,{title:"xclip or wl-clipboard not found",body:"Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"}),a(new Error("Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"));const l=r.toString().trim();let c=!1;if(t.basename(l)!==t.basename(i)&&e.existsSync(l)&&(c=!0),"no image"!==l&&!e.existsSync(l))return a(new Error(`Can't find ${l}`));s({imgPath:l,shouldKeepAfterUploading:c})})})},rt=new n.EventEmitter,it=new S.Agent({maxVersion:"TLSv1.2",minVersion:"TLSv1.2"});function st(e,t,n){"object"==typeof n&&"value"in n&&"options"in n?e.append(t,n.value,n.options):e.append(t,n)}function at(e){return{...e,statusCode:e.status,body:e.data}}function ot(e){const t={method:e?.config?.method?.toUpperCase()||"",url:e?.config?.url||"",statusCode:e?.response?.status||0,message:e?.message||"",stack:e?.stack||{},response:{status:e?.response?.status||0,statusCode:e?.response?.status||0,body:e?.response?.data||""}};return Promise.reject(t)}class lt{ctx;proxy="";options={};constructor(e){this.ctx=e,this.init(),rt.on(exports.IBusEvent.CONFIG_CHANGE,e=>{switch(e.configName){case"picBed":e.value?.proxy&&(this.proxy=e.value.proxy);break;case"picBed.proxy":this.proxy=e.value}})}init(){const e=this.ctx.getConfig("picBed.proxy");e&&(this.proxy=e)}handleProxy(){if(this.proxy)try{const e=new o.URL(this.proxy);return{host:e.hostname,port:parseInt(e.port||"0",10),protocol:e.protocol}}catch(e){}return!1}request(e){this.options.proxy=this.handleProxy(),this.options.headers=e.headers||{},this.options.maxBodyLength=1/0,this.options.maxContentLength=1/0,this.options.proxy&&e.url?.startsWith("https://")?(this.options.httpsAgent=A.httpsOverHttp({proxy:{host:this.options.proxy.host,port:this.options.proxy.port}}),this.options.proxy=!1):this.options.httpsAgent=it;const t=D.create(this.options);t.interceptors.response.use(at,ot);const n=function(e){let t=!1;const n={...e,url:e.url||"",headers:e.headers||{}};if(e.proxy){let r=e.proxy;if("string"==typeof r){try{r=new o.URL(e.proxy)}catch(e){r=!1,n.proxy=!1,console.error(e)}t=!0}r&&(e.url?.startsWith("https://")?(n.proxy=!1,n.httpsAgent=A.httpsOverHttp({proxy:{host:r?.hostname,port:parseInt(r?.port,10)}})):n.proxy={host:r.hostname,port:parseInt(r.port,10),protocol:"http"})}if("formData"in e){const r=new L;for(const t in e.formData)st(r,t,e.formData[t]);n.data=r,n.headers=Object.assign(n.headers||{},r.getHeaders()),t=!0,delete n.formData}return"body"in e&&(n.data=e.body,t=!0,delete n.body),"qs"in e&&(n.params=e.qs,t=!0),n.__isOldOptions=t,n}(e);return t.interceptors.request.use(function(e){let t="";return e?.headers?.contentType?(t=e.headers.contentType,delete e.headers.contentType):e?.headers?.ContentType?(t=e.headers.ContentType,delete e.headers.ContentType):e?.headers?.["content-type"]&&(t=e.headers["content-type"],delete e.headers["content-type"]),""!==t&&e.headers&&(e.headers["Content-Type"]=t),e}),"resolveWithFullResponse"in e&&e.resolveWithFullResponse?t.request(n):t.request(n).then(t=>n.__isOldOptions?"json"in e?e.json?t.data:void 0:JSON.stringify(t.data):t.data)}}class ct{ctx;db;constructor(e){if(this.ctx=e,this.db=new T.JSONStore(this.ctx.configPath),!this.db.has("picBed"))try{this.db.set("picBed",{uploader:"smms",current:"smms"})}catch(e){throw this.ctx.log.error(e),e}if(!this.db.has("picgoPlugins"))try{this.db.set("picgoPlugins",{})}catch(e){throw this.ctx.log.error(e),e}}read(e){return this.db.read(e)}get(e=""){return this.read(!0),this.db.get(e)}set(e,t){return this.read(!0),this.db.set(e,t)}has(e){return this.read(!0),this.db.has(e)}unset(e,t){return this.read(!0),this.db.unset(e,t)}saveConfig(e){Object.keys(e).forEach(t=>{this.set(t,e[t])})}removeConfig(e){Object.keys(e).forEach(t=>{this.unset(t,e[t])})}}class ut{ctx;constructor(e){this.ctx=e}async install(e,t={},n){const r=[],i=e.map(e=>pt(this.ctx,e)).filter(e=>this.ctx.pluginLoader.hasPlugin(e.pkgName)?(r.push(e.pkgName),this.ctx.log.success(`PicGo has already installed ${e.pkgName}`),!1):!!e.success),s=i.map(e=>e.fullName),a=i.map(e=>e.pkgName);if(s.length>0){const e=await this.execCommand("install",s,this.ctx.baseDir,t,n);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("installFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED"),body:t});return{success:!1,body:t}}a.forEach(e=>{this.ctx.pluginLoader.registerPlugin(e)}),this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS")),this.ctx.emit("installSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS"),body:[...a,...r]});return{success:!0,body:[...a,...r]}}if(0===r.length){const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("installFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED"),body:e});return{success:!1,body:e}}this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS")),this.ctx.emit("installSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS"),body:[...a,...r]});return{success:!0,body:[...a,...r]}}async uninstall(e){const t=e.map(e=>pt(this.ctx,e)).filter(e=>e.success).map(e=>e.pkgName);if(t.length>0){const e=await this.execCommand("uninstall",t,this.ctx.baseDir);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("uninstallFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED"),body:t});return{success:!1,body:t}}t.forEach(e=>{this.ctx.pluginLoader.unregisterPlugin(e)}),this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS")),this.ctx.emit("uninstallSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS"),body:t});return{success:!0,body:t}}{const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("uninstallFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED"),body:e});return{success:!1,body:e}}}async update(e,t={},n){const r=e.map(e=>pt(this.ctx,e)).filter(e=>e.success).map(e=>e.pkgName);if(r.length>0){const e=await this.execCommand("update",r,this.ctx.baseDir,t,n);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("updateFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED"),body:t});return{success:!1,body:t}}this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS")),this.ctx.emit("updateSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS"),body:r});return{success:!0,body:r}}{const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("updateFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED"),body:e});return{success:!1,body:e}}}async execCommand(e,t,n,r={},i={}){const s=r.npmRegistry||this.ctx.getConfig("settings.npmRegistry"),a=r.npmProxy||this.ctx.getConfig("settings.npmProxy");return await new Promise(r=>{let o=[e].concat(t).concat("--color=always").concat("--save");s&&(o=o.concat(`--registry=${s}`)),a&&(o=o.concat(`--proxy=${a}`));try{const e=B("npm",o,{cwd:n,env:Object.assign({},process.env,i)});let t="";e.stdout?.on("data",e=>{t+=e}).pipe(process.stdout),e.stderr?.on("data",e=>{t+=e}).pipe(process.stderr),e.on("close",e=>{r(e?{code:e,data:t}:{code:0,data:t})}),e.on("error",e=>{this.ctx.log.error(e),this.ctx.log.error("NPM is not installed"),this.ctx.emit(exports.IBuildInEvent.FAILED,"NPM is not installed")})}catch(e){this.ctx.log.error(e),this.ctx.emit(exports.IBuildInEvent.FAILED,e)}})}}const pt=(e,t)=>{const n={success:!1,fullName:"",pkgName:""},r=K(t,e.log);if(!r)return n;const i=Y(r,e.log);return i?{success:!0,fullName:r,pkgName:i}:n},Et={"zh-CN":{UPLOAD_FAILED:"上传失败",CHECK_SETTINGS:"请检查你的配置项是否正确",CHECK_SETTINGS_AND_NETWORK:"请检查你的配置项以及网络",UPLOAD_FAILED_REASON:"错误码:${code},请打开浏览器粘贴地址查看相关原因",SERVER_ERROR:"服务端出错,请重试",AUTH_FAILED:"认证失败",PICBED_SMMS:"SM.MS",PICBED_SMMS_TOKEN:"设定Token",PICBED_SMMS_BACKUP_DOMAIN:"备用上传域名",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例如 smms.app",PICBED_ALICLOUD:"阿里云OSS",PICBED_ALICLOUD_ACCESSKEYID:"设定KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"设定KeySecret",PICBED_ALICLOUD_BUCKET:"设定Bucket",PICBED_ALICLOUD_AREA:"设定存储区域",PICBED_ALICLOUD_PATH:"设定存储路径",PICBED_ALICLOUD_CUSTOMURL:"设定自定义域名",PICBED_ALICLOUD_OPTIONS:"设定网址后缀",PICBED_ALICLOUD_MESSAGE_AREA:"例如:oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例如:test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例如:?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD:"腾讯云COS",PICBED_TENCENTCLOUD_VERSION:"COS版本",PICBED_TENCENTCLOUD_SECRETID:"设定SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"设定SecretKey",PICBED_TENCENTCLOUD_APPID:"设定AppId",PICBED_TENCENTCLOUD_BUCKET:"设定Bucket",PICBED_TENCENTCLOUD_AREA:"设定存储区域",PICBED_TENCENTCLOUD_ENDPOINT:"设定Endpoint",PICBED_TENCENTCLOUD_PATH:"设定存储路径",PICBED_TENCENTCLOUD_OPTIONS:"设定网址后缀",PICBED_TENCENTCLOUD_CUSTOMURL:"设定自定义域名",PICBED_TENCENTCLOUD_SLIM:"极智压缩",PICBED_TENCENTCLOUD_SLIM_TIP:"图片极智压缩,详情请参考[文档说明](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"开启",PICBED_TENCENTCLOUD_SLIM_CANCEL:"关闭",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例如:1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例如:ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例如:cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例如:test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例如:?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"设定Token",PICBED_GITHUB_REPO:"设定仓库名",PICBED_GITHUB_PATH:"设定存储路径",PICBED_GITHUB_BRANCH:"设定分支名",PICBED_GITHUB_CUSTOMURL:"设定自定义域名",PICBED_GITHUB_MESSAGE_REPO:"格式:username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例如:main",PICBED_GITHUB_MESSAGE_PATH:"例如:test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_QINIU:"七牛云",PICBED_QINIU_ACCESSKEY:"设定AccessKey",PICBED_QINIU_SECRETKEY:"设定SecretKey",PICBED_QINIU_BUCKET:"设定Bucket",PICBED_QINIU_PATH:"设定存储路径",PICBED_QINIU_URL:"设定访问网址",PICBED_QINIU_OPTIONS:"设定网址后缀",PICBED_QINIU_AREA:"设定存储区域",PICBED_QINIU_MESSAGE_PATH:"例如:test/",PICBED_QINIU_MESSAGE_AREA:"例如:z0",PICBED_QINIU_MESSAGE_OPTIONS:"例如:?imageslim",PICBED_QINIU_MESSAGE_URL:"例如:https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"设定ClientId",PICBED_IMGUR_PROXY:"设定代理",PICBED_IMGUR_MESSAGE_PROXY:"例如:http://127.0.0.1:1080",PICBED_UPYUN:"又拍云",PICBED_UPYUN_BUCKET:"设定Bucket",PICBED_UPYUN_OPERATOR:"设定操作员",PICBED_UPYUN_PASSWORD:"设定操作员密码",PICBED_UPYUN_PATH:"设定存储路径",PICBED_UPYUN_URL:"设定加速域名",PICBED_UPYUN_OPTIONS:"设定网址后缀",PICBED_UPYUN_MESSAGE_OPERATOR:"例如:me",PICBED_UPYUN_MESSAGE_PASSWORD:"输入操作员密码",PICBED_UPYUN_MESSAGE_URL:"例如:http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例如:!imgslim",PICBED_UPYUN_MESSAGE_PATH:"例如:test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"插件安装成功",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"插件安装失败",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"插件安装失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"插件安装失败,请输入合法插件名或合法安装路径",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"插件卸载成功",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"插件卸载失败",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"插件卸载失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"插件卸载失败,请输入合法插件名",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"插件更新成功",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"插件更新失败",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"插件更新失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"插件更新失败,请输入合法插件名"},"zh-TW":{UPLOAD_FAILED:"上傳失敗",CHECK_SETTINGS:"請檢查你的設定是否正確",CHECK_SETTINGS_AND_NETWORK:"請檢查你的設定及網路",UPLOAD_FAILED_REASON:"錯誤碼:${code},請打開瀏覽器貼上地址查看相關原因",SERVER_ERROR:"伺服器出錯,請重試",AUTH_FAILED:"認證失敗",PICBED_SMMS:"SM.MS",PICBED_SMMS_TOKEN:"設定Token",PICBED_SMMS_BACKUP_DOMAIN:"備用上傳網址",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例如 smms.app",PICBED_ALICLOUD:"阿里云OSS",PICBED_ALICLOUD_ACCESSKEYID:"設定KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"設定KeySecret",PICBED_ALICLOUD_BUCKET:"設定Bucket",PICBED_ALICLOUD_AREA:"設定儲存區域",PICBED_ALICLOUD_PATH:"設定儲存路徑",PICBED_ALICLOUD_CUSTOMURL:"設定自訂網址",PICBED_ALICLOUD_OPTIONS:"設定網址後綴",PICBED_ALICLOUD_MESSAGE_AREA:"例如:oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例如:test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例如:?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD:"騰訊云COS",PICBED_TENCENTCLOUD_VERSION:"COS版本",PICBED_TENCENTCLOUD_SECRETID:"設定SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"設定SecretKey",PICBED_TENCENTCLOUD_APPID:"設定AppId",PICBED_TENCENTCLOUD_BUCKET:"設定Bucket",PICBED_TENCENTCLOUD_AREA:"設定儲存區域",PICBED_TENCENTCLOUD_ENDPOINT:"設定Endpoint",PICBED_TENCENTCLOUD_PATH:"設定儲存路徑",PICBED_TENCENTCLOUD_OPTIONS:"設定網址後綴",PICBED_TENCENTCLOUD_SLIM:"極智壓縮",PICBED_TENCENTCLOUD_SLIM_CANCEL:"關閉",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"開啓",PICBED_TENCENTCLOUD_SLIM_TIP:"圖片極智壓縮,詳情請參考[文檔說明](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_CUSTOMURL:"設定自訂網址",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例如:1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例如:ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例如:cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例如:test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例如:?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"設定Token",PICBED_GITHUB_REPO:"設定倉庫名稱",PICBED_GITHUB_PATH:"設定儲存路徑",PICBED_GITHUB_BRANCH:"設定分支名稱",PICBED_GITHUB_CUSTOMURL:"設定自訂網址",PICBED_GITHUB_MESSAGE_REPO:"格式:username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例如:main",PICBED_GITHUB_MESSAGE_PATH:"例如:test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_QINIU:"七牛云",PICBED_QINIU_ACCESSKEY:"設定AccessKey",PICBED_QINIU_SECRETKEY:"設定SecretKey",PICBED_QINIU_BUCKET:"設定Bucket",PICBED_QINIU_PATH:"設定儲存路徑",PICBED_QINIU_URL:"設定訪問網址",PICBED_QINIU_OPTIONS:"設定網址後綴",PICBED_QINIU_AREA:"設定儲存區域",PICBED_QINIU_MESSAGE_PATH:"例如:test/",PICBED_QINIU_MESSAGE_AREA:"例如:z0",PICBED_QINIU_MESSAGE_OPTIONS:"例如:?imageslim",PICBED_QINIU_MESSAGE_URL:"例如:https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"設定ClientId",PICBED_IMGUR_PROXY:"設定PROXY",PICBED_IMGUR_MESSAGE_PROXY:"例如:http://127.0.0.1:1080",PICBED_UPYUN:"又拍云",PICBED_UPYUN_BUCKET:"設定Bucket",PICBED_UPYUN_OPERATOR:"設定操作員",PICBED_UPYUN_PASSWORD:"設定操作員密碼",PICBED_UPYUN_PATH:"設定儲存路徑",PICBED_UPYUN_URL:"設定加速網址",PICBED_UPYUN_OPTIONS:"設定網址後綴",PICBED_UPYUN_MESSAGE_OPERATOR:"例如:me",PICBED_UPYUN_MESSAGE_PASSWORD:"輸入操作員密碼",PICBED_UPYUN_MESSAGE_URL:"例如:http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例如:!imgslim",PICBED_UPYUN_MESSAGE_PATH:"例如:test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"插件安裝成功",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"插件安裝失敗",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"插件安裝失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"插件安裝失敗,請輸入正確的插件名稱或正確的安裝路徑",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"插件卸載成功",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"插件卸載失敗",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"插件卸載失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"插件卸載失敗,請輸入正確的插件名稱",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"插件更新成功",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"插件更新失敗",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"插件更新失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"插件更新失敗,請輸入正確的插件名稱"},en:{UPLOAD_FAILED:"Upload failed",CHECK_SETTINGS:"Please check your settings",CHECK_SETTINGS_AND_NETWORK:"Please check your settings and network",UPLOAD_FAILED_REASON:"Error code: ${code}, please open the browser and paste the address to see the reason",SERVER_ERROR:"Server error, please try again later",AUTH_FAILED:"Authentication failed",PICBED_SMMS:"SM.MS",PICBED_SMMS_TOKEN:"Set Token",PICBED_SMMS_BACKUP_DOMAIN:"Set Backup Upload Domain",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"Ex. smms.app",PICBED_ALICLOUD:"Ali Cloud",PICBED_ALICLOUD_ACCESSKEYID:"Set KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"Set KeySecret",PICBED_ALICLOUD_BUCKET:"Set Bucket",PICBED_ALICLOUD_AREA:"Set Area",PICBED_ALICLOUD_PATH:"Set Path",PICBED_ALICLOUD_CUSTOMURL:"Set Custom URL",PICBED_ALICLOUD_OPTIONS:"Set URL Suffix",PICBED_ALICLOUD_MESSAGE_AREA:"Ex. oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"Ex. test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"Ex. ?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"Ex. https://test.com",PICBED_TENCENTCLOUD:"Tencent Cloud",PICBED_TENCENTCLOUD_VERSION:"Choose COS version",PICBED_TENCENTCLOUD_SECRETID:"Set SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"Set SecretKey",PICBED_TENCENTCLOUD_APPID:"Set AppId",PICBED_TENCENTCLOUD_BUCKET:"Set Bucket",PICBED_TENCENTCLOUD_AREA:"Set Area",PICBED_TENCENTCLOUD_ENDPOINT:"Set Endpoint",PICBED_TENCENTCLOUD_PATH:"Set Path",PICBED_TENCENTCLOUD_OPTIONS:"Set URL Suffix",PICBED_TENCENTCLOUD_SLIM:"Set ImageSlim",PICBED_TENCENTCLOUD_SLIM_TIP:"Image extremely intelligent compression, please refer to the [document description](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"OPEN",PICBED_TENCENTCLOUD_SLIM_CANCEL:"CLOSE",PICBED_TENCENTCLOUD_CUSTOMURL:"Set Custom URL",PICBED_TENCENTCLOUD_MESSAGE_APPID:"Ex. 1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"Ex. ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"Ex. cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"Ex. test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"Ex. http://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"Ex. ?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"Set Token",PICBED_GITHUB_REPO:"Set Repo Name",PICBED_GITHUB_PATH:"Set Path",PICBED_GITHUB_BRANCH:"Set Branch",PICBED_GITHUB_CUSTOMURL:"Set Custom URL",PICBED_GITHUB_MESSAGE_REPO:"Ex. username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"Ex. main",PICBED_GITHUB_MESSAGE_PATH:"Ex. test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"Ex. https://test.com",PICBED_QINIU:"Qiniu",PICBED_QINIU_ACCESSKEY:"Set AccessKey",PICBED_QINIU_SECRETKEY:"Set SecretKey",PICBED_QINIU_BUCKET:"Set Bucket",PICBED_QINIU_PATH:"Set Path",PICBED_QINIU_URL:"Set URL",PICBED_QINIU_OPTIONS:"Set URL Suffix",PICBED_QINIU_AREA:"Set Area",PICBED_QINIU_MESSAGE_PATH:"Ex. test/",PICBED_QINIU_MESSAGE_AREA:"Ex. z0",PICBED_QINIU_MESSAGE_OPTIONS:"Ex. ?imageslim",PICBED_QINIU_MESSAGE_URL:"Ex. https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"Set ClientId",PICBED_IMGUR_PROXY:"Set Proxy",PICBED_IMGUR_MESSAGE_PROXY:"Ex. http://127.0.0.1:1080",PICBED_UPYUN:"Upyun",PICBED_UPYUN_BUCKET:"Set Bucket",PICBED_UPYUN_OPERATOR:"Set Operator",PICBED_UPYUN_PASSWORD:"Set Operator Password",PICBED_UPYUN_PATH:"Set Path",PICBED_UPYUN_URL:"Set URL",PICBED_UPYUN_OPTIONS:"Set URL Suffix",PICBED_UPYUN_MESSAGE_OPERATOR:"Ex. me",PICBED_UPYUN_MESSAGE_PASSWORD:"Please type the operator password",PICBED_UPYUN_MESSAGE_URL:"Ex. http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"Ex. !imgslim",PICBED_UPYUN_MESSAGE_PATH:"Ex. test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"Plugin installed successfully",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"Plugin installation failed",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"Plugin installation failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"Plugin installation failed, please enter a valid plugin name or valid installation path",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"Plugin uninstalled successfully",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"Plugin uninstall failed",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"Plugin uninstall failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"Plugin uninstall failed, please enter a valid plugin name",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"Plugin updated successfully",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"Plugin update failed",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"Plugin update failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"Plugin update failed, please enter a valid plugin name"}};class gt{i18n;objectAdapter;ctx;constructor(e){this.ctx=e,this.objectAdapter=new y.ObjectAdapter(Et);let t=this.ctx.getConfig("settings.language")||"zh-CN";Et[t]||(t="zh-CN"),this.i18n=new y.I18n({adapter:this.objectAdapter,defaultLanguage:t}),this.loadOutterI18n()}loadOutterI18n(){const n=this.getOutterI18nFolder();e.readdirSync(n,{withFileTypes:!0}).forEach(r=>{if(r.isFile()&&r.name.endsWith(".yml")){const i=t.join(n,r.name),s=e.readFileSync(i,"utf8");try{const e=O.load(s);Et[r.name.replace(/\.yml$/,"")]=e}catch(e){console.error(e)}}})}getOutterI18nFolder(){const n=t.join(this.ctx.baseDir,"i18n-cli");return e.pathExistsSync(n)||e.ensureDirSync(n),n}translate(e,t){return this.i18n.translate(e,t)||e}setLanguage(e){this.i18n.setLanguage(e),this.ctx.saveConfig({"settings.language":e})}addLocale(e,t){const n=this.objectAdapter.getLocale(e);if(!n)return!1;const r=f.merge(n,t);return this.objectAdapter.setLocale(e,r),!0}addLanguage(e,t){return!this.objectAdapter.getLocale(e)&&(this.objectAdapter.setLocale(e,t),Et[e]=t,!0)}getLanguageList(){return Object.keys(Et)}}class It extends n.EventEmitter{_config;lifecycle;db;_pluginLoader;configPath;baseDir;helper;log;cmd;output;input;pluginHandler;Request;i18n;VERSION="1.6.2";GUI_VERSION;get pluginLoader(){return this._pluginLoader}constructor(e=""){super(),this.configPath=e,this.output=[],this.input=[],this.helper={transformer:new de("transformer"),uploader:new de("uploader"),beforeTransformPlugins:new de("beforeTransformPlugins"),beforeUploadPlugins:new de("beforeUploadPlugins"),afterUploadPlugins:new de("afterUploadPlugins")},this.initConfigPath(),this.log=new Pe(this),this.cmd=new he(this),this.pluginHandler=new ut(this),this.initConfig(),this.init()}initConfigPath(){if(""===this.configPath&&(this.configPath=r.homedir()+"/.picgo/config.json"),".JSON"!==t.extname(this.configPath).toUpperCase())throw this.configPath="",Error("The configuration file only supports JSON format.");this.baseDir=t.dirname(this.configPath);e.pathExistsSync(this.configPath)||e.ensureFileSync(`${this.configPath}`)}initConfig(){this.db=new ct(this),this._config=this.db.read(!0)}init(){try{this.i18n=new gt(this),this.Request=new lt(this),this._pluginLoader=new Xe(this),_e("picgo"),We().register(this),{register(e){e.helper.transformer.register("path",Ve),e.helper.transformer.register("base64",Je)}}.register(this),_e(""),this._pluginLoader.load(),this.lifecycle=new fe(this)}catch(e){throw this.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,-1),this.log.error(e),e}}use(e,t){if(t)return this.pluginLoader.registerPlugin(t,e),this.pluginLoader.getPlugin(t);return e(this)}registerCommands(){""!==this.configPath&&(this.cmd.init(),this.cmd.loadCommands())}getConfig(e){return e?f.get(this._config,e):this._config}saveConfig(e){V(e)?(this.setConfig(e),this.db.saveConfig(e)):this.log.warn("the format of config is invalid, please provide object")}removeConfig(e,t){e&&t&&(z(e)?this.log.warn(`the config.${e} can't be removed`):(this.unsetConfig(e,t),this.db.unset(e,t)))}setConfig(e){V(e)?Object.keys(e).forEach(t=>{z(t)&&(this.log.warn(`the config.${t} can't be modified`),delete e[t]),f.set(this._config,t,e[t]),rt.emit(exports.IBusEvent.CONFIG_CHANGE,{configName:t,value:e[t]})}):this.log.warn("the format of config is invalid, please provide object")}unsetConfig(e,t){e&&t&&(z(e)?this.log.warn(`the config.${e} can't be unset`):f.unset(this.getConfig(e),t))}get request(){return this.Request.request.bind(this.Request)}async upload(t){if(""===this.configPath)return this.log.error("The configuration file only supports JSON format."),[];if(void 0!==t&&0!==t.length){const{output:e}=await this.lifecycle.start(t);return e}try{const{imgPath:t,shouldKeepAfterUploading:n}=await nt(this);if("no image"===t)throw new Error("image not found in clipboard");{this.once(exports.IBuildInEvent.FAILED,()=>{n||e.remove(t).catch(e=>{this.log.error(e)})}),this.once("finished",()=>{n||e.remove(t).catch(e=>{this.log.error(e)})});const{output:r}=await this.lifecycle.start([t]);return r}}catch(e){throw this.emit(exports.IBuildInEvent.FAILED,e),e}}}exports.Commander=he,exports.Lifecycle=fe,exports.LifecyclePlugins=de,exports.Logger=Pe,exports.PicGo=It,exports.PicGoUtils=ee,exports.PluginHandler=ut,exports.PluginLoader=Xe,exports.Request=lt;
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.esm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"fs-extra";import t from"path";import{EventEmitter as n}from"events";import r,{homedir as i}from"os";import{Command as s}from"commander";import a from"inquirer";import{imageSize as o}from"image-size";import{URL as l}from"url";import c from"chalk";import u from"minimatch";import p from"globby";import g from"ejs";import E from"download-git-repo";import{rimrafSync as _}from"rimraf";import I from"dayjs";import d from"util";import m from"crypto";import h from"mime-types";import C 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 y from"https";import B from"tunnel";import{JSONStore as b}from"@picgo/store";import x from"cross-spawn";import G from"js-yaml";import{ObjectAdapter as R,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:r,registry:i}=n,s={npmProxy:r,npmRegistry:i};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:r,registry:i}=n,s={npmProxy:r,npmRegistry:i};e.pluginHandler.update(t,s).catch(t=>{e.log.error(t)})})}},$={handle:e=>{e.cmd.program.option("-c, --config <path>","set config path")}},H=e=>e.startsWith("http://")||e.startsWith("https://"),F=e=>{e=e||"";try{return e!==decodeURI(e)}catch(e){return!1}},v=e=>(F(e)||(e=encodeURI(e)),e),k=(...e)=>e.join("").replace(/\/{2,}/g,"/").split("/").map(e=>encodeURIComponent(e)).join("/"),q=e=>{try{const{width:t=0,height:n=0,type:r}=o(e);return{real:!0,width:t,height:n,extname:r?`.${r}`:".png"}}catch(e){return{real:!1,width:200,height:200,extname:".png"}}},K=async n=>{try{return{extname:t.extname(n),fileName:t.basename(n),filePath:n,buffer:await e.readFile(n),success:!0}}catch{return{reason:`read file ${n} error`,success:!1}}},Y=async(e,n)=>{e=v(e);let r,i=!1,s="";const a=new Promise((a,o)=>{(async()=>{try{const o=await n.request({method:"get",url:e,resolveWithFullResponse:!0,responseType:"arraybuffer"}).then(e=>{const t=e.headers["content-type"];return t?.includes("image")&&(i=!0,s=`.${t.split("image/")[1]}`),e.data});if(clearTimeout(r),i){const n=new l(e).pathname,r=decodeURIComponent(t.basename(n));a({buffer:o,fileName:r,extname:s,success:!0})}else a({success:!1,reason:`${e} is not image`})}catch(t){clearTimeout(r),a({success:!1,reason:`request ${e} error, ${t?.message??""}`})}})().catch(o)}),o=new Promise(t=>{r=setTimeout(()=>{t({success:!1,reason:`request ${e} timeout`})},1e4)});return Promise.race([a,o])},j=e=>/^@[^/]+\/picgo-plugin-/.test(e)?"scope":e.startsWith("picgo-plugin-")?"normal":Q(e)?"simple":"unknown",Q=n=>{if(t.isAbsolute(n))return!1;const r=t.join(process.cwd(),n);return!e.existsSync(r)&&(!n.includes("/")&&!n.includes("\\"))},W=(e,t="")=>t?`@${t}/picgo-plugin-${e}`:`picgo-plugin-${e}`,V=(n,r=console)=>{switch(j(n)){case"normal":case"scope":return n;case"simple":return W(n);default:{let i=n;return t.isAbsolute(n)&&e.existsSync(n)?X(i):(i=t.join(process.cwd(),n),e.existsSync(i)?X(i):(r.warn(`Can't find plugin ${n}`),""))}}},z=(n,r=console)=>{switch(j(n)){case"normal":return J(n);case"scope":return J(n,!0);case"simple":return J(W(n));default:{if(!e.existsSync(n))return r.warn(`Can't find plugin: ${n}`),"";const i=t.posix.join(n,"package.json");if(e.existsSync(i)){const t=e.readJSONSync(i)||{};return t.name?.includes("picgo-plugin-")?t.name:(r.warn(`The plugin package.json's name filed is ${t.name||"empty"}, need to include the prefix: picgo-plugin-`),"")}return r.warn(`Can't find plugin: ${n}`),""}}},X=e=>e.split(t.sep).join("/"),J=(e,t=!1)=>{if(e.includes("@")){let n=/(.+\/)?(picgo-plugin-\w+)(@.+)*/;t&&(n=/(.+\/)?(^@[^/]+\/picgo-plugin-\w+)(@.+)*/);const r=e.match(n);return r?r[2]:(console.warn("can not remove plugin version"),e)}return e},Z=[],ee=e=>Z.some(t=>e.startsWith(t)),te=e=>"object"==typeof e&&!Array.isArray(e)&&Object.keys(e).length>0;function ne(e){try{return JSON.parse(e)}catch(t){return e}}const re=(e=0)=>isNaN(Number(e))?0:Number(e),ie=()=>"development"===process.env.NODE_ENV;var se=Object.freeze({__proto__:null,configBlackList:Z,forceNumber:re,getFSFile:K,getImageSize:q,getNormalPluginName:z,getPluginNameType:j,getProcessPluginName:V,getURLFile:Y,handleCompletePluginName:W,handleStreamlinePluginName:e=>/^@[^/]+\/picgo-plugin-/.test(e)?e.replace(/^@[^/]+\/picgo-plugin-/,""):e.replace(/picgo-plugin-/,""),handleUnixStylePath:X,handleUrlEncode:v,handleUrlPathSafeEncode:k,isConfigKeyInBlackList:ee,isDev:ie,isInputConfigValid:te,isProd:()=>"production"===process.env.NODE_ENV,isSimpleName:Q,isUrl:H,isUrlEncode:F,removePluginVersion:J,safeParse:ne});const ae={handle:n=>{n.cmd.program.command("upload").description("upload, go go go").arguments("[input...]").alias("u").action(r=>{(async()=>{const i=r.map(e=>H(e)?e:t.resolve(e)).filter(t=>{const r=e.existsSync(t)||H(t);return r||n.log.warn(`${t} does not exist.`),r});await n.upload(i)})().catch(e=>{n.log.error(e)})})}},oe=async(e,t,n,r)=>{const i=await e.cmd.inquirer.prompt(t),s="uploader"===n?`picBed.${r}`:"transformer"===n?`transformer.${r}`:r;e.saveConfig({[s]:i}),"uploader"===n?e.saveConfig({"picBed.current":r,"picBed.uploader":r}):"transformer"===n&&e.saveConfig({"picBed.transformer":r})},le={handle:e=>{e.cmd.program.command("set").alias("config").arguments("<module> [name]").description("configure config of picgo modules").action((t,n)=>{(async()=>{try{switch(t){case"uploader":case"transformer":if(n){const r=e.helper[t].get(n);if(!r)return e.log.error(`No ${t} named ${n}`);r.config&&await oe(e,r.config(e),t,n)}else{const n=[{type:"list",name:`${t}`,choices:e.helper[t].getIdList(),message:`Choose a(n) ${t}`}],r=await e.cmd.inquirer.prompt(n),i=e.helper[t].get(r[t]);i?.config&&await oe(e,i.config(e),t,r[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}`);e.pluginLoader.getPlugin(n)?.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);e.pluginLoader.getPlugin(n.plugin)?.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)})})}},ce={handle:async e=>{const t=e.cmd;t.program.command("use").arguments("[module]").description("use modules of picgo").action(n=>{(async()=>{try{let r=[];const i={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(!i[n])return e.log.warn(`No module named ${n}`),e.log.warn("Available modules are uploader|transformer|plugins");r.push(i[n])}else r=Object.keys(i).map(e=>i[e]);const s=await t.inquirer.prompt(r);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)})})}},ue={handle:e=>{e.cmd.program.option("-p, --proxy <url>","set proxy for uploading",t=>{e.setConfig({"picBed.proxy":t})})}},pe=async(e,n)=>{try{const r=Ee(n.tmp),i=t.join(n.tmp,"template");let s={};r.prompts&&r.prompts.length>0&&(s=await e.cmd.inquirer.prompt(r.prompts));let a=await p(["**/*"],{cwd:i,dot:!0});const o=Object.keys(r.filters||{});if(o.length>0&&(a=a.filter(t=>{let n="";for(const e of o)if(u(t,e,{dot:!0})){n=t;break}return!n||ge(e,r.filters[n],s)})),0===a.length)return e.log.warn("Template files not found!");const l=_e(a,i,s);Ie(n.dest,l),"function"==typeof r.complete&&r.complete({answers:s,options:n,files:a,ctx:e}),r.completeMessage&&e.log.success(r.completeMessage),e.log.success("Done!")}catch(t){return e.log.error(t)}},ge=(e,t,n)=>{const r=new Function("data","with (data) { return "+t+"}");try{return r(n)}catch(n){return e.log.error(`Error when evaluating filter condition: ${JSON.stringify(t)}`),!1}},Ee=n=>{const r=t.join(n,"index.js");if(e.existsSync(r)){return require(r)}return{}},_e=(n,r,i)=>{const s={};return n.forEach(n=>{const a=e.readFileSync(t.join(r,n),"utf8"),o=g.render(a,i);(Buffer.isBuffer(o)||/[^\s]/.test(o))&&(s[n]=o)}),s},Ie=(n,r)=>{Object.keys(r).forEach(i=>{const s=t.join(n,i);e.ensureDirSync(t.dirname(s)),e.writeFileSync(s,r[i])})},de=(t,n)=>{n.offline?e.existsSync(n.template)?pe(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,me(t,n))},me=(t,n)=>{e.existsSync(n.tmp)&&_(n.tmp),t.log.info("Template files are downloading..."),E(n.template,n.tmp,{clone:n.clone},e=>{if(e)return t.log.error(e);t.log.success("Template files are downloaded!"),pe(t,n).catch(e=>{t.log.error(e)})})},he={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((r,s,a)=>{(async()=>{try{const o=r.includes("/"),l=!s||"."===s,c=t.resolve(s||"."),u=a.clone||!1,p=a.offline||!1,g=t.join(i(),".picgo/templates",r.replace(/[/:]/g,"-"));a.offline&&(r=g);const E={template:r,project:s,hasSlash:o,inPlace:l,dest:c,clone:u,tmp:g,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&&de(n,E)}):de(n,E)}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"}],r=await e.cmd.inquirer.prompt(t);return e.i18n.setLanguage(r.i18n),void e.log.success(`Language set to ${r.i18n}`)}if(!n.includes(t))return e.log.warn("No such language");e.i18n.setLanguage(t),e.log.success(`Language set to ${t}`)})}};class Pe{static currentPlugin;list;pluginIdMap;name;constructor(e){this.name=e,this.list=new Map,this.pluginIdMap=new Map}register(e,t){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),Pe.currentPlugin&&(this.pluginIdMap.has(Pe.currentPlugin)?this.pluginIdMap.get(Pe.currentPlugin)?.push(e):this.pluginIdMap.set(Pe.currentPlugin,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);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 fe=(e=null)=>{Pe.currentPlugin=e};class Ne{name="commander";static currentPlugin;list=new Map;pluginIdMap=new Map;ctx;program;inquirer;constructor(e){this.program=new s,this.inquirer=a,this.ctx=e}getName(){return this.name}init(){var e;this.program.version("1.6.1","-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",le),e.cmd.register("upload",ae),e.cmd.register("use",ce),e.cmd.register("proxy",ue),e.cmd.register("init",he),e.cmd.register("i18n",Ce)}register(e,t){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 n=Pe.currentPlugin;null!==n&&(this.pluginIdMap.has(n)?this.pluginIdMap.get(n)?.push(e):this.pluginIdMap.set(n,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);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 Ue,De,Le;!function(e){e.success="success",e.info="info",e.warn="warn",e.error="error"}(Ue||(Ue={})),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"}(De||(De={})),function(e){e.CONFIG_CHANGE="CONFIG_CHANGE"}(Le||(Le={}));class Se{level={[Ue.success]:"green",[Ue.info]:"blue",[Ue.warn]:"yellow",[Ue.error]:"red"};ctx;logLevel;logPath;constructor(e){this.ctx=e}handleLog(e,...n){if(this.logLevel=this.ctx.getConfig("settings.logLevel"),!this.ctx.getConfig("silent")&&this.checkLogLevel(e,this.logLevel)){const r=c[this.level[e]](`[PicGo ${e.toUpperCase()}]:`);console.log(r,...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,r=1024*re(this.ctx.getConfig("settings.logFileSizeLimit")||10)*1024;return{isLarge:n>r,logFileSize:n,logFileSizeLimit:r}}return{isLarge:!1}}recreateLogFile(t){e.existsSync(t)&&(e.unlinkSync(t),e.createFileSync(t))}handleWriteLog(t,n,...r){try{let i=`${I().format("YYYY-MM-DD HH:mm:ss")} [PicGo ${n.toUpperCase()}] `;r.forEach(e=>{e instanceof Error&&"error"===n?i+=`\n------Error Stack Begin------\n${d.format(e?.stack)}\n-------Error Stack End------- `:("object"==typeof e&&(e=JSON.stringify(e,null,2)),i+=`${e} `)}),i+="\n",e.appendFileSync(t,i)}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(Ue.success,...e)}info(...e){return this.handleLog(Ue.info,...e)}error(...e){return this.handleLog(Ue.error,...e)}warn(...e){return this.handleLog(Ue.warn,...e)}debug(...e){ie()&&this.handleLog(Ue.info,...e)}}class Ae extends n{ctx;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(De.FAILED),t.emit(De.UPLOAD_PROGRESS,-1),t.emit(De.FAILED,e),t.log.error(e),t.getConfig("debug"))throw e;return t}}async beforeTransform(e){return e.emit(De.UPLOAD_PROGRESS,0),e.emit(De.BEFORE_TRANSFORM,e),e.log.info("Before transform"),await this.handlePlugins(e.helper.beforeTransformPlugins,e),e}async doTransform(e){e.emit(De.UPLOAD_PROGRESS,30);const t=e.getConfig("picBed.transformer")||"path";let n=t,r=e.helper.transformer.get(t);return r||(r=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(r?.handle(e)),e}async beforeUpload(e){return e.emit(De.UPLOAD_PROGRESS,60),e.log.info("Before upload"),e.emit(De.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),r=t;n||(t="smms",r="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 [${r}]`),await(n?.handle(e));for(const n of e.output)n.type=t;return e}async afterUpload(e){e.emit(De.AFTER_UPLOAD,e),e.emit(De.UPLOAD_PROGRESS,100),await this.handlePlugins(e.helper.afterUploadPlugins,e);let t="";const n=e.output.length,r=!0===e.getConfig("settings.encodeOutputURL");for(let i=0;i<n;i++)void 0!==e.output[i].imgUrl&&(t+=r?v(e.output[i].imgUrl):e.output[i].imgUrl,i!==n-1&&(t+="\n")),delete e.output[i].base64Image,delete e.output[i].buffer;return e.emit(De.FINISHED,e),e.log.success(`\n${t}`),e}async handlePlugins(e,t){const n=e.getList(),r=e.getIdList(),i=e.getName();return await Promise.all(n.map(async(e,n)=>{try{t.log.info(`${i}: ${r[n]} running`),await e.handle(t)}catch(e){throw t.log.error(`${i}: ${r[n]} error`),e}})),t}}const Te=(e,t,n,r="")=>({method:"POST",url:`https://${r||"sm.ms"}/api/v2/upload`,headers:{contentType:"multipart/form-data","User-Agent":"PicGo",Authorization:n},formData:{smfile:{value:t,options:{filename:e}},ssl:"true"}}),Oe=async e=>{const t=e.getConfig("picBed.smms");if(!t)throw new Error("Can not find smms config!");const n=e.output;for(const r of n)if(r.fileName&&r.buffer){let n=r.buffer;!n&&r.base64Image&&(n=Buffer.from(r.base64Image,"base64"));const i=Te(r.fileName,n,t?.token,t?.backupDomain);try{const t=await e.request(i),n=JSON.parse(t);if("success"===n.code)delete r.base64Image,delete r.buffer,r.imgUrl=n.data.url;else{if("image_repeated"!==n.code||"string"!=typeof n.images)throw e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:n.message}),new Error(n.message);delete r.base64Image,delete r.buffer,r.imgUrl=n.images}}catch(t){throw e.log.error(t),t}}return e},ye=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=>h.lookup(e)||"application/octet-stream",be=(e,t,n,r)=>{const i=e.secretId,s=e.secretKey,a=e.appId,o=e.bucket;let l,c="";if(e.version&&"v4"!==e.version){const i=Math.floor((new Date).getTime()/1e3);c=`${i};${i+86400}`;const a=m.createHmac("sha1",s).update(c).digest("hex"),o=e.endpoint?e.endpoint:`cos.${e.area}.myqcloud.com`,p=`put\n/${e.path}${t}\n\ncontent-length=${r}&content-type=${u=n,encodeURIComponent(u).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A")}&host=${e.bucket}.${o}\n`,g=`sha1\n${c}\n${m.createHash("sha1").update(p).digest("hex")}\n`;l=m.createHmac("sha1",a).update(g).digest("hex")}else{const e=Math.floor(1e10*Math.random()),t=Math.floor((new Date).getTime()/1e3)-1,n=`a=${a}&b=${o}&k=${i}&e=${t+3600}&t=${t}&r=${e}&f=`,r=m.createHmac("sha1",s).update(n).digest(),c=Buffer.concat([r,Buffer.from(n)]);l=Buffer.from(c).toString("base64")}var u;return{signature:l,appId:a,bucket:o,signTime:c}},xe=(e,t,n,r,i)=>{const s=e.area,a=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}/${k(a,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=content-length;content-type;host&q-url-param-list=&q-signature=${n.signature}`,contentType:Be(t),contentLength:r.byteLength,"User-Agent":`PicGo;${i};null;null`},body:r,resolveWithFullResponse:!0}}return{method:"POST",url:`http://${s}.file.myqcloud.com/files/v2/${n.appId}/${n.bucket}/${k(a,t)}`,headers:{Host:`${s}.file.myqcloud.com`,Authorization:n.signature,contentType:"multipart/form-data","User-Agent":`PicGo;${i};null;null`},formData:{op:"upload",filecontent:r},resolveWithFullResponse:!0}},Ge=async e=>{const t=e.getConfig("picBed.tcyun");if(!t)throw new Error("Can't find tencent COS config");try{const n=e.output,r=t.customUrl,i=t.path,s=!t.version||"v4"===t.version;for(const a of n)if(a.fileName&&a.buffer){let n=a.buffer;!n&&a.base64Image&&(n=Buffer.from(a.base64Image,"base64"));const o=be(t,a.fileName,Be(a.fileName),n.byteLength);if(!o)return!1;const l=xe(t,a.fileName,o,n,e.GUI_VERSION||e.VERSION),c=await e.request(l).then(e=>e).catch(t=>({statusCode:400,body:{msg:e.i18n.translate("AUTH_FAILED"),err:t}}));let u;if(u=s&&"string"==typeof c?JSON.parse(c):c,400===u.statusCode)throw u?.body?.err?u.body.err:new Error(u?.body?.msg||u?.body?.message);const p=t.options||"",g=t.slim||"";if(s&&"SUCCESS"===u.message)delete a.base64Image,delete a.buffer,a.imgUrl=r?`${r}/${i}${a.fileName}`:`${u.data.source_url}${p}`;else{if(s||!u||200!==u.statusCode)throw new Error(c.body.msg);if(delete a.base64Image,delete a.buffer,r)a.imgUrl=`${r}/${encodeURI(i)}${k(a.fileName)}${p}`;else{const e=t.endpoint?t.endpoint:`cos.${t.area}.myqcloud.com`;a.imgUrl=`https://${t.bucket}.${e}/${encodeURI(i)}${k(a.fileName)}${p}`}}g&&(a.imgUrl+=p?"&imageSlim":"?imageSlim")}return e}catch(n){if(!t.version||"v4"===t.version)try{const t=JSON.parse(n.error);e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("UPLOAD_FAILED_REASON",{code:t.code}),text:"https://cloud.tencent.com/document/product/436/8432"})}catch(e){}throw n}},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 we=(e,t,n)=>{const r=t.path||"",{token:i,repo:s}=t;return{method:"PUT",url:`https://api.github.com/repos/${s}/contents/${k(r,e)}`,headers:{Authorization:`token ${i}`,"User-Agent":"PicGo","Content-Type":h.lookup(e)},body:n,json:!0}},Me=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 r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i={message:"Upload by PicGo",branch:t.branch,content:n,path:t.path+encodeURI(r.fileName)},s=we(r.fileName,t,i);try{const n=await e.request(s);if(!n)throw new Error("Server error, please try again");delete r.base64Image,delete r.buffer,t.customUrl?r.imgUrl=`${t.customUrl}/${k(t.path||"",r.fileName)}`:r.imgUrl=n.content.download_url}catch(e){if(422!==e.statusCode)throw e;delete r.base64Image,delete r.buffer,t.customUrl?r.imgUrl=`${t.customUrl}/${k(t.path||"",r.fileName)}`:r.imgUrl=`https://raw.githubusercontent.com/${t.repo}/${t.branch}/${k(t.path||"",r.fileName)}`}}return e}catch(t){throw e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK")}),t}},$e=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 He(e,t,n,r){const i=function(e){return"z0"===e?"":"-"+e}(e.area||"z0"),s=e.path||"";return{method:"POST",url:`http://upload${i}.qiniup.com/putb64/-1/key/${Buffer.from(s+t,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_")}`,headers:{Authorization:`UpToken ${n}`,"Content-Type":h.lookup(t)||"application/octet-stream"},body:r}}function Fe(e){const t=e.accessKey,n=e.secretKey,r=new C.auth.digest.Mac(t,n),i={scope:e.bucket};return new C.rs.PutPolicy(i).uploadToken(r)}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 r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i=He(t,r.fileName,Fe(t),n),s=await e.request(i),a=JSON.parse(s);if(!a?.key)throw e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:a.msg}),e.log.error("qiniu error",a),new Error("Upload failed");{delete r.base64Image,delete r.buffer;const e=t.url,n=t.options;r.imgUrl=`${e}/${a.key}${n}`}}return e}catch(t){if("Upload failed"!==t.message&&t.response){const n=t.response.body;e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:n.error})}throw t}},ke=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 qe=(e,t,n)=>{const r={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&&(r.proxy=e.proxy),r},Ke=async e=>{const t=e.getConfig("picBed.imgur");if(!t)throw new Error("Can't find imgur config");try{const n=e.output;for(const r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i=qe(t,r.fileName,n),s=await e.request(i),a="string"==typeof s?JSON.parse(s):s;if(!a.success)throw new Error("Server error, please try again");delete r.base64Image,delete r.buffer,r.imgUrl=a.data.link}return e}catch(t){throw e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK"),text:"http://docs.imgur.com/api/errno/"}),t?.response?.data||t}},Ye=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 je=(e,t)=>{const n=(new Date).toUTCString(),r=h.lookup(t);if(!r)throw Error(`No mime type found for file ${t}`);const i=`PUT\n\n${r}\n${n}\n/${e.bucket}/${e.path}${t}`,s=m.createHmac("sha1",e.accessKeySecret).update(i).digest("base64");return`OSS ${e.accessKeyId}:${s}`},Qe=(e,t,n,r)=>{const i=e.path||"";return{method:"PUT",url:`https://${e.bucket}.${e.area}.aliyuncs.com/${k(i,t)}`,headers:{Host:`${e.bucket}.${e.area}.aliyuncs.com`,Authorization:n,Date:(new Date).toUTCString(),"Content-Type":h.lookup(t)},body:r,resolveWithFullResponse:!0}},We=async e=>{const t=e.getConfig("picBed.aliyun");if(!t)throw new Error("Can't find aliYun OSS config");try{const n=e.output,r=t.customUrl,i=t.path||"";for(const s of n)if(s.fileName&&s.buffer){const n=je(t,s.fileName);let a=s.buffer;!a&&s.base64Image&&(a=Buffer.from(s.base64Image,"base64"));const o=Qe(t,s.fileName,n,a);if(200!==(await e.request(o)).statusCode)throw new Error("Upload failed");{delete s.base64Image,delete s.buffer;const e=t.options||"";s.imgUrl=r?`${r}/${k(i,s.fileName)}${e}`:`https://${t.bucket}.${t.area}.aliyuncs.com/${k(i,s.fileName)}${e}`}}return e}catch(t){throw e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")}),t}},Ve=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 ze=(e,t)=>{const n=e.path||"",r=e.operator,i=e.password,s=P(i),a=(new Date).toUTCString(),o=`PUT&${`/${e.bucket}/${k(n,t)}`}&${a}`;return`UPYUN ${r}:${m.createHmac("sha1",s).update(o).digest("base64")}`},Xe=(e,t,n,r)=>{const i=e.bucket,s=e.path||"";return{method:"PUT",url:`https://v0.api.upyun.com/${i}/${k(s,t)}`,headers:{Authorization:n,Date:(new Date).toUTCString(),"Content-Type":h.lookup(t)||"application/octet-stream"},body:r,resolveWithFullResponse:!0}},Je=async e=>{const t=e.getConfig("picBed.upyun");if(!t)throw new Error("Can't find upYun config");try{const n=e.output,r=t.path||"";for(const i of n)if(i.fileName&&i.buffer){let n=i.buffer;!n&&i.base64Image&&(n=Buffer.from(i.base64Image,"base64"));const s=ze(t,i.fileName),a=Xe(t,i.fileName,s,n);if(200!==(await e.request(a)).statusCode)throw new Error("Upload failed");delete i.base64Image,delete i.buffer,i.imgUrl=`${t.url}/${k(r,i.fileName)}${t.options}`}return e}catch(t){if("Upload failed"===t.message)e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")});else{const n=ne(t.error);e.emit(De.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}},Ze=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 et=()=>({register(e){!function(e){e.helper.uploader.register("aliyun",{get name(){return e.i18n.translate("PICBED_ALICLOUD")},handle:We,config:Ve})}(e),function(e){e.helper.uploader.register("tcyun",{get name(){return e.i18n.translate("PICBED_TENCENTCLOUD")},handle:Ge,config:Re})}(e),function(e){e.helper.uploader.register("smms",{get name(){return e.i18n.translate("PICBED_SMMS")},handle:Oe,config:ye})}(e),function(e){e.helper.uploader.register("github",{get name(){return e.i18n.translate("PICBED_GITHUB")},handle:Me,config:$e})}(e),function(e){e.helper.uploader.register("qiniu",{get name(){return e.i18n.translate("PICBED_QINIU")},handle:ve,config:ke})}(e),function(e){e.helper.uploader.register("imgur",{get name(){return e.i18n.translate("PICBED_IMGUR")},handle:Ke,config:Ye})}(e),function(e){e.helper.uploader.register("upyun",{get name(){return e.i18n.translate("PICBED_UPYUN")},handle:Je,config:Ze})}(e)}}),tt=(e,t,n)=>{const r=q(t);return r.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")),r};var nt={handle:async e=>{const t=e.output;return await Promise.all(e.input.map(async(n,r)=>{let i;if(i=Buffer.isBuffer(n)?{success:!0,buffer:n,fileName:"",extname:""}:H(n)?await Y(n,e):await K(n),i.success&&i.buffer){const s=tt(e,i.buffer,n),a=i.extname||s.extname||".png";t[r]={buffer:i.buffer,fileName:i.fileName||`${I().format("YYYYMMDDHHmmssSSS")}${a}}`,width:s.width,height:s.height,filePath:i.filePath,extname:a,mimeType:h.lookup(a)||"application/octet-stream"}}else e.log.error(i.reason)})),e.output=t.filter(e=>e),e}};var rt={handle:async e=>(e.output.push(...e.input),e)};class it{ctx;list=[];fullList=new Set;pluginMap=new Map;constructor(e){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(r){return t.join(e.baseDir,"node_modules",n)}}load(){const n=t.join(this.ctx.baseDir,"package.json"),r=t.join(this.ctx.baseDir,"node_modules/");if(!e.existsSync(r))return!1;const i=e.readJSONSync(n),s=Object.keys(i.dependencies||{}),a=Object.keys(i.devDependencies||{}),o=s.concat(a).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 o)this.registerPlugin(e);return!0}registerPlugin(e,t){if(e&&"string"==typeof e){this.fullList.add(e);try{if(t){this.list.push(e),fe(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),fe(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(De.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),fe(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/"),r=require(n+e)(this.ctx);return this.pluginMap.set(e,r),r}getList(){return this.list}hasPlugin(e){return this.fullList.has(e)}getFullList(){return[...this.fullList]}}const st="picgo-clipboard-images",at={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\nelse\n # fallback for unsupported session types\n echo >&2 "Error: Unsupported session type \'$XDG_SESSION_TYPE\'."\n echo >&2 "Solution: The variable of XDG_SESSION_TYPE must set as \'x11\' or \'wayland\'."\n exit 1\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'},ot={darwin:"mac.applescript",win32:"windows.ps1",win10:"windows10.ps1",linux:"linux.sh",wsl:"wsl.sh"};const lt=async n=>{!function(n){const r=t.join(n.baseDir,st);e.existsSync(r)||e.mkdirSync(r)}(n);const i=t.join(n.baseDir,st,`${I().format("YYYYMMDDHHmmssSSS")}.png`);return await new Promise((s,a)=>{const o=(()=>{const e=process.platform;if(A)return"wsl";if("win32"===e)return"10"===r.release().split(".")[0]?"win10":"win32";return"darwin"===e?"darwin":"linux"})(),l=t.join(n.baseDir,ot[o]);let c;e.existsSync(l)||e.writeFileSync(l,at[o],"utf8"),c="darwin"===o?S("osascript",[l,i]):"win32"===o||"win10"===o?S("powershell",["-noprofile","-noninteractive","-nologo","-sta","-executionpolicy","unrestricted","-file",l,i]):S("sh",[l,i]),c.stdout.on("data",r=>{if("linux"===o&&"no xclip or wl-clipboard"===r.toString().trim())return n.emit(De.NOTIFICATION,{title:"xclip or wl-clipboard not found",body:"Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"}),a(new Error("Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"));const l=r.toString().trim();let c=!1;if(t.basename(l)!==t.basename(i)&&e.existsSync(l)&&(c=!0),"no image"!==l&&!e.existsSync(l))return a(new Error(`Can't find ${l}`));s({imgPath:l,shouldKeepAfterUploading:c})})})},ct=new n,ut=new y.Agent({maxVersion:"TLSv1.2",minVersion:"TLSv1.2"});function pt(e,t,n){"object"==typeof n&&"value"in n&&"options"in n?e.append(t,n.value,n.options):e.append(t,n)}function gt(e){return{...e,statusCode:e.status,body:e.data}}function Et(e){const t={method:e?.config?.method?.toUpperCase()||"",url:e?.config?.url||"",statusCode:e?.response?.status||0,message:e?.message||"",stack:e?.stack||{},response:{status:e?.response?.status||0,statusCode:e?.response?.status||0,body:e?.response?.data||""}};return Promise.reject(t)}class _t{ctx;proxy="";options={};constructor(e){this.ctx=e,this.init(),ct.on(Le.CONFIG_CHANGE,e=>{switch(e.configName){case"picBed":e.value?.proxy&&(this.proxy=e.value.proxy);break;case"picBed.proxy":this.proxy=e.value}})}init(){const e=this.ctx.getConfig("picBed.proxy");e&&(this.proxy=e)}handleProxy(){if(this.proxy)try{const e=new l(this.proxy);return{host:e.hostname,port:parseInt(e.port||"0",10),protocol:e.protocol}}catch(e){}return!1}request(e){this.options.proxy=this.handleProxy(),this.options.headers=e.headers||{},this.options.maxBodyLength=1/0,this.options.maxContentLength=1/0,this.options.proxy&&e.url?.startsWith("https://")?(this.options.httpsAgent=B.httpsOverHttp({proxy:{host:this.options.proxy.host,port:this.options.proxy.port}}),this.options.proxy=!1):this.options.httpsAgent=ut;const t=T.create(this.options);t.interceptors.response.use(gt,Et);const n=function(e){let t=!1;const n={...e,url:e.url||"",headers:e.headers||{}};if(e.proxy){let r=e.proxy;if("string"==typeof r){try{r=new l(e.proxy)}catch(e){r=!1,n.proxy=!1,console.error(e)}t=!0}r&&(e.url?.startsWith("https://")?(n.proxy=!1,n.httpsAgent=B.httpsOverHttp({proxy:{host:r?.hostname,port:parseInt(r?.port,10)}})):n.proxy={host:r.hostname,port:parseInt(r.port,10),protocol:"http"})}if("formData"in e){const r=new O;for(const t in e.formData)pt(r,t,e.formData[t]);n.data=r,n.headers=Object.assign(n.headers||{},r.getHeaders()),t=!0,delete n.formData}return"body"in e&&(n.data=e.body,t=!0,delete n.body),"qs"in e&&(n.params=e.qs,t=!0),n.__isOldOptions=t,n}(e);return t.interceptors.request.use(function(e){let t="";return e?.headers?.contentType?(t=e.headers.contentType,delete e.headers.contentType):e?.headers?.ContentType?(t=e.headers.ContentType,delete e.headers.ContentType):e?.headers?.["content-type"]&&(t=e.headers["content-type"],delete e.headers["content-type"]),""!==t&&e.headers&&(e.headers["Content-Type"]=t),e}),"resolveWithFullResponse"in e&&e.resolveWithFullResponse?t.request(n):t.request(n).then(t=>n.__isOldOptions?"json"in e?e.json?t.data:void 0:JSON.stringify(t.data):t.data)}}class It{ctx;db;constructor(e){if(this.ctx=e,this.db=new b(this.ctx.configPath),!this.db.has("picBed"))try{this.db.set("picBed",{uploader:"smms",current:"smms"})}catch(e){throw this.ctx.log.error(e),e}if(!this.db.has("picgoPlugins"))try{this.db.set("picgoPlugins",{})}catch(e){throw this.ctx.log.error(e),e}}read(e){return this.db.read(e)}get(e=""){return this.read(!0),this.db.get(e)}set(e,t){return this.read(!0),this.db.set(e,t)}has(e){return this.read(!0),this.db.has(e)}unset(e,t){return this.read(!0),this.db.unset(e,t)}saveConfig(e){Object.keys(e).forEach(t=>{this.set(t,e[t])})}removeConfig(e){Object.keys(e).forEach(t=>{this.unset(t,e[t])})}}class dt{ctx;constructor(e){this.ctx=e}async install(e,t={},n){const r=[],i=e.map(e=>mt(this.ctx,e)).filter(e=>this.ctx.pluginLoader.hasPlugin(e.pkgName)?(r.push(e.pkgName),this.ctx.log.success(`PicGo has already installed ${e.pkgName}`),!1):!!e.success),s=i.map(e=>e.fullName),a=i.map(e=>e.pkgName);if(s.length>0){const e=await this.execCommand("install",s,this.ctx.baseDir,t,n);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("installFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED"),body:t});return{success:!1,body:t}}a.forEach(e=>{this.ctx.pluginLoader.registerPlugin(e)}),this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS")),this.ctx.emit("installSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS"),body:[...a,...r]});return{success:!0,body:[...a,...r]}}if(0===r.length){const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("installFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED"),body:e});return{success:!1,body:e}}this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS")),this.ctx.emit("installSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS"),body:[...a,...r]});return{success:!0,body:[...a,...r]}}async uninstall(e){const t=e.map(e=>mt(this.ctx,e)).filter(e=>e.success).map(e=>e.pkgName);if(t.length>0){const e=await this.execCommand("uninstall",t,this.ctx.baseDir);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("uninstallFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED"),body:t});return{success:!1,body:t}}t.forEach(e=>{this.ctx.pluginLoader.unregisterPlugin(e)}),this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS")),this.ctx.emit("uninstallSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS"),body:t});return{success:!0,body:t}}{const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("uninstallFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED"),body:e});return{success:!1,body:e}}}async update(e,t={},n){const r=e.map(e=>mt(this.ctx,e)).filter(e=>e.success).map(e=>e.pkgName);if(r.length>0){const e=await this.execCommand("update",r,this.ctx.baseDir,t,n);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("updateFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED"),body:t});return{success:!1,body:t}}this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS")),this.ctx.emit("updateSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS"),body:r});return{success:!0,body:r}}{const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("updateFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED"),body:e});return{success:!1,body:e}}}async execCommand(e,t,n,r={},i={}){const s=r.npmRegistry||this.ctx.getConfig("settings.npmRegistry"),a=r.npmProxy||this.ctx.getConfig("settings.npmProxy");return await new Promise(r=>{let o=[e].concat(t).concat("--color=always").concat("--save");s&&(o=o.concat(`--registry=${s}`)),a&&(o=o.concat(`--proxy=${a}`));try{const e=x("npm",o,{cwd:n,env:Object.assign({},process.env,i)});let t="";e.stdout?.on("data",e=>{t+=e}).pipe(process.stdout),e.stderr?.on("data",e=>{t+=e}).pipe(process.stderr),e.on("close",e=>{r(e?{code:e,data:t}:{code:0,data:t})}),e.on("error",e=>{this.ctx.log.error(e),this.ctx.log.error("NPM is not installed"),this.ctx.emit(De.FAILED,"NPM is not installed")})}catch(e){this.ctx.log.error(e),this.ctx.emit(De.FAILED,e)}})}}const mt=(e,t)=>{const n={success:!1,fullName:"",pkgName:""},r=V(t,e.log);if(!r)return n;const i=z(r,e.log);return i?{success:!0,fullName:r,pkgName:i}:n},ht={"zh-CN":{UPLOAD_FAILED:"上传失败",CHECK_SETTINGS:"请检查你的配置项是否正确",CHECK_SETTINGS_AND_NETWORK:"请检查你的配置项以及网络",UPLOAD_FAILED_REASON:"错误码:${code},请打开浏览器粘贴地址查看相关原因",SERVER_ERROR:"服务端出错,请重试",AUTH_FAILED:"认证失败",PICBED_SMMS:"SM.MS",PICBED_SMMS_TOKEN:"设定Token",PICBED_SMMS_BACKUP_DOMAIN:"备用上传域名",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例如 smms.app",PICBED_ALICLOUD:"阿里云OSS",PICBED_ALICLOUD_ACCESSKEYID:"设定KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"设定KeySecret",PICBED_ALICLOUD_BUCKET:"设定Bucket",PICBED_ALICLOUD_AREA:"设定存储区域",PICBED_ALICLOUD_PATH:"设定存储路径",PICBED_ALICLOUD_CUSTOMURL:"设定自定义域名",PICBED_ALICLOUD_OPTIONS:"设定网址后缀",PICBED_ALICLOUD_MESSAGE_AREA:"例如:oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例如:test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例如:?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD:"腾讯云COS",PICBED_TENCENTCLOUD_VERSION:"COS版本",PICBED_TENCENTCLOUD_SECRETID:"设定SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"设定SecretKey",PICBED_TENCENTCLOUD_APPID:"设定AppId",PICBED_TENCENTCLOUD_BUCKET:"设定Bucket",PICBED_TENCENTCLOUD_AREA:"设定存储区域",PICBED_TENCENTCLOUD_ENDPOINT:"设定Endpoint",PICBED_TENCENTCLOUD_PATH:"设定存储路径",PICBED_TENCENTCLOUD_OPTIONS:"设定网址后缀",PICBED_TENCENTCLOUD_CUSTOMURL:"设定自定义域名",PICBED_TENCENTCLOUD_SLIM:"极智压缩",PICBED_TENCENTCLOUD_SLIM_TIP:"图片极智压缩,详情请参考[文档说明](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"开启",PICBED_TENCENTCLOUD_SLIM_CANCEL:"关闭",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例如:1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例如:ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例如:cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例如:test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例如:?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"设定Token",PICBED_GITHUB_REPO:"设定仓库名",PICBED_GITHUB_PATH:"设定存储路径",PICBED_GITHUB_BRANCH:"设定分支名",PICBED_GITHUB_CUSTOMURL:"设定自定义域名",PICBED_GITHUB_MESSAGE_REPO:"格式:username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例如:main",PICBED_GITHUB_MESSAGE_PATH:"例如:test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_QINIU:"七牛云",PICBED_QINIU_ACCESSKEY:"设定AccessKey",PICBED_QINIU_SECRETKEY:"设定SecretKey",PICBED_QINIU_BUCKET:"设定Bucket",PICBED_QINIU_PATH:"设定存储路径",PICBED_QINIU_URL:"设定访问网址",PICBED_QINIU_OPTIONS:"设定网址后缀",PICBED_QINIU_AREA:"设定存储区域",PICBED_QINIU_MESSAGE_PATH:"例如:test/",PICBED_QINIU_MESSAGE_AREA:"例如:z0",PICBED_QINIU_MESSAGE_OPTIONS:"例如:?imageslim",PICBED_QINIU_MESSAGE_URL:"例如:https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"设定ClientId",PICBED_IMGUR_PROXY:"设定代理",PICBED_IMGUR_MESSAGE_PROXY:"例如:http://127.0.0.1:1080",PICBED_UPYUN:"又拍云",PICBED_UPYUN_BUCKET:"设定Bucket",PICBED_UPYUN_OPERATOR:"设定操作员",PICBED_UPYUN_PASSWORD:"设定操作员密码",PICBED_UPYUN_PATH:"设定存储路径",PICBED_UPYUN_URL:"设定加速域名",PICBED_UPYUN_OPTIONS:"设定网址后缀",PICBED_UPYUN_MESSAGE_OPERATOR:"例如:me",PICBED_UPYUN_MESSAGE_PASSWORD:"输入操作员密码",PICBED_UPYUN_MESSAGE_URL:"例如:http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例如:!imgslim",PICBED_UPYUN_MESSAGE_PATH:"例如:test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"插件安装成功",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"插件安装失败",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"插件安装失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"插件安装失败,请输入合法插件名或合法安装路径",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"插件卸载成功",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"插件卸载失败",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"插件卸载失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"插件卸载失败,请输入合法插件名",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"插件更新成功",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"插件更新失败",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"插件更新失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"插件更新失败,请输入合法插件名"},"zh-TW":{UPLOAD_FAILED:"上傳失敗",CHECK_SETTINGS:"請檢查你的設定是否正確",CHECK_SETTINGS_AND_NETWORK:"請檢查你的設定及網路",UPLOAD_FAILED_REASON:"錯誤碼:${code},請打開瀏覽器貼上地址查看相關原因",SERVER_ERROR:"伺服器出錯,請重試",AUTH_FAILED:"認證失敗",PICBED_SMMS:"SM.MS",PICBED_SMMS_TOKEN:"設定Token",PICBED_SMMS_BACKUP_DOMAIN:"備用上傳網址",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例如 smms.app",PICBED_ALICLOUD:"阿里云OSS",PICBED_ALICLOUD_ACCESSKEYID:"設定KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"設定KeySecret",PICBED_ALICLOUD_BUCKET:"設定Bucket",PICBED_ALICLOUD_AREA:"設定儲存區域",PICBED_ALICLOUD_PATH:"設定儲存路徑",PICBED_ALICLOUD_CUSTOMURL:"設定自訂網址",PICBED_ALICLOUD_OPTIONS:"設定網址後綴",PICBED_ALICLOUD_MESSAGE_AREA:"例如:oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例如:test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例如:?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD:"騰訊云COS",PICBED_TENCENTCLOUD_VERSION:"COS版本",PICBED_TENCENTCLOUD_SECRETID:"設定SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"設定SecretKey",PICBED_TENCENTCLOUD_APPID:"設定AppId",PICBED_TENCENTCLOUD_BUCKET:"設定Bucket",PICBED_TENCENTCLOUD_AREA:"設定儲存區域",PICBED_TENCENTCLOUD_ENDPOINT:"設定Endpoint",PICBED_TENCENTCLOUD_PATH:"設定儲存路徑",PICBED_TENCENTCLOUD_OPTIONS:"設定網址後綴",PICBED_TENCENTCLOUD_SLIM:"極智壓縮",PICBED_TENCENTCLOUD_SLIM_CANCEL:"關閉",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"開啓",PICBED_TENCENTCLOUD_SLIM_TIP:"圖片極智壓縮,詳情請參考[文檔說明](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_CUSTOMURL:"設定自訂網址",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例如:1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例如:ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例如:cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例如:test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例如:?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"設定Token",PICBED_GITHUB_REPO:"設定倉庫名稱",PICBED_GITHUB_PATH:"設定儲存路徑",PICBED_GITHUB_BRANCH:"設定分支名稱",PICBED_GITHUB_CUSTOMURL:"設定自訂網址",PICBED_GITHUB_MESSAGE_REPO:"格式:username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例如:main",PICBED_GITHUB_MESSAGE_PATH:"例如:test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_QINIU:"七牛云",PICBED_QINIU_ACCESSKEY:"設定AccessKey",PICBED_QINIU_SECRETKEY:"設定SecretKey",PICBED_QINIU_BUCKET:"設定Bucket",PICBED_QINIU_PATH:"設定儲存路徑",PICBED_QINIU_URL:"設定訪問網址",PICBED_QINIU_OPTIONS:"設定網址後綴",PICBED_QINIU_AREA:"設定儲存區域",PICBED_QINIU_MESSAGE_PATH:"例如:test/",PICBED_QINIU_MESSAGE_AREA:"例如:z0",PICBED_QINIU_MESSAGE_OPTIONS:"例如:?imageslim",PICBED_QINIU_MESSAGE_URL:"例如:https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"設定ClientId",PICBED_IMGUR_PROXY:"設定PROXY",PICBED_IMGUR_MESSAGE_PROXY:"例如:http://127.0.0.1:1080",PICBED_UPYUN:"又拍云",PICBED_UPYUN_BUCKET:"設定Bucket",PICBED_UPYUN_OPERATOR:"設定操作員",PICBED_UPYUN_PASSWORD:"設定操作員密碼",PICBED_UPYUN_PATH:"設定儲存路徑",PICBED_UPYUN_URL:"設定加速網址",PICBED_UPYUN_OPTIONS:"設定網址後綴",PICBED_UPYUN_MESSAGE_OPERATOR:"例如:me",PICBED_UPYUN_MESSAGE_PASSWORD:"輸入操作員密碼",PICBED_UPYUN_MESSAGE_URL:"例如:http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例如:!imgslim",PICBED_UPYUN_MESSAGE_PATH:"例如:test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"插件安裝成功",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"插件安裝失敗",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"插件安裝失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"插件安裝失敗,請輸入正確的插件名稱或正確的安裝路徑",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"插件卸載成功",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"插件卸載失敗",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"插件卸載失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"插件卸載失敗,請輸入正確的插件名稱",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"插件更新成功",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"插件更新失敗",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"插件更新失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"插件更新失敗,請輸入正確的插件名稱"},en:{UPLOAD_FAILED:"Upload failed",CHECK_SETTINGS:"Please check your settings",CHECK_SETTINGS_AND_NETWORK:"Please check your settings and network",UPLOAD_FAILED_REASON:"Error code: ${code}, please open the browser and paste the address to see the reason",SERVER_ERROR:"Server error, please try again later",AUTH_FAILED:"Authentication failed",PICBED_SMMS:"SM.MS",PICBED_SMMS_TOKEN:"Set Token",PICBED_SMMS_BACKUP_DOMAIN:"Set Backup Upload Domain",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"Ex. smms.app",PICBED_ALICLOUD:"Ali Cloud",PICBED_ALICLOUD_ACCESSKEYID:"Set KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"Set KeySecret",PICBED_ALICLOUD_BUCKET:"Set Bucket",PICBED_ALICLOUD_AREA:"Set Area",PICBED_ALICLOUD_PATH:"Set Path",PICBED_ALICLOUD_CUSTOMURL:"Set Custom URL",PICBED_ALICLOUD_OPTIONS:"Set URL Suffix",PICBED_ALICLOUD_MESSAGE_AREA:"Ex. oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"Ex. test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"Ex. ?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"Ex. https://test.com",PICBED_TENCENTCLOUD:"Tencent Cloud",PICBED_TENCENTCLOUD_VERSION:"Choose COS version",PICBED_TENCENTCLOUD_SECRETID:"Set SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"Set SecretKey",PICBED_TENCENTCLOUD_APPID:"Set AppId",PICBED_TENCENTCLOUD_BUCKET:"Set Bucket",PICBED_TENCENTCLOUD_AREA:"Set Area",PICBED_TENCENTCLOUD_ENDPOINT:"Set Endpoint",PICBED_TENCENTCLOUD_PATH:"Set Path",PICBED_TENCENTCLOUD_OPTIONS:"Set URL Suffix",PICBED_TENCENTCLOUD_SLIM:"Set ImageSlim",PICBED_TENCENTCLOUD_SLIM_TIP:"Image extremely intelligent compression, please refer to the [document description](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"OPEN",PICBED_TENCENTCLOUD_SLIM_CANCEL:"CLOSE",PICBED_TENCENTCLOUD_CUSTOMURL:"Set Custom URL",PICBED_TENCENTCLOUD_MESSAGE_APPID:"Ex. 1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"Ex. ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"Ex. cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"Ex. test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"Ex. http://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"Ex. ?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"Set Token",PICBED_GITHUB_REPO:"Set Repo Name",PICBED_GITHUB_PATH:"Set Path",PICBED_GITHUB_BRANCH:"Set Branch",PICBED_GITHUB_CUSTOMURL:"Set Custom URL",PICBED_GITHUB_MESSAGE_REPO:"Ex. username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"Ex. main",PICBED_GITHUB_MESSAGE_PATH:"Ex. test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"Ex. https://test.com",PICBED_QINIU:"Qiniu",PICBED_QINIU_ACCESSKEY:"Set AccessKey",PICBED_QINIU_SECRETKEY:"Set SecretKey",PICBED_QINIU_BUCKET:"Set Bucket",PICBED_QINIU_PATH:"Set Path",PICBED_QINIU_URL:"Set URL",PICBED_QINIU_OPTIONS:"Set URL Suffix",PICBED_QINIU_AREA:"Set Area",PICBED_QINIU_MESSAGE_PATH:"Ex. test/",PICBED_QINIU_MESSAGE_AREA:"Ex. z0",PICBED_QINIU_MESSAGE_OPTIONS:"Ex. ?imageslim",PICBED_QINIU_MESSAGE_URL:"Ex. https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"Set ClientId",PICBED_IMGUR_PROXY:"Set Proxy",PICBED_IMGUR_MESSAGE_PROXY:"Ex. http://127.0.0.1:1080",PICBED_UPYUN:"Upyun",PICBED_UPYUN_BUCKET:"Set Bucket",PICBED_UPYUN_OPERATOR:"Set Operator",PICBED_UPYUN_PASSWORD:"Set Operator Password",PICBED_UPYUN_PATH:"Set Path",PICBED_UPYUN_URL:"Set URL",PICBED_UPYUN_OPTIONS:"Set URL Suffix",PICBED_UPYUN_MESSAGE_OPERATOR:"Ex. me",PICBED_UPYUN_MESSAGE_PASSWORD:"Please type the operator password",PICBED_UPYUN_MESSAGE_URL:"Ex. http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"Ex. !imgslim",PICBED_UPYUN_MESSAGE_PATH:"Ex. test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"Plugin installed successfully",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"Plugin installation failed",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"Plugin installation failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"Plugin installation failed, please enter a valid plugin name or valid installation path",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"Plugin uninstalled successfully",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"Plugin uninstall failed",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"Plugin uninstall failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"Plugin uninstall failed, please enter a valid plugin name",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"Plugin updated successfully",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"Plugin update failed",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"Plugin update failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"Plugin update failed, please enter a valid plugin name"}};class Ct{i18n;objectAdapter;ctx;constructor(e){this.ctx=e,this.objectAdapter=new R(ht);let t=this.ctx.getConfig("settings.language")||"zh-CN";ht[t]||(t="zh-CN"),this.i18n=new w({adapter:this.objectAdapter,defaultLanguage:t}),this.loadOutterI18n()}loadOutterI18n(){const n=this.getOutterI18nFolder();e.readdirSync(n,{withFileTypes:!0}).forEach(r=>{if(r.isFile()&&r.name.endsWith(".yml")){const i=t.join(n,r.name),s=e.readFileSync(i,"utf8");try{const e=G.load(s);ht[r.name.replace(/\.yml$/,"")]=e}catch(e){console.error(e)}}})}getOutterI18nFolder(){const n=t.join(this.ctx.baseDir,"i18n-cli");return e.pathExistsSync(n)||e.ensureDirSync(n),n}translate(e,t){return this.i18n.translate(e,t)||e}setLanguage(e){this.i18n.setLanguage(e),this.ctx.saveConfig({"settings.language":e})}addLocale(e,t){const n=this.objectAdapter.getLocale(e);if(!n)return!1;const r=N(n,t);return this.objectAdapter.setLocale(e,r),!0}addLanguage(e,t){return!this.objectAdapter.getLocale(e)&&(this.objectAdapter.setLocale(e,t),ht[e]=t,!0)}getLanguageList(){return Object.keys(ht)}}class Pt extends n{_config;lifecycle;db;_pluginLoader;configPath;baseDir;helper;log;cmd;output;input;pluginHandler;Request;i18n;VERSION="1.6.1";GUI_VERSION;get pluginLoader(){return this._pluginLoader}constructor(e=""){super(),this.configPath=e,this.output=[],this.input=[],this.helper={transformer:new Pe("transformer"),uploader:new Pe("uploader"),beforeTransformPlugins:new Pe("beforeTransformPlugins"),beforeUploadPlugins:new Pe("beforeUploadPlugins"),afterUploadPlugins:new Pe("afterUploadPlugins")},this.initConfigPath(),this.log=new Se(this),this.cmd=new Ne(this),this.pluginHandler=new dt(this),this.initConfig(),this.init()}initConfigPath(){if(""===this.configPath&&(this.configPath=i()+"/.picgo/config.json"),".JSON"!==t.extname(this.configPath).toUpperCase())throw this.configPath="",Error("The configuration file only supports JSON format.");this.baseDir=t.dirname(this.configPath);e.pathExistsSync(this.configPath)||e.ensureFileSync(`${this.configPath}`)}initConfig(){this.db=new It(this),this._config=this.db.read(!0)}init(){try{this.i18n=new Ct(this),this.Request=new _t(this),this._pluginLoader=new it(this),fe("picgo"),et().register(this),{register(e){e.helper.transformer.register("path",nt),e.helper.transformer.register("base64",rt)}}.register(this),fe(""),this._pluginLoader.load(),this.lifecycle=new Ae(this)}catch(e){throw this.emit(De.UPLOAD_PROGRESS,-1),this.log.error(e),e}}use(e,t){if(t)return this.pluginLoader.registerPlugin(t,e),this.pluginLoader.getPlugin(t);return e(this)}registerCommands(){""!==this.configPath&&(this.cmd.init(),this.cmd.loadCommands())}getConfig(e){return e?U(this._config,e):this._config}saveConfig(e){te(e)?(this.setConfig(e),this.db.saveConfig(e)):this.log.warn("the format of config is invalid, please provide object")}removeConfig(e,t){e&&t&&(ee(e)?this.log.warn(`the config.${e} can't be removed`):(this.unsetConfig(e,t),this.db.unset(e,t)))}setConfig(e){te(e)?Object.keys(e).forEach(t=>{ee(t)&&(this.log.warn(`the config.${t} can't be modified`),delete e[t]),D(this._config,t,e[t]),ct.emit(Le.CONFIG_CHANGE,{configName:t,value:e[t]})}):this.log.warn("the format of config is invalid, please provide object")}unsetConfig(e,t){e&&t&&(ee(e)?this.log.warn(`the config.${e} can't be unset`):L(this.getConfig(e),t))}get request(){return this.Request.request.bind(this.Request)}async upload(t){if(""===this.configPath)return this.log.error("The configuration file only supports JSON format."),[];if(void 0!==t&&0!==t.length){const{output:e}=await this.lifecycle.start(t);return e}try{const{imgPath:t,shouldKeepAfterUploading:n}=await lt(this);if("no image"===t)throw new Error("image not found in clipboard");{this.once(De.FAILED,()=>{n||e.remove(t).catch(e=>{this.log.error(e)})}),this.once("finished",()=>{n||e.remove(t).catch(e=>{this.log.error(e)})});const{output:r}=await this.lifecycle.start([t]);return r}}catch(e){throw this.emit(De.FAILED,e),e}}}export{Ne as Commander,De as IBuildInEvent,Le as IBusEvent,Ue as ILogType,Ae as Lifecycle,Pe as LifecyclePlugins,Se as Logger,Pt as PicGo,se as PicGoUtils,dt as PluginHandler,it as PluginLoader,_t as Request};
|
|
1
|
+
import e from"fs-extra";import t from"path";import{EventEmitter as n}from"events";import r,{homedir as i}from"os";import{Command as s}from"commander";import a from"inquirer";import{imageSize as o}from"image-size";import{URL as l}from"url";import c from"chalk";import u from"minimatch";import p from"globby";import g from"ejs";import E from"download-git-repo";import{rimrafSync as _}from"rimraf";import I from"dayjs";import d from"util";import m from"crypto";import h from"mime-types";import C 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 y from"https";import B from"tunnel";import{JSONStore as b}from"@picgo/store";import x from"cross-spawn";import G from"js-yaml";import{ObjectAdapter as R,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:r,registry:i}=n,s={npmProxy:r,npmRegistry:i};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:r,registry:i}=n,s={npmProxy:r,npmRegistry:i};e.pluginHandler.update(t,s).catch(t=>{e.log.error(t)})})}},$={handle:e=>{e.cmd.program.option("-c, --config <path>","set config path")}},H=e=>e.startsWith("http://")||e.startsWith("https://"),F=e=>{e=e||"";try{return e!==decodeURI(e)}catch(e){return!1}},v=e=>(F(e)||(e=encodeURI(e)),e),k=(...e)=>e.join("").replace(/\/{2,}/g,"/").split("/").map(e=>encodeURIComponent(e)).join("/"),q=e=>{try{const{width:t=0,height:n=0,type:r}=o(e);return{real:!0,width:t,height:n,extname:r?`.${r}`:".png"}}catch(e){return{real:!1,width:200,height:200,extname:".png"}}},K=async n=>{try{return{extname:t.extname(n),fileName:t.basename(n),filePath:n,buffer:await e.readFile(n),success:!0}}catch{return{reason:`read file ${n} error`,success:!1}}},Y=async(e,n)=>{e=v(e);let r,i=!1,s="";const a=new Promise((a,o)=>{(async()=>{try{const o=await n.request({method:"get",url:e,resolveWithFullResponse:!0,responseType:"arraybuffer"}).then(e=>{const t=e.headers["content-type"];return t?.includes("image")&&(i=!0,s=`.${t.split("image/")[1]}`),e.data});if(clearTimeout(r),i){const n=new l(e).pathname,r=decodeURIComponent(t.basename(n));a({buffer:o,fileName:r,extname:s,success:!0})}else a({success:!1,reason:`${e} is not image`})}catch(t){clearTimeout(r),a({success:!1,reason:`request ${e} error, ${t?.message??""}`})}})().catch(o)}),o=new Promise(t=>{r=setTimeout(()=>{t({success:!1,reason:`request ${e} timeout`})},1e4)});return Promise.race([a,o])},j=e=>/^@[^/]+\/picgo-plugin-/.test(e)?"scope":e.startsWith("picgo-plugin-")?"normal":Q(e)?"simple":"unknown",Q=n=>{if(t.isAbsolute(n))return!1;const r=t.join(process.cwd(),n);return!e.existsSync(r)&&(!n.includes("/")&&!n.includes("\\"))},W=(e,t="")=>t?`@${t}/picgo-plugin-${e}`:`picgo-plugin-${e}`,V=(n,r=console)=>{switch(j(n)){case"normal":case"scope":return n;case"simple":return W(n);default:{let i=n;return t.isAbsolute(n)&&e.existsSync(n)?X(i):(i=t.join(process.cwd(),n),e.existsSync(i)?X(i):(r.warn(`Can't find plugin ${n}`),""))}}},z=(n,r=console)=>{switch(j(n)){case"normal":return J(n);case"scope":return J(n,!0);case"simple":return J(W(n));default:{if(!e.existsSync(n))return r.warn(`Can't find plugin: ${n}`),"";const i=t.posix.join(n,"package.json");if(e.existsSync(i)){const t=e.readJSONSync(i)||{};return t.name?.includes("picgo-plugin-")?t.name:(r.warn(`The plugin package.json's name filed is ${t.name||"empty"}, need to include the prefix: picgo-plugin-`),"")}return r.warn(`Can't find plugin: ${n}`),""}}},X=e=>e.split(t.sep).join("/"),J=(e,t=!1)=>{if(e.includes("@")){let n=/(.+\/)?(picgo-plugin-\w+)(@.+)*/;t&&(n=/(.+\/)?(^@[^/]+\/picgo-plugin-\w+)(@.+)*/);const r=e.match(n);return r?r[2]:(console.warn("can not remove plugin version"),e)}return e},Z=[],ee=e=>Z.some(t=>e.startsWith(t)),te=e=>"object"==typeof e&&!Array.isArray(e)&&Object.keys(e).length>0;function ne(e){try{return JSON.parse(e)}catch(t){return e}}const re=(e=0)=>isNaN(Number(e))?0:Number(e),ie=()=>"development"===process.env.NODE_ENV;var se=Object.freeze({__proto__:null,configBlackList:Z,forceNumber:re,getFSFile:K,getImageSize:q,getNormalPluginName:z,getPluginNameType:j,getProcessPluginName:V,getURLFile:Y,handleCompletePluginName:W,handleStreamlinePluginName:e=>/^@[^/]+\/picgo-plugin-/.test(e)?e.replace(/^@[^/]+\/picgo-plugin-/,""):e.replace(/picgo-plugin-/,""),handleUnixStylePath:X,handleUrlEncode:v,handleUrlPathSafeEncode:k,isConfigKeyInBlackList:ee,isDev:ie,isInputConfigValid:te,isProd:()=>"production"===process.env.NODE_ENV,isSimpleName:Q,isUrl:H,isUrlEncode:F,removePluginVersion:J,safeParse:ne});const ae={handle:n=>{n.cmd.program.command("upload").description("upload, go go go").arguments("[input...]").alias("u").action(r=>{(async()=>{const i=r.map(e=>H(e)?e:t.resolve(e)).filter(t=>{const r=e.existsSync(t)||H(t);return r||n.log.warn(`${t} does not exist.`),r});await n.upload(i)})().catch(e=>{n.log.error(e)})})}},oe=async(e,t,n,r)=>{const i=await e.cmd.inquirer.prompt(t),s="uploader"===n?`picBed.${r}`:"transformer"===n?`transformer.${r}`:r;e.saveConfig({[s]:i}),"uploader"===n?e.saveConfig({"picBed.current":r,"picBed.uploader":r}):"transformer"===n&&e.saveConfig({"picBed.transformer":r})},le={handle:e=>{e.cmd.program.command("set").alias("config").arguments("<module> [name]").description("configure config of picgo modules").action((t,n)=>{(async()=>{try{switch(t){case"uploader":case"transformer":if(n){const r=e.helper[t].get(n);if(!r)return e.log.error(`No ${t} named ${n}`);r.config&&await oe(e,r.config(e),t,n)}else{const n=[{type:"list",name:`${t}`,choices:e.helper[t].getIdList(),message:`Choose a(n) ${t}`}],r=await e.cmd.inquirer.prompt(n),i=e.helper[t].get(r[t]);i?.config&&await oe(e,i.config(e),t,r[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}`);e.pluginLoader.getPlugin(n)?.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);e.pluginLoader.getPlugin(n.plugin)?.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)})})}},ce={handle:async e=>{const t=e.cmd;t.program.command("use").arguments("[module]").description("use modules of picgo").action(n=>{(async()=>{try{let r=[];const i={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(!i[n])return e.log.warn(`No module named ${n}`),e.log.warn("Available modules are uploader|transformer|plugins");r.push(i[n])}else r=Object.keys(i).map(e=>i[e]);const s=await t.inquirer.prompt(r);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)})})}},ue={handle:e=>{e.cmd.program.option("-p, --proxy <url>","set proxy for uploading",t=>{e.setConfig({"picBed.proxy":t})})}},pe=async(e,n)=>{try{const r=Ee(n.tmp),i=t.join(n.tmp,"template");let s={};r.prompts&&r.prompts.length>0&&(s=await e.cmd.inquirer.prompt(r.prompts));let a=await p(["**/*"],{cwd:i,dot:!0});const o=Object.keys(r.filters||{});if(o.length>0&&(a=a.filter(t=>{let n="";for(const e of o)if(u(t,e,{dot:!0})){n=t;break}return!n||ge(e,r.filters[n],s)})),0===a.length)return e.log.warn("Template files not found!");const l=_e(a,i,s);Ie(n.dest,l),"function"==typeof r.complete&&r.complete({answers:s,options:n,files:a,ctx:e}),r.completeMessage&&e.log.success(r.completeMessage),e.log.success("Done!")}catch(t){return e.log.error(t)}},ge=(e,t,n)=>{const r=new Function("data","with (data) { return "+t+"}");try{return r(n)}catch(n){return e.log.error(`Error when evaluating filter condition: ${JSON.stringify(t)}`),!1}},Ee=n=>{const r=t.join(n,"index.js");if(e.existsSync(r)){return require(r)}return{}},_e=(n,r,i)=>{const s={};return n.forEach(n=>{const a=e.readFileSync(t.join(r,n),"utf8"),o=g.render(a,i);(Buffer.isBuffer(o)||/[^\s]/.test(o))&&(s[n]=o)}),s},Ie=(n,r)=>{Object.keys(r).forEach(i=>{const s=t.join(n,i);e.ensureDirSync(t.dirname(s)),e.writeFileSync(s,r[i])})},de=(t,n)=>{n.offline?e.existsSync(n.template)?pe(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,me(t,n))},me=(t,n)=>{e.existsSync(n.tmp)&&_(n.tmp),t.log.info("Template files are downloading..."),E(n.template,n.tmp,{clone:n.clone},e=>{if(e)return t.log.error(e);t.log.success("Template files are downloaded!"),pe(t,n).catch(e=>{t.log.error(e)})})},he={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((r,s,a)=>{(async()=>{try{const o=r.includes("/"),l=!s||"."===s,c=t.resolve(s||"."),u=a.clone||!1,p=a.offline||!1,g=t.join(i(),".picgo/templates",r.replace(/[/:]/g,"-"));a.offline&&(r=g);const E={template:r,project:s,hasSlash:o,inPlace:l,dest:c,clone:u,tmp:g,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&&de(n,E)}):de(n,E)}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"}],r=await e.cmd.inquirer.prompt(t);return e.i18n.setLanguage(r.i18n),void e.log.success(`Language set to ${r.i18n}`)}if(!n.includes(t))return e.log.warn("No such language");e.i18n.setLanguage(t),e.log.success(`Language set to ${t}`)})}};class Pe{static currentPlugin;list;pluginIdMap;name;constructor(e){this.name=e,this.list=new Map,this.pluginIdMap=new Map}register(e,t){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),Pe.currentPlugin&&(this.pluginIdMap.has(Pe.currentPlugin)?this.pluginIdMap.get(Pe.currentPlugin)?.push(e):this.pluginIdMap.set(Pe.currentPlugin,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);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 fe=(e=null)=>{Pe.currentPlugin=e};class Ne{name="commander";static currentPlugin;list=new Map;pluginIdMap=new Map;ctx;program;inquirer;constructor(e){this.program=new s,this.inquirer=a,this.ctx=e}getName(){return this.name}init(){var e;this.program.version("1.6.2","-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",le),e.cmd.register("upload",ae),e.cmd.register("use",ce),e.cmd.register("proxy",ue),e.cmd.register("init",he),e.cmd.register("i18n",Ce)}register(e,t){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 n=Pe.currentPlugin;null!==n&&(this.pluginIdMap.has(n)?this.pluginIdMap.get(n)?.push(e):this.pluginIdMap.set(n,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);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 Ue,De,Le;!function(e){e.success="success",e.info="info",e.warn="warn",e.error="error"}(Ue||(Ue={})),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"}(De||(De={})),function(e){e.CONFIG_CHANGE="CONFIG_CHANGE"}(Le||(Le={}));class Se{level={[Ue.success]:"green",[Ue.info]:"blue",[Ue.warn]:"yellow",[Ue.error]:"red"};ctx;logLevel;logPath;constructor(e){this.ctx=e}handleLog(e,...n){if(this.logLevel=this.ctx.getConfig("settings.logLevel"),!this.ctx.getConfig("silent")&&this.checkLogLevel(e,this.logLevel)){const r=c[this.level[e]](`[PicGo ${e.toUpperCase()}]:`);console.log(r,...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,r=1024*re(this.ctx.getConfig("settings.logFileSizeLimit")||10)*1024;return{isLarge:n>r,logFileSize:n,logFileSizeLimit:r}}return{isLarge:!1}}recreateLogFile(t){e.existsSync(t)&&(e.unlinkSync(t),e.createFileSync(t))}handleWriteLog(t,n,...r){try{let i=`${I().format("YYYY-MM-DD HH:mm:ss")} [PicGo ${n.toUpperCase()}] `;r.forEach(e=>{e instanceof Error&&"error"===n?i+=`\n------Error Stack Begin------\n${d.format(e?.stack)}\n-------Error Stack End------- `:("object"==typeof e&&(e=JSON.stringify(e,null,2)),i+=`${e} `)}),i+="\n",e.appendFileSync(t,i)}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(Ue.success,...e)}info(...e){return this.handleLog(Ue.info,...e)}error(...e){return this.handleLog(Ue.error,...e)}warn(...e){return this.handleLog(Ue.warn,...e)}debug(...e){ie()&&this.handleLog(Ue.info,...e)}}class Ae extends n{ctx;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(De.FAILED),t.emit(De.UPLOAD_PROGRESS,-1),t.emit(De.FAILED,e),t.log.error(e),t.getConfig("debug"))throw e;return t}}async beforeTransform(e){return e.emit(De.UPLOAD_PROGRESS,0),e.emit(De.BEFORE_TRANSFORM,e),e.log.info("Before transform"),await this.handlePlugins(e.helper.beforeTransformPlugins,e),e}async doTransform(e){e.emit(De.UPLOAD_PROGRESS,30);const t=e.getConfig("picBed.transformer")||"path";let n=t,r=e.helper.transformer.get(t);return r||(r=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(r?.handle(e)),e}async beforeUpload(e){return e.emit(De.UPLOAD_PROGRESS,60),e.log.info("Before upload"),e.emit(De.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),r=t;n||(t="smms",r="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 [${r}]`),await(n?.handle(e));for(const n of e.output)n.type=t;return e}async afterUpload(e){e.emit(De.AFTER_UPLOAD,e),e.emit(De.UPLOAD_PROGRESS,100),await this.handlePlugins(e.helper.afterUploadPlugins,e);let t="";const n=e.output.length,r=!0===e.getConfig("settings.encodeOutputURL");for(let i=0;i<n;i++)void 0!==e.output[i].imgUrl&&(t+=r?v(e.output[i].imgUrl):e.output[i].imgUrl,i!==n-1&&(t+="\n")),delete e.output[i].base64Image,delete e.output[i].buffer;return e.emit(De.FINISHED,e),e.log.success(`\n${t}`),e}async handlePlugins(e,t){const n=e.getList(),r=e.getIdList(),i=e.getName();return await Promise.all(n.map(async(e,n)=>{try{t.log.info(`${i}: ${r[n]} running`),await e.handle(t)}catch(e){throw t.log.error(`${i}: ${r[n]} error`),e}})),t}}const Te=(e,t,n,r="")=>({method:"POST",url:`https://${r||"sm.ms"}/api/v2/upload`,headers:{contentType:"multipart/form-data","User-Agent":"PicGo",Authorization:n},formData:{smfile:{value:t,options:{filename:e}},ssl:"true"}}),Oe=async e=>{const t=e.getConfig("picBed.smms");if(!t)throw new Error("Can not find smms config!");const n=e.output;for(const r of n)if(r.fileName&&r.buffer){let n=r.buffer;!n&&r.base64Image&&(n=Buffer.from(r.base64Image,"base64"));const i=Te(r.fileName,n,t?.token,t?.backupDomain);try{const t=await e.request(i),n=JSON.parse(t);if("success"===n.code)delete r.base64Image,delete r.buffer,r.imgUrl=n.data.url;else{if("image_repeated"!==n.code||"string"!=typeof n.images)throw e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:n.message}),new Error(n.message);delete r.base64Image,delete r.buffer,r.imgUrl=n.images}}catch(t){throw e.log.error(t),t}}return e},ye=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=>h.lookup(e)||"application/octet-stream",be=(e,t,n,r)=>{const i=e.secretId,s=e.secretKey,a=e.appId,o=e.bucket;let l,c="";if(e.version&&"v4"!==e.version){const i=Math.floor((new Date).getTime()/1e3);c=`${i};${i+86400}`;const a=m.createHmac("sha1",s).update(c).digest("hex"),o=e.endpoint?e.endpoint:`cos.${e.area}.myqcloud.com`,p=`put\n/${e.path}${t}\n\ncontent-length=${r}&content-type=${u=n,encodeURIComponent(u).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A")}&host=${e.bucket}.${o}\n`,g=`sha1\n${c}\n${m.createHash("sha1").update(p).digest("hex")}\n`;l=m.createHmac("sha1",a).update(g).digest("hex")}else{const e=Math.floor(1e10*Math.random()),t=Math.floor((new Date).getTime()/1e3)-1,n=`a=${a}&b=${o}&k=${i}&e=${t+3600}&t=${t}&r=${e}&f=`,r=m.createHmac("sha1",s).update(n).digest(),c=Buffer.concat([r,Buffer.from(n)]);l=Buffer.from(c).toString("base64")}var u;return{signature:l,appId:a,bucket:o,signTime:c}},xe=(e,t,n,r,i)=>{const s=e.area,a=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}/${k(a,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=content-length;content-type;host&q-url-param-list=&q-signature=${n.signature}`,contentType:Be(t),contentLength:r.byteLength,"User-Agent":`PicGo;${i};null;null`},body:r,resolveWithFullResponse:!0}}return{method:"POST",url:`http://${s}.file.myqcloud.com/files/v2/${n.appId}/${n.bucket}/${k(a,t)}`,headers:{Host:`${s}.file.myqcloud.com`,Authorization:n.signature,contentType:"multipart/form-data","User-Agent":`PicGo;${i};null;null`},formData:{op:"upload",filecontent:r},resolveWithFullResponse:!0}},Ge=async e=>{const t=e.getConfig("picBed.tcyun");if(!t)throw new Error("Can't find tencent COS config");try{const n=e.output,r=t.customUrl,i=t.path,s=!t.version||"v4"===t.version;for(const a of n)if(a.fileName&&a.buffer){let n=a.buffer;!n&&a.base64Image&&(n=Buffer.from(a.base64Image,"base64"));const o=be(t,a.fileName,Be(a.fileName),n.byteLength);if(!o)return!1;const l=xe(t,a.fileName,o,n,e.GUI_VERSION||e.VERSION),c=await e.request(l).then(e=>e).catch(t=>({statusCode:400,body:{msg:e.i18n.translate("AUTH_FAILED"),err:t}}));let u;if(u=s&&"string"==typeof c?JSON.parse(c):c,400===u.statusCode)throw u?.body?.err?u.body.err:new Error(u?.body?.msg||u?.body?.message);const p=t.options||"",g=t.slim||"";if(s&&"SUCCESS"===u.message)delete a.base64Image,delete a.buffer,a.imgUrl=r?`${r}/${i}${a.fileName}`:`${u.data.source_url}${p}`;else{if(s||!u||200!==u.statusCode)throw new Error(c.body.msg);if(delete a.base64Image,delete a.buffer,r)a.imgUrl=`${r}/${encodeURI(i)}${k(a.fileName)}${p}`;else{const e=t.endpoint?t.endpoint:`cos.${t.area}.myqcloud.com`;a.imgUrl=`https://${t.bucket}.${e}/${encodeURI(i)}${k(a.fileName)}${p}`}}g&&(a.imgUrl+=p?"&imageSlim":"?imageSlim")}return e}catch(n){if(!t.version||"v4"===t.version)try{const t=JSON.parse(n.error);e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("UPLOAD_FAILED_REASON",{code:t.code}),text:"https://cloud.tencent.com/document/product/436/8432"})}catch(e){}throw n}},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 we=(e,t,n)=>{const r=t.path||"",{token:i,repo:s}=t;return{method:"PUT",url:`https://api.github.com/repos/${s}/contents/${k(r,e)}`,headers:{Authorization:`token ${i}`,"User-Agent":"PicGo","Content-Type":h.lookup(e)},body:n,json:!0}},Me=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 r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i={message:"Upload by PicGo",branch:t.branch,content:n,path:t.path+encodeURI(r.fileName)},s=we(r.fileName,t,i);try{const n=await e.request(s);if(!n)throw new Error("Server error, please try again");delete r.base64Image,delete r.buffer,t.customUrl?r.imgUrl=`${t.customUrl}/${k(t.path||"",r.fileName)}`:r.imgUrl=n.content.download_url}catch(e){if(422!==e.statusCode)throw e;delete r.base64Image,delete r.buffer,t.customUrl?r.imgUrl=`${t.customUrl}/${k(t.path||"",r.fileName)}`:r.imgUrl=`https://raw.githubusercontent.com/${t.repo}/${t.branch}/${k(t.path||"",r.fileName)}`}}return e}catch(t){throw e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK")}),t}},$e=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 He(e,t,n,r){const i=function(e){return"z0"===e?"":"-"+e}(e.area||"z0"),s=e.path||"";return{method:"POST",url:`http://upload${i}.qiniup.com/putb64/-1/key/${Buffer.from(s+t,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_")}`,headers:{Authorization:`UpToken ${n}`,"Content-Type":h.lookup(t)||"application/octet-stream"},body:r}}function Fe(e){const t=e.accessKey,n=e.secretKey,r=new C.auth.digest.Mac(t,n),i={scope:e.bucket};return new C.rs.PutPolicy(i).uploadToken(r)}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 r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i=He(t,r.fileName,Fe(t),n),s=await e.request(i),a=JSON.parse(s);if(!a?.key)throw e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:a.msg}),e.log.error("qiniu error",a),new Error("Upload failed");{delete r.base64Image,delete r.buffer;const e=t.url,n=t.options;r.imgUrl=`${e}/${a.key}${n}`}}return e}catch(t){if("Upload failed"!==t.message&&t.response){const n=t.response.body;e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:n.error})}throw t}},ke=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 qe=(e,t,n)=>{const r={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&&(r.proxy=e.proxy),r},Ke=async e=>{const t=e.getConfig("picBed.imgur");if(!t)throw new Error("Can't find imgur config");try{const n=e.output;for(const r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i=qe(t,r.fileName,n),s=await e.request(i),a="string"==typeof s?JSON.parse(s):s;if(!a.success)throw new Error("Server error, please try again");delete r.base64Image,delete r.buffer,r.imgUrl=a.data.link}return e}catch(t){throw e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK"),text:"http://docs.imgur.com/api/errno/"}),t?.response?.data||t}},Ye=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 je=(e,t)=>{const n=(new Date).toUTCString(),r=h.lookup(t);if(!r)throw Error(`No mime type found for file ${t}`);const i=`PUT\n\n${r}\n${n}\n/${e.bucket}/${e.path}${t}`,s=m.createHmac("sha1",e.accessKeySecret).update(i).digest("base64");return`OSS ${e.accessKeyId}:${s}`},Qe=(e,t,n,r)=>{const i=e.path||"";return{method:"PUT",url:`https://${e.bucket}.${e.area}.aliyuncs.com/${k(i,t)}`,headers:{Host:`${e.bucket}.${e.area}.aliyuncs.com`,Authorization:n,Date:(new Date).toUTCString(),"Content-Type":h.lookup(t)},body:r,resolveWithFullResponse:!0}},We=async e=>{const t=e.getConfig("picBed.aliyun");if(!t)throw new Error("Can't find aliYun OSS config");try{const n=e.output,r=t.customUrl,i=t.path||"";for(const s of n)if(s.fileName&&s.buffer){const n=je(t,s.fileName);let a=s.buffer;!a&&s.base64Image&&(a=Buffer.from(s.base64Image,"base64"));const o=Qe(t,s.fileName,n,a);if(200!==(await e.request(o)).statusCode)throw new Error("Upload failed");{delete s.base64Image,delete s.buffer;const e=t.options||"";s.imgUrl=r?`${r}/${k(i,s.fileName)}${e}`:`https://${t.bucket}.${t.area}.aliyuncs.com/${k(i,s.fileName)}${e}`}}return e}catch(t){throw e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")}),t}},Ve=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 ze=(e,t)=>{const n=e.path||"",r=e.operator,i=e.password,s=P(i),a=(new Date).toUTCString(),o=`PUT&${`/${e.bucket}/${k(n,t)}`}&${a}`;return`UPYUN ${r}:${m.createHmac("sha1",s).update(o).digest("base64")}`},Xe=(e,t,n,r)=>{const i=e.bucket,s=e.path||"";return{method:"PUT",url:`https://v0.api.upyun.com/${i}/${k(s,t)}`,headers:{Authorization:n,Date:(new Date).toUTCString(),"Content-Type":h.lookup(t)||"application/octet-stream"},body:r,resolveWithFullResponse:!0}},Je=async e=>{const t=e.getConfig("picBed.upyun");if(!t)throw new Error("Can't find upYun config");try{const n=e.output,r=t.path||"";for(const i of n)if(i.fileName&&i.buffer){let n=i.buffer;!n&&i.base64Image&&(n=Buffer.from(i.base64Image,"base64"));const s=ze(t,i.fileName),a=Xe(t,i.fileName,s,n);if(200!==(await e.request(a)).statusCode)throw new Error("Upload failed");delete i.base64Image,delete i.buffer,i.imgUrl=`${t.url}/${k(r,i.fileName)}${t.options}`}return e}catch(t){if("Upload failed"===t.message)e.emit(De.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")});else{const n=ne(t.error);e.emit(De.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}},Ze=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 et=()=>({register(e){!function(e){e.helper.uploader.register("aliyun",{get name(){return e.i18n.translate("PICBED_ALICLOUD")},handle:We,config:Ve})}(e),function(e){e.helper.uploader.register("tcyun",{get name(){return e.i18n.translate("PICBED_TENCENTCLOUD")},handle:Ge,config:Re})}(e),function(e){e.helper.uploader.register("smms",{get name(){return e.i18n.translate("PICBED_SMMS")},handle:Oe,config:ye})}(e),function(e){e.helper.uploader.register("github",{get name(){return e.i18n.translate("PICBED_GITHUB")},handle:Me,config:$e})}(e),function(e){e.helper.uploader.register("qiniu",{get name(){return e.i18n.translate("PICBED_QINIU")},handle:ve,config:ke})}(e),function(e){e.helper.uploader.register("imgur",{get name(){return e.i18n.translate("PICBED_IMGUR")},handle:Ke,config:Ye})}(e),function(e){e.helper.uploader.register("upyun",{get name(){return e.i18n.translate("PICBED_UPYUN")},handle:Je,config:Ze})}(e)}}),tt=(e,t,n)=>{const r=q(t);return r.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")),r};var nt={handle:async e=>{const t=e.output;return await Promise.all(e.input.map(async(n,r)=>{let i;if(i=Buffer.isBuffer(n)?{success:!0,buffer:n,fileName:"",extname:""}:H(n)?await Y(n,e):await K(n),i.success&&i.buffer){const s=tt(e,i.buffer,n),a=i.extname||s.extname||".png";t[r]={buffer:i.buffer,fileName:i.fileName||`${I().format("YYYYMMDDHHmmssSSS")}${a}}`,width:s.width,height:s.height,filePath:i.filePath,extname:a,mimeType:h.lookup(a)||"application/octet-stream"}}else e.log.error(i.reason)})),e.output=t.filter(e=>e),e}};var rt={handle:async e=>(e.output.push(...e.input),e)};class it{ctx;list=[];fullList=new Set;pluginMap=new Map;constructor(e){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(r){return t.join(e.baseDir,"node_modules",n)}}load(){const n=t.join(this.ctx.baseDir,"package.json"),r=t.join(this.ctx.baseDir,"node_modules/");if(!e.existsSync(r))return!1;const i=e.readJSONSync(n),s=Object.keys(i.dependencies||{}),a=Object.keys(i.devDependencies||{}),o=s.concat(a).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 o)this.registerPlugin(e);return!0}registerPlugin(e,t){if(e&&"string"==typeof e){this.fullList.add(e);try{if(t){this.list.push(e),fe(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),fe(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(De.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),fe(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/"),r=require(n+e)(this.ctx);return this.pluginMap.set(e,r),r}getList(){return this.list}hasPlugin(e){return this.fullList.has(e)}getFullList(){return[...this.fullList]}}const st="picgo-clipboard-images",at={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\nelse\n # fallback for unsupported session types\n echo >&2 "Error: Unsupported session type \'$XDG_SESSION_TYPE\'."\n echo >&2 "Solution: The variable of XDG_SESSION_TYPE must set as \'x11\' or \'wayland\'."\n exit 1\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'},ot={darwin:"mac.applescript",win32:"windows.ps1",win10:"windows10.ps1",linux:"linux.sh",wsl:"wsl.sh"};const lt=async n=>{!function(n){const r=t.join(n.baseDir,st);e.existsSync(r)||e.mkdirSync(r)}(n);const i=t.join(n.baseDir,st,`${I().format("YYYYMMDDHHmmssSSS")}.png`);return await new Promise((s,a)=>{const o=(()=>{const e=process.platform;if(A)return"wsl";if("win32"===e)return"10"===r.release().split(".")[0]?"win10":"win32";return"darwin"===e?"darwin":"linux"})(),l=t.join(n.baseDir,ot[o]);let c;e.existsSync(l)||e.writeFileSync(l,at[o],"utf8"),c="darwin"===o?S("osascript",[l,i]):"win32"===o||"win10"===o?S("powershell",["-noprofile","-noninteractive","-nologo","-sta","-executionpolicy","unrestricted","-file",l,i]):S("sh",[l,i]),c.stdout.on("data",r=>{if("linux"===o&&"no xclip or wl-clipboard"===r.toString().trim())return n.emit(De.NOTIFICATION,{title:"xclip or wl-clipboard not found",body:"Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"}),a(new Error("Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"));const l=r.toString().trim();let c=!1;if(t.basename(l)!==t.basename(i)&&e.existsSync(l)&&(c=!0),"no image"!==l&&!e.existsSync(l))return a(new Error(`Can't find ${l}`));s({imgPath:l,shouldKeepAfterUploading:c})})})},ct=new n,ut=new y.Agent({maxVersion:"TLSv1.2",minVersion:"TLSv1.2"});function pt(e,t,n){"object"==typeof n&&"value"in n&&"options"in n?e.append(t,n.value,n.options):e.append(t,n)}function gt(e){return{...e,statusCode:e.status,body:e.data}}function Et(e){const t={method:e?.config?.method?.toUpperCase()||"",url:e?.config?.url||"",statusCode:e?.response?.status||0,message:e?.message||"",stack:e?.stack||{},response:{status:e?.response?.status||0,statusCode:e?.response?.status||0,body:e?.response?.data||""}};return Promise.reject(t)}class _t{ctx;proxy="";options={};constructor(e){this.ctx=e,this.init(),ct.on(Le.CONFIG_CHANGE,e=>{switch(e.configName){case"picBed":e.value?.proxy&&(this.proxy=e.value.proxy);break;case"picBed.proxy":this.proxy=e.value}})}init(){const e=this.ctx.getConfig("picBed.proxy");e&&(this.proxy=e)}handleProxy(){if(this.proxy)try{const e=new l(this.proxy);return{host:e.hostname,port:parseInt(e.port||"0",10),protocol:e.protocol}}catch(e){}return!1}request(e){this.options.proxy=this.handleProxy(),this.options.headers=e.headers||{},this.options.maxBodyLength=1/0,this.options.maxContentLength=1/0,this.options.proxy&&e.url?.startsWith("https://")?(this.options.httpsAgent=B.httpsOverHttp({proxy:{host:this.options.proxy.host,port:this.options.proxy.port}}),this.options.proxy=!1):this.options.httpsAgent=ut;const t=T.create(this.options);t.interceptors.response.use(gt,Et);const n=function(e){let t=!1;const n={...e,url:e.url||"",headers:e.headers||{}};if(e.proxy){let r=e.proxy;if("string"==typeof r){try{r=new l(e.proxy)}catch(e){r=!1,n.proxy=!1,console.error(e)}t=!0}r&&(e.url?.startsWith("https://")?(n.proxy=!1,n.httpsAgent=B.httpsOverHttp({proxy:{host:r?.hostname,port:parseInt(r?.port,10)}})):n.proxy={host:r.hostname,port:parseInt(r.port,10),protocol:"http"})}if("formData"in e){const r=new O;for(const t in e.formData)pt(r,t,e.formData[t]);n.data=r,n.headers=Object.assign(n.headers||{},r.getHeaders()),t=!0,delete n.formData}return"body"in e&&(n.data=e.body,t=!0,delete n.body),"qs"in e&&(n.params=e.qs,t=!0),n.__isOldOptions=t,n}(e);return t.interceptors.request.use(function(e){let t="";return e?.headers?.contentType?(t=e.headers.contentType,delete e.headers.contentType):e?.headers?.ContentType?(t=e.headers.ContentType,delete e.headers.ContentType):e?.headers?.["content-type"]&&(t=e.headers["content-type"],delete e.headers["content-type"]),""!==t&&e.headers&&(e.headers["Content-Type"]=t),e}),"resolveWithFullResponse"in e&&e.resolveWithFullResponse?t.request(n):t.request(n).then(t=>n.__isOldOptions?"json"in e?e.json?t.data:void 0:JSON.stringify(t.data):t.data)}}class It{ctx;db;constructor(e){if(this.ctx=e,this.db=new b(this.ctx.configPath),!this.db.has("picBed"))try{this.db.set("picBed",{uploader:"smms",current:"smms"})}catch(e){throw this.ctx.log.error(e),e}if(!this.db.has("picgoPlugins"))try{this.db.set("picgoPlugins",{})}catch(e){throw this.ctx.log.error(e),e}}read(e){return this.db.read(e)}get(e=""){return this.read(!0),this.db.get(e)}set(e,t){return this.read(!0),this.db.set(e,t)}has(e){return this.read(!0),this.db.has(e)}unset(e,t){return this.read(!0),this.db.unset(e,t)}saveConfig(e){Object.keys(e).forEach(t=>{this.set(t,e[t])})}removeConfig(e){Object.keys(e).forEach(t=>{this.unset(t,e[t])})}}class dt{ctx;constructor(e){this.ctx=e}async install(e,t={},n){const r=[],i=e.map(e=>mt(this.ctx,e)).filter(e=>this.ctx.pluginLoader.hasPlugin(e.pkgName)?(r.push(e.pkgName),this.ctx.log.success(`PicGo has already installed ${e.pkgName}`),!1):!!e.success),s=i.map(e=>e.fullName),a=i.map(e=>e.pkgName);if(s.length>0){const e=await this.execCommand("install",s,this.ctx.baseDir,t,n);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("installFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED"),body:t});return{success:!1,body:t}}a.forEach(e=>{this.ctx.pluginLoader.registerPlugin(e)}),this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS")),this.ctx.emit("installSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS"),body:[...a,...r]});return{success:!0,body:[...a,...r]}}if(0===r.length){const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("installFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED"),body:e});return{success:!1,body:e}}this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS")),this.ctx.emit("installSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS"),body:[...a,...r]});return{success:!0,body:[...a,...r]}}async uninstall(e){const t=e.map(e=>mt(this.ctx,e)).filter(e=>e.success).map(e=>e.pkgName);if(t.length>0){const e=await this.execCommand("uninstall",t,this.ctx.baseDir);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("uninstallFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED"),body:t});return{success:!1,body:t}}t.forEach(e=>{this.ctx.pluginLoader.unregisterPlugin(e)}),this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS")),this.ctx.emit("uninstallSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS"),body:t});return{success:!0,body:t}}{const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("uninstallFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED"),body:e});return{success:!1,body:e}}}async update(e,t={},n){const r=e.map(e=>mt(this.ctx,e)).filter(e=>e.success).map(e=>e.pkgName);if(r.length>0){const e=await this.execCommand("update",r,this.ctx.baseDir,t,n);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("updateFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED"),body:t});return{success:!1,body:t}}this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS")),this.ctx.emit("updateSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS"),body:r});return{success:!0,body:r}}{const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("updateFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED"),body:e});return{success:!1,body:e}}}async execCommand(e,t,n,r={},i={}){const s=r.npmRegistry||this.ctx.getConfig("settings.npmRegistry"),a=r.npmProxy||this.ctx.getConfig("settings.npmProxy");return await new Promise(r=>{let o=[e].concat(t).concat("--color=always").concat("--save");s&&(o=o.concat(`--registry=${s}`)),a&&(o=o.concat(`--proxy=${a}`));try{const e=x("npm",o,{cwd:n,env:Object.assign({},process.env,i)});let t="";e.stdout?.on("data",e=>{t+=e}).pipe(process.stdout),e.stderr?.on("data",e=>{t+=e}).pipe(process.stderr),e.on("close",e=>{r(e?{code:e,data:t}:{code:0,data:t})}),e.on("error",e=>{this.ctx.log.error(e),this.ctx.log.error("NPM is not installed"),this.ctx.emit(De.FAILED,"NPM is not installed")})}catch(e){this.ctx.log.error(e),this.ctx.emit(De.FAILED,e)}})}}const mt=(e,t)=>{const n={success:!1,fullName:"",pkgName:""},r=V(t,e.log);if(!r)return n;const i=z(r,e.log);return i?{success:!0,fullName:r,pkgName:i}:n},ht={"zh-CN":{UPLOAD_FAILED:"上传失败",CHECK_SETTINGS:"请检查你的配置项是否正确",CHECK_SETTINGS_AND_NETWORK:"请检查你的配置项以及网络",UPLOAD_FAILED_REASON:"错误码:${code},请打开浏览器粘贴地址查看相关原因",SERVER_ERROR:"服务端出错,请重试",AUTH_FAILED:"认证失败",PICBED_SMMS:"SM.MS",PICBED_SMMS_TOKEN:"设定Token",PICBED_SMMS_BACKUP_DOMAIN:"备用上传域名",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例如 smms.app",PICBED_ALICLOUD:"阿里云OSS",PICBED_ALICLOUD_ACCESSKEYID:"设定KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"设定KeySecret",PICBED_ALICLOUD_BUCKET:"设定Bucket",PICBED_ALICLOUD_AREA:"设定存储区域",PICBED_ALICLOUD_PATH:"设定存储路径",PICBED_ALICLOUD_CUSTOMURL:"设定自定义域名",PICBED_ALICLOUD_OPTIONS:"设定网址后缀",PICBED_ALICLOUD_MESSAGE_AREA:"例如:oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例如:test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例如:?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD:"腾讯云COS",PICBED_TENCENTCLOUD_VERSION:"COS版本",PICBED_TENCENTCLOUD_SECRETID:"设定SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"设定SecretKey",PICBED_TENCENTCLOUD_APPID:"设定AppId",PICBED_TENCENTCLOUD_BUCKET:"设定Bucket",PICBED_TENCENTCLOUD_AREA:"设定存储区域",PICBED_TENCENTCLOUD_ENDPOINT:"设定Endpoint",PICBED_TENCENTCLOUD_PATH:"设定存储路径",PICBED_TENCENTCLOUD_OPTIONS:"设定网址后缀",PICBED_TENCENTCLOUD_CUSTOMURL:"设定自定义域名",PICBED_TENCENTCLOUD_SLIM:"极智压缩",PICBED_TENCENTCLOUD_SLIM_TIP:"图片极智压缩,详情请参考[文档说明](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"开启",PICBED_TENCENTCLOUD_SLIM_CANCEL:"关闭",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例如:1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例如:ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例如:cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例如:test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例如:?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"设定Token",PICBED_GITHUB_REPO:"设定仓库名",PICBED_GITHUB_PATH:"设定存储路径",PICBED_GITHUB_BRANCH:"设定分支名",PICBED_GITHUB_CUSTOMURL:"设定自定义域名",PICBED_GITHUB_MESSAGE_REPO:"格式:username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例如:main",PICBED_GITHUB_MESSAGE_PATH:"例如:test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_QINIU:"七牛云",PICBED_QINIU_ACCESSKEY:"设定AccessKey",PICBED_QINIU_SECRETKEY:"设定SecretKey",PICBED_QINIU_BUCKET:"设定Bucket",PICBED_QINIU_PATH:"设定存储路径",PICBED_QINIU_URL:"设定访问网址",PICBED_QINIU_OPTIONS:"设定网址后缀",PICBED_QINIU_AREA:"设定存储区域",PICBED_QINIU_MESSAGE_PATH:"例如:test/",PICBED_QINIU_MESSAGE_AREA:"例如:z0",PICBED_QINIU_MESSAGE_OPTIONS:"例如:?imageslim",PICBED_QINIU_MESSAGE_URL:"例如:https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"设定ClientId",PICBED_IMGUR_PROXY:"设定代理",PICBED_IMGUR_MESSAGE_PROXY:"例如:http://127.0.0.1:1080",PICBED_UPYUN:"又拍云",PICBED_UPYUN_BUCKET:"设定Bucket",PICBED_UPYUN_OPERATOR:"设定操作员",PICBED_UPYUN_PASSWORD:"设定操作员密码",PICBED_UPYUN_PATH:"设定存储路径",PICBED_UPYUN_URL:"设定加速域名",PICBED_UPYUN_OPTIONS:"设定网址后缀",PICBED_UPYUN_MESSAGE_OPERATOR:"例如:me",PICBED_UPYUN_MESSAGE_PASSWORD:"输入操作员密码",PICBED_UPYUN_MESSAGE_URL:"例如:http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例如:!imgslim",PICBED_UPYUN_MESSAGE_PATH:"例如:test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"插件安装成功",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"插件安装失败",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"插件安装失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"插件安装失败,请输入合法插件名或合法安装路径",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"插件卸载成功",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"插件卸载失败",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"插件卸载失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"插件卸载失败,请输入合法插件名",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"插件更新成功",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"插件更新失败",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"插件更新失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"插件更新失败,请输入合法插件名"},"zh-TW":{UPLOAD_FAILED:"上傳失敗",CHECK_SETTINGS:"請檢查你的設定是否正確",CHECK_SETTINGS_AND_NETWORK:"請檢查你的設定及網路",UPLOAD_FAILED_REASON:"錯誤碼:${code},請打開瀏覽器貼上地址查看相關原因",SERVER_ERROR:"伺服器出錯,請重試",AUTH_FAILED:"認證失敗",PICBED_SMMS:"SM.MS",PICBED_SMMS_TOKEN:"設定Token",PICBED_SMMS_BACKUP_DOMAIN:"備用上傳網址",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例如 smms.app",PICBED_ALICLOUD:"阿里云OSS",PICBED_ALICLOUD_ACCESSKEYID:"設定KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"設定KeySecret",PICBED_ALICLOUD_BUCKET:"設定Bucket",PICBED_ALICLOUD_AREA:"設定儲存區域",PICBED_ALICLOUD_PATH:"設定儲存路徑",PICBED_ALICLOUD_CUSTOMURL:"設定自訂網址",PICBED_ALICLOUD_OPTIONS:"設定網址後綴",PICBED_ALICLOUD_MESSAGE_AREA:"例如:oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例如:test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例如:?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD:"騰訊云COS",PICBED_TENCENTCLOUD_VERSION:"COS版本",PICBED_TENCENTCLOUD_SECRETID:"設定SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"設定SecretKey",PICBED_TENCENTCLOUD_APPID:"設定AppId",PICBED_TENCENTCLOUD_BUCKET:"設定Bucket",PICBED_TENCENTCLOUD_AREA:"設定儲存區域",PICBED_TENCENTCLOUD_ENDPOINT:"設定Endpoint",PICBED_TENCENTCLOUD_PATH:"設定儲存路徑",PICBED_TENCENTCLOUD_OPTIONS:"設定網址後綴",PICBED_TENCENTCLOUD_SLIM:"極智壓縮",PICBED_TENCENTCLOUD_SLIM_CANCEL:"關閉",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"開啓",PICBED_TENCENTCLOUD_SLIM_TIP:"圖片極智壓縮,詳情請參考[文檔說明](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_CUSTOMURL:"設定自訂網址",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例如:1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例如:ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例如:cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例如:test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例如:?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"設定Token",PICBED_GITHUB_REPO:"設定倉庫名稱",PICBED_GITHUB_PATH:"設定儲存路徑",PICBED_GITHUB_BRANCH:"設定分支名稱",PICBED_GITHUB_CUSTOMURL:"設定自訂網址",PICBED_GITHUB_MESSAGE_REPO:"格式:username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例如:main",PICBED_GITHUB_MESSAGE_PATH:"例如:test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_QINIU:"七牛云",PICBED_QINIU_ACCESSKEY:"設定AccessKey",PICBED_QINIU_SECRETKEY:"設定SecretKey",PICBED_QINIU_BUCKET:"設定Bucket",PICBED_QINIU_PATH:"設定儲存路徑",PICBED_QINIU_URL:"設定訪問網址",PICBED_QINIU_OPTIONS:"設定網址後綴",PICBED_QINIU_AREA:"設定儲存區域",PICBED_QINIU_MESSAGE_PATH:"例如:test/",PICBED_QINIU_MESSAGE_AREA:"例如:z0",PICBED_QINIU_MESSAGE_OPTIONS:"例如:?imageslim",PICBED_QINIU_MESSAGE_URL:"例如:https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"設定ClientId",PICBED_IMGUR_PROXY:"設定PROXY",PICBED_IMGUR_MESSAGE_PROXY:"例如:http://127.0.0.1:1080",PICBED_UPYUN:"又拍云",PICBED_UPYUN_BUCKET:"設定Bucket",PICBED_UPYUN_OPERATOR:"設定操作員",PICBED_UPYUN_PASSWORD:"設定操作員密碼",PICBED_UPYUN_PATH:"設定儲存路徑",PICBED_UPYUN_URL:"設定加速網址",PICBED_UPYUN_OPTIONS:"設定網址後綴",PICBED_UPYUN_MESSAGE_OPERATOR:"例如:me",PICBED_UPYUN_MESSAGE_PASSWORD:"輸入操作員密碼",PICBED_UPYUN_MESSAGE_URL:"例如:http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例如:!imgslim",PICBED_UPYUN_MESSAGE_PATH:"例如:test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"插件安裝成功",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"插件安裝失敗",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"插件安裝失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"插件安裝失敗,請輸入正確的插件名稱或正確的安裝路徑",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"插件卸載成功",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"插件卸載失敗",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"插件卸載失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"插件卸載失敗,請輸入正確的插件名稱",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"插件更新成功",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"插件更新失敗",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"插件更新失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"插件更新失敗,請輸入正確的插件名稱"},en:{UPLOAD_FAILED:"Upload failed",CHECK_SETTINGS:"Please check your settings",CHECK_SETTINGS_AND_NETWORK:"Please check your settings and network",UPLOAD_FAILED_REASON:"Error code: ${code}, please open the browser and paste the address to see the reason",SERVER_ERROR:"Server error, please try again later",AUTH_FAILED:"Authentication failed",PICBED_SMMS:"SM.MS",PICBED_SMMS_TOKEN:"Set Token",PICBED_SMMS_BACKUP_DOMAIN:"Set Backup Upload Domain",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"Ex. smms.app",PICBED_ALICLOUD:"Ali Cloud",PICBED_ALICLOUD_ACCESSKEYID:"Set KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"Set KeySecret",PICBED_ALICLOUD_BUCKET:"Set Bucket",PICBED_ALICLOUD_AREA:"Set Area",PICBED_ALICLOUD_PATH:"Set Path",PICBED_ALICLOUD_CUSTOMURL:"Set Custom URL",PICBED_ALICLOUD_OPTIONS:"Set URL Suffix",PICBED_ALICLOUD_MESSAGE_AREA:"Ex. oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"Ex. test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"Ex. ?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"Ex. https://test.com",PICBED_TENCENTCLOUD:"Tencent Cloud",PICBED_TENCENTCLOUD_VERSION:"Choose COS version",PICBED_TENCENTCLOUD_SECRETID:"Set SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"Set SecretKey",PICBED_TENCENTCLOUD_APPID:"Set AppId",PICBED_TENCENTCLOUD_BUCKET:"Set Bucket",PICBED_TENCENTCLOUD_AREA:"Set Area",PICBED_TENCENTCLOUD_ENDPOINT:"Set Endpoint",PICBED_TENCENTCLOUD_PATH:"Set Path",PICBED_TENCENTCLOUD_OPTIONS:"Set URL Suffix",PICBED_TENCENTCLOUD_SLIM:"Set ImageSlim",PICBED_TENCENTCLOUD_SLIM_TIP:"Image extremely intelligent compression, please refer to the [document description](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"OPEN",PICBED_TENCENTCLOUD_SLIM_CANCEL:"CLOSE",PICBED_TENCENTCLOUD_CUSTOMURL:"Set Custom URL",PICBED_TENCENTCLOUD_MESSAGE_APPID:"Ex. 1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"Ex. ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"Ex. cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"Ex. test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"Ex. http://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"Ex. ?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"Set Token",PICBED_GITHUB_REPO:"Set Repo Name",PICBED_GITHUB_PATH:"Set Path",PICBED_GITHUB_BRANCH:"Set Branch",PICBED_GITHUB_CUSTOMURL:"Set Custom URL",PICBED_GITHUB_MESSAGE_REPO:"Ex. username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"Ex. main",PICBED_GITHUB_MESSAGE_PATH:"Ex. test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"Ex. https://test.com",PICBED_QINIU:"Qiniu",PICBED_QINIU_ACCESSKEY:"Set AccessKey",PICBED_QINIU_SECRETKEY:"Set SecretKey",PICBED_QINIU_BUCKET:"Set Bucket",PICBED_QINIU_PATH:"Set Path",PICBED_QINIU_URL:"Set URL",PICBED_QINIU_OPTIONS:"Set URL Suffix",PICBED_QINIU_AREA:"Set Area",PICBED_QINIU_MESSAGE_PATH:"Ex. test/",PICBED_QINIU_MESSAGE_AREA:"Ex. z0",PICBED_QINIU_MESSAGE_OPTIONS:"Ex. ?imageslim",PICBED_QINIU_MESSAGE_URL:"Ex. https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"Set ClientId",PICBED_IMGUR_PROXY:"Set Proxy",PICBED_IMGUR_MESSAGE_PROXY:"Ex. http://127.0.0.1:1080",PICBED_UPYUN:"Upyun",PICBED_UPYUN_BUCKET:"Set Bucket",PICBED_UPYUN_OPERATOR:"Set Operator",PICBED_UPYUN_PASSWORD:"Set Operator Password",PICBED_UPYUN_PATH:"Set Path",PICBED_UPYUN_URL:"Set URL",PICBED_UPYUN_OPTIONS:"Set URL Suffix",PICBED_UPYUN_MESSAGE_OPERATOR:"Ex. me",PICBED_UPYUN_MESSAGE_PASSWORD:"Please type the operator password",PICBED_UPYUN_MESSAGE_URL:"Ex. http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"Ex. !imgslim",PICBED_UPYUN_MESSAGE_PATH:"Ex. test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"Plugin installed successfully",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"Plugin installation failed",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"Plugin installation failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"Plugin installation failed, please enter a valid plugin name or valid installation path",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"Plugin uninstalled successfully",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"Plugin uninstall failed",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"Plugin uninstall failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"Plugin uninstall failed, please enter a valid plugin name",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"Plugin updated successfully",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"Plugin update failed",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"Plugin update failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"Plugin update failed, please enter a valid plugin name"}};class Ct{i18n;objectAdapter;ctx;constructor(e){this.ctx=e,this.objectAdapter=new R(ht);let t=this.ctx.getConfig("settings.language")||"zh-CN";ht[t]||(t="zh-CN"),this.i18n=new w({adapter:this.objectAdapter,defaultLanguage:t}),this.loadOutterI18n()}loadOutterI18n(){const n=this.getOutterI18nFolder();e.readdirSync(n,{withFileTypes:!0}).forEach(r=>{if(r.isFile()&&r.name.endsWith(".yml")){const i=t.join(n,r.name),s=e.readFileSync(i,"utf8");try{const e=G.load(s);ht[r.name.replace(/\.yml$/,"")]=e}catch(e){console.error(e)}}})}getOutterI18nFolder(){const n=t.join(this.ctx.baseDir,"i18n-cli");return e.pathExistsSync(n)||e.ensureDirSync(n),n}translate(e,t){return this.i18n.translate(e,t)||e}setLanguage(e){this.i18n.setLanguage(e),this.ctx.saveConfig({"settings.language":e})}addLocale(e,t){const n=this.objectAdapter.getLocale(e);if(!n)return!1;const r=N(n,t);return this.objectAdapter.setLocale(e,r),!0}addLanguage(e,t){return!this.objectAdapter.getLocale(e)&&(this.objectAdapter.setLocale(e,t),ht[e]=t,!0)}getLanguageList(){return Object.keys(ht)}}class Pt extends n{_config;lifecycle;db;_pluginLoader;configPath;baseDir;helper;log;cmd;output;input;pluginHandler;Request;i18n;VERSION="1.6.2";GUI_VERSION;get pluginLoader(){return this._pluginLoader}constructor(e=""){super(),this.configPath=e,this.output=[],this.input=[],this.helper={transformer:new Pe("transformer"),uploader:new Pe("uploader"),beforeTransformPlugins:new Pe("beforeTransformPlugins"),beforeUploadPlugins:new Pe("beforeUploadPlugins"),afterUploadPlugins:new Pe("afterUploadPlugins")},this.initConfigPath(),this.log=new Se(this),this.cmd=new Ne(this),this.pluginHandler=new dt(this),this.initConfig(),this.init()}initConfigPath(){if(""===this.configPath&&(this.configPath=i()+"/.picgo/config.json"),".JSON"!==t.extname(this.configPath).toUpperCase())throw this.configPath="",Error("The configuration file only supports JSON format.");this.baseDir=t.dirname(this.configPath);e.pathExistsSync(this.configPath)||e.ensureFileSync(`${this.configPath}`)}initConfig(){this.db=new It(this),this._config=this.db.read(!0)}init(){try{this.i18n=new Ct(this),this.Request=new _t(this),this._pluginLoader=new it(this),fe("picgo"),et().register(this),{register(e){e.helper.transformer.register("path",nt),e.helper.transformer.register("base64",rt)}}.register(this),fe(""),this._pluginLoader.load(),this.lifecycle=new Ae(this)}catch(e){throw this.emit(De.UPLOAD_PROGRESS,-1),this.log.error(e),e}}use(e,t){if(t)return this.pluginLoader.registerPlugin(t,e),this.pluginLoader.getPlugin(t);return e(this)}registerCommands(){""!==this.configPath&&(this.cmd.init(),this.cmd.loadCommands())}getConfig(e){return e?U(this._config,e):this._config}saveConfig(e){te(e)?(this.setConfig(e),this.db.saveConfig(e)):this.log.warn("the format of config is invalid, please provide object")}removeConfig(e,t){e&&t&&(ee(e)?this.log.warn(`the config.${e} can't be removed`):(this.unsetConfig(e,t),this.db.unset(e,t)))}setConfig(e){te(e)?Object.keys(e).forEach(t=>{ee(t)&&(this.log.warn(`the config.${t} can't be modified`),delete e[t]),D(this._config,t,e[t]),ct.emit(Le.CONFIG_CHANGE,{configName:t,value:e[t]})}):this.log.warn("the format of config is invalid, please provide object")}unsetConfig(e,t){e&&t&&(ee(e)?this.log.warn(`the config.${e} can't be unset`):L(this.getConfig(e),t))}get request(){return this.Request.request.bind(this.Request)}async upload(t){if(""===this.configPath)return this.log.error("The configuration file only supports JSON format."),[];if(void 0!==t&&0!==t.length){const{output:e}=await this.lifecycle.start(t);return e}try{const{imgPath:t,shouldKeepAfterUploading:n}=await lt(this);if("no image"===t)throw new Error("image not found in clipboard");{this.once(De.FAILED,()=>{n||e.remove(t).catch(e=>{this.log.error(e)})}),this.once("finished",()=>{n||e.remove(t).catch(e=>{this.log.error(e)})});const{output:r}=await this.lifecycle.start([t]);return r}}catch(e){throw this.emit(De.FAILED,e),e}}}export{Ne as Commander,De as IBuildInEvent,Le as IBusEvent,Ue as ILogType,Ae as Lifecycle,Pe as LifecyclePlugins,Se as Logger,Pt as PicGo,se as PicGoUtils,dt as PluginHandler,it as PluginLoader,_t as Request};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|
package/dist/types/index.d.ts
CHANGED
|
@@ -229,10 +229,10 @@ export interface IImgInfo {
|
|
|
229
229
|
extname?: string;
|
|
230
230
|
imgUrl?: string;
|
|
231
231
|
mimeType?: string;
|
|
232
|
+
filePath?: string;
|
|
232
233
|
[propName: string]: any;
|
|
233
234
|
}
|
|
234
235
|
export interface IPathTransformedImgInfo extends IImgInfo {
|
|
235
|
-
filePath?: string;
|
|
236
236
|
success: boolean;
|
|
237
237
|
}
|
|
238
238
|
export interface IStringKeyMap<T> {
|