piclist
Version:
Modified PicGo core, A tool for picture uploading
1 lines • 719 kB
JavaScript
import{EventEmitter as e}from"events";import t,{readFile as r,readJSONSync as n,ensureDirSync as i,createFileSync as a,emptyDirSync as s,removeSync as o,moveSync as E,pathExistsSync as S,ensureFileSync as I,remove as _}from"fs-extra";import{cloneDeep as l,merge as P,get as c,set as u,unset as p}from"lodash";import A,{homedir as C}from"os";import D from"path";import{Command as T}from"commander";import d from"inquirer";import{imageSize as g}from"image-size";import m,{URL as L}from"url";import h from"text-to-svg";import f from"sharp";import B from"crypto";import{v4 as N}from"uuid";import U from"chalk";import R from"download-git-repo";import{sync as O}from"rimraf";import M from"minimatch";import y from"globby";import{render as G}from"ejs";import w from"dayjs";import b from"util";import{spawn as x}from"cross-spawn";import{sync as W}from"resolve";import v from"axios";import F from"form-data";import H from"https";import{httpsOverHttp as K}from"tunnel";import $ from"heic-convert";import{lookup as k}from"mime-types";import{S3Client as Y,PutObjectCommand as V,GetObjectCommand as j}from"@aws-sdk/client-s3";import{getSignedUrl as q}from"@aws-sdk/s3-request-presigner";import{NodeHttpHandler as z}from"@smithy/node-http-handler";import X from"file-type";import Q from"mime";import{HttpsProxyAgent as Z,HttpProxyAgent as J}from"hpagent";import ee from"qiniu";import{NodeSSH as te}from"node-ssh-no-cpu-features";import{AuthType as re,createClient as ne}from"webdav";import{spawn as ie}from"child_process";import ae from"is-wsl";import{JSONStore as se}from"@picgo/store";import oe from"js-yaml";import{ObjectAdapter as Ee,I18n as Se}from"@picgo/i18n";const Ie=(e,t,r,n,i,a)=>{let s=e.program.command(t).description(r).alias(n);(null==a?void 0:a.proxy)&&(s=s.option("-p, --proxy <proxy>","Add proxy for installing plugins")),(null==a?void 0:a.registry)&&(s=s.option("-r, --registry <registry>","Choose a registry for installing plugins")),s.action(i)},_e={handle:e=>{const t=e.cmd;Ie(t,"install <plugins...>","install picgo plugin","add",((t,r)=>{const{proxy:n,registry:i}=r,a={proxy:n,registry:i};e.pluginHandler.install(t,a).catch((t=>{e.log.error(t)}))}),{proxy:!0,registry:!0}),Ie(t,"uninstall <plugins...>","uninstall picgo plugin","rm",(t=>{e.pluginHandler.uninstall(t).catch((t=>{e.log.error(t)}))})),Ie(t,"update <plugins...>","update picgo plugin","up",((t,r)=>{const{proxy:n,registry:i}=r,a={proxy:n,registry:i};e.pluginHandler.update(t,a).catch((t=>{e.log.error(t)}))}),{proxy:!0,registry:!0})}},le={handle:e=>{e.cmd.program.option("-c, --config <path>","set config path")}};function Pe(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";return Array.from({length:e}).map((()=>t.charAt(Math.floor(Math.random()*t.length)))).join("")}function ce(e){return 1===e.toString().length?`0${e}`:e.toString()}function ue(e){return B.createHash("md5").update(e).digest("hex")}function pe(e,t,r,n){const i=new Date,a=i.getFullYear().toString(),s=D.basename(e,D.extname(e)),o={"{Y}":()=>a,"{y}":()=>a.slice(2),"{m}":()=>ce(i.getMonth()+1),"{d}":()=>ce(i.getDate()),"{h}":()=>ce(i.getHours()),"{i}":()=>ce(i.getMinutes()),"{s}":()=>ce(i.getSeconds()),"{ms}":()=>i.getMilliseconds().toString().padStart(3,"0"),"{md5}":()=>ue(n||s),"{md5-16}":()=>ue(n||s).slice(0,16),"{filename}":()=>r?D.basename(r,D.extname(r)):s,"{uuid}":()=>N().replace(/-/g,""),"{timestamp}":()=>i.getTime().toString()};if(void 0===t||!Object.keys(o).some((e=>t.includes(e)))&&!t.includes("localFolder:")&&!t.includes("str-"))return e;const E=D.extname(e);let S=Object.keys(o).reduce(((e,t)=>e.replace(new RegExp(t,"g"),o[t]())),t)+E;return S=S.replace(/{str-(\d+)}/gi,((e,t)=>Pe(parseInt(t,10)))),S=S.replace(/{(localFolder:?(\d+)?)}/gi,((t,r,n)=>{n=Math.max(1,n||0);return D.dirname(e).split(D.sep).slice(0-n).reduce(((e,t)=>`${e}/${t}`)).replace(/:/g,"")})),S}const Ae=e=>/^https?:\/\//.test(e),Ce=e=>{e=e||"";try{return e!==decodeURI(e)}catch(e){return!1}},De=e=>(Ce(e)||(e=encodeURI(e)),e),Te=e=>{try{const{width:t=0,height:r=0,type:n}=g(e);return{real:!0,width:t,height:r,extname:n?`.${n}`:".png"}}catch(e){return{real:!1,width:200,height:200,extname:".png"}}},de=async e=>{try{return{extname:D.extname(e),fileName:D.basename(e),buffer:await r(e),success:!0}}catch(t){return{reason:`read file ${e} error`,success:!1}}},ge=async(e,t)=>{let r;e=De(e);const n=new Promise(((n,i)=>{(async()=>{var i;try{const i=await t.request({method:"get",url:e,resolveWithFullResponse:!0,responseType:"arraybuffer"}).then((e=>e.data));clearTimeout(r);const a=new L(e).pathname;let s="";try{s=new L(e).searchParams.get("wx_fmt")||D.extname(a)||""}catch(e){s=D.extname(a)||""}!s.startsWith(".")&&s&&(s=`.${s}`),n({buffer:i,fileName:D.basename(a),extname:s,success:!0})}catch(t){clearTimeout(r),n({success:!1,reason:`request ${e} error, ${null!==(i=null==t?void 0:t.message)&&void 0!==i?i:""}`})}})().catch(i)})),i=new Promise((t=>{r=setTimeout((()=>{t({success:!1,reason:`request ${e} timeout`})}),3e4)}));return Promise.race([n,i])},me=e=>/^@[^/]+\/picgo-plugin-/.test(e)?"scope":e.startsWith("picgo-plugin-")?"normal":Le(e)?"simple":"unknown",Le=e=>{if(D.isAbsolute(e))return!1;const r=D.join(process.cwd(),e);return!t.existsSync(r)&&(!e.includes("/")&&!e.includes("\\"))},he=(e,t="")=>t?`@${t}/picgo-plugin-${e}`:`picgo-plugin-${e}`,fe=(e,r=console)=>{switch(me(e)){case"normal":case"scope":return e;case"simple":return he(e);default:{let n=e;return D.isAbsolute(e)&&t.existsSync(e)?Ne(n):(n=D.join(process.cwd(),e),t.existsSync(n)?Ne(n):(r.warn(`Can't find plugin ${e}`),""))}}},Be=(e,r=console)=>{var i;switch(me(e)){case"normal":return Ue(e);case"scope":return Ue(e,!0);case"simple":return Ue(he(e));default:{if(!t.existsSync(e))return r.warn(`Can't find plugin: ${e}`),"";const a=D.posix.join(e,"package.json");if(t.existsSync(a)){const e=n(a)||{};return(null===(i=e.name)||void 0===i?void 0:i.includes("picgo-plugin-"))?e.name:(r.warn(`The plugin package.json's name filed is ${e.name||"empty"}, need to include the prefix: picgo-plugin-`),"")}return r.warn(`Can't find plugin: ${e}`),""}}},Ne=e=>e.split(D.sep).join("/"),Ue=(e,t=!1)=>{if(e.includes("@")){let r=/(.+\/)?(picgo-plugin-\w+)(@.+)*/;t&&(r=/(.+\/)?(^@[^/]+\/picgo-plugin-\w+)(@.+)*/);const n=e.match(r);return n?n[2]:(console.warn("can not remove plugin version"),e)}return e},Re=[],Oe=e=>Re.some((t=>e.startsWith(t))),Me=e=>"object"==typeof e&&!Array.isArray(e)&&Object.keys(e).length>0;function ye(e){try{return JSON.parse(e)}catch(t){return e}}const Ge=(e=0)=>isNaN(Number(e))?0:Number(e),we=()=>"development"===process.env.NODE_ENV;const be=D.join(__dirname,"assets","piclist.png");async function xe(e,t,r,n,i,a,s,o,E,S,I){o=!o||o<0||o>1?.15:o;const _=f(e,{animated:!0}),{width:l=200}=await _.metadata(),P=await async function(e,t,r,n,i,a,s,o=200,E=0){let S;"image"===e?(s=s||be,S=await f(s).toBuffer()):S=await async function(e,t,r,n){t=t||"测试",n=n||e;const i={anchor:"top",attributes:{fill:r=r||"rgba(204, 204, 204, 0.45)"}},a=h.loadSync(n).getSVG(t,i);return Buffer.from(a)}(t,r,a,n||t);const{width:I,height:_}=await async function(e){const{width:t,height:r}=await f(e).metadata();return{width:t||200,height:r||200}}(S),l=Math.floor(o*Ge(i)),P=Math.floor(l*_/I);return await f(S).resize(l,P,{fit:"inside"}).rotate(E,{background:{r:255,g:255,b:255,alpha:0}}).toBuffer()}(t,r,a,s,o,E,S,l,i);return await _.composite([{input:P,gravity:I||"southeast",tile:n}]).toBuffer()}const We=(...e)=>e.every((e=>null!=e&&("string"==typeof e?""!==e:"number"==typeof e?e>0:"object"!=typeof e||Object.keys(e).length>0))),ve=["avif","dz","fits","gif","heif","input","jpeg","jpg","jp2","jxl","magick","openslide","pdf","png","ppm","raw","svg","tiff","tif","v","webp"],Fe=["jpg","jpeg","png","webp","bmp","tiff","tif","svg","ico","avif","heif","heic","gif"],He=e=>ve.includes(e);async function Ke(e,t,r,n){try{let n=f(e,{animated:!0});return n=f(await xe(e,t.watermarkType||"text",r,t.isFullScreenWatermark,Ge(t.watermarkDegree),t.watermarkText,t.watermarkFontPath,Ge(t.watermarkScaleRatio),t.watermarkColor,t.watermarkImagePath,t.watermarkPosition),{animated:!0}),await n.toBuffer()}catch(t){return n.error(`Image add watermark error: ${t}`),e}}function $e(e){const t="string"==typeof e.formatConvertObj?ye(e.formatConvertObj):e.formatConvertObj;return{quality:Ge(e.quality),isConvert:e.isConvert||!1,convertFormat:e.convertFormat||"jpg",isReSize:e.isReSize||!1,reSizeHeight:Ge(e.reSizeHeight),reSizeWidth:Ge(e.reSizeWidth),skipReSizeOfSmallImg:e.skipReSizeOfSmallImg||!1,isReSizeByPercent:e.isReSizeByPercent||!1,reSizePercent:Ge(e.reSizePercent),isRotate:e.isRotate||!1,isFlip:e.isFlip||!1,isFlop:e.isFlop||!1,rotateDegree:Ge(e.rotateDegree),picBed:e.picBed||"smms",formatConvertObj:t||{}}}async function ke(e,t,r,n){t=$e(t);try{if(r=Ye(r),!Fe.includes(r)||"gif"===r)return e;let n=f(e,{animated:!0}),i=100;if(We(t.quality)&&t.quality<100&&(i=Math.min(Math.max(Math.round(t.quality),1),100)),t.isReSizeByPercent){if(We(t.reSizePercent)){const e=await n.metadata().then((e=>e.width)),r=await n.metadata().then((e=>e.height));e&&r&&(n=n.resize(Math.round(e*t.reSizePercent/100),Math.round(r*t.reSizePercent/100),{fit:"inside"}))}}else if(t.isReSize)if("number"==typeof t.reSizeHeight&&t.reSizeHeight>0&&"number"==typeof t.reSizeWidth&&t.reSizeWidth>0)n=n.resize(t.reSizeWidth,t.reSizeHeight,{fit:"fill"});else if("number"==typeof t.reSizeHeight&&t.reSizeHeight>0&&("number"!=typeof t.reSizeWidth||0===t.reSizeWidth)){const e=await n.metadata().then((e=>e.width)),r=await n.metadata().then((e=>e.height));if(e&&r&&(!t.skipReSizeOfSmallImg||t.skipReSizeOfSmallImg&&t.reSizeHeight<r)){const i=t.reSizeHeight/r;n=n.resize(Math.round(e*i),t.reSizeHeight,{fit:"inside"})}}else if("number"==typeof t.reSizeWidth&&t.reSizeWidth>0&&("number"!=typeof t.reSizeHeight||0===t.reSizeHeight)){const e=await n.metadata().then((e=>e.width)),r=await n.metadata().then((e=>e.height));if(e&&r&&(!t.skipReSizeOfSmallImg||t.skipReSizeOfSmallImg&&t.reSizeWidth<e)){const i=t.reSizeWidth/e;n=n.resize(t.reSizeWidth,Math.round(r*i),{fit:"inside"})}}if(t.isRotate&&t.rotateDegree&&(n=n.rotate(t.rotateDegree,{background:{r:255,g:255,b:255,alpha:0}})),t.isFlip&&(n=n.flip()),t.isFlop&&(n=n.flop()),t.isConvert){const e=Ve(t,r);e!==r&&(n=n.toFormat(e,{quality:i,mozjpeg:!0}))}else n=r&&He(r)?n.toFormat(r,{quality:i,mozjpeg:!0}):n.toFormat("jpg",{quality:i,mozjpeg:!0});return await n.toBuffer()}catch(t){return n.error(`Image process error: ${t}`),e}}const Ye=e=>e.toLowerCase().replace(".","");function Ve(e,t){if(e=$e(e||{}),"gif"===(t=Ye(t)))return"gif";let r=(null==e?void 0:e.convertFormat)||"jpg";if((null==e?void 0:e.formatConvertObj)&&Object.keys(e.formatConvertObj).length>0){const n=e.formatConvertObj;Object.keys(n).includes(t)&&(r=n[t],He(r)||(r="jpg"))}return"imgur"===(null==e?void 0:e.picBed)&&"webp"===r&&(r="jpg"),r}const je=(e,t)=>(t=Ye(t),!!e&&!!e.isAddWatermark&&Fe.includes(t)&&"svg"!==t),qe=(e,t)=>{if(!Fe.includes(Ye(t))||!e)return!1;const{quality:r,isReSizeByPercent:n,reSizePercent:i,isReSize:a,reSizeHeight:s,reSizeWidth:o,isRotate:E,rotateDegree:S,isConvert:I,convertFormat:_,isFlip:l,isFlop:P}=$e(e);if(We(r)&&r<100)return!0;if(n&&We(i))return!0;if(a&&("number"==typeof s&&s>0||"number"==typeof o&&o>0))return!0;if(E&&S)return!0;if(l||P)return!0;if(I){return t!==(_||"jpg")}return!1},ze=async(e,t)=>(t=Ye(t),Fe.includes(t)&&"svg"!==t?await f(e,{animated:!0}).toBuffer():e);var Xe=Object.freeze({__proto__:null,randomStringGenerator:Pe,renameFileNameWithTimestamp:function(e){return`${Math.floor(Date.now()/1e3)}${Pe(5)}${D.extname(e)}`},renameFileNameWithRandomString:function(e,t=5){return`${Pe(t)}${D.extname(e)}`},renameFileNameWithCustomString:pe,isUrl:Ae,isUrlEncode:Ce,handleUrlEncode:De,getImageSize:Te,getFSFile:de,getURLFile:ge,getPluginNameType:me,isSimpleName:Le,handleStreamlinePluginName:e=>/^@[^/]+\/picgo-plugin-/.test(e)?e.replace(/^@[^/]+\/picgo-plugin-/,""):e.replace(/picgo-plugin-/,""),handleCompletePluginName:he,getProcessPluginName:fe,getNormalPluginName:Be,handleUnixStylePath:Ne,removePluginVersion:Ue,configBlackList:Re,isConfigKeyInBlackList:Oe,isInputConfigValid:Me,safeParse:ye,forceNumber:Ge,isDev:we,AddWatermark:xe,imageAddWaterMark:Ke,imageCompress:ke,getConvertedFormat:Ve,isNeedAddWatermark:je,isNeedCompress:qe,removeExif:ze});const Qe={handle:e=>{e.cmd.program.command("upload").description("upload, go go go").arguments("[input...]").alias("u").action((r=>{(async()=>{const n=r.map((e=>Ae(e)?e:D.resolve(e))).filter((r=>{const n=t.existsSync(r)||Ae(r);return n||e.log.warn(`${r} does not exist.`),n}));await e.upload(n)})().catch((t=>{e.log.error(t)}))}))}};function Ze({path:e,startSlash:t=!1,endSlash:r=!0,rootToEmpty:n=!0}){const i=null==e?void 0:e.replace(/^\/+|\/+$/g,"").replace(/\/{2,}/g,"/");return i?`${t?"/":""}${i}${r?"/":""}`:n?"":"/"}function Je(e){return e.replace(/\/{2,}/g,"/").split("/").map((e=>encodeURIComponent(e))).join("/")}const et="advancedplist",tt="alistplist",rt="aliyun",nt="aws-s3-plist",it="github",at="imgur",st="local",ot="lskyplist",Et="piclist",St="qiniu",It="sftpplist",_t="smms",lt="tcyun",Pt="upyun",ct="webdavplist",ut=(e,t,r,n,i,a,s="PICBED",o)=>Object.assign({name:r,type:n,get prefix(){return e.i18n.translate(`${s}_${t.toUpperCase()}_${r.toUpperCase()}`)},get alias(){return e.i18n.translate(`${s}_${t.toUpperCase()}_${r.toUpperCase()}`)},default:i,required:a},o);const pt=e=>({advancedplist:e.i18n.translate("PICBED_ADVANCEDPLIST"),alistplist:e.i18n.translate("PICBED_ALIST_PLIST"),aliyun:e.i18n.translate("PICBED_ALICLOUD"),"aws-s3-plist":e.i18n.translate("PICBED_AWSS3PLIST"),github:e.i18n.translate("PICBED_GITHUB"),imgur:e.i18n.translate("PICBED_IMGUR"),local:e.i18n.translate("PICBED_LOCAL"),lskyplist:e.i18n.translate("PICBED_LSKY_PLIST"),piclist:e.i18n.translate("PICBED_PICLIST"),qiniu:e.i18n.translate("PICBED_QINIU"),sftpplist:e.i18n.translate("PICBED_SFTPPLIST"),smms:e.i18n.translate("PICBED_SMMS"),tcyun:e.i18n.translate("PICBED_TENCENTCLOUD"),upyun:e.i18n.translate("PICBED_UPYUN"),webdavplist:e.i18n.translate("PICBED_WEBDAVPLIST")}),At={compress:{config:{config:e=>{const t=e.getConfig("buildIn.compress")||{};return[ut(e,"compress","quality","input",t.quality||100,!1,"BUILDIN"),ut(e,"compress","isConvert","confirm",t.isConvert||!1,!1,"BUILDIN"),ut(e,"compress","convertFormat","list",t.convertFormat||"jpg",!1,"BUILDIN",{choices:["avif","dz","fits","gif","heif","input","jpeg","jpg","jp2","jxl","magick","openslide","pdf","png","ppm","raw","svg","tiff","tif","v","webp"]}),ut(e,"compress","isReSize","confirm",t.isReSize||!1,!1,"BUILDIN"),ut(e,"compress","reSizeWidth","input",t.reSizeWidth||500,!1,"BUILDIN"),ut(e,"compress","reSizeHeight","input",t.reSizeHeight||500,!1,"BUILDIN"),ut(e,"compress","skipReSizeOfSmallImg","confirm",t.skipReSizeOfSmallImg||!1,!1,"BUILDIN"),ut(e,"compress","isReSizeByPercent","confirm",t.isReSizeByPercent||!1,!1,"BUILDIN"),ut(e,"compress","reSizePercent","input",t.reSizePercent||50,!1,"BUILDIN"),ut(e,"compress","isFlip","confirm",t.isFlip||!1,!1,"BUILDIN"),ut(e,"compress","isFlop","confirm",t.isFlop||!1,!1,"BUILDIN"),ut(e,"compress","isRotate","confirm",t.isRotate||!1,!1,"BUILDIN"),ut(e,"compress","rotateDegree","input",t.rotateDegree||90,!1,"BUILDIN"),ut(e,"compress","isRemoveExif","confirm",t.isRemoveExif||!1,!1,"BUILDIN")]}}.config,key:"BUILDIN_COMPRESS"},watermark:{config:{config:e=>{const t=e.getConfig("buildIn.watermark")||{};return[ut(e,"watermark","isAddWatermark","confirm",t.isAddWatermark||!1,!1,"BUILDIN"),ut(e,"watermark","watermarkType","list",t.watermarkType||"text",!1,"BUILDIN",{choices:["text","image"]}),ut(e,"watermark","isFullScreenWatermark","confirm",t.isFullScreenWatermark||!1,!1,"BUILDIN"),ut(e,"watermark","watermarkDegree","input",t.watermarkDegree||0,!1,"BUILDIN"),ut(e,"watermark","watermarkText","input",t.watermarkText||"",!1,"BUILDIN"),ut(e,"watermark","watermarkFontPath","input",t.watermarkFontPath||"",!1,"BUILDIN"),ut(e,"watermark","watermarkScaleRatio","input",t.watermarkScaleRatio||.15,!1,"BUILDIN"),ut(e,"watermark","watermarkColor","input",t.watermarkColor||"rgba(204, 204, 204, 0.45)",!1,"BUILDIN"),ut(e,"watermark","watermarkImagePath","input",t.watermarkImagePath||"",!1,"BUILDIN"),ut(e,"watermark","watermarkPosition","list",t.watermarkPosition||"southeast",!1,"BUILDIN",{choices:["north","northeast","southeast","south","southwest","northwest","west","east","center","centre"]})]}}.config,key:"BUILDIN_WATERMARK"},rename:{config:{config:e=>{const t=e.getConfig("buildIn.rename")||{};return[ut(e,"rename","format","input",t.format||"{filename}",!1,"BUILDIN"),ut(e,"rename","enable","confirm",t.enable||!1,!1,"BUILDIN")]}}.config,key:"BUILDIN_RENAME"},skipProcess:{config:{config:e=>{const t=e.getConfig("buildIn.skipProcess")||{};return[ut(e,"skipProcess","skipProcessExtList","input",t.skipProcessExtList||"zip,rar,7z,tar,gz,tar.gz,tar.bz2,tar.xz",!1,"BUILDIN")]}}.config,key:"BUILDIN_SKIPPROCESS"}},Ct=async(e,t,r,n)=>{const i=await e.cmd.inquirer.prompt(t),a=Dt(r,n);e.saveConfig({[a]:i}),"uploader"===r?e.saveConfig({"picBed.current":n,"picBed.uploader":n}):"transformer"===r&&e.saveConfig({"picBed.transformer":n})},Dt=(e,t)=>({uploader:`picBed.${t}`,transformer:`transformer.${t}`,buildin:`buildIn.${t}`}[e]||t),Tt={handle:e=>{e.cmd.program.command("set").alias("config").arguments("<module> [name]").description("configure config of picgo modules, uploader|transformer|plugin|buildin").action(((t,r)=>{(async()=>{try{switch(t){case"buildin":await(async(e,t)=>{if(t&&t in At){const r=At[t];return void await Ct(e,r.config(e),"buildin",t)}const r=[{type:"list",name:"buildin",choices:Object.entries(At).map((([t,{key:r}])=>({name:e.i18n.translate(r),value:t}))),message:"Choose a buildin module"}],n=await e.cmd.inquirer.prompt(r),i=At[n.buildin];await Ct(e,i.config(e),"buildin",n.buildin)})(e,r);break;case"uploader":case"transformer":await(async(e,t,r)=>{if(r){const n=e.helper[t].get(r);return n?void(n.config&&await Ct(e,n.config(e),t,r)):void e.log.error(`No ${t} named ${r}`)}const n=e.helper[t].getIdList().map((t=>({name:pt(e)[t]||t,value:t}))),i=[{type:"list",name:t,choices:n,message:`Choose a(n) ${t}`}],a=await e.cmd.inquirer.prompt(i),s=e.helper[t].get(a[t]);(null==s?void 0:s.config)&&await Ct(e,s.config(e),t,a[t])})(e,t,r);break;case"plugin":await(async(e,t)=>{if(t){const r=t.includes("picgo-plugin-")?t:`picgo-plugin-${t}`;if(!Object.keys(e.getConfig("picgoPlugins")).includes(r))return void e.log.error(`No plugin named ${r}`);const n=e.pluginLoader.getPlugin(r);return void((null==n?void 0:n.config)&&await Ct(e,n.config(e),"plugin",r))}const r=[{type:"list",name:"plugin",choices:e.pluginLoader.getFullList(),message:"Choose a plugin"}],n=await e.cmd.inquirer.prompt(r),i=e.pluginLoader.getPlugin(n.plugin);(null==i?void 0:i.config)&&await Ct(e,i.config(e),"plugin",n.plugin)})(e,r);break;default:return e.log.warn(`No module named ${t}`),void e.log.warn("Available modules are uploader|transformer|plugin|buildin")}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)}))}))}},dt={handle:async e=>{const t=e.cmd;t.program.command("use").arguments("[module]").description("use modules of picgo").action((r=>{(async()=>{try{let n=[];const i={uploader:{type:"list",name:"uploader",message:"Use an uploader",choices:e.helper.uploader.getIdList().map((t=>({name:pt(e)[t]||t,value:t}))),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(r){if(!i[r])return e.log.warn(`No module named ${r}`),void e.log.warn("Available modules are uploader|transformer|plugins");n.push(i[r])}else n=Object.keys(i).map((e=>i[e]));const a=await t.inquirer.prompt(n);if(a.plugins){const t=e.getConfig("picgoPlugins");Object.keys(t).forEach((e=>{a.plugins.includes(e)?t[e]=!0:t[e]=!1})),e.saveConfig({picgoPlugins:t})}e.saveConfig({"picBed.current":a.uploader||e.getConfig("picBed.current"),"picBed.uploader":a.uploader||e.getConfig("picBed.current"),"picBed.transformer":a.transformer||"path"}),e.log.success("Configure saved successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}})().catch((t=>{e.log.error(t)}))}))}},gt={handle:e=>{e.cmd.program.option("-p, --proxy <url>","set proxy for uploading",(t=>{e.setConfig({"picBed.proxy":t})}))}},mt=async(e,t)=>{try{const r=ht(t.tmp),n=D.join(t.tmp,"template");let i={};r.prompts&&r.prompts.length>0&&(i=await e.cmd.inquirer.prompt(r.prompts));let a=await y(["**/*"],{cwd:n,dot:!0});if(a=a.filter((t=>{let n="";return Object.keys(r.filters).forEach((e=>{M(t,e,{dot:!0})&&(n=t)})),!n||Lt(e,r.filters[n],i)})),0===a.length)return void e.log.warn("Template files not found!");const s=ft(a,n,i);Bt(t.dest,s),"function"==typeof r.complete&&r.complete({answers:i,options:t,files:a,ctx:e}),r.completeMessage&&e.log.success(r.completeMessage),e.log.success("Done!")}catch(t){e.log.error(t)}},Lt=(e,t,r)=>{const n=new Function("data","with (data) { return "+t+"}");try{return n(r)}catch(r){return e.log.error(`Error when evaluating filter condition: ${JSON.stringify(t)}`),!1}},ht=e=>{const r=D.join(e,"index.js");if(t.existsSync(r)){return require(r)}return{}},ft=(e,r,n)=>{const i={};return e.forEach((e=>{const a=t.readFileSync(D.join(r,e),"utf8"),s=G(a,n);(Buffer.isBuffer(s)||/[^\s]/.test(s))&&(i[e]=s)})),i},Bt=(e,r)=>{Object.keys(r).forEach((n=>{const a=D.join(e,n);i(D.dirname(a)),t.writeFileSync(a,r[n])}))},Nt=(e,r)=>{r.offline?t.existsSync(r.template)?mt(e,r).catch((t=>{e.log.error(t)})):e.log.error(`Local template ${r.template} not found`):(r.template=r.hasSlash?r.template:"PicGo/picgo-template-"+r.template,Ut(e,r))},Ut=(e,r)=>{t.existsSync(r.tmp)&&O(r.tmp),e.log.info("Template files are downloading..."),R(r.template,r.tmp,{clone:r.clone},(t=>{t?e.log.error(t):(e.log.success("Template files are downloaded!"),mt(e,r).catch((t=>{e.log.error(t)})))}))},Rt={handle:async e=>{e.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,n,i)=>{(async()=>{try{const a=r.includes("/"),s=!n||"."===n,o=D.resolve(n||"."),E=i.clone||!1,S=i.offline||!1,I=D.join(C(),".piclist/templates",r.replace(/[/:]/g,"-"));i.offline&&(r=I);const _={template:r,project:n,hasSlash:a,inPlace:s,dest:o,clone:E,tmp:I,offline:S};s||t.existsSync(o)?await e.cmd.inquirer.prompt([{type:"confirm",message:s?"Generate project in current directory?":"Target directory exists. Continue?",name:"ok"}]).then((t=>{t.ok&&Nt(e,_)})):Nt(e,_)}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}})().catch((t=>{e.log.error(t)}))})).on("--help",(()=>{console.log(),console.log("Examples:"),console.log(),console.log(U.gray(" # create a new project with an official template")),console.log(" $ picgo init plugin my-project"),console.log(),console.log(U.gray(" # create a new project straight from a github template")),console.log(" $ picgo init username/repo my-project"),console.log()}))}},Ot={handle:e=>{e.cmd.program.command("i18n").arguments("[lang]").description("change language, zh-CN, zh-TW, en").action((async(t="")=>{const r=e.i18n.getLanguageList();if(!t){const n=[{type:"list",name:"i18n",choices:r,message:"Choose a language",default:e.getConfig("settings.language")||"zh-CN"}];t=(await e.cmd.inquirer.prompt(n)).i18n}r.includes(t)?(e.i18n.setLanguage(t),e.log.success(`Language set to ${t}`)):e.log.warn("No such language")}))}};class Mt{constructor(e){this.name=e,this.list=new Map,this.pluginIdMap=new Map}register(e,t){var r;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),Mt.currentPlugin&&(this.pluginIdMap.has(Mt.currentPlugin)?null===(r=this.pluginIdMap.get(Mt.currentPlugin))||void 0===r||r.push(e):this.pluginIdMap.set(Mt.currentPlugin,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);null==t||t.forEach((e=>{this.list.delete(e)}))}}getName(){return this.name}get(e){return this.list.get(e)}getList(){return[...this.list.values()]}getIdList(){return[...this.list.keys()]}}const yt=(e=null)=>{Mt.currentPlugin=e};class Gt{constructor(e){this.name="commander",this.list=new Map,this.pluginIdMap=new Map,this.program=new T,this.inquirer=d,this.ctx=e}getName(){return this.name}init(){var e;this.program.version("1.9.14","-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",_e),e.cmd.register("config",le),e.cmd.register("setting",Tt),e.cmd.register("upload",Qe),e.cmd.register("use",dt),e.cmd.register("proxy",gt),e.cmd.register("init",Rt),e.cmd.register("i18n",Ot)}register(e,t){var r;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=Mt.currentPlugin;null!==n&&(this.pluginIdMap.has(n)?null===(r=this.pluginIdMap.get(n))||void 0===r||r.push(e):this.pluginIdMap.set(n,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);null==t||t.forEach((e=>{this.list.delete(e)}))}}loadCommands(){this.getList().forEach((e=>{try{e.handle(this.ctx)}catch(e){this.ctx.log.error(e)}}))}get(e){return this.list.get(e)}getList(){return[...this.list.values()]}getIdList(){return[...this.list.keys()]}}var wt,bt,xt;!function(e){e.success="success",e.info="info",e.warn="warn",e.error="error"}(wt||(wt={})),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"}(bt||(bt={})),function(e){e.CONFIG_CHANGE="CONFIG_CHANGE"}(xt||(xt={}));class Wt{constructor(e){this.level={[wt.success]:"green",[wt.info]:"blue",[wt.warn]:"yellow",[wt.error]:"red"},this.ctx=e}handleLog(e,...t){if(this.logLevel=this.ctx.getConfig("settings.logLevel"),!this.ctx.getConfig("silent")&&this.checkLogLevel(e,this.logLevel)){const r=U[this.level[e]](`[PicList ${e.toUpperCase()}]:`);console.log(r,...t),this.logPath=this.ctx.getConfig("settings.logPath")||D.join(this.ctx.baseDir,"./piclist.log"),setTimeout((()=>{try{const r=this.checkLogFileIsLarge(this.logPath);if(r.isLarge){const e=`Log file is too large (> ${r.logFileSizeLimit/1024/1024||"10"} MB), recreate log file`;console.log(U.yellow("[PicList WARN]:"),e),this.recreateLogFile(this.logPath),t.unshift(e)}this.handleWriteLog(this.logPath,e,...t)}catch(e){console.error("[PicList Error] on checking log file size",e)}}),0)}}checkLogFileIsLarge(e){if(t.existsSync(e)){const r=t.statSync(e).size,n=1024*Ge(this.ctx.getConfig("settings.logFileSizeLimit")||10)*1024;return{isLarge:r>n,logFileSize:r,logFileSizeLimit:n}}return{isLarge:!1}}recreateLogFile(e){t.existsSync(e)&&(t.unlinkSync(e),a(e))}handleWriteLog(e,r,...n){try{let i=`${w().format("YYYY-MM-DD HH:mm:ss")} [PicList ${r.toUpperCase()}] `;n.forEach((e=>{e instanceof Error&&"error"===r?i+=`\n------Error Stack Begin------\n${b.format(null==e?void 0:e.stack)}\n-------Error Stack End------- `:("object"==typeof e&&(e=JSON.stringify(e,null,2)),i+=`${e} `)})),i+="\n",t.appendFileSync(e,i)}catch(e){console.error("[PicList 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){this.handleLog(wt.success,...e)}info(...e){this.handleLog(wt.info,...e)}error(...e){this.handleLog(wt.error,...e)}warn(...e){this.handleLog(wt.warn,...e)}debug(...e){we()&&this.handleLog(wt.info,...e)}}class vt{constructor(e){this.ctx=e}async install(e,t={},r){const n=[],i=e.map((e=>Ft(this.ctx,e))).filter((e=>this.ctx.pluginLoader.hasPlugin(e.pkgName)?(n.push(e.pkgName),this.ctx.log.success(`PicList has already installed ${e.pkgName}`),!1):!!e.success)),a=i.map((e=>e.fullName)),s=i.map((e=>e.pkgName));if(a.length>0){const e=await this.execCommand("install",a,this.ctx.baseDir,t,r);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}}s.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:[...s,...n]});return{success:!0,body:[...s,...n]}}if(0===n.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:[...s,...n]});return{success:!0,body:[...s,...n]}}async uninstall(e){const t=e.map((e=>Ft(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={},r){const n=e.map((e=>Ft(this.ctx,e))).filter((e=>e.success)).map((e=>e.pkgName));if(n.length>0){const e=await this.execCommand("update",n,this.ctx.baseDir,t,r);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:n});return{success:!0,body:n}}{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,r,n={},i={}){const a=n.registry||this.ctx.getConfig("settings.registry"),s=n.proxy||this.ctx.getConfig("settings.proxy");return await new Promise((n=>{var o,E;let S=[e].concat(t).concat("--color=always").concat("--save");a&&(S=S.concat(`--registry=${a}`)),s&&(S=S.concat(`--proxy=${s}`));try{const e=x("npm",S,{cwd:r,env:Object.assign({},process.env,i)});let t="";null===(o=e.stdout)||void 0===o||o.on("data",(e=>{t+=e})).pipe(process.stdout),null===(E=e.stderr)||void 0===E||E.on("data",(e=>{t+=e})).pipe(process.stderr),e.on("close",(e=>{n(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(bt.FAILED,"NPM is not installed")}))}catch(e){this.ctx.log.error(e),this.ctx.emit(bt.FAILED,e)}}))}}const Ft=(e,t)=>{const r={success:!1,fullName:"",pkgName:""},n=fe(t,e.log);if(!n)return r;const i=Be(n,e.log);return i?{success:!0,fullName:n,pkgName:i}:r};class Ht{constructor(e){this.list=[],this.fullList=new Set,this.pluginMap=new Map,this.ctx=e,this.init()}init(){const e=D.join(this.ctx.baseDir,"package.json");if(!t.existsSync(e)){const r={name:"picgo-plugins",description:"picgo-plugins",repository:"https://github.com/Kuingsmile/PicList-Core",license:"MIT"};t.writeFileSync(e,JSON.stringify(r),"utf8")}}resolvePlugin(e,t){try{return W(t,{basedir:e.baseDir})}catch(r){return D.join(e.baseDir,"node_modules",t)}}load(){const e=D.join(this.ctx.baseDir,"node_modules/");if(!t.existsSync(e))return!1;const r=D.join(this.ctx.baseDir,"package.json"),i=n(r),a=Object.keys(i.dependencies||{}),s=Object.keys(i.devDependencies||{}),o=a.concat(s).filter((e=>{if(!/^picgo-plugin-|^@[^/]+\/picgo-plugin-/.test(e))return!1;const r=this.resolvePlugin(this.ctx,e);return t.existsSync(r)}));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),yt(e);const r=t(this.ctx);this.pluginMap.set(e,r),r.register(this.ctx)}else if(!0===this.ctx.getConfig(`picgoPlugins.${e}`)||void 0===this.ctx.getConfig(`picgoPlugins.${e}`)){this.list.push(e),yt(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(bt.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),yt(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 t=D.join(this.ctx.baseDir,"node_modules/"),r=require(t+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 Kt=new e,$t=new H.Agent({maxVersion:"TLSv1.2",minVersion:"TLSv1.2",rejectUnauthorized:!1});function kt(e,t,r){"object"==typeof r&&"value"in r&&"options"in r?e.append(t,r.value,r.options):e.append(t,r)}function Yt(e){return Object.assign(Object.assign({},e),{statusCode:e.status,body:e.data})}function Vt(e){var t,r,n,i,a,s,o;const E={method:(null===(r=null===(t=null==e?void 0:e.config)||void 0===t?void 0:t.method)||void 0===r?void 0:r.toUpperCase())||"",url:(null===(n=null==e?void 0:e.config)||void 0===n?void 0:n.url)||"",statusCode:(null===(i=null==e?void 0:e.response)||void 0===i?void 0:i.status)||0,message:(null==e?void 0:e.message)||"",stack:(null==e?void 0:e.stack)||{},response:{status:(null===(a=null==e?void 0:e.response)||void 0===a?void 0:a.status)||0,statusCode:(null===(s=null==e?void 0:e.response)||void 0===s?void 0:s.status)||0,body:(null===(o=null==e?void 0:e.response)||void 0===o?void 0:o.data)||""}};return Promise.reject(E)}class jt{constructor(e){this.proxy="",this.options={},this.ctx=e,this.init(),Kt.on(xt.CONFIG_CHANGE,(e=>{var t;switch(e.configName){case"picBed":(null===(t=e.value)||void 0===t?void 0:t.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){var t;this.options.proxy=this.handleProxy(),this.options.headers=e.headers||{},this.options.maxBodyLength=1/0,this.options.maxContentLength=1/0,this.options.proxy&&(null===(t=e.url)||void 0===t?void 0:t.startsWith("https://"))?(this.options.httpsAgent=K({proxy:{host:this.options.proxy.host,port:this.options.proxy.port}}),this.options.proxy=!1):this.options.httpsAgent=$t;const r=v.create(this.options);r.interceptors.response.use(Yt,Vt);const n=function(e){var t;let r=!1;const n=Object.assign(Object.assign({},e),{url:e.url||"",headers:e.headers||{}});if(e.proxy){let i=e.proxy;if("string"==typeof i){try{i=new L(e.proxy)}catch(e){i=!1,n.proxy=!1,console.error(e)}r=!0}i&&((null===(t=e.url)||void 0===t?void 0:t.startsWith("https://"))?(n.proxy=!1,n.httpsAgent=K({proxy:{host:null==i?void 0:i.hostname,port:parseInt(null==i?void 0:i.port,10)}})):n.proxy={host:i.hostname,port:parseInt(i.port,10),protocol:"http"})}if("formData"in e){const t=new F;for(const r in e.formData)kt(t,r,e.formData[r]);n.data=t,n.headers=Object.assign(n.headers||{},t.getHeaders()),r=!0,delete n.formData}return"body"in e&&(n.data=e.body,r=!0,delete n.body),"qs"in e&&(n.params=e.qs,r=!0),n.__isOldOptions=r,n}(e);return r.interceptors.request.use((function(e){var t,r,n;let i="";return(null===(t=null==e?void 0:e.headers)||void 0===t?void 0:t.contentType)?(i=e.headers.contentType,delete e.headers.contentType):(null===(r=null==e?void 0:e.headers)||void 0===r?void 0:r.ContentType)?(i=e.headers.ContentType,delete e.headers.ContentType):(null===(n=null==e?void 0:e.headers)||void 0===n?void 0:n["content-type"])&&(i=e.headers["content-type"],delete e.headers["content-type"]),""!==i&&e.headers&&(e.headers["Content-Type"]=i),e})),"resolveWithFullResponse"in e&&e.resolveWithFullResponse?r.request(n):r.request(n).then((t=>n.__isOldOptions?"json"in e?e.json?t.data:void 0:JSON.stringify(t.data):t.data))}}const qt="Add watermark to image",zt="Compress or convert image",Xt="Remove exif info",Qt="Download ttf file",Zt="Download ttf file successfully",Jt="Download ttf file failed",er="Download ttf file failed, skip add watermark",tr=0,rr=30,nr=60,ir=-1,ar=["zip","rar","7z","tar","gz","tar.gz","tar.bz2","tar.xz"];class sr extends e{constructor(e){super(),this.ctx=e,this.ttfPath=D.join(e.baseDir,"assets","simhei.ttf"),this.initializeDirs()}initializeDirs(){i(D.join(this.ctx.baseDir,"imgTemp"));this.ctx.getConfig("settings.enableSecondUploader")||!1||s(D.join(this.ctx.baseDir,"piclistTemp"))}async downloadTTF(){try{if(i(D.dirname(this.ttfPath)),t.existsSync(this.ttfPath)&&t.statSync(this.ttfPath).size>0)return!0;this.ctx.log.info(Qt);const e=await v.get("https://release.piclist.cn/simhei.ttf",{responseType:"arraybuffer"});return t.writeFileSync(this.ttfPath,e.data),this.ctx.log.info(Zt),!0}catch(e){return this.ctx.log.error(Jt),!1}}getProcessingOptions(e){const t=e.getConfig("buildIn.compress"),r=e.getConfig("buildIn.watermark");if(t){const r=this.getUploaderType(e),n=e.helper.uploader.get(r);t.picBed=n?r:"smms"}return{compressOptions:t,watermarkOptions:r}}getUploaderType(e){return e.getConfig("picBed.uploader")||e.getConfig("picBed.current")||"smms"}getSkipExtensions(e){const t=e.getConfig("buildIn.skipProcess")||{},r=t.skipProcessExtList?t.skipProcessExtList.split(",").map((e=>e.trim())):ar;return new Set(r.map((e=>{const t=e.trim().toLowerCase();return t.startsWith(".")?t:`.${t}`})))}async start(e,t=!1){const r=(e=>({configPath:e.configPath,baseDir:e.baseDir,log:e.log,cmd:e.cmd,output:[],input:[],rawInput:[],processedInput:[],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),uploadReturnCtx:e.uploadReturnCtx.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 this.initializeContext(r,e),t?await this.handleSkipProcess(r):await this.executeLifecycle(r)}catch(e){return this.handleError(r,e)}}initializeContext(e,t){e.input=t,e.output=[],e.rawInputPath=[],e.rawInput=l(t)}async handleSkipProcess(e){return e.log.info("Skip process."),e.output=e.input,await this.doUpload(e),e.input=e.rawInput,await this.afterUpload(e),e}async executeLifecycle(e){return await this.preprocess(e),await this.beforeTransform(e),await this.doTransform(e),await this.buildInRename(e),await this.beforeUpload(e),e.processedInput=l(e.output),await this.doUpload(e),e.input=e.rawInput,await this.afterUpload(e),e}handleError(e,t){if(e.log.warn(bt.FAILED),e.emit(bt.UPLOAD_PROGRESS,ir),e.emit(bt.FAILED,t),e.log.error(t),e.getConfig("debug"))throw t;return e}async preprocess(e){const{compressOptions:t,watermarkOptions:r}=this.getProcessingOptions(e),n=this.getSkipExtensions(e);if(e.emit(bt.UPLOAD_PROGRESS,tr),e.emit(bt.BEFORE_TRANSFORM,e),e.log.info("Before transform"),t||r){const i=D.join(e.baseDir,"piclistTemp");await this.processImages(e,i,t,r,n)}else this.initializeRawInputPaths(e);return e}initializeRawInputPaths(e){for(const t of e.input)e.rawInputPath.push(t)}async processImages(e,t,r,n,i){await Promise.allSettled(e.input.map((async(a,s)=>{await this.processImage(a,s,e,t,r,n,i)})))}async processImage(e,r,n,i,a,s,o){const E=Ae(e),S=E?await ge(e,n):{success:!1};if(E&&(!S.success||!S.buffer))return;n.rawInputPath[r]=e;const I=E?S.extname||"":D.extname(e),_=o.has(I.toLowerCase()),l=E?S.buffer:t.readFileSync(e),P=await this.applyProcessing(l,I,a,s,_,e,i,n);P&&await this.saveProcessedImage(e,r,n,i,P,I,a,E,S)}async applyProcessing(e,t,r,n,i,a,s,o){let E;return je(n,t)&&!i&&(E=await this.addWatermark(e,n,o)),qe(r,t)&&!i&&(E=await this.compressImage(e,E,t,r,a,s,o)),E||!(null==r?void 0:r.isRemoveExif)||i||(o.log.info(Xt),E=await ze(e,t)),E}async addWatermark(e,t,r){if(!(null==t?void 0:t.watermarkFontPath)&&"image"!==(null==t?void 0:t.watermarkType)){if(!await this.downloadTTF())return void this.ctx.log.warn(er)}return r.log.info(qt),await Ke(e,t,this.ttfPath,r.log)}async compressImage(e,t,r,n,i,a,s){s.log.info(zt);const o=r.toLowerCase();return Ae(i)||".heic"!==o&&".heif"!==o?await ke(null!=t?t:e,n,r,s.log):await this.convertHeicAndCompress(e,i,r,a,n,s)}async convertHeicAndCompress(e,r,n,i,a,s){const o=await $({buffer:e,format:"JPEG",quality:1}),E=D.join(i,`${D.basename(r,n)}.jpg`);return t.writeFileSync(E,Buffer.from(o)),await ke(t.readFileSync(E),a,".jpg",s.log)}async saveProcessedImage(e,r,n,i,a,s,o,E,S){let I=(null==o?void 0:o.isConvert)?Ve(o,s):s;I=I.startsWith(".")?I:`.${I}`;const _=E?D.join(i,`${this.getFileBaseName(S)}${I}`):D.join(i,`${D.basename(e,s)}${I}`);n.rawInputPath[r]=D.join(D.dirname(e),E?D.basename(_):`${D.basename(e,s)}${I}`),t.writeFileSync(_,a),n.input[r]=_}getFileBaseName(e){return e.fileName?D.basename(e.fileName,D.extname(e.fileName)):(new Date).getTime().toString()}async buildInRename(e){const t=e.getConfig("buildIn.rename")||{};if(!t.enable)return e;const r=t.format||"{filename}";return e.output=e.output.map(((t,n)=>{let i=t.fileName;return r&&(i=pe(e.rawInputPath[n],r,void 0,t.base64Image?t.base64Image:t.buffer),i=i.replace(/\/+/g,"/"),"/"===i.slice(-1)&&(i+=n.toString())),t.fileName=i,t})),e}async beforeTransform(e){return await this.handlePlugins(e.helper.beforeTransformPlugins,e),e}async doTransform(e){e.emit(bt.UPLOAD_PROGRESS,rr);const t=e.getConfig("picBed.transformer")||"path";let r=e.helper.transformer.get(t),n=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(null==r?void 0:r.handle(e)),e}async beforeUpload(e){return e.emit(bt.UPLOAD_PROGRESS,nr),e.log.info("Before upload"),e.emit(bt.BEFORE_UPLOAD,e),await this.handlePlugins(e.helper.beforeUploadPlugins,e),e}async doUpload(e){const t=this.getUploaderType(e);let r=e.helper.uploader.get(t),n=t;r||(e.log.warn(`Can't find uploader - ${t}, switch to default uploader - smms`),n="smms",r=e.helper.uploader.get("smms")),e.log.info(`Uploading... Current uploader is [${n}]`),await(null==r?void 0:r.handle(e));for(const t of e.output)t.type=n;return e}async afterUpload(e){e.emit(bt.AFTER_UPLOAD,e),e.emit(bt.UPLOAD_PROGRESS,100),await this.handlePlugins(e.helper.afterUploadPlugins,e);let t="";const r=e.output.length,n=!0===e.getConfig("settings.encodeOutputURL");for(let i=0;i<r;i++)void 0!==e.output[i].imgUrl&&(t+=n?De(e.output[i].imgUrl):e.output[i].imgUrl,i!==r-1&&(t+="\n")),delete e.output[i].base64Image,delete e.output[i].buffer;return e.emit(bt.FINISHED,e),e.log.success(`\n${t}`),e}async handlePlugins(e,t){const r=e.getList(),n=e.getIdList(),i=e.getName();return await Promise.all(r.map((async(e,r)=>{try{t.log.info(`${i}: ${n[r]} running`),await e.handle(t)}catch(e){throw t.log.error(`${i}: ${n[r]} error`),e}}))),t}}const or=(e,t,r,n,i,a,s)=>({method:n.toUpperCase(),url:r,headers:Object.assign({contentType:"multipart/form-data","User-Agent":"PicList"},i),formData:Object.assign({[s]:{value:e,options:{filename:t}}},a),json:!0}),Er=async e=>{const t=e.getConfig("picBed.advancedplist");if(!t)throw new Error("Can not find advancedplist config");const r=e.output;for(const n of r)if(n.fileName&&n.buffer){const r=n.buffer||(n.base64Image?Buffer.from(n.base64Image,"base64"):null);if(!r)continue;const i=or(r,n.fileName,t.endpoint,t.method||"POST",JSON.parse(t.headers||"{}"),JSON.parse(t.body||"{}"),t.formDataKey||"file");let a=await e.request(i);a="string"==typeof a?JSON.parse(a):a;let s=a;const o=t.resDataPath||"data.url";for(const e of o.split(".")){if(!s||"object"!=typeof s||!(e in s)){s=void 0;break}s=s[e]}if(!s||"string"!=typeof s)throw e.emit(bt.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:a.message}),console.error("AdvancedPlist upload failed:",a),new Error(a.message);if(delete n.base64Image,delete n.buffer,t.webPath){const e=s.split("/").pop()||s;s=(t.webPath.endsWith("/")?t.webPath:t.webPath+"/")+e}n.imgUrl=t.customPrefix?t.customPrefix+s:s}return e},Sr=e=>{const t=e.getConfig("picBed.advancedplist")||{},r=(r,n,i,a=!1,s)=>Object.assign({name:r,type:n,get prefix(){return e.i18n.translate(`PICBED_ADVANCEDPLIST_${r.toUpperCase()}`)},get alias(){return e.i18n.translate(`PICBED_ADVANCEDPLIST_${r.toUpperCase()}`)},get message(){return e.i18n.translate(`PICBED_ADVANCEDPLIST_MESSAGE_${r.toUpperCase()}`)},default:t[r]||i,required:a},s);return[r("endpoint","input","",!0),r("method","list","POST",!1,{choices:["POST","PUT","GET"]}),r("formDataKey","input","file"),r("headers","input","{}"),r("body","input","{}"),r("customPrefix","input",""),r("webPath","input",""),r("resDataPath","input","data.url")]};const Ir=(e,t,r,n,i)=>({method:"PUT",url:`${e}/api/fs/form`,headers:{contentType:"multipart/form-data","User-Agent":"PicList",Authorization:t,"File-Path":encodeURIComponent(n)},formData:{file:{value:i,options:{filename:r}}},resolveWithFullResponse:!0}),_r=(e,t)=>{if(200!==t.statusCode||200!==t.body.code||"success"!==t.body.message)throw e.emit(bt.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK"),text:t.body.message}),new Error(t.body.message)},lr=(e,t,r)=>({method:"POST",url:e,headers:{Authorization:t,"Content-Type":"application/json"},body:r,resolveWithFullResponse:!0}),Pr=e=>{const{url:t,token:r,username:n,password:i,uploadPath:a,webPath:s,customUrl:o}=e;return{url:(t||"").replace(/\/$/,""),token:r||"",username:n||"",password:i||"",uploadPath:Ze({path:a||"",startSlash:!0,endSlash:!0,rootToEmpty:!1}),webPath:s?Ze({path:s||"",startSlash:!0,endSlash:!0,rootToEmpty:!1}):"",customUrl:(o||"").replace(/\/$/,"")}},cr=async e=>{const t=e.getConfig("picBed.alistplist");if(!t)throw new Error("Can not find alist config!");const{url:r,username:n,password:i,uploadPath:a,webPath:s,customUrl:o}=Pr(t);let{token:E}=Pr(t);if(E||(E=await(async(e,t,r,n)=>{const i=e.getConfig("picgo-plugin-buildin-alistplist");if(i&&i.refreshedAt&&Date.now()-i.refreshedAt<36e5&&i.token)return i.token;const a=await v.post(`${t}/api/auth/login`,{username:r,password:n});if(200===a.data.code&&"success"===a.data.message){const t=a.data.data.token;return e.saveConfig({"picgo-plugin-buildin-alistplist":{token:t,refreshedAt:Date.now()}}),t}throw new Error("Get token failed")})(e,r,n,i)),!r||!(E||n&&i))throw new Error("Please check your alist config!");const S=e.output;for(const t of S)if(t.fileName&&t.buffer){let n=t.buffer;!n&&t.base64Image&&(n=Buffer.from(t.base64Image,"base64"));const i=`${a}${t.fileName}`,S=Ir(r,E,t.fileName,i,n),I=await e.request(S);_r(e,I);const _=await e.request(lr(`${r}/api/fs/list`,E,{password:"",page:1,per_page:1,refresh:!0,path:D.dirname(i)}));_r(e,_);const l=await e.request(lr(`${r}/api/fs/get`,E,{password:"",path:i,page:1,per_page:1,refresh:!0}));_r(e,l);const P=l.body.data.sign,c=Je(`${s||a}${t.f