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