picgo 2.0.3 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +4 -1
- package/CLAUDE.md +1 -0
- package/CONTEXT.md +53 -0
- package/README.md +57 -2
- package/dist/core/Lifecycle.d.ts +4 -2
- package/dist/core/PicGo.d.ts +2 -2
- package/dist/i18n/zh-CN.d.ts +62 -0
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/dist/lib/Cloud/ApiErrorCode.d.ts +11 -0
- package/dist/lib/Cloud/Request.d.ts +29 -1
- package/dist/lib/Cloud/__mocks__/lifecycleScenarios.d.ts +16 -0
- package/dist/lib/Cloud/index.d.ts +17 -4
- package/dist/lib/Cloud/services/AlbumService.d.ts +39 -0
- package/dist/lib/Cloud/services/BillingService.d.ts +9 -0
- package/dist/lib/Cloud/services/FileService.d.ts +20 -0
- package/dist/lib/Cloud/services/UserService.d.ts +3 -4
- package/dist/lib/Cloud/services/multipart/MultipartStorage.d.ts +37 -0
- package/dist/lib/Cloud/services/multipart/MultipartUploadService.d.ts +49 -0
- package/dist/lib/Cloud/utils.d.ts +8 -1
- package/dist/lib/Logger.d.ts +28 -1
- package/dist/lib/Server/index.d.ts +3 -0
- package/dist/lib/Server/routes.d.ts +3 -1
- package/dist/plugins/commander/cloud/actions/configSync.d.ts +7 -0
- package/dist/plugins/commander/cloud/actions/index.d.ts +3 -0
- package/dist/plugins/commander/cloud/actions/login.d.ts +2 -0
- package/dist/plugins/commander/cloud/actions/logout.d.ts +2 -0
- package/dist/plugins/commander/cloud/delete.d.ts +4 -0
- package/dist/plugins/commander/cloud/get.d.ts +4 -0
- package/dist/plugins/commander/cloud/import.d.ts +13 -0
- package/dist/plugins/commander/cloud/index.d.ts +3 -0
- package/dist/plugins/commander/cloud/list.d.ts +18 -0
- package/dist/plugins/commander/cloud/retry.d.ts +4 -0
- package/dist/plugins/commander/cloud/shared.d.ts +16 -0
- package/dist/plugins/commander/cloud/status.d.ts +16 -0
- package/dist/plugins/commander/cloud/update.d.ts +4 -0
- package/dist/plugins/commander/get.d.ts +16 -0
- package/dist/plugins/commander/upload.d.ts +1 -1
- package/dist/plugins/commander/utils/progressRenderer.d.ts +31 -0
- package/dist/plugins/uploader/picgoCloud.d.ts +3 -0
- package/dist/types/index.d.ts +351 -5
- package/dist/types/internal.d.ts +8 -2
- package/dist/utils/enum.d.ts +13 -1
- package/dist/utils/interfaces.d.ts +23 -1
- package/dist/utils/pluginConfig.d.ts +50 -0
- package/dist/utils/progressBar.d.ts +11 -0
- package/dist/utils/static.d.ts +18 -0
- package/dist/utils/uploadWithProgress.d.ts +39 -0
- package/package.json +5 -3
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";require("dotenv/config");var e=require("fs-extra"),t=require("path"),n=require("events"),r=require("os"),i=require("commander"),s=require("inquirer"),o=require("image-size"),a=require("url"),c=require("lodash"),l=require("comment-json"),u=require("axios"),p=require("crypto"),g=require("chalk"),E=require("util"),d=require("dayjs"),h=require("mime-types"),_=require("node:crypto"),f=require("md5"),I=require("resolve"),C=require("child_process"),m=require("is-wsl"),S=require("form-data"),N=require("https"),L=require("tunnel"),P=require("@picgo/store"),D=require("cross-spawn"),U=require("js-yaml"),y=require("@picgo/i18n"),T=require("@hono/node-server"),A=require("@hono/node-server/serve-static"),O=require("hono"),R=require("hono/logger"),x=require("hono/cors");function w(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var B=w(_);const b=e=>{const t=`${!0===e.global?"g":""}${!0===e.ignoreCase?"i":""}`;return new RegExp(e.match,t)},G=(e,t,n)=>{if(e.imgUrl)for(const r of t){if(!(!1!==r.enable))continue;let t;try{t=b(r)}catch(e){n.log.error(e);continue}if(!t.test(e.imgUrl))continue;const i=e.imgUrl,s=i.replace(t,r.replace);if(s!==i&&void 0===e.originImgUrl&&(e.originImgUrl=i),e.imgUrl=s,""===s){const e=n.i18n?.translate("URL_REWRITE_EMPTY_RESULT")??"URL_REWRITE_EMPTY_RESULT";n.log.warn(e)}break}},v={handle:e=>{const t=e.cmd;t.program.command("install <plugins...>").description("install picgo plugin").alias("add").option("-p, --proxy <proxy>","Add proxy for installing plugins").option("-r, --registry <registry>","Choose a registry for installing plugins").action((t,n)=>{const{proxy:r,registry:i}=n,s={npmProxy:r,npmRegistry:i};e.pluginHandler.install(t,s).catch(t=>{e.log.error(t)})}),t.program.command("uninstall <plugins...>").alias("rm").description("uninstall picgo plugin").action(t=>{e.pluginHandler.uninstall(t).catch(t=>{e.log.error(t)})}),t.program.command("update <plugins...>").description("update picgo plugin").option("-p, --proxy <proxy>","Add proxy for installing plugins").option("-r, --registry <registry>","Choose a registry for installing plugins").action((t,n)=>{const{proxy:r,registry:i}=n,s={npmProxy:r,npmRegistry:i};e.pluginHandler.update(t,s).catch(t=>{e.log.error(t)})})}},M={handle:e=>{e.cmd.program.option("-c, --config <path>","set config path")}},$=e=>e.startsWith("http://")||e.startsWith("https://"),F=e=>{if(!e)return"";try{return new a.URL(e).href}catch(t){if(e.startsWith("//"))try{return new a.URL("http:"+e).href.slice(5)}catch(e){}return encodeURI(e)}},H=(...e)=>e.join("").replace(/\/{2,}/g,"/").split("/").map(e=>encodeURIComponent(e)).join("/"),k=e=>{try{const{width:t=0,height:n=0,type:r}=o.imageSize(e);return{real:!0,width:t,height:n,extname:r?`.${r}`:".png"}}catch(e){return{real:!1,width:200,height:200,extname:".png"}}},Y=async n=>{try{return{extname:t.extname(n),fileName:t.basename(n),filePath:n,buffer:await e.readFile(n),success:!0}}catch{return{reason:`read file ${n} error`,success:!1}}},q=async(e,n)=>{e=F(e);let r,i=!1,s="";const o=new Promise((o,c)=>{(async()=>{try{const c=await n.request({method:"get",url:e,resolveWithFullResponse:!0,responseType:"arraybuffer"}).then(e=>{const t=e.headers["content-type"];return t?.includes("image")&&(i=!0,s=`.${t.split("image/")[1]}`),e.data});clearTimeout(r);const l=new a.URL(e).pathname,u=decodeURIComponent(t.basename(l));o(i?{buffer:c,fileName:u,extname:s||t.extname(u)||".png",success:!0}:{buffer:c,fileName:u,extname:t.extname(u)||".png",success:!0})}catch(t){clearTimeout(r),o({success:!1,reason:`request ${e} error, ${t?.message??""}`})}})().catch(c)}),c=new Promise(t=>{r=setTimeout(()=>{t({success:!1,reason:`request ${e} timeout`})},1e4)});return Promise.race([o,c])},V=e=>/^@[^/]+\/picgo-plugin-/.test(e)?"scope":e.startsWith("picgo-plugin-")?"normal":K(e)?"simple":"unknown",K=n=>{if(t.isAbsolute(n))return!1;const r=t.join(process.cwd(),n);return!e.existsSync(r)&&(!n.includes("/")&&!n.includes("\\"))},j=(e,t="")=>t?`@${t}/picgo-plugin-${e}`:`picgo-plugin-${e}`,W=(n,r=console)=>{switch(V(n)){case"normal":case"scope":return n;case"simple":return j(n);default:{let i=n;return t.isAbsolute(n)&&e.existsSync(n)?z(i):(i=t.join(process.cwd(),n),e.existsSync(i)?z(i):(r.warn(`Can't find plugin ${n}`),""))}}},Q=(n,r=console)=>{switch(V(n)){case"normal":return J(n);case"scope":return J(n,!0);case"simple":return J(j(n));default:{if(!e.existsSync(n))return r.warn(`Can't find plugin: ${n}`),"";const i=t.posix.join(n,"package.json");if(e.existsSync(i)){const t=e.readJSONSync(i)||{};return t.name?.includes("picgo-plugin-")?t.name:(r.warn(`The plugin package.json's name filed is ${t.name||"empty"}, need to include the prefix: picgo-plugin-`),"")}return r.warn(`Can't find plugin: ${n}`),""}}},z=e=>e.split(t.sep).join("/"),J=(e,t=!1)=>{if(e.includes("@")){let n=/(.+\/)?(picgo-plugin-\w+)(@.+)*/;t&&(n=/(.+\/)?(^@[^/]+\/picgo-plugin-\w+)(@.+)*/);const r=e.match(n);return r?r[2]:(console.warn("can not remove plugin version"),e)}return e},X=[],Z=e=>X.some(t=>e.startsWith(t)),ee=e=>"object"==typeof e&&!Array.isArray(e)&&Object.keys(e).length>0;function te(e){try{return JSON.parse(e)}catch(t){return e}}const ne=(e=0)=>isNaN(Number(e))?0:Number(e),re=()=>"development"===process.env.NODE_ENV;var ie=Object.freeze({__proto__:null,configBlackList:X,forceNumber:ne,getFSFile:Y,getImageSize:k,getNormalPluginName:Q,getPluginNameType:V,getProcessPluginName:W,getURLFile:q,handleCompletePluginName:j,handleStreamlinePluginName:e=>/^@[^/]+\/picgo-plugin-/.test(e)?e.replace(/^@[^/]+\/picgo-plugin-/,""):e.replace(/picgo-plugin-/,""),handleUnixStylePath:z,handleUrlEncode:F,handleUrlPathSafeEncode:H,isConfigKeyInBlackList:Z,isDev:re,isInputConfigValid:ee,isProd:()=>"production"===process.env.NODE_ENV,isSimpleName:K,isUrl:$,removePluginVersion:J,safeParse:te});const se={handle:n=>{n.cmd.program.command("upload").description("upload, go go go").arguments("[input...]").alias("u").action(async r=>{try{const i=r.map(e=>$(e)?e:t.resolve(e)).filter(t=>{const r=e.existsSync(t)||$(t);return r||n.log.warn(`${t} does not exist.`),r});await n.upload(i)}catch(e){if(n.log.error(e),process.argv.includes("--debug"))throw e}})}};var oe,ae,ce,le,ue,pe;exports.SyncStatus=void 0,(oe=exports.SyncStatus||(exports.SyncStatus={})).SUCCESS="success",oe.CONFLICT="conflict",oe.FAILED="failed",exports.ConflictType=void 0,(ae=exports.ConflictType||(exports.ConflictType={})).CLEAN="clean",ae.CONFLICT="conflict",ae.ADDED="added",ae.DELETED="deleted",ae.MODIFIED="modified",exports.E2EVersion=void 0,(ce=exports.E2EVersion||(exports.E2EVersion={}))[ce.NONE=0]="NONE",ce[ce.V1=1]="V1",exports.EncryptionMethod=void 0,(le=exports.EncryptionMethod||(exports.EncryptionMethod={})).AUTO="auto",le.SSE="sse",le.E2EE="e2ee",exports.E2EAskPinReason=void 0,(ue=exports.E2EAskPinReason||(exports.E2EAskPinReason={})).SETUP="setup",ue.DECRYPT="decrypt",ue.RETRY="retry",function(e){e.GUI="gui",e.CLI="cli"}(pe||(pe={}));const ge=process.env.PICGO_API_URL||"https://api.picgo.app",Ee=process.env.PICGO_CLOUD_URL||"https://cloud.picgo.app";class de{ctx;baseURL;constructor(e,t=ge){this.ctx=e,this.baseURL=t}async request(e,t){const n=t??this.ctx.getConfig("settings.picgoCloud.token"),r=e.headers||{};n&&(r.Authorization=`Bearer ${n}`);return(await u.request({baseURL:this.baseURL,...e,headers:r})).data}}class he{client;ctx;appType=pe.CLI;constructor(e){this.client=new de(e),this.ctx=e}async fetchConfig(){this.appType=this.ctx.GUI_VERSION?pe.GUI:pe.CLI;try{const e=await this.client.request({method:"GET",url:"/api/config",params:{appType:this.appType}});return e?.config&&""!==e.config.trim()?e:null}catch(e){if(u.isAxiosError(e)){const t=e.response?.status;if(404===t)return null;const n=e.response?.data?.message??e.message;throw this.ctx.log.warn("[ConfigService] Failed to fetch config:",n),new Error(n)}throw e}}async updateConfig(e,t,n){this.appType=this.ctx.GUI_VERSION?pe.GUI:pe.CLI;try{return{success:!0,version:(await this.client.request({method:"PUT",url:"/api/config",data:{appType:this.appType,config:e,baseVersion:t,historyLimit:10,...n??{}}})).version}}catch(e){if(u.isAxiosError(e)){const n=e.response?.data;if("CONFIG_CONFLICT"===n?.code)return{success:!1,conflict:!0,version:"number"==typeof n.currentVersion?n.currentVersion:t};const r=n?.message??e.message;throw this.ctx.log.warn("[ConfigService] Failed to update config:",r),new Error(r)}throw e}}}const _e=(e,t)=>!(!e||"object"!=typeof e)&&Object.prototype.hasOwnProperty.call(e,t),fe=e=>{const t=Object.getPrototypeOf(e),n=Object.create(t);for(const t of Object.getOwnPropertySymbols(e)){const r=Object.getOwnPropertyDescriptor(e,t);r&&Object.defineProperty(n,t,r)}return n},Ie=(e,t)=>{const n=fe(e),r=[],i=new Set;for(const t of Object.keys(e))i.has(t)||(r.push(t),i.add(t));for(const e of Object.keys(t))i.has(e)||(r.push(e),i.add(e));for(const i of r){if(!_e(t,i)){delete n[i];continue}const r=_e(e,i)?e[i]:void 0,s=t[i];c.isPlainObject(r)&&c.isPlainObject(s)?n[i]=Ie(r,s):n[i]=s}return n},Ce=(e,t)=>c.isEqual(e,t)?exports.ConflictType.CLEAN:void 0===e&&void 0!==t?exports.ConflictType.ADDED:void 0!==e&&void 0===t?exports.ConflictType.DELETED:exports.ConflictType.MODIFIED;class me{static merge3Way(e,t,n,r="root"){if(c.isEqual(t,n)){const i=Ce(e,t);return{value:t,conflict:!1,diffNode:i===exports.ConflictType.CLEAN?void 0:{key:r,status:i,snapshotValue:e,localValue:t,remoteValue:n}}}const i=c.isPlainObject(t),s=c.isPlainObject(n),o=c.isPlainObject(e);if(c.isEqual(e,t)){if(i&&s){const i=Ie(t,n),s=Ce(e,i);return{value:i,conflict:!1,diffNode:s===exports.ConflictType.CLEAN?void 0:{key:r,status:s,snapshotValue:e,localValue:t,remoteValue:n}}}const o=Ce(e,n);return{value:n,conflict:!1,diffNode:o===exports.ConflictType.CLEAN?void 0:{key:r,status:o,snapshotValue:e,localValue:t,remoteValue:n}}}if(c.isEqual(e,n)){const i=Ce(e,t);return{value:t,conflict:!1,diffNode:i===exports.ConflictType.CLEAN?void 0:{key:r,status:i,snapshotValue:e,localValue:t,remoteValue:n}}}if(i&&s&&(o||null==e)){const i=o?e:{},s=t,a=n,c=[],l=new Set;for(const e of Object.keys(s))l.has(e)||(c.push(e),l.add(e));for(const e of Object.keys(a))l.has(e)||(c.push(e),l.add(e));for(const e of Object.keys(i))l.has(e)||(c.push(e),l.add(e));const u=fe(s),p=[];let g=!1;for(const e of c){const t=_e(i,e)?i[e]:void 0,n=_e(s,e)?s[e]:void 0,r=_e(a,e)?a[e]:void 0,o=me.merge3Way(t,n,r,e);o.conflict&&(g=!0),void 0===o.value?delete u[e]:u[e]=o.value,o.diffNode&&o.diffNode.status!==exports.ConflictType.CLEAN&&p.push(o.diffNode)}const E=g?exports.ConflictType.CONFLICT:Ce(e,u);return{value:u,conflict:g,diffNode:E===exports.ConflictType.CLEAN?void 0:{key:r,status:E,snapshotValue:e,localValue:t,remoteValue:n,children:p.length?p:void 0}}}return{value:t,conflict:!0,diffNode:{key:r,status:exports.ConflictType.CONFLICT,snapshotValue:e,localValue:t,remoteValue:n}}}}class Se extends Error{constructor(e){super(e),this.name=new.target.name}}class Ne extends Se{constructor(e="Encrypted config payload is corrupted"){super(e)}}class Le extends Se{constructor(e="Unsupported E2E version"){super(e)}}class Pe extends Se{constructor(e="PIN handler is required for E2E operations"){super(e)}}class De extends Se{constructor(e="Encryption switch confirmation handler is required"){super(e)}}class Ue extends Se{constructor(e="Invalid PIN input"){super(e)}}class ye extends Se{constructor(e="Maximum retry attempts exceeded"){super(e)}}class Te extends Se{constructor(e="Failed to decrypt payload"){super(e)}}class Ae extends Se{value;constructor(e){super("Invalid encryption method"),this.value=e}}const Oe=12,Re="aes-256-gcm";class xe{generateE2EPayload(e,t){const n=p.randomBytes(16),r=p.randomBytes(32),i=this.wrapDEK(r,t,n),s=this.encryptConfig(e,r);return{payload:{e2eVersion:exports.E2EVersion.V1,clientKekSalt:n.toString("base64"),clientDekEncrypted:i,config:s},dek:r}}encryptConfig(e,t){return this.encryptWithKey(Buffer.from(e,"utf8"),t)}decryptConfig(e,t){return this.decryptWithKey(e,t).toString("utf8")}wrapDEK(e,t,n){const r=this.deriveKEK(t,n);return this.encryptWithKey(e,r)}unwrapDEK(e,t,n){const r=this.deriveKEK(t,n);return this.decryptWithKey(e,r)}decodeSalt(e){const t=Buffer.from(e,"base64");if(16!==t.length)throw new Ne("Invalid salt length");return t}deriveKEK(e,t){return p.pbkdf2Sync(e,t,6e5,32,"sha256")}encryptWithKey(e,t){const n=p.randomBytes(Oe),r=p.createCipheriv(Re,t,n),i=Buffer.concat([r.update(e),r.final()]),s=r.getAuthTag();return Buffer.concat([n,s,i]).toString("base64")}decryptWithKey(e,t){const n=Buffer.from(e,"base64");if(n.length<28)throw new Ne("Encrypted payload is too short");const r=n.subarray(0,Oe),i=n.subarray(Oe,28),s=n.subarray(28);try{const e=p.createDecipheriv(Re,t,r);return e.setAuthTag(i),Buffer.concat([e.update(s),e.final()])}catch(e){const t=e instanceof Error?e.message:"Failed to decrypt payload";throw new Te(t)}}}const we="settings.picgoCloud.encryptionMethod",Be=["settings.picgoCloud.token",we],be=(e,t,n={})=>{const r=c.cloneDeep(e),i=!0===n.cleanupEmptyParents;return Be.forEach(e=>{const n=c.get(t,e);void 0!==n?c.set(r,e,n):(c.unset(r,e),i&&((e,t)=>{const n=t.split(".");for(let t=n.length-1;t>0;t-=1){const r=n.slice(0,t).join("."),i=c.get(e,r);if(!c.isPlainObject(i)||0!==Object.keys(i).length)break;c.unset(e,r)}})(r,e))}),r},Ge=(e,t)=>{if(e)return e;const n=(e=>{const t=c.get(e,we);if(void 0!==t){if(t===exports.EncryptionMethod.AUTO||t===exports.EncryptionMethod.SSE||t===exports.EncryptionMethod.E2EE)return t;throw new Ae(t)}})(t);return n??exports.EncryptionMethod.AUTO},ve=async t=>{if(await e.pathExists(t)){const n=await e.readFile(t,"utf8");return l.parse(n)}return{}},Me=async t=>{if(!await e.pathExists(t))return{version:0,updatedAt:"",data:{}};const n=await ve(t);return(e=>{if(!c.isPlainObject(e))return!1;const t=e;return"number"==typeof t.version&&Object.prototype.hasOwnProperty.call(t,"data")})(n)?{version:n.version,updatedAt:"string"==typeof n.updatedAt?n.updatedAt:"",data:n.data??{}}:{version:0,updatedAt:"",data:n}},$e=async(t,n,r)=>{await(async(t,n)=>{const r=l.stringify(n,null,2);await e.writeFile(t,r,"utf8")})(t,{version:r,updatedAt:(new Date).toISOString(),data:n})};class Fe{ctx;snapshotPath;configService;onAskPin;onAskEncryptionSwitch;e2eService;currentRemoteVersion=0;originalRemote=null;remoteE2EVersion=exports.E2EVersion.NONE;remoteClientKekSalt;remoteClientDekEncrypted;cachedDEK;cachedClientDekEncrypted;constructor(e,n={}){this.ctx=e,this.snapshotPath=t.join(e.baseDir,"config.snapshot.json"),this.configService=new he(e),this.onAskPin=n.onAskPin,this.onAskEncryptionSwitch=n.onAskEncryptionSwitch,this.e2eService=new xe}async sync(t={},n=0){try{const r=await ve(this.ctx.configPath);if(!c.isPlainObject(r))return{status:exports.SyncStatus.FAILED,message:"Local config is not a valid JSON object"};const i=r,s=Ge(t.encryptionMethod,i),o=await e.pathExists(this.snapshotPath),a=await Me(this.snapshotPath),l=await this.fetchRemoteConfig();if(l&&!c.isPlainObject(l))return{status:exports.SyncStatus.FAILED,message:"Remote config is not a valid JSON object"};if(this.originalRemote=l||null,!this.originalRemote){const e=!o;e?this.ctx.log.info("First time sync detected. Initializing remote config..."):this.ctx.log.warn("Remote config missing (sync chain broken). Re-initializing from Local...");try{const e=await this.buildPushPayload(i,s);await this.pushRemoteConfig(e.configStr,e.e2eFields)}catch(e){if("Remote config modified by another device"===(e instanceof Error?e.message:String(e)))return n<1?(this.ctx.log.warn("Conflict detected during sync. Retrying automatically..."),this.sync(t,n+1)):{status:exports.SyncStatus.FAILED,message:"Sync failed: Remote config is changing too frequently. Please try again later."};throw e}return await $e(this.snapshotPath,i,this.currentRemoteVersion),{status:exports.SyncStatus.SUCCESS,message:e?"Config sync initialized":"Remote config restored from local",mergedConfig:i}}if(this.originalRemote&&this.isEncryptionModeSwitch(s)&&!t.skipEncryptionSwitchConfirm){if(!await this.confirmEncryptionSwitch(s))return{status:exports.SyncStatus.FAILED,message:this.ctx.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_CANCELLED")}}const u=be(this.originalRemote,i);this.ctx.log.info("Merging configs for sync...");const p=me.merge3Way(a.data,i,u);if(p.conflict)return{status:exports.SyncStatus.CONFLICT,message:"Config sync conflict detected",diffTree:p.diffNode};const g=p.value;!c.isEqual(i,g)&&this.ctx.saveConfig(g);const E=be(g,this.originalRemote,{cleanupEmptyParents:!0});if(this.isEncryptionModeSwitch(s)||!c.isEqual(this.originalRemote,E))try{const e=await this.buildPushPayload(E,s);await this.pushRemoteConfig(e.configStr,e.e2eFields)}catch(e){if("Remote config modified by another device"===(e instanceof Error?e.message:String(e)))return n<1?(this.ctx.log.warn("Conflict detected during sync. Retrying automatically..."),this.sync(t,n+1)):{status:exports.SyncStatus.FAILED,message:"Sync failed: Remote config is changing too frequently. Please try again later."};throw e}return await $e(this.snapshotPath,g,this.currentRemoteVersion),{status:exports.SyncStatus.SUCCESS,message:"Config sync success",mergedConfig:g}}catch(e){if(e instanceof Ae)return{status:exports.SyncStatus.FAILED,message:this.ctx.i18n.translate("CONFIG_SYNC_INVALID_ENCRYPTION_METHOD",{value:`"${String(e.value)}"`})};if(e instanceof De)return{status:exports.SyncStatus.FAILED,message:this.ctx.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_MISSING_HANDLER")};const t=e instanceof Error?e.message:String(e);return{status:exports.SyncStatus.FAILED,message:t}}}async applyResolvedConfig(e,t={}){try{if(!c.isPlainObject(e))return{status:exports.SyncStatus.FAILED,message:"Resolved config is not a valid JSON object"};const n=await ve(this.ctx.configPath);if(!c.isPlainObject(n))return{status:exports.SyncStatus.FAILED,message:"Local config is not a valid JSON object"};const r=be(e,n);if(this.ctx.saveConfig(r),!this.originalRemote){const e=await this.fetchRemoteConfig();if(e&&!c.isPlainObject(e))return{status:exports.SyncStatus.FAILED,message:"Remote config is not a valid JSON object"};this.originalRemote=e||null}const i=this.originalRemote?be(r,this.originalRemote,{cleanupEmptyParents:!0}):r,s=t.useE2E??this.remoteE2EVersion===exports.E2EVersion.V1?exports.EncryptionMethod.E2EE:exports.EncryptionMethod.SSE,o=await this.buildPushPayload(i,s);return await this.pushRemoteConfig(o.configStr,o.e2eFields),await $e(this.snapshotPath,r,this.currentRemoteVersion),{status:exports.SyncStatus.SUCCESS,message:"Config conflict resolved",mergedConfig:r}}catch(e){const t=e instanceof Error?e.message:String(e);return{status:exports.SyncStatus.FAILED,message:t}}}async fetchRemoteConfig(){this.ctx.log.info("Fetching remote config for sync...");const e=await this.configService.fetchConfig();if(!e)return this.currentRemoteVersion=0,this.setRemoteE2EState(exports.E2EVersion.NONE),null;this.currentRemoteVersion=e.version;if((e=>{if(e===exports.E2EVersion.V1)return exports.E2EVersion.V1;if(e===exports.E2EVersion.NONE||void 0===e)return exports.E2EVersion.NONE;if("number"==typeof e)throw new Le(`Unsupported E2E version: ${e}`);return exports.E2EVersion.NONE})(e.encryption?.e2eVersion)===exports.E2EVersion.V1){const t=(e=>{if(!e.encryption?.clientKekSalt)throw new Ne("Missing clientKekSalt for encrypted config");return e.encryption.clientKekSalt})(e),n=(e=>{if(!e.encryption?.clientDekEncrypted)throw new Ne("Missing clientDekEncrypted for encrypted config");return e.encryption.clientDekEncrypted})(e);this.setRemoteE2EState(exports.E2EVersion.V1,t,n);const r=await this.decryptRemoteConfig(e.config,t,n);return l.parse(r)}return this.setRemoteE2EState(exports.E2EVersion.NONE),l.parse(e.config)}async pushRemoteConfig(e,t){this.ctx.log.info("Pushing merged config to remote...");const n=await this.configService.updateConfig(e,this.currentRemoteVersion,t);if(n.conflict)throw this.currentRemoteVersion=n.version,new Error("Remote config modified by another device");this.currentRemoteVersion=n.version,this.applyE2EStateAfterPush(t)}applyE2EStateAfterPush(e){e.e2eVersion===exports.E2EVersion.V1&&e.clientKekSalt&&e.clientDekEncrypted?this.setRemoteE2EState(exports.E2EVersion.V1,e.clientKekSalt,e.clientDekEncrypted):e.e2eVersion===exports.E2EVersion.NONE&&this.setRemoteE2EState(exports.E2EVersion.NONE)}setRemoteE2EState(e,t,n){this.remoteE2EVersion=e,this.remoteClientKekSalt=t,this.remoteClientDekEncrypted=n,n&&n===this.cachedClientDekEncrypted||(this.cachedDEK=void 0,this.cachedClientDekEncrypted=void 0)}async confirmEncryptionSwitch(e){if(!this.onAskEncryptionSwitch)throw new De;const t=this.remoteE2EVersion===exports.E2EVersion.V1?exports.EncryptionMethod.E2EE:exports.EncryptionMethod.SSE,n=this.shouldUseE2E(e)?exports.EncryptionMethod.E2EE:exports.EncryptionMethod.SSE;return this.onAskEncryptionSwitch({from:t,to:n})}async buildPushPayload(e,t){const n=l.stringify(e);if(!this.shouldUseE2E(t))return{configStr:n,e2eFields:{e2eVersion:exports.E2EVersion.NONE}};if(this.remoteE2EVersion===exports.E2EVersion.V1&&this.remoteClientKekSalt&&this.remoteClientDekEncrypted){const e=await this.ensureDEK(this.remoteClientKekSalt,this.remoteClientDekEncrypted);return{configStr:this.e2eService.encryptConfig(n,e),e2eFields:{e2eVersion:exports.E2EVersion.V1,clientKekSalt:this.remoteClientKekSalt,clientDekEncrypted:this.remoteClientDekEncrypted}}}const r=await this.askPin(exports.E2EAskPinReason.SETUP,0),{payload:i,dek:s}=this.e2eService.generateE2EPayload(n,r);return this.cachedDEK=s,this.cachedClientDekEncrypted=i.clientDekEncrypted,{configStr:i.config,e2eFields:{e2eVersion:i.e2eVersion,clientKekSalt:i.clientKekSalt,clientDekEncrypted:i.clientDekEncrypted}}}shouldUseE2E(e){return e===exports.EncryptionMethod.E2EE||e!==exports.EncryptionMethod.SSE&&this.remoteE2EVersion===exports.E2EVersion.V1}isEncryptionModeSwitch(e){return this.shouldUseE2E(e)!==(this.remoteE2EVersion===exports.E2EVersion.V1)}async decryptRemoteConfig(e,t,n){const r=await this.ensureDEK(t,n);try{return this.e2eService.decryptConfig(e,r)}catch(e){if(e instanceof Te)throw new Ne("Failed to decrypt remote config payload");throw e}}async ensureDEK(e,t){if(this.cachedDEK&&this.cachedClientDekEncrypted===t)return this.cachedDEK;const n=this.e2eService.decodeSalt(e);for(let e=0;e<4;e+=1){const r=0===e?exports.E2EAskPinReason.DECRYPT:exports.E2EAskPinReason.RETRY,i=await this.askPin(r,e);try{const e=this.e2eService.unwrapDEK(t,i,n);return this.cachedDEK=e,this.cachedClientDekEncrypted=t,e}catch(e){if(e instanceof Te)continue;throw e}}throw new ye}async askPin(e,t){if(!this.onAskPin)throw new Pe;const n=await this.onAskPin(e,t);if(null==n||0===n.length)throw new Ue;return n}}const He=e=>{if(void 0===e)return"undefined";try{return JSON.stringify(e)}catch{return E.inspect(e,{depth:4,breakLength:120,maxArrayLength:50})}},ke=(e,t=0)=>{const n=" ".repeat(2*t),r=e.status===exports.ConflictType.CONFLICT?g.red:e.status===exports.ConflictType.ADDED?g.green:e.status===exports.ConflictType.DELETED?g.gray:e.status===exports.ConflictType.MODIFIED?g.yellow:g.white;if(console.log(`${n}${r(`[${e.status}]`)} ${e.key}`),e.status!==exports.ConflictType.CONFLICT||e.children&&0!==e.children.length||(console.log(`${n} ${g.gray("snapshot:")} ${He(e.snapshotValue)}`),console.log(`${n} ${g.cyan("local :")} ${He(e.localValue)}`),console.log(`${n} ${g.magenta("remote:")} ${He(e.remoteValue)}`)),e.children?.length)for(const n of e.children)ke(n,t+1)},Ye={handle:e=>{e.cmd.program.command("config").description("manage picgo config").command("sync").description("sync config with picgo cloud").option("--encrypt [method]","encryption method (auto|sse|e2ee)").option("--skip-encryption-switch-confirm","skip encryption switch confirmation").action(async t=>{const n=t.encrypt;let r;if(void 0!==n){const t="string"==typeof n?n:void 0;if(t!==exports.EncryptionMethod.AUTO&&t!==exports.EncryptionMethod.SSE&&t!==exports.EncryptionMethod.E2EE){const n=t??"undefined";return void e.log.error(e.i18n.translate("CONFIG_SYNC_INVALID_ENCRYPTION_METHOD",{value:`"${n}"`}))}r=t,e.saveConfig({"settings.picgoCloud.encryptionMethod":t})}const i=new Fe(e,{onAskPin:async(t,n)=>{if(t===exports.E2EAskPinReason.SETUP){for(let t=0;t<3;t+=1){const{pin:t}=await e.cmd.inquirer.prompt([{type:"password",name:"pin",message:"Set up E2E encryption. Enter PIN",mask:"*"}]),{confirmPin:n}=await e.cmd.inquirer.prompt([{type:"password",name:"confirmPin",message:"Confirm PIN",mask:"*"}]);if(t===n)return t;e.log.warn("PIN confirmation does not match. Please try again.")}return null}const r=t===exports.E2EAskPinReason.DECRYPT?"Enter PIN to decrypt config":`Incorrect PIN. Retry (${n}/3)`,{pin:i}=await e.cmd.inquirer.prompt([{type:"password",name:"pin",message:r,mask:"*"}]);return i},onAskEncryptionSwitch:async({from:t,to:n})=>{const r=e.i18n.translate(t===exports.EncryptionMethod.E2EE?"CONFIG_SYNC_ENCRYPTION_METHOD_E2EE":"CONFIG_SYNC_ENCRYPTION_METHOD_SSE"),i=e.i18n.translate(n===exports.EncryptionMethod.E2EE?"CONFIG_SYNC_ENCRYPTION_METHOD_E2EE":"CONFIG_SYNC_ENCRYPTION_METHOD_SSE"),s=e.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_TITLE"),o=e.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_BODY",{from:r,to:i}),{confirm:a}=await e.cmd.inquirer.prompt([{type:"list",name:"confirm",message:`${s}\n\n${o}`,choices:[{name:e.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_CONFIRM"),value:!0},{name:e.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_CANCEL"),value:!1}]}]);return a}}),s=await i.sync({encryptionMethod:r,skipEncryptionSwitchConfirm:t.skipEncryptionSwitchConfirm});if(s.status!==exports.SyncStatus.SUCCESS){if(s.status===exports.SyncStatus.CONFLICT){e.log.warn(s.message||"Config sync conflict detected."),s.diffTree&&ke(s.diffTree);const{strategy:t}=await e.cmd.inquirer.prompt([{type:"list",name:"strategy",message:"Choose a strategy to resolve conflicts",choices:[{name:"Use Local",value:"local"},{name:"Use Remote",value:"remote"},{name:"Abort",value:"abort"}]}]);if("abort"===t)return void e.log.warn("Config sync aborted.");const n="local"===t?s.diffTree?.localValue:s.diffTree?.remoteValue;if(!n||!c.isPlainObject(n))return void e.log.error("Invalid resolved config, please resolve it manually.");let o;if(r===exports.EncryptionMethod.E2EE)o={useE2E:!0};else if(r===exports.EncryptionMethod.SSE)o={useE2E:!1};else{const t=e.getConfig("settings.picgoCloud.encryptionMethod");t===exports.EncryptionMethod.E2EE?o={useE2E:!0}:t===exports.EncryptionMethod.SSE&&(o={useE2E:!1})}const a=await i.applyResolvedConfig(n,o);return a.status===exports.SyncStatus.SUCCESS?void e.log.success(a.message||"Config sync resolved!"):void e.log.error(a.message||"Failed to apply resolved config")}e.log.error(s.message||"Config sync failed")}else e.log.success(s.message||"Config sync success!")})}},qe=e=>e.trim(),Ve=e=>qe(e).toLowerCase(),Ke=(e,t)=>{const n=Ve(t);return e.find(e=>Ve(e)===n)},je=async(e,t,n,r)=>{const i=await e.cmd.inquirer.prompt(t),s="transformer"===n?`transformer.${r}`:r;e.saveConfig({[s]:i}),"transformer"===n&&e.saveConfig({"picBed.transformer":r})},We={handle:e=>{e.cmd.program.command("set").arguments("<module> [name] [configName]").description("configure config of picgo modules (uploader/transformer/plugin)").action(async(t,n,r)=>{try{switch(t){case"uploader":{const t=n||(await e.cmd.inquirer.prompt([{type:"list",name:"uploaderType",choices:e.helper.uploader.getIdList(),message:"Choose an uploader",default:e.getConfig("picBed.uploader")||e.getConfig("picBed.current")||"smms"}])).uploaderType,i=e.helper.uploader.get(t);if(!i)return e.log.error(`No uploader named ${t}`);if(!i.config)return e.log.error(`Uploader ${t} has no config`);const s=e.uploaderConfig.getConfigList(t),o=s.map(e=>e._configName);let a="string"==typeof r?qe(r):"";if(!a)if(o.length>0){const t=await e.cmd.inquirer.prompt([{type:"list",name:"configChoice",message:"Choose a config",choices:[{name:"[Create New Config]",value:"__CREATE__"},...o]}]);if("__CREATE__"===t.configChoice){const t=await e.cmd.inquirer.prompt([{type:"input",name:"newConfigName",message:"Enter config name",validate:e=>{const t=qe(e);return t?!Ke(o,t)||`Config name ${t} already exists`:"Config name can not be empty"}}]);a=qe(t.newConfigName)}else a=String(t.configChoice)}else{const t=await e.cmd.inquirer.prompt([{type:"input",name:"newConfigName",message:"Enter config name",validate:e=>!!qe(e)||"Config name can not be empty"}]);a=qe(t.newConfigName)}const c=Ke(o,a);if(c){const n=s.find(e=>Ve(e._configName)===Ve(c));n&&e.setConfig({[`picBed.${t}`]:n})}const l=await e.cmd.inquirer.prompt(i.config(e));e.uploaderConfig.createOrUpdate(t,a,l)}break;case"transformer":if(n){const r=e.helper.transformer.get(n);if(!r)return e.log.error(`No transformer named ${n}`);r.config&&await je(e,r.config(e),t,n)}else{const n=[{type:"list",name:"transformer",choices:e.helper.transformer.getIdList(),message:"Choose a transformer"}],r=await e.cmd.inquirer.prompt(n),i=e.helper.transformer.get(r.transformer);i?.config&&await je(e,i.config(e),t,r.transformer)}break;case"plugin":if(n){if(n.includes("picgo-plugin-")||(n=`picgo-plugin-${n}`),!Object.keys(e.getConfig("picgoPlugins")).includes(n))return e.log.error(`No plugin named ${n}`);e.pluginLoader.getPlugin(n)?.config&&await je(e,e.pluginLoader.getPlugin(n).config(e),"plugin",n)}else{const t=[{type:"list",name:"plugin",choices:e.pluginLoader.getFullList(),message:"Choose a plugin"}],n=await e.cmd.inquirer.prompt(t);e.pluginLoader.getPlugin(n.plugin)?.config&&await je(e,e.pluginLoader.getPlugin(n.plugin).config(e),"plugin",n.plugin)}break;default:return e.log.warn(`No module named ${t}`),e.log.warn("Available modules are uploader|transformer|plugin")}e.log.success("Configure config successfully!"),"plugin"===t&&e.log.info("If you want to use this config, please run 'picgo use plugins'")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}})}},Qe={handle:async e=>{const t=e.cmd;t.program.command("use").arguments("[module] [name] [configName]").description("use a module (uploader/transformer/plugin) of picgo").action(async(n,r,i)=>{try{if("uploader"===n&&r)return e.uploaderConfig.use(r,i),void e.log.success("Activated config successfully!");const s=["uploader","transformer","plugins"];let o=[];const a={uploader:{type:"list",name:"uploader",message:"Use an uploader",choices:e.helper.uploader.getIdList(),default:e.getConfig("picBed.uploader")||e.getConfig("picBed.current")||"smms"},transformer:{type:"list",name:"transformer",message:"Use a transformer",choices:e.helper.transformer.getIdList(),default:e.getConfig("picBed.transformer")||"path"},plugins:{type:"checkbox",name:"plugins",message:"Use plugins",choices:e.pluginLoader.getFullList(),default:Object.keys(e.getConfig("picgoPlugins")).filter(t=>e.getConfig(`picgoPlugins.${t}`))}};if(n){if("uploader"!==n&&"transformer"!==n&&"plugins"!==n)return e.log.warn(`No module named ${n}`),e.log.warn(`Available modules are ${s.join("|")}`);o.push(a[n])}else o=s.map(e=>a[e]);const c=await t.inquirer.prompt(o);if(c.plugins){const t=c.plugins,n=e.getConfig("picgoPlugins");Object.keys(n).forEach(e=>{n[e]=t.includes(e)}),e.saveConfig({picgoPlugins:n})}if(c.uploader){const n=c.uploader,r=e.uploaderConfig.getConfigList(n);if(r.length>1){const i=e.uploaderConfig.getActiveConfig(n),s=await t.inquirer.prompt([{type:"list",name:"uploaderConfigName",message:"Use an uploader config",choices:r.map(e=>e._configName),default:i?._configName}]);e.uploaderConfig.use(n,s.uploaderConfigName)}else e.uploaderConfig.use(n)}void 0!==c.transformer&&e.saveConfig({"picBed.transformer":c.transformer||"path"}),e.log.success("Configure config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}})}},ze={handle:e=>{e.cmd.program.option("-p, --proxy <url>","set proxy for uploading",t=>{e.setConfig({"picBed.proxy":t})})}},Je={handle:e=>{e.cmd.program.command("i18n").arguments("[lang]").description("change picgo language").action(async(t="")=>{const n=e.i18n.getLanguageList();if(!t){const t=[{type:"list",name:"i18n",choices:n,message:"Choose a language",default:e.getConfig("settings.language")||"zh-CN"}],r=await e.cmd.inquirer.prompt(t);return e.i18n.setLanguage(r.i18n),void e.log.success(`Language set to ${r.i18n}`)}if(!n.includes(t))return e.log.warn("No such language");e.i18n.setLanguage(t),e.log.success(`Language set to ${t}`)})}},Xe={handle:e=>{e.cmd.program.command("server").description("run PicGo as a standalone server").helpOption("--help","display help for command").option("-p, --port <n>","server port").option("-h, --host <s>","server host").option("-i, --ignore-existing-external-server","ignore existing PicGo server instance").option("--secret <s>","server authentication secret").action(async t=>{try{const n=t.port?Number(t.port):void 0,r=t.host;await e.server.listen(n,r,t.ignoreExistingExternalServer,t.secret)}catch(t){e.log.error(t)}})}},Ze={handle:e=>{e.cmd.program.command("login").description("login to cloud.picgo.app").arguments("[token]").action(async t=>{try{await e.cloud.login(t)}catch(t){e.log.error(t)}})}},et={handle:e=>{e.cmd.program.command("logout").description("logout from cloud.picgo.app").action(async()=>{try{e.cloud.logout()}catch(t){e.log.error(t)}})}},tt=e=>e.trim(),nt=e=>tt(e).toLowerCase(),rt=(e,t)=>{const n=e.getConfig("picBed.current"),r=[];for(const i of t){n===i?r.push(g.green.bold(`+ ${i} [Current Uploader]`)):r.push(`+ ${i}`);const t=e.uploaderConfig.getConfigList(i);if(0===t.length){r.push(g.grey(" (No configs found)"));continue}const s=e.getConfig(`uploader.${i}.defaultId`);for(const e of t)e._id===s?r.push(g.blue(` * ${e._configName} [Default Config]`)):r.push(` ${e._configName}`)}return`\n${r.join("\n")}`},it={handle:e=>{const t=e.cmd,n=t.program.command("uploader").description("manage uploader configurations").action(async()=>{try{const n=[{name:"List all configurations",value:"list"},{name:"Rename config",value:"rename"},{name:"Copy config",value:"copy"},{name:"Delete config",value:"delete"}],r=await t.inquirer.prompt([{type:"list",name:"operation",message:"Choose an operation:",choices:n}]);if("list"===r.operation){const t=e.uploaderConfig.listUploaderTypes();return void console.log(rt(e,t))}const i=e.uploaderConfig.listUploaderTypes().filter(t=>e.uploaderConfig.getConfigList(t).length>0);if(0===i.length)return void e.log.warn("No configs found");const s=await t.inquirer.prompt([{type:"list",name:"type",message:"Choose an uploader:",choices:i}]),o=String(s.type),a=e.uploaderConfig.getConfigList(o).map(e=>e._configName),c=await t.inquirer.prompt([{type:"list",name:"configName",message:"rename"===r.operation?"Choose a config to rename:":"copy"===r.operation?"Choose a config to copy:":"Choose a config to delete:",choices:a}]),l=String(c.configName);if("rename"===r.operation){const n=await t.inquirer.prompt([{type:"input",name:"newName",message:"Enter new name:",validate:e=>{const t=tt(e);if(!t)return"Config name can not be empty";return!a.some(e=>nt(e)===nt(t)&&nt(e)!==nt(l))||`Config name ${t} already exists`}}]);return e.uploaderConfig.rename(o,l,String(n.newName)),void e.log.success("Rename config successfully!")}if("copy"===r.operation){const n=await t.inquirer.prompt([{type:"input",name:"newName",message:"Enter new name:",validate:e=>{const t=tt(e);if(!t)return"Config name can not be empty";return!a.some(e=>nt(e)===nt(t))||`Config name ${t} already exists`}}]);return e.uploaderConfig.copy(o,l,String(n.newName)),void e.log.success("Copy config successfully!")}if(!(await t.inquirer.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete ${l}?`,default:!1}])).confirm)return;e.uploaderConfig.remove(o,l),e.log.success("Delete config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}});n.command("list [type]").description("list uploader configurations").action(async t=>{try{const n=e.uploaderConfig.listUploaderTypes();if("string"==typeof t&&t)return n.includes(t)?void console.log(rt(e,[t])):void e.log.error(`Type ${t} not found`);console.log(rt(e,n))}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}}),n.command("rename <type> <oldName> <newName>").description("rename a config").action(async(t,n,r)=>{try{e.uploaderConfig.rename(t,n,r),e.log.success("Rename config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}}),n.command("copy <type> <configName> <newConfigName>").description("copy a config (does not switch current uploader)").action(async(t,n,r)=>{try{e.uploaderConfig.copy(t,n,r),e.log.success("Copy config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}}),n.command("rm <type> <configName>").description("remove a config").action(async(t,n)=>{try{e.uploaderConfig.remove(t,n),e.log.success("Delete config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}})}};class st{static currentPlugin;list;pluginIdMap;name;constructor(e){this.name=e,this.list=new Map,this.pluginIdMap=new Map}register(e,t){if(!e)throw new TypeError("id is required!");if("function"!=typeof t.handle)throw new TypeError("plugin.handle must be a function!");if(this.list.has(e))throw new TypeError(`${this.name} duplicate id: ${e}!`);this.list.set(e,t),st.currentPlugin&&(this.pluginIdMap.has(st.currentPlugin)?this.pluginIdMap.get(st.currentPlugin)?.push(e):this.pluginIdMap.set(st.currentPlugin,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);t?.forEach(e=>{this.list.delete(e)})}}getName(){return this.name}get(e){return this.list.get(e)}getList(){return[...this.list.values()]}getIdList(){return[...this.list.keys()]}}const ot=(e=null)=>{st.currentPlugin=e};class at{name="commander";static currentPlugin;list=new Map;pluginIdMap=new Map;ctx;program;inquirer;constructor(e){this.program=new i.Command,this.inquirer=s,this.ctx=e}getName(){return this.name}init(){var e;this.program.version("2.0.3","-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",v),e.cmd.register("configPath",M),e.cmd.register("config",Ye),e.cmd.register("setting",We),e.cmd.register("upload",se),e.cmd.register("use",Qe),e.cmd.register("proxy",ze),e.cmd.register("i18n",Je),e.cmd.register("server",Xe),e.cmd.register("login",Ze),e.cmd.register("logout",et),e.cmd.register("uploader",it)}register(e,t){if(!e)throw new TypeError("name is required!");if("function"!=typeof t.handle)throw new TypeError("plugin.handle must be a function!");if(this.list.has(e))throw new TypeError(`${this.name} plugin duplicate id: ${e}!`);this.list.set(e,t);const n=st.currentPlugin;null!==n&&(this.pluginIdMap.has(n)?this.pluginIdMap.get(n)?.push(e):this.pluginIdMap.set(n,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);t?.forEach(e=>{this.list.delete(e)})}}loadCommands(){this.getList().forEach(e=>{try{e.handle(this.ctx)}catch(e){this.ctx.log.error(e)}})}get(e){return this.list.get(e)}getList(){return[...this.list.values()]}getIdList(){return[...this.list.keys()]}}var ct,lt;exports.ILogType=void 0,(ct=exports.ILogType||(exports.ILogType={})).success="success",ct.info="info",ct.warn="warn",ct.error="error",exports.IBuildInEvent=void 0,(lt=exports.IBuildInEvent||(exports.IBuildInEvent={})).UPLOAD_PROGRESS="uploadProgress",lt.FAILED="failed",lt.BEFORE_TRANSFORM="beforeTransform",lt.BEFORE_UPLOAD="beforeUpload",lt.AFTER_UPLOAD="afterUpload",lt.FINISHED="finished",lt.INSTALL="install",lt.UNINSTALL="uninstall",lt.UPDATE="update",lt.NOTIFICATION="notification",exports.IBusEvent=void 0,(exports.IBusEvent||(exports.IBusEvent={})).CONFIG_CHANGE="CONFIG_CHANGE";class ut{level={[exports.ILogType.success]:"green",[exports.ILogType.info]:"blue",[exports.ILogType.warn]:"yellow",[exports.ILogType.error]:"red"};ctx;logLevel;logPath;constructor(e){this.ctx=e}handleLog(e,...n){if(this.logLevel=this.ctx.getConfig("settings.logLevel"),!this.ctx.getConfig("silent")&&this.checkLogLevel(e,this.logLevel)){const r=g[this.level[e]](`[PicGo ${e.toUpperCase()}]:`);console.log(r,...n),this.logPath=this.ctx.getConfig("settings.logPath")||t.join(this.ctx.baseDir,"./picgo.log"),setTimeout(()=>{try{const t=this.checkLogFileIsLarge(this.logPath);if(t.isLarge){const e=`Log file is too large (> ${t.logFileSizeLimit/1024/1024||"10"} MB), recreate log file`;console.log(g.yellow("[PicGo WARN]:"),e),this.recreateLogFile(this.logPath),n.unshift(e)}this.handleWriteLog(this.logPath,e,...n)}catch(e){console.error("[PicGo Error] on checking log file size",e)}},0)}}checkLogFileIsLarge(t){if(e.existsSync(t)){const n=e.statSync(t).size,r=1024*ne(this.ctx.getConfig("settings.logFileSizeLimit")||10)*1024;return{isLarge:n>r,logFileSize:n,logFileSizeLimit:r}}return{isLarge:!1}}recreateLogFile(t){e.existsSync(t)&&(e.unlinkSync(t),e.createFileSync(t))}handleWriteLog(t,n,...r){try{let i=`${d().format("YYYY-MM-DD HH:mm:ss")} [PicGo ${n.toUpperCase()}] `;r.forEach(e=>{e instanceof Error&&"error"===n?i+=`\n------Error Stack Begin------\n${E.format(e?.stack)}\n-------Error Stack End------- `:("object"==typeof e&&(e=JSON.stringify(e,null,2)),i+=`${e} `)}),i+="\n",e.appendFileSync(t,i)}catch(e){console.error("[PicGo Error] on writing log file",e)}}checkLogLevel(e,t){return void 0===t||"all"===t||(Array.isArray(t)?t.some(t=>t===e||"all"===t):e===t)}success(...e){return this.handleLog(exports.ILogType.success,...e)}info(...e){return this.handleLog(exports.ILogType.info,...e)}error(...e){return this.handleLog(exports.ILogType.error,...e)}warn(...e){return this.handleLog(exports.ILogType.warn,...e)}debug(...e){re()&&this.handleLog(exports.ILogType.info,...e)}}class pt extends n.EventEmitter{ctx;constructor(e){super(),this.ctx=e}async start(e){const t=(e=>({configPath:e.configPath,baseDir:e.baseDir,log:e.log,cmd:e.cmd,server:e.server,cloud:e.cloud,uploaderConfig:e.uploaderConfig,output:[],input:[],pluginLoader:e.pluginLoader,pluginHandler:e.pluginHandler,Request:e.Request,helper:e.helper,VERSION:e.VERSION,GUI_VERSION:e.GUI_VERSION,request:e.request,openUrl:e.openUrl.bind(e),i18n:e.i18n,getConfig:e.getConfig.bind(e),saveConfig:e.saveConfig.bind(e),removeConfig:e.removeConfig.bind(e),setConfig:e.setConfig.bind(e),unsetConfig:e.unsetConfig.bind(e),upload:e.upload.bind(e),addListener:e.addListener.bind(e),on:e.on.bind(e),once:e.once.bind(e),removeListener:e.removeListener.bind(e),off:e.off.bind(e),removeAllListeners:e.removeAllListeners.bind(e),setMaxListeners:e.setMaxListeners.bind(e),getMaxListeners:e.getMaxListeners.bind(e),listeners:e.listeners.bind(e),rawListeners:e.rawListeners.bind(e),emit:e.emit.bind(e),listenerCount:e.listenerCount.bind(e),prependListener:e.prependListener.bind(e),prependOnceListener:e.prependOnceListener.bind(e),eventNames:e.eventNames.bind(e)}))(this.ctx);try{if(!Array.isArray(e))throw new Error("Input must be an array.");return t.input=e,t.output=[],await this.beforeTransform(t),await this.doTransform(t),await this.beforeUpload(t),await this.doUpload(t),await this.afterUpload(t),t}catch(e){if(t.log.warn(exports.IBuildInEvent.FAILED),t.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,-1),t.emit(exports.IBuildInEvent.FAILED,e),t.log.error(e),t.getConfig("debug"))throw e;return t}}async beforeTransform(e){return e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,0),e.emit(exports.IBuildInEvent.BEFORE_TRANSFORM,e),e.log.info("Before transform"),await this.handlePlugins(e.helper.beforeTransformPlugins,e),e}async doTransform(e){e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,30);const t=e.getConfig("picBed.transformer")||"path";let n=t,r=e.helper.transformer.get(t);return r||(r=e.helper.transformer.get("path"),n="path",e.log.warn(`Can't find transformer - ${t}, switch to default transformer - path`)),e.log.info(`Transforming... Current transformer is [${n}]`),await(r?.handle(e)),e}async beforeUpload(e){return e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,60),e.log.info("Before upload"),e.emit(exports.IBuildInEvent.BEFORE_UPLOAD,e),await this.handlePlugins(e.helper.beforeUploadPlugins,e),e}async doUpload(e){let t=e.getConfig("picBed.uploader")||e.getConfig("picBed.current")||"smms",n=e.helper.uploader.get(t),r=t;n||(t="smms",r="smms",n=e.helper.uploader.get("smms"),e.log.warn(`Can't find uploader - ${t}, switch to default uploader - smms`)),e.log.info(`Uploading... Current uploader is [${r}]`),await(n?.handle(e));for(const n of e.output)n.type=t;return e}async afterUpload(e){e.emit(exports.IBuildInEvent.AFTER_UPLOAD,e),e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,100),(e=>{const t=e.getConfig("settings.urlRewrite.rules");if(Array.isArray(t)&&0!==t.length)for(const n of e.output)G(n,t,e)})(e),await this.handlePlugins(e.helper.afterUploadPlugins,e);let t="";const n=e.output.length,r=!0===e.getConfig("settings.encodeOutputURL");for(let i=0;i<n;i++)void 0!==e.output[i].imgUrl&&(t+=r?F(e.output[i].imgUrl):e.output[i].imgUrl,i!==n-1&&(t+="\n")),delete e.output[i].base64Image,delete e.output[i].buffer;return e.emit(exports.IBuildInEvent.FINISHED,e),e.log.success(`\n${t}`),e}async handlePlugins(e,t){const n=e.getList(),r=e.getIdList(),i=e.getName();return await Promise.all(n.map(async(e,n)=>{try{t.log.info(`${i}: ${r[n]} running`),await e.handle(t)}catch(e){throw t.log.error(`${i}: ${r[n]} error`),e}})),t}}const gt=(e,t,n,r="")=>{const i=r||"s.ee";return{method:"POST",url:`https://${i}${"s.ee"===i?"/api/v1/file/upload":"/api/v2/upload"}`,headers:{contentType:"multipart/form-data","User-Agent":"PicGo",Authorization:n},formData:{smfile:{value:t,options:{filename:e}}}}},Et=async e=>{const t=e.getConfig("picBed.smms");if(!t)throw new Error("Can not find smms config!");const n=e.output;for(const r of n)if(r.fileName&&r.buffer){let n=r.buffer;!n&&r.base64Image&&(n=Buffer.from(r.base64Image,"base64"));const i=gt(r.fileName,n,t?.token,t?.backupDomain);try{const t=await e.request(i),n=JSON.parse(t);if(200!==n.code&&"success"!==n.message)throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:n.message}),new Error(n.message);delete r.base64Image,delete r.buffer,r.imgUrl=n.data.url}catch(t){throw e.log.error(t),t}}return e},dt=e=>{const t=e.getConfig("picBed.smms")||{};return[{name:"token",message:"api token",type:"password",get alias(){return e.i18n.translate("PICBED_SMMS_TOKEN")},default:t.token||"",required:!0},{name:"backupDomain",type:"input",get prefix(){return e.i18n.translate("PICBED_SMMS_BACKUP_DOMAIN")},get message(){return e.i18n.translate("PICBED_SMMS_MESSAGE_BACKUP_DOMAIN")},get alias(){return e.i18n.translate("PICBED_SMMS_BACKUP_DOMAIN")},default:t.backupDomain||"",required:!1}]};const ht=e=>h.lookup(e)||"application/octet-stream",_t=(e,t,n,r)=>{const i=e.secretId,s=e.secretKey,o=e.appId,a=e.bucket;let c,l="";if(e.version&&"v4"!==e.version){const i=Math.floor((new Date).getTime()/1e3);l=`${i};${i+86400}`;const o=p.createHmac("sha1",s).update(l).digest("hex"),a=e.endpoint?e.endpoint:`cos.${e.area}.myqcloud.com`,g=`put\n/${e.path}${t}\n\ncontent-length=${r}&content-type=${u=n,encodeURIComponent(u).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A")}&host=${e.bucket}.${a}\n`,E=`sha1\n${l}\n${p.createHash("sha1").update(g).digest("hex")}\n`;c=p.createHmac("sha1",o).update(E).digest("hex")}else{const e=Math.floor(1e10*Math.random()),t=Math.floor((new Date).getTime()/1e3)-1,n=`a=${o}&b=${a}&k=${i}&e=${t+3600}&t=${t}&r=${e}&f=`,r=p.createHmac("sha1",s).update(n).digest(),l=Buffer.concat([r,Buffer.from(n)]);c=Buffer.from(l).toString("base64")}var u;return{signature:c,appId:o,bucket:a,signTime:l}},ft=(e,t,n,r,i)=>{const s=e.area,o=e.path;if(e.version&&"v4"!==e.version){const s=e.endpoint?e.endpoint:`cos.${e.area}.myqcloud.com`;return{method:"PUT",url:`http://${e.bucket}.${s}/${H(o,t)}`,headers:{Host:`${e.bucket}.${s}`,Authorization:`q-sign-algorithm=sha1&q-ak=${e.secretId}&q-sign-time=${n.signTime}&q-key-time=${n.signTime}&q-header-list=content-length;content-type;host&q-url-param-list=&q-signature=${n.signature}`,contentType:ht(t),contentLength:r.byteLength,"User-Agent":`PicGo;${i};null;null`},body:r,resolveWithFullResponse:!0}}return{method:"POST",url:`http://${s}.file.myqcloud.com/files/v2/${n.appId}/${n.bucket}/${H(o,t)}`,headers:{Host:`${s}.file.myqcloud.com`,Authorization:n.signature,contentType:"multipart/form-data","User-Agent":`PicGo;${i};null;null`},formData:{op:"upload",filecontent:r},resolveWithFullResponse:!0}},It=async e=>{const t=e.getConfig("picBed.tcyun");if(!t)throw new Error("Can't find tencent COS config");try{const n=e.output,r=t.customUrl,i=t.path,s=!t.version||"v4"===t.version;for(const o of n)if(o.fileName&&o.buffer){let n=o.buffer;!n&&o.base64Image&&(n=Buffer.from(o.base64Image,"base64"));const a=_t(t,o.fileName,ht(o.fileName),n.byteLength);if(!a)return!1;const c=ft(t,o.fileName,a,n,e.GUI_VERSION||e.VERSION),l=await e.request(c).then(e=>e).catch(t=>({statusCode:400,body:{msg:e.i18n.translate("AUTH_FAILED"),err:t}}));let u;if(u=s&&"string"==typeof l?JSON.parse(l):l,400===u.statusCode)throw u?.body?.err?u.body.err:new Error(u?.body?.msg||u?.body?.message);const p=t.options||"",g=t.slim||"";if(s&&"SUCCESS"===u.message)delete o.base64Image,delete o.buffer,o.imgUrl=r?`${r}/${i}${o.fileName}`:`${u.data.source_url}${p}`;else{if(s||!u||200!==u.statusCode)throw new Error(l.body.msg);if(delete o.base64Image,delete o.buffer,r)o.imgUrl=`${r}/${encodeURI(i)}${H(o.fileName)}${p}`;else{const e=t.endpoint?t.endpoint:`cos.${t.area}.myqcloud.com`;o.imgUrl=`https://${t.bucket}.${e}/${encodeURI(i)}${H(o.fileName)}${p}`}}g&&(o.imgUrl+=p?"&imageSlim":"?imageSlim")}return e}catch(n){if(!t.version||"v4"===t.version)try{const t=JSON.parse(n.error);e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("UPLOAD_FAILED_REASON",{code:t.code}),text:"https://cloud.tencent.com/document/product/436/8432"})}catch(e){}throw n}},Ct=e=>{const t=e.getConfig("picBed.tcyun")||{};return[{name:"version",type:"list",alias:e.i18n.translate("PICBED_TENCENTCLOUD_VERSION"),choices:["v4","v5"],default:"v5",required:!1},{name:"secretId",type:"input",get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_SECRETID")},default:t.secretId||"",required:!0},{name:"secretKey",type:"password",get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_SECRETKEY")},default:t.secretKey||"",required:!0},{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_BUCKET")},default:t.bucket||"",required:!0},{name:"appId",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_APPID")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_APPID")},default:t.appId||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_APPID")},required:!0},{name:"area",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_AREA")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_AREA")},default:t.area||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_AREA")},required:!0},{name:"endpoint",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_ENDPOINT")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_ENDPOINT")},default:t.endpoint||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT")},required:!1},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_PATH")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_PATH")},default:t.path||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_PATH")},required:!1},{name:"customUrl",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_CUSTOMURL")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_CUSTOMURL")},default:t.customUrl||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL")},required:!1},{name:"options",type:"input",default:t.options||"",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_OPTIONS")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_OPTIONS")},get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_OPTIONS")},required:!1},{name:"slim",type:"confirm",default:t.options||"",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM")},required:!1,get confirmText(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM_CONFIRM")},get cancelText(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM_CANCEL")},get tips(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM_TIP")}}]};const mt=(e,t,n)=>{const r=t.path||"",{token:i,repo:s}=t;return{method:"PUT",url:`https://api.github.com/repos/${s}/contents/${H(r,e)}`,headers:{Authorization:`token ${i}`,"User-Agent":"PicGo","Content-Type":h.lookup(e)},body:n,json:!0}},St=async e=>{const t=e.getConfig("picBed.github");if(!t)throw new Error("Can't find github config");try{const n=e.output;for(const r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i={message:"Upload by PicGo",branch:t.branch,content:n,path:t.path+encodeURI(r.fileName)},s=mt(r.fileName,t,i);try{const n=await e.request(s);if(!n)throw new Error("Server error, please try again");delete r.base64Image,delete r.buffer,t.customUrl?r.imgUrl=`${t.customUrl}/${H(t.path||"",r.fileName)}`:r.imgUrl=n.content.download_url}catch(e){if(422!==e.statusCode)throw e;delete r.base64Image,delete r.buffer,t.customUrl?r.imgUrl=`${t.customUrl}/${H(t.path||"",r.fileName)}`:r.imgUrl=`https://raw.githubusercontent.com/${t.repo}/${t.branch}/${H(t.path||"",r.fileName)}`}}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK")}),t}},Nt=e=>{const t=e.getConfig("picBed.github")||{};return[{name:"repo",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_REPO")},get alias(){return e.i18n.translate("PICBED_GITHUB_REPO")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_REPO")},default:t.repo||"",required:!0},{name:"branch",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_BRANCH")},get alias(){return e.i18n.translate("PICBED_GITHUB_BRANCH")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_BRANCH")},default:t.branch||"master",required:!0},{name:"token",type:"password",get alias(){return e.i18n.translate("PICBED_GITHUB_TOKEN")},default:t.token||"",required:!0},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_PATH")},get alias(){return e.i18n.translate("PICBED_GITHUB_PATH")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_PATH")},default:t.path||"",required:!1},{name:"customUrl",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_CUSTOMURL")},get alias(){return e.i18n.translate("PICBED_GITHUB_CUSTOMURL")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_CUSTOMURL")},default:t.customUrl||"",required:!1}]};function Lt(e,t,n,r){const i=function(e){return"z0"===e?"":"-"+e}(e.area||"z0"),s=e.path||"";return{method:"POST",url:`http://upload${i}.qiniup.com/putb64/-1/key/${Buffer.from(s+t,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_")}`,headers:{Authorization:`UpToken ${n}`,"Content-Type":h.lookup(t)||"application/octet-stream"},body:r}}function Pt(e){return e.replace(/\//g,"_").replace(/\+/g,"-")}function Dt(e){const t=e.accessKey,n=e.secretKey,r={scope:e.bucket,deadline:3600+Math.floor(Date.now()/1e3)},i=(s=JSON.stringify(r),Pt(Buffer.from(s).toString("base64")));var s;const o=Pt(function(e,t){const n=_.createHmac("sha1",t);return n.update(e),n.digest("base64")}(i,n));return[t,o,i].join(":")}const Ut=async e=>{const t=e.getConfig("picBed.qiniu");if(!t)throw new Error("Can't find qiniu config");try{const n=e.output;for(const r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i=Lt(t,r.fileName,Dt(t),n),s=await e.request(i),o=JSON.parse(s);if(!o?.key)throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:o.msg}),e.log.error("qiniu error",o),new Error("Upload failed");{delete r.base64Image,delete r.buffer;const e=t.url,n=t.options;r.imgUrl=`${e}/${o.key}${n}`}}return e}catch(t){if("Upload failed"!==t.message&&t.response){const n=t.response.body;e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:n.error})}throw t}},yt=e=>{const t=e.getConfig("picBed.qiniu")||{};return[{name:"accessKey",type:"input",get alias(){return e.i18n.translate("PICBED_QINIU_ACCESSKEY")},default:t.accessKey||"",required:!0},{name:"secretKey",type:"password",get alias(){return e.i18n.translate("PICBED_QINIU_SECRETKEY")},default:t.secretKey||"",required:!0},{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_QINIU_BUCKET")},default:t.bucket||"",required:!0},{name:"url",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_URL")},get alias(){return e.i18n.translate("PICBED_QINIU_URL")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_URL")},default:t.url||"",required:!0},{name:"area",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_AREA")},get alias(){return e.i18n.translate("PICBED_QINIU_AREA")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_AREA")},default:t.area||"",required:!0},{name:"options",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_OPTIONS")},get alias(){return e.i18n.translate("PICBED_QINIU_OPTIONS")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_OPTIONS")},default:t.options||"",required:!1},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_PATH")},get alias(){return e.i18n.translate("PICBED_QINIU_PATH")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_PATH")},default:t.path||"",required:!1}]};const Tt=(e,t,n)=>{const r={method:"POST",url:"https://api.imgur.com/3/image",headers:{Authorization:`Client-ID ${e.clientId}`,"content-type":"multipart/form-data",Host:"api.imgur.com","User-Agent":"PicGo"},formData:{image:n,type:"base64",name:t}};return e.proxy&&(r.proxy=e.proxy),r},At=async e=>{const t=e.getConfig("picBed.imgur");if(!t)throw new Error("Can't find imgur config");try{const n=e.output;for(const r of n)if(r.fileName&&r.buffer){const n=r.base64Image||Buffer.from(r.buffer).toString("base64"),i=Tt(t,r.fileName,n),s=await e.request(i),o="string"==typeof s?JSON.parse(s):s;if(!o.success)throw new Error("Server error, please try again");delete r.base64Image,delete r.buffer,r.imgUrl=o.data.link}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK"),text:"http://docs.imgur.com/api/errno/"}),t?.response?.data||t}},Ot=e=>{const t=e.getConfig("picBed.imgur")||{};return[{name:"clientId",type:"input",get alias(){return e.i18n.translate("PICBED_IMGUR_CLIENTID")},default:t.clientId||"",required:!0},{name:"proxy",type:"input",get prefix(){return e.i18n.translate("PICBED_IMGUR_PROXY")},get alias(){return e.i18n.translate("PICBED_IMGUR_PROXY")},get message(){return e.i18n.translate("PICBED_IMGUR_MESSAGE_PROXY")},default:t.proxy||"",required:!1}]};const Rt=(e,t)=>{const n=(new Date).toUTCString(),r=h.lookup(t);if(!r)throw Error(`No mime type found for file ${t}`);const i=`PUT\n\n${r}\n${n}\n/${e.bucket}/${e.path}${t}`,s=p.createHmac("sha1",e.accessKeySecret).update(i).digest("base64");return`OSS ${e.accessKeyId}:${s}`},xt=(e,t,n,r)=>{const i=e.path||"";return{method:"PUT",url:`https://${e.bucket}.${e.area}.aliyuncs.com/${H(i,t)}`,headers:{Host:`${e.bucket}.${e.area}.aliyuncs.com`,Authorization:n,Date:(new Date).toUTCString(),"Content-Type":h.lookup(t)},body:r,resolveWithFullResponse:!0}},wt=async e=>{const t=e.getConfig("picBed.aliyun");if(!t)throw new Error("Can't find aliYun OSS config");try{const n=e.output,r=t.customUrl,i=t.path||"";for(const s of n)if(s.fileName&&s.buffer){const n=Rt(t,s.fileName);let o=s.buffer;!o&&s.base64Image&&(o=Buffer.from(s.base64Image,"base64"));const a=xt(t,s.fileName,n,o);if(200!==(await e.request(a)).statusCode)throw new Error("Upload failed");{delete s.base64Image,delete s.buffer;const e=t.options||"";s.imgUrl=r?`${r}/${H(i,s.fileName)}${e}`:`https://${t.bucket}.${t.area}.aliyuncs.com/${H(i,s.fileName)}${e}`}}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")}),t}},Bt=e=>{const t=e.getConfig("picBed.aliyun")||{};return[{name:"accessKeyId",type:"input",get alias(){return e.i18n.translate("PICBED_ALICLOUD_ACCESSKEYID")},default:t.accessKeyId||"",required:!0},{name:"accessKeySecret",type:"password",get alias(){return e.i18n.translate("PICBED_ALICLOUD_ACCESSKEYSECRET")},default:t.accessKeySecret||"",required:!0},{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_ALICLOUD_BUCKET")},default:t.bucket||"",required:!0},{name:"area",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_AREA")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_AREA")},default:t.area||"",get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_AREA")},required:!0},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_PATH")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_PATH")},get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_PATH")},default:t.path||"",required:!1},{name:"customUrl",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_CUSTOMURL")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_CUSTOMURL")},get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_CUSTOMURL")},default:t.customUrl||"",required:!1},{name:"options",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_OPTIONS")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_OPTIONS")},get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_OPTIONS")},default:t.options||"",required:!1}]};const bt=(e,t)=>{const n=e.path||"",r=e.operator,i=e.password,s=f(i),o=(new Date).toUTCString(),a=`PUT&${`/${e.bucket}/${H(n,t)}`}&${o}`;return`UPYUN ${r}:${p.createHmac("sha1",s).update(a).digest("base64")}`},Gt=(e,t,n,r)=>{const i=e.bucket,s=e.path||"";return{method:"PUT",url:`https://v0.api.upyun.com/${i}/${H(s,t)}`,headers:{Authorization:n,Date:(new Date).toUTCString(),"Content-Type":h.lookup(t)||"application/octet-stream"},body:r,resolveWithFullResponse:!0}},vt=async e=>{const t=e.getConfig("picBed.upyun");if(!t)throw new Error("Can't find upYun config");try{const n=e.output,r=t.path||"";for(const i of n)if(i.fileName&&i.buffer){let n=i.buffer;!n&&i.base64Image&&(n=Buffer.from(i.base64Image,"base64"));const s=bt(t,i.fileName),o=Gt(t,i.fileName,s,n);if(200!==(await e.request(o)).statusCode)throw new Error("Upload failed");delete i.base64Image,delete i.buffer,i.imgUrl=`${t.url}/${H(r,i.fileName)}${t.options}`}return e}catch(t){if("Upload failed"===t.message)e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")});else{const n=te(t.error);e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("UPLOAD_FAILED_REASON",{code:"object"==typeof n?n.code:n}),text:"http://docs.upyun.com/api/errno/"})}throw t}},Mt=e=>{const t=e.getConfig("picBed.upyun")||{};return[{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_UPYUN_BUCKET")},default:t.bucket||"",required:!0},{name:"operator",type:"input",get alias(){return e.i18n.translate("PICBED_UPYUN_OPERATOR")},get prefix(){return e.i18n.translate("PICBED_UPYUN_OPERATOR")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_OPERATOR")},default:t.operator||"",required:!0},{name:"password",type:"password",get prefix(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_PASSWORD")},get alias(){return e.i18n.translate("PICBED_UPYUN_PASSWORD")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_PASSWORD")},default:t.password||"",required:!0},{name:"url",type:"input",get alias(){return e.i18n.translate("PICBED_UPYUN_URL")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_URL")},default:t.url||"",required:!0},{name:"options",type:"input",get prefix(){return e.i18n.translate("PICBED_UPYUN_OPTIONS")},get alias(){return e.i18n.translate("PICBED_UPYUN_OPTIONS")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_OPTIONS")},default:t.options||"",required:!1},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_UPYUN_PATH")},get alias(){return e.i18n.translate("PICBED_UPYUN_PATH")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_PATH")},default:t.path||"",required:!1}]};const $t=()=>({register(e){!function(e){e.helper.uploader.register("aliyun",{get name(){return e.i18n.translate("PICBED_ALICLOUD")},handle:wt,config:Bt})}(e),function(e){e.helper.uploader.register("tcyun",{get name(){return e.i18n.translate("PICBED_TENCENTCLOUD")},handle:It,config:Ct})}(e),function(e){e.helper.uploader.register("smms",{get name(){return e.i18n.translate("PICBED_SMMS")},handle:Et,config:dt})}(e),function(e){e.helper.uploader.register("github",{get name(){return e.i18n.translate("PICBED_GITHUB")},handle:St,config:Nt})}(e),function(e){e.helper.uploader.register("qiniu",{get name(){return e.i18n.translate("PICBED_QINIU")},handle:Ut,config:yt})}(e),function(e){e.helper.uploader.register("imgur",{get name(){return e.i18n.translate("PICBED_IMGUR")},handle:At,config:Ot})}(e),function(e){e.helper.uploader.register("upyun",{get name(){return e.i18n.translate("PICBED_UPYUN")},handle:vt,config:Mt})}(e)}}),Ft=(e,t,n)=>{const r=k(t);return r.real||("string"==typeof n?e.log.warn(`can't get ${n}'s image size`):e.log.warn("can't get image size"),e.log.warn("fallback to 200 * 200")),r};var Ht={handle:async e=>{const t=e.output;return await Promise.all(e.input.map(async(n,r)=>{let i;if(i=Buffer.isBuffer(n)?{success:!0,buffer:n,fileName:"",extname:""}:$(n)?await q(n,e):await Y(n),i.success&&i.buffer){const s=Ft(e,i.buffer,n),o=i.extname||s.extname||".png";t[r]={buffer:i.buffer,fileName:i.fileName||`${d().format("YYYYMMDDHHmmssSSS")}${o}}`,width:s.width,height:s.height,filePath:i.filePath,extname:o,size:i.buffer?.length||0,mimeType:h.lookup(o)||"application/octet-stream"}}else e.log.error(i.reason)})),e.output=t.filter(e=>e),e}};var kt={handle:async e=>(e.output.push(...e.input),e)};class Yt{ctx;list=[];fullList=new Set;pluginMap=new Map;constructor(e){this.ctx=e,this.init()}init(){const n=t.join(this.ctx.baseDir,"package.json");if(!e.existsSync(n)){const t={name:"picgo-plugins",description:"picgo-plugins",repository:"https://github.com/PicGo/PicGo-Core",license:"MIT"};e.writeFileSync(n,JSON.stringify(t),"utf8")}}resolvePlugin(e,n){try{return I.sync(n,{basedir:e.baseDir})}catch(r){return t.join(e.baseDir,"node_modules",n)}}load(){const n=t.join(this.ctx.baseDir,"package.json"),r=t.join(this.ctx.baseDir,"node_modules/");if(!e.existsSync(r))return!1;const i=e.readJSONSync(n),s=Object.keys(i.dependencies||{}),o=Object.keys(i.devDependencies||{}),a=s.concat(o).filter(t=>{if(!/^picgo-plugin-|^@[^/]+\/picgo-plugin-/.test(t))return!1;const n=this.resolvePlugin(this.ctx,t);return e.existsSync(n)});for(const e of a)this.registerPlugin(e);return!0}registerPlugin(e,t){if(e&&"string"==typeof e){this.fullList.add(e);try{if(t){this.list.push(e),ot(e);const n=t(this.ctx);this.pluginMap.set(e,n),n.register(this.ctx)}else if(!0===this.ctx.getConfig(`picgoPlugins.${e}`)||void 0===this.ctx.getConfig(`picgoPlugins.${e}`)){this.list.push(e),ot(e),this.getPlugin(e).register(this.ctx);const t=`picgoPlugins[${e}]`;this.ctx.saveConfig({[t]:!0})}}catch(t){this.pluginMap.delete(e),this.list=this.list.filter(t=>t!==e),this.fullList.delete(e),this.ctx.log.error(t),this.ctx.emit(exports.IBuildInEvent.NOTIFICATION,{title:`Plugin ${e} Load Error`,body:t})}}else this.ctx.log.warn("Please provide valid plugin")}unregisterPlugin(e){this.list=this.list.filter(t=>t!==e),this.fullList.delete(e),this.pluginMap.delete(e),ot(e),this.ctx.helper.uploader.unregister(e),this.ctx.helper.transformer.unregister(e),this.ctx.helper.beforeTransformPlugins.unregister(e),this.ctx.helper.beforeUploadPlugins.unregister(e),this.ctx.helper.afterUploadPlugins.unregister(e),this.ctx.cmd.unregister(e),this.ctx.removeConfig("picgoPlugins",e)}getPlugin(e){if(this.pluginMap.has(e))return this.pluginMap.get(e);const n=t.join(this.ctx.baseDir,"node_modules/"),r=require(n+e)(this.ctx);return this.pluginMap.set(e,r),r}getList(){return this.list}hasPlugin(e){return this.fullList.has(e)}getFullList(){return[...this.fullList]}}const qt="picgo-clipboard-images",Vt={darwin:'-- From https://github.com/mushanshitiancai/vscode-paste-image\nproperty fileTypes : {{«class PNGf», ".png"}}\n\non run argv\n\tif argv is {} then\n\t\treturn ""\n\tend if\n\n\tif ((clipboard info) as string) contains "«class furl»" then\n\t\treturn POSIX path of (the clipboard as «class furl»)\n\telse\n\t\tset imagePath to (item 1 of argv)\n\t\tset theType to getType()\n\n\t\tif theType is not missing value then\n\t\t\ttry\n\t\t\t\tset myFile to (open for access imagePath with write permission)\n\t\t\t\tset eof myFile to 0\n\t\t\t\twrite (the clipboard as (first item of theType)) to myFile\n\t\t\t\tclose access myFile\n\t\t\t\treturn (POSIX path of imagePath)\n\t\t\ton error\n\t\t\t\ttry\n\t\t\t\t\tclose access myFile\n\t\t\t\tend try\n\t\t\t\treturn "no image"\n\t\t\tend try\n\t\telse\n\t\t\treturn "no image"\n\t\tend if\n\tend if\nend run\n\non getType()\n\trepeat with aType in fileTypes\n\t\trepeat with theInfo in (clipboard info)\n\t\t\tif (first item of theInfo) is equal to (first item of aType) then return aType\n\t\tend repeat\n\tend repeat\n\treturn missing value\nend getType\n',win32:'\nparam($imagePath)\n\n# Adapted from https://github.com/octan3/img-clipboard-dump/blob/master/dump-clipboard-png.ps1\n\nAdd-Type -Assembly PresentationCore\n$img = [Windows.Clipboard]::GetImage()\n\nif ($img -eq $null) {\n "no image"\n Exit 1\n}\n\nif (-not $imagePath) {\n "no image"\n Exit 1\n}\n\n$fcb = new-object Windows.Media.Imaging.FormatConvertedBitmap($img, [Windows.Media.PixelFormats]::Rgb24, $null, 0)\n$stream = [IO.File]::Open($imagePath, "OpenOrCreate")\n$encoder = New-Object Windows.Media.Imaging.PngBitmapEncoder\n$encoder.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($fcb)) | out-null\n$encoder.Save($stream) | out-null\n$stream.Dispose() | out-null\n\n$imagePath\n',win10:'# Adapted from https://github.com/octan3/img-clipboard-dump/blob/master/dump-clipboard-png.ps1\nparam($imagePath)\n\n# https://github.com/PowerShell/PowerShell/issues/7233\n# fix the output encoding bug\n[console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding\n\nAdd-Type -Assembly PresentationCore\nfunction main {\n $img = [Windows.Clipboard]::GetImage()\n\n if ($img -eq $null) {\n "no image"\n Exit 1\n }\n\n if (-not $imagePath) {\n "no image"\n Exit 1\n }\n\n $fcb = new-object Windows.Media.Imaging.FormatConvertedBitmap($img, [Windows.Media.PixelFormats]::Rgb24, $null, 0)\n $stream = [IO.File]::Open($imagePath, "OpenOrCreate")\n $encoder = New-Object Windows.Media.Imaging.PngBitmapEncoder\n $encoder.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($fcb)) | out-null\n $encoder.Save($stream) | out-null\n $stream.Dispose() | out-null\n\n $imagePath\n # fix windows 10 native cmd crash bug when "picgo upload"\n # https://github.com/PicGo/PicGo-Core/issues/32\n Exit 1\n}\n\ntry {\n # For WIN10\n $file = Get-Clipboard -Format FileDropList\n if ($file -ne $null) {\n Convert-Path $file\n Exit 1\n }\n} catch {\n # For WIN7 WIN8 WIN10\n main\n}\n\nmain',linux:'#!/bin/sh\nif [ "$XDG_SESSION_TYPE" = "x11" ]; then\n # require xclip(see http://stackoverflow.com/questions/592620/check-if-a-program-exists-from-a-bash-script/677212#677212)\n command -v xclip >/dev/null 2>&1 || { echo >&1 "no xclip"; exit 1; }\n # write image in clipboard to file (see http://unix.stackexchange.com/questions/145131/copy-image-from-clipboard-to-file)\n filePath=`xclip -selection clipboard -o 2>/dev/null | grep ^file:// | cut -c8-`\n if [ ! -n "$filePath" ] ;then\n if\n xclip -selection clipboard -target image/png -o >/dev/null 2>&1\n then\n xclip -selection clipboard -target image/png -o >$1 2>/dev/null\n echo $1\n else\n echo "no image"\n fi\n else\n echo $filePath\n fi\nelif [ "$XDG_SESSION_TYPE" = "wayland" ]; then\n command -v wl-paste >/dev/null 2>&1 || { echo >&1 "no wl-clipboard"; exit 1; }\n isImage=`wl-paste --list-types | grep image`\n if [ -n "$isImage" ]; then\n wl-paste --type image/png > $1 2>/dev/null\n echo $1\n else\n echo "no image"\n exit 1\n fi\nelse\n # fallback for unsupported session types\n echo >&2 "Error: Unsupported session type \'$XDG_SESSION_TYPE\'."\n echo >&2 "Solution: The variable of XDG_SESSION_TYPE must set as \'x11\' or \'wayland\'."\n exit 1\nfi\n',wsl:'#!/bin/sh\n# grab the paths\nscriptPath=$(echo $0 | awk \'{ print substr( $0, 1, length($0)-6 ) }\')"windows10.ps1"\nimagePath=$(echo $1 | awk \'{ print substr( $0, 1, length($0)-18 ) }\')\nimageName=$(echo $1 | awk \'{ print substr( $0, length($0)-17, length($0) ) }\')\n\n# run the powershell script\nres=$(powershell.exe -noprofile -noninteractive -nologo -sta -executionpolicy unrestricted -file $(wslpath -w $scriptPath) $(wslpath -w $imagePath)"\\\\"$imageName)\n\n# note that there is a return symbol in powershell result\nnoImage=$(echo "no image\\r")\n\n# check whether image exists\nif [ "$res" = "$noImage" ] ;then\n echo "no image"\nelse\n echo $(wslpath -u -a "${res}")\nfi\n'},Kt={darwin:"mac.applescript",win32:"windows.ps1",win10:"windows10.ps1",linux:"linux.sh",wsl:"wsl.sh"};const jt=async n=>{!function(n){const r=t.join(n.baseDir,qt);e.existsSync(r)||e.mkdirSync(r)}(n);const i=t.join(n.baseDir,qt,`${d().format("YYYYMMDDHHmmssSSS")}.png`);return await new Promise((s,o)=>{const a=(()=>{const e=process.platform;if(m)return"wsl";if("win32"===e)return"10"===r.release().split(".")[0]?"win10":"win32";return"darwin"===e?"darwin":"linux"})(),c=t.join(n.baseDir,Kt[a]);let l;e.existsSync(c)||e.writeFileSync(c,Vt[a],"utf8"),l="darwin"===a?C.spawn("osascript",[c,i]):"win32"===a||"win10"===a?C.spawn("powershell",["-noprofile","-noninteractive","-nologo","-sta","-executionpolicy","unrestricted","-file",c,i]):C.spawn("sh",[c,i]),l.stdout.on("data",r=>{if("linux"===a&&"no xclip or wl-clipboard"===r.toString().trim())return n.emit(exports.IBuildInEvent.NOTIFICATION,{title:"xclip or wl-clipboard not found",body:"Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"}),o(new Error("Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"));const c=r.toString().trim();let l=!1;if(t.basename(c)!==t.basename(i)&&e.existsSync(c)&&(l=!0),"no image"!==c&&!e.existsSync(c))return o(new Error(`Can't find ${c}`));s({imgPath:c,shouldKeepAfterUploading:l})})})},Wt=new n.EventEmitter,Qt=new N.Agent({maxVersion:"TLSv1.2",minVersion:"TLSv1.2"});function zt(e,t,n){"object"==typeof n&&"value"in n&&"options"in n?e.append(t,n.value,n.options):e.append(t,n)}function Jt(e){return{...e,statusCode:e.status,body:e.data}}function Xt(e){const t={method:e?.config?.method?.toUpperCase()||"",url:e?.config?.url||"",statusCode:e?.response?.status||0,message:e?.message||"",stack:e?.stack||{},response:{status:e?.response?.status||0,statusCode:e?.response?.status||0,body:e?.response?.data||""}};return Promise.reject(t)}class Zt{ctx;proxy="";options={};constructor(e){this.ctx=e,this.init(),Wt.on(exports.IBusEvent.CONFIG_CHANGE,e=>{switch(e.configName){case"picBed":e.value?.proxy&&(this.proxy=e.value.proxy);break;case"picBed.proxy":this.proxy=e.value}})}init(){const e=this.ctx.getConfig("picBed.proxy");e&&(this.proxy=e)}handleProxy(){if(this.proxy)try{const e=new a.URL(this.proxy);return{host:e.hostname,port:parseInt(e.port||"0",10),protocol:e.protocol}}catch(e){}return!1}request(e){this.options.proxy=this.handleProxy(),this.options.headers=e.headers||{},this.options.maxBodyLength=1/0,this.options.maxContentLength=1/0,this.options.proxy&&e.url?.startsWith("https://")?(this.options.httpsAgent=L.httpsOverHttp({proxy:{host:this.options.proxy.host,port:this.options.proxy.port}}),this.options.proxy=!1):this.options.httpsAgent=Qt;const t=u.create(this.options);t.interceptors.response.use(Jt,Xt);const n=function(e){let t=!1;const n={...e,url:e.url||"",headers:e.headers||{}};if(e.proxy){let r=e.proxy;if("string"==typeof r){try{r=new a.URL(e.proxy)}catch(e){r=!1,n.proxy=!1,console.error(e)}t=!0}r&&(e.url?.startsWith("https://")?(n.proxy=!1,n.httpsAgent=L.httpsOverHttp({proxy:{host:r?.hostname,port:parseInt(r?.port,10)}})):n.proxy={host:r.hostname,port:parseInt(r.port,10),protocol:"http"})}if("formData"in e){const r=new S;for(const t in e.formData)zt(r,t,e.formData[t]);n.data=r,n.headers=Object.assign(n.headers||{},r.getHeaders()),t=!0,delete n.formData}return"body"in e&&(n.data=e.body,t=!0,delete n.body),"qs"in e&&(n.params=e.qs,t=!0),n.__isOldOptions=t,n}(e);return t.interceptors.request.use(function(e){let t="";return e?.headers?.contentType?(t=e.headers.contentType,delete e.headers.contentType):e?.headers?.ContentType?(t=e.headers.ContentType,delete e.headers.ContentType):e?.headers?.["content-type"]&&(t=e.headers["content-type"],delete e.headers["content-type"]),""!==t&&e.headers&&(e.headers["Content-Type"]=t),e}),"resolveWithFullResponse"in e&&e.resolveWithFullResponse?t.request(n):t.request(n).then(t=>n.__isOldOptions?"json"in e?e.json?t.data:void 0:JSON.stringify(t.data):t.data)}}class en{ctx;db;constructor(e){if(this.ctx=e,this.db=new P.JSONStore(this.ctx.configPath),!this.db.has("picBed"))try{this.db.set("picBed",{uploader:"smms",current:"smms"})}catch(e){throw this.ctx.log.error(e),e}if(!this.db.has("picgoPlugins"))try{this.db.set("picgoPlugins",{})}catch(e){throw this.ctx.log.error(e),e}}read(e){return this.db.read(e)}get(e=""){return this.read(!0),this.db.get(e)}set(e,t){return this.read(!0),this.db.set(e,t)}has(e){return this.read(!0),this.db.has(e)}unset(e,t){return this.read(!0),this.db.unset(e,t)}saveConfig(e){Object.keys(e).forEach(t=>{this.set(t,e[t])})}removeConfig(e){Object.keys(e).forEach(t=>{this.unset(t,e[t])})}}class tn{ctx;constructor(e){this.ctx=e}async install(e,t={},n){const r=[],i=e.map(e=>nn(this.ctx,e)).filter(e=>this.ctx.pluginLoader.hasPlugin(e.pkgName)?(r.push(e.pkgName),this.ctx.log.success(`PicGo has already installed ${e.pkgName}`),!1):!!e.success),s=i.map(e=>e.fullName),o=i.map(e=>e.pkgName);if(s.length>0){const e=await this.execCommand("install",s,this.ctx.baseDir,t,n);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("installFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED"),body:t});return{success:!1,body:t}}o.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:[...o,...r]});return{success:!0,body:[...o,...r]}}if(0===r.length){const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("installFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED"),body:e});return{success:!1,body:e}}this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS")),this.ctx.emit("installSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS"),body:[...o,...r]});return{success:!0,body:[...o,...r]}}async uninstall(e,t){const n=e.map(e=>nn(this.ctx,e)).filter(e=>e.success).map(e=>e.pkgName);if(n.length>0){const e=await this.execCommand("uninstall",n,this.ctx.baseDir,void 0,t);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}}n.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:n});return{success:!0,body:n}}{const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("uninstallFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED"),body:e});return{success:!1,body:e}}}async update(e,t={},n){const r=e.map(e=>nn(this.ctx,e)).filter(e=>e.success).map(e=>e.pkgName);if(r.length>0){const e=await this.execCommand("update",r,this.ctx.baseDir,t,n);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("updateFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED"),body:t});return{success:!1,body:t}}this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS")),this.ctx.emit("updateSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS"),body:r});return{success:!0,body:r}}{const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("updateFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED"),body:e});return{success:!1,body:e}}}async execCommand(e,t,n,r={},i={}){const s=r.npmRegistry||this.ctx.getConfig("settings.npmRegistry"),o=r.npmProxy||this.ctx.getConfig("settings.npmProxy");return await new Promise(r=>{let a=[e].concat(t).concat("--color=always").concat("--save");s&&(a=a.concat(`--registry=${s}`)),o&&(a=a.concat(`--proxy=${o}`));try{const e=D("npm",a,{cwd:n,env:Object.assign({},process.env,i)});let t="";e.stdout?.on("data",e=>{t+=e}).pipe(process.stdout),e.stderr?.on("data",e=>{t+=e}).pipe(process.stderr),e.on("close",e=>{r(e?{code:e,data:t}:{code:0,data:t})}),e.on("error",e=>{this.ctx.log.error(e),this.ctx.log.error("NPM is not installed"),this.ctx.emit(exports.IBuildInEvent.FAILED,"NPM is not installed")})}catch(e){this.ctx.log.error(e),this.ctx.emit(exports.IBuildInEvent.FAILED,e)}})}}const nn=(e,t)=>{const n={success:!1,fullName:"",pkgName:""},r=W(t,e.log);if(!r)return n;const i=Q(r,e.log);return i?{success:!0,fullName:r,pkgName:i}:n},rn={"zh-CN":{UPLOAD_FAILED:"上传失败",CHECK_SETTINGS:"请检查你的配置项是否正确",CHECK_SETTINGS_AND_NETWORK:"请检查你的配置项以及网络",UPLOAD_FAILED_REASON:"错误码:${code},请打开浏览器粘贴地址查看相关原因",SERVER_ERROR:"服务端出错,请重试",AUTH_FAILED:"认证失败",CLOUD_LOGIN_CANCELLED:"登录已取消",CLOUD_LOGIN_IN_PROGRESS:"登录正在进行中",CLOUD_LOGIN_INVALID_TOKEN:"无效的 token",CLOUD_LOGIN_SUCCESS:"登录成功!",CLOUD_LOGOUT_SUCCESS:"退出登录成功!",CLOUD_LOGIN_SERVER_START_FAILED:"启动登录服务失败",CLOUD_LOGIN_OPEN_BROWSER_FAILED:"无法自动打开浏览器:${message}",CLOUD_LOGIN_OPEN_BROWSER_TIP:"请在浏览器中打开该链接:${url}",CLOUD_LOGIN_STATE_MISMATCH_WARN:"State 校验失败或缺失,请求已拦截",CLOUD_LOGIN_STATE_INVALID:"State 无效,请重新登录。",CLOUD_LOGIN_TOKEN_MISSING:"回调中缺少 token。",CLOUD_LOGIN_CODE_MISSING:"回调中缺少 code。",CLOUD_LOGIN_EXCHANGE_FAILED:"登录 code 交换失败。",CLOUD_LOGIN_NOT_IN_PROGRESS:"当前没有进行中的登录流程。",CLOUD_LOGIN_PAGE_TITLE:"PicGo 登录",CLOUD_LOGIN_RESULT_SUCCESS_TITLE:"授权成功!",CLOUD_LOGIN_RESULT_FAILED_TITLE:"授权失败",CLOUD_LOGIN_RESULT_SUCCESS_MESSAGE:"你可以关闭此窗口并返回 PicGo。",SERVER_INVALID_JSON_BODY:"JSON 请求体无效",SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED:"请求体无效:需要 { list: string[] }",SERVER_FORMDATA_NO_FILES_IN_FILES_FIELD:"form-data 的 files 字段未找到文件",SERVER_FORMDATA_FILES_MUST_BE_FILES:"form-data 无效:files 必须是文件",SERVER_AUTH_ENABLED:"[PicGo Server] 认证已启用。",SERVER_AUTH_DISABLED_WARNING:"[PicGo Server] 警告:认证已关闭,任何人都可以上传图片。",SERVER_AUTH_UNAUTHORIZED_REQUEST:"[PicGo Server] 未授权的请求,来源 ${ip}",SERVER_AUTH_QUERY_SECRET_WARNING:"[PicGo Server] 警告:通过 URL 参数传递 secret 不安全,请使用 Authorization Header。",URL_REWRITE_EMPTY_RESULT:"URL 重写结果为空,请检查你的规则配置",PICBED_SMMS:"SM.MS(S.EE)",PICBED_SMMS_TOKEN:"设定Token",PICBED_SMMS_BACKUP_DOMAIN:"备用上传域名",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例如 sm.ms",PICBED_ALICLOUD:"阿里云OSS",PICBED_ALICLOUD_ACCESSKEYID:"设定KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"设定KeySecret",PICBED_ALICLOUD_BUCKET:"设定Bucket",PICBED_ALICLOUD_AREA:"设定存储区域",PICBED_ALICLOUD_PATH:"设定存储路径",PICBED_ALICLOUD_CUSTOMURL:"设定自定义域名",PICBED_ALICLOUD_OPTIONS:"设定网址后缀",PICBED_ALICLOUD_MESSAGE_AREA:"例如:oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例如:test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例如:?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD:"腾讯云COS",PICBED_TENCENTCLOUD_VERSION:"COS版本",PICBED_TENCENTCLOUD_SECRETID:"设定SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"设定SecretKey",PICBED_TENCENTCLOUD_APPID:"设定AppId",PICBED_TENCENTCLOUD_BUCKET:"设定Bucket",PICBED_TENCENTCLOUD_AREA:"设定存储区域",PICBED_TENCENTCLOUD_ENDPOINT:"设定Endpoint",PICBED_TENCENTCLOUD_PATH:"设定存储路径",PICBED_TENCENTCLOUD_OPTIONS:"设定网址后缀",PICBED_TENCENTCLOUD_CUSTOMURL:"设定自定义域名",PICBED_TENCENTCLOUD_SLIM:"极智压缩",PICBED_TENCENTCLOUD_SLIM_TIP:"图片极智压缩,详情请参考[文档说明](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"开启",PICBED_TENCENTCLOUD_SLIM_CANCEL:"关闭",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例如:1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例如:ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例如:cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例如:test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例如:?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"设定Token",PICBED_GITHUB_REPO:"设定仓库名",PICBED_GITHUB_PATH:"设定存储路径",PICBED_GITHUB_BRANCH:"设定分支名",PICBED_GITHUB_CUSTOMURL:"设定自定义域名",PICBED_GITHUB_MESSAGE_REPO:"格式:username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例如:main",PICBED_GITHUB_MESSAGE_PATH:"例如:test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_QINIU:"七牛云",PICBED_QINIU_ACCESSKEY:"设定AccessKey",PICBED_QINIU_SECRETKEY:"设定SecretKey",PICBED_QINIU_BUCKET:"设定Bucket",PICBED_QINIU_PATH:"设定存储路径",PICBED_QINIU_URL:"设定访问网址",PICBED_QINIU_OPTIONS:"设定网址后缀",PICBED_QINIU_AREA:"设定存储区域",PICBED_QINIU_MESSAGE_PATH:"例如:test/",PICBED_QINIU_MESSAGE_AREA:"例如:z0",PICBED_QINIU_MESSAGE_OPTIONS:"例如:?imageslim",PICBED_QINIU_MESSAGE_URL:"例如:https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"设定ClientId",PICBED_IMGUR_PROXY:"设定代理",PICBED_IMGUR_MESSAGE_PROXY:"例如:http://127.0.0.1:1080",PICBED_UPYUN:"又拍云",PICBED_UPYUN_BUCKET:"设定Bucket",PICBED_UPYUN_OPERATOR:"设定操作员",PICBED_UPYUN_PASSWORD:"设定操作员密码",PICBED_UPYUN_PATH:"设定存储路径",PICBED_UPYUN_URL:"设定加速域名",PICBED_UPYUN_OPTIONS:"设定网址后缀",PICBED_UPYUN_MESSAGE_OPERATOR:"例如:me",PICBED_UPYUN_MESSAGE_PASSWORD:"输入操作员密码",PICBED_UPYUN_MESSAGE_URL:"例如:http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例如:!imgslim",PICBED_UPYUN_MESSAGE_PATH:"例如:test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"插件安装成功",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"插件安装失败",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"插件安装失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"插件安装失败,请输入合法插件名或合法安装路径",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"插件卸载成功",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"插件卸载失败",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"插件卸载失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"插件卸载失败,请输入合法插件名",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"插件更新成功",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"插件更新失败",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"插件更新失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"插件更新失败,请输入合法插件名",CONFIG_SYNC_INVALID_ENCRYPTION_METHOD:'配置无效:settings.picgoCloud.encryptionMethod 必须是 "auto"、"sse" 或 "e2ee" 之一,当前为:${value}',CONFIG_SYNC_ENCRYPTION_METHOD_E2EE:"端到端加密",CONFIG_SYNC_ENCRYPTION_METHOD_SSE:"服务端加密",CONFIG_SYNC_ENCRYPTION_SWITCH_TITLE:"确认切换加密方式吗?",CONFIG_SYNC_ENCRYPTION_SWITCH_BODY:"您正在从“${from}”切换为“${to}”。\n\n注意:切换加密模式将清空您所有的云端历史版本记录。\n这是因为旧的历史版本无法在新模式下被解密或验证。\n切换后,系统将立即为您创建一份新的备份作为起点。",CONFIG_SYNC_ENCRYPTION_SWITCH_CONFIRM:"确认切换并清空历史",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCEL:"取消",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCELLED:"已取消切换加密方式",CONFIG_SYNC_ENCRYPTION_SWITCH_MISSING_HANDLER:"需要提供加密方式切换确认处理器"},"zh-TW":{UPLOAD_FAILED:"上傳失敗",CHECK_SETTINGS:"請檢查你的設定是否正確",CHECK_SETTINGS_AND_NETWORK:"請檢查你的設定及網路",UPLOAD_FAILED_REASON:"錯誤碼:${code},請打開瀏覽器貼上地址查看相關原因",SERVER_ERROR:"伺服器出錯,請重試",AUTH_FAILED:"認證失敗",CLOUD_LOGIN_CANCELLED:"登入已取消",CLOUD_LOGIN_IN_PROGRESS:"登入正在進行中",CLOUD_LOGIN_INVALID_TOKEN:"無效的 token",CLOUD_LOGIN_SUCCESS:"登入成功!",CLOUD_LOGOUT_SUCCESS:"登出成功!",CLOUD_LOGIN_SERVER_START_FAILED:"啟動登入服務失敗",CLOUD_LOGIN_OPEN_BROWSER_FAILED:"無法自動打開瀏覽器:${message}",CLOUD_LOGIN_OPEN_BROWSER_TIP:"請在瀏覽器中打開此連結:${url}",CLOUD_LOGIN_STATE_MISMATCH_WARN:"State 驗證失敗或缺失,請求已攔截",CLOUD_LOGIN_STATE_INVALID:"State 無效,請重新登入。",CLOUD_LOGIN_TOKEN_MISSING:"回呼中缺少 token。",CLOUD_LOGIN_CODE_MISSING:"回呼中缺少 code。",CLOUD_LOGIN_EXCHANGE_FAILED:"登入 code 交換失敗。",CLOUD_LOGIN_NOT_IN_PROGRESS:"目前沒有進行中的登入流程。",CLOUD_LOGIN_PAGE_TITLE:"PicGo 登入",CLOUD_LOGIN_RESULT_SUCCESS_TITLE:"授權成功!",CLOUD_LOGIN_RESULT_FAILED_TITLE:"授權失敗",CLOUD_LOGIN_RESULT_SUCCESS_MESSAGE:"你可以關閉此視窗並返回 PicGo。",SERVER_INVALID_JSON_BODY:"JSON 請求內容無效",SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED:"請求內容無效:需要 { list: string[] }",SERVER_FORMDATA_NO_FILES_IN_FILES_FIELD:"form-data 的 files 欄位未找到檔案",SERVER_FORMDATA_FILES_MUST_BE_FILES:"form-data 無效:files 必須是檔案",SERVER_AUTH_ENABLED:"[PicGo Server] 認證已啟用。",SERVER_AUTH_DISABLED_WARNING:"[PicGo Server] 警告:認證已關閉,任何人都可以上傳圖片。",SERVER_AUTH_UNAUTHORIZED_REQUEST:"[PicGo Server] 未授權的請求,來源 ${ip}",SERVER_AUTH_QUERY_SECRET_WARNING:"[PicGo Server] 警告:透過 URL 參數傳遞 secret 不安全,請使用 Authorization Header。",URL_REWRITE_EMPTY_RESULT:"URL 重寫結果為空,請檢查你的規則設定",PICBED_SMMS:"SM.MS(S.EE)",PICBED_SMMS_TOKEN:"設定Token",PICBED_SMMS_BACKUP_DOMAIN:"備用上傳網址",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例如 sm.ms",PICBED_ALICLOUD:"阿里云OSS",PICBED_ALICLOUD_ACCESSKEYID:"設定KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"設定KeySecret",PICBED_ALICLOUD_BUCKET:"設定Bucket",PICBED_ALICLOUD_AREA:"設定儲存區域",PICBED_ALICLOUD_PATH:"設定儲存路徑",PICBED_ALICLOUD_CUSTOMURL:"設定自訂網址",PICBED_ALICLOUD_OPTIONS:"設定網址後綴",PICBED_ALICLOUD_MESSAGE_AREA:"例如:oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例如:test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例如:?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD:"騰訊云COS",PICBED_TENCENTCLOUD_VERSION:"COS版本",PICBED_TENCENTCLOUD_SECRETID:"設定SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"設定SecretKey",PICBED_TENCENTCLOUD_APPID:"設定AppId",PICBED_TENCENTCLOUD_BUCKET:"設定Bucket",PICBED_TENCENTCLOUD_AREA:"設定儲存區域",PICBED_TENCENTCLOUD_ENDPOINT:"設定Endpoint",PICBED_TENCENTCLOUD_PATH:"設定儲存路徑",PICBED_TENCENTCLOUD_OPTIONS:"設定網址後綴",PICBED_TENCENTCLOUD_SLIM:"極智壓縮",PICBED_TENCENTCLOUD_SLIM_CANCEL:"關閉",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"開啓",PICBED_TENCENTCLOUD_SLIM_TIP:"圖片極智壓縮,詳情請參考[文檔說明](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_CUSTOMURL:"設定自訂網址",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例如:1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例如:ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例如:cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例如:test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例如:?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"設定Token",PICBED_GITHUB_REPO:"設定倉庫名稱",PICBED_GITHUB_PATH:"設定儲存路徑",PICBED_GITHUB_BRANCH:"設定分支名稱",PICBED_GITHUB_CUSTOMURL:"設定自訂網址",PICBED_GITHUB_MESSAGE_REPO:"格式:username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例如:main",PICBED_GITHUB_MESSAGE_PATH:"例如:test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_QINIU:"七牛云",PICBED_QINIU_ACCESSKEY:"設定AccessKey",PICBED_QINIU_SECRETKEY:"設定SecretKey",PICBED_QINIU_BUCKET:"設定Bucket",PICBED_QINIU_PATH:"設定儲存路徑",PICBED_QINIU_URL:"設定訪問網址",PICBED_QINIU_OPTIONS:"設定網址後綴",PICBED_QINIU_AREA:"設定儲存區域",PICBED_QINIU_MESSAGE_PATH:"例如:test/",PICBED_QINIU_MESSAGE_AREA:"例如:z0",PICBED_QINIU_MESSAGE_OPTIONS:"例如:?imageslim",PICBED_QINIU_MESSAGE_URL:"例如:https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"設定ClientId",PICBED_IMGUR_PROXY:"設定PROXY",PICBED_IMGUR_MESSAGE_PROXY:"例如:http://127.0.0.1:1080",PICBED_UPYUN:"又拍云",PICBED_UPYUN_BUCKET:"設定Bucket",PICBED_UPYUN_OPERATOR:"設定操作員",PICBED_UPYUN_PASSWORD:"設定操作員密碼",PICBED_UPYUN_PATH:"設定儲存路徑",PICBED_UPYUN_URL:"設定加速網址",PICBED_UPYUN_OPTIONS:"設定網址後綴",PICBED_UPYUN_MESSAGE_OPERATOR:"例如:me",PICBED_UPYUN_MESSAGE_PASSWORD:"輸入操作員密碼",PICBED_UPYUN_MESSAGE_URL:"例如:http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例如:!imgslim",PICBED_UPYUN_MESSAGE_PATH:"例如:test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"插件安裝成功",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"插件安裝失敗",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"插件安裝失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"插件安裝失敗,請輸入正確的插件名稱或正確的安裝路徑",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"插件卸載成功",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"插件卸載失敗",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"插件卸載失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"插件卸載失敗,請輸入正確的插件名稱",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"插件更新成功",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"插件更新失敗",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"插件更新失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"插件更新失敗,請輸入正確的插件名稱",CONFIG_SYNC_INVALID_ENCRYPTION_METHOD:"設定無效:settings.picgoCloud.encryptionMethod 必須是「auto」、「sse」或「e2ee」之一,目前為:${value}",CONFIG_SYNC_ENCRYPTION_METHOD_E2EE:"端對端加密",CONFIG_SYNC_ENCRYPTION_METHOD_SSE:"伺服器端加密",CONFIG_SYNC_ENCRYPTION_SWITCH_TITLE:"確認切換加密方式嗎?",CONFIG_SYNC_ENCRYPTION_SWITCH_BODY:"您正在從「${from}」切換為「${to}」。\n\n注意:切換加密模式將清空您所有的雲端歷史版本記錄。\n這是因為舊的歷史版本無法在新模式下被解密或驗證。\n切換後,系統將立即為您建立一份新的備份作為起點。",CONFIG_SYNC_ENCRYPTION_SWITCH_CONFIRM:"確認切換並清空歷史",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCEL:"取消",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCELLED:"已取消切換加密方式",CONFIG_SYNC_ENCRYPTION_SWITCH_MISSING_HANDLER:"需要提供加密方式切換確認處理器"},en:{UPLOAD_FAILED:"Upload failed",CHECK_SETTINGS:"Please check your settings",CHECK_SETTINGS_AND_NETWORK:"Please check your settings and network",UPLOAD_FAILED_REASON:"Error code: ${code}, please open the browser and paste the address to see the reason",SERVER_ERROR:"Server error, please try again later",AUTH_FAILED:"Authentication failed",CLOUD_LOGIN_CANCELLED:"Login cancelled",CLOUD_LOGIN_IN_PROGRESS:"Login is already in progress",CLOUD_LOGIN_INVALID_TOKEN:"Invalid token",CLOUD_LOGIN_SUCCESS:"Login success!",CLOUD_LOGOUT_SUCCESS:"Logout success!",CLOUD_LOGIN_SERVER_START_FAILED:"Failed to start PicGo server for login",CLOUD_LOGIN_OPEN_BROWSER_FAILED:"Failed to open browser automatically: ${message}",CLOUD_LOGIN_OPEN_BROWSER_TIP:"Please open this url in browser: ${url}",CLOUD_LOGIN_STATE_MISMATCH_WARN:"State mismatch or missing. Request blocked.",CLOUD_LOGIN_STATE_INVALID:"Invalid state. Please try logging in again.",CLOUD_LOGIN_TOKEN_MISSING:"Token missing in callback.",CLOUD_LOGIN_CODE_MISSING:"Code missing in callback.",CLOUD_LOGIN_EXCHANGE_FAILED:"Failed to exchange login code.",CLOUD_LOGIN_NOT_IN_PROGRESS:"Login flow is not in progress.",CLOUD_LOGIN_PAGE_TITLE:"PicGo Auth",CLOUD_LOGIN_RESULT_SUCCESS_TITLE:"Authorization Successful!",CLOUD_LOGIN_RESULT_FAILED_TITLE:"Authorization Failed",CLOUD_LOGIN_RESULT_SUCCESS_MESSAGE:"You can now close this window and return to PicGo.",SERVER_INVALID_JSON_BODY:"Invalid JSON body",SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED:"Invalid request body: { list: string[] } required",SERVER_FORMDATA_NO_FILES_IN_FILES_FIELD:"No files found in form-data: files",SERVER_FORMDATA_FILES_MUST_BE_FILES:"Invalid form-data: files must be file(s)",SERVER_AUTH_ENABLED:"[PicGo Server] Authentication enabled.",SERVER_AUTH_DISABLED_WARNING:"[PicGo Server] Warning: Authentication disabled. Anyone can upload images.",SERVER_AUTH_UNAUTHORIZED_REQUEST:"[PicGo Server] Unauthorized request from ${ip}",SERVER_AUTH_QUERY_SECRET_WARNING:"[PicGo Server] Warning: Passing secret via URL query is insecure. Please use Authorization header.",URL_REWRITE_EMPTY_RESULT:"URL rewrite produced an empty result, please check your rule config",PICBED_SMMS:"SM.MS(S.EE)",PICBED_SMMS_TOKEN:"Set Token",PICBED_SMMS_BACKUP_DOMAIN:"Set Backup Upload Domain",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"Ex. sm.ms",PICBED_ALICLOUD:"Ali Cloud",PICBED_ALICLOUD_ACCESSKEYID:"Set KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"Set KeySecret",PICBED_ALICLOUD_BUCKET:"Set Bucket",PICBED_ALICLOUD_AREA:"Set Area",PICBED_ALICLOUD_PATH:"Set Path",PICBED_ALICLOUD_CUSTOMURL:"Set Custom URL",PICBED_ALICLOUD_OPTIONS:"Set URL Suffix",PICBED_ALICLOUD_MESSAGE_AREA:"Ex. oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"Ex. test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"Ex. ?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"Ex. https://test.com",PICBED_TENCENTCLOUD:"Tencent Cloud",PICBED_TENCENTCLOUD_VERSION:"Choose COS version",PICBED_TENCENTCLOUD_SECRETID:"Set SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"Set SecretKey",PICBED_TENCENTCLOUD_APPID:"Set AppId",PICBED_TENCENTCLOUD_BUCKET:"Set Bucket",PICBED_TENCENTCLOUD_AREA:"Set Area",PICBED_TENCENTCLOUD_ENDPOINT:"Set Endpoint",PICBED_TENCENTCLOUD_PATH:"Set Path",PICBED_TENCENTCLOUD_OPTIONS:"Set URL Suffix",PICBED_TENCENTCLOUD_SLIM:"Set ImageSlim",PICBED_TENCENTCLOUD_SLIM_TIP:"Image extremely intelligent compression, please refer to the [document description](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"OPEN",PICBED_TENCENTCLOUD_SLIM_CANCEL:"CLOSE",PICBED_TENCENTCLOUD_CUSTOMURL:"Set Custom URL",PICBED_TENCENTCLOUD_MESSAGE_APPID:"Ex. 1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"Ex. ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"Ex. cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"Ex. test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"Ex. http://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"Ex. ?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"Set Token",PICBED_GITHUB_REPO:"Set Repo Name",PICBED_GITHUB_PATH:"Set Path",PICBED_GITHUB_BRANCH:"Set Branch",PICBED_GITHUB_CUSTOMURL:"Set Custom URL",PICBED_GITHUB_MESSAGE_REPO:"Ex. username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"Ex. main",PICBED_GITHUB_MESSAGE_PATH:"Ex. test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"Ex. https://test.com",PICBED_QINIU:"Qiniu",PICBED_QINIU_ACCESSKEY:"Set AccessKey",PICBED_QINIU_SECRETKEY:"Set SecretKey",PICBED_QINIU_BUCKET:"Set Bucket",PICBED_QINIU_PATH:"Set Path",PICBED_QINIU_URL:"Set URL",PICBED_QINIU_OPTIONS:"Set URL Suffix",PICBED_QINIU_AREA:"Set Area",PICBED_QINIU_MESSAGE_PATH:"Ex. test/",PICBED_QINIU_MESSAGE_AREA:"Ex. z0",PICBED_QINIU_MESSAGE_OPTIONS:"Ex. ?imageslim",PICBED_QINIU_MESSAGE_URL:"Ex. https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"Set ClientId",PICBED_IMGUR_PROXY:"Set Proxy",PICBED_IMGUR_MESSAGE_PROXY:"Ex. http://127.0.0.1:1080",PICBED_UPYUN:"Upyun",PICBED_UPYUN_BUCKET:"Set Bucket",PICBED_UPYUN_OPERATOR:"Set Operator",PICBED_UPYUN_PASSWORD:"Set Operator Password",PICBED_UPYUN_PATH:"Set Path",PICBED_UPYUN_URL:"Set URL",PICBED_UPYUN_OPTIONS:"Set URL Suffix",PICBED_UPYUN_MESSAGE_OPERATOR:"Ex. me",PICBED_UPYUN_MESSAGE_PASSWORD:"Please type the operator password",PICBED_UPYUN_MESSAGE_URL:"Ex. http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"Ex. !imgslim",PICBED_UPYUN_MESSAGE_PATH:"Ex. test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"Plugin installed successfully",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"Plugin installation failed",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"Plugin installation failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"Plugin installation failed, please enter a valid plugin name or valid installation path",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"Plugin uninstalled successfully",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"Plugin uninstall failed",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"Plugin uninstall failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"Plugin uninstall failed, please enter a valid plugin name",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"Plugin updated successfully",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"Plugin update failed",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"Plugin update failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"Plugin update failed, please enter a valid plugin name",CONFIG_SYNC_INVALID_ENCRYPTION_METHOD:"Invalid configuration: settings.picgoCloud.encryptionMethod must be one of 'auto', 'sse', 'e2ee'. Found: ${value}",CONFIG_SYNC_ENCRYPTION_METHOD_E2EE:"End-to-end encryption",CONFIG_SYNC_ENCRYPTION_METHOD_SSE:"Server-side encryption",CONFIG_SYNC_ENCRYPTION_SWITCH_TITLE:"Confirm switch encryption method?",CONFIG_SYNC_ENCRYPTION_SWITCH_BODY:'You are switching from "${from}" to "${to}".\n\nNote: Switching encryption modes will clear all your cloud history versions.\nThis is because older history versions cannot be decrypted or verified under the new mode.\nAfter switching, the system will immediately create a new backup as the starting point.',CONFIG_SYNC_ENCRYPTION_SWITCH_CONFIRM:"Confirm switch and clear history",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCEL:"Cancel",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCELLED:"Encryption switch cancelled by user",CONFIG_SYNC_ENCRYPTION_SWITCH_MISSING_HANDLER:"Encryption switch confirmation handler is required"}};class sn{i18n;objectAdapter;ctx;constructor(e){this.ctx=e,this.objectAdapter=new y.ObjectAdapter(rn);let t=this.ctx.getConfig("settings.language")||"en";rn[t]||(t="en"),this.i18n=new y.I18n({adapter:this.objectAdapter,defaultLanguage:t}),this.loadOutsideI18n()}loadOutsideI18n(){const n=this.getOutsideI18nFolder();e.readdirSync(n,{withFileTypes:!0}).forEach(r=>{if(r.isFile()&&r.name.endsWith(".yml")){const i=t.join(n,r.name),s=e.readFileSync(i,"utf8");try{const e=U.load(s);rn[r.name.replace(/\.yml$/,"")]=e}catch(e){console.error(e)}}})}getOutsideI18nFolder(){const n=t.join(this.ctx.baseDir,"i18n-cli");return e.pathExistsSync(n)||e.ensureDirSync(n),n}translate(e,t){return this.i18n.translate(e,t)||e}setLanguage(e){this.i18n.setLanguage(e),this.ctx.saveConfig({"settings.language":e})}addLocale(e,t){const n=this.objectAdapter.getLocale(e);if(!n)return!1;const r=c.merge(n,t);return this.objectAdapter.setLocale(e,r),!0}addLanguage(e,t){return!this.objectAdapter.getLocale(e)&&(this.objectAdapter.setLocale(e,t),rn[e]=t,!0)}getLanguageList(){return Object.keys(rn)}}var on;function an(e){return Object.values(on).includes(e)}!function(e){e.AUTH_CALLBACK="/auth/callback",e.UPLOAD="/upload",e.HEARTBEAT="/heartbeat"}(on||(on={}));const cn=e=>{if(e instanceof Error)return e.message;if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}};var ln;!function(e){e[e.Clipboard=0]="Clipboard",e[e.List=1]="List",e[e.Invalid=2]="Invalid"}(ln||(ln={}));const un=e=>"object"==typeof e&&null!==e&&("arrayBuffer"in e&&"function"==typeof e.arrayBuffer),pn=e=>{const t=e.name;return"string"==typeof t&&""!==t.trim()?t:`${_.randomUUID()}.png`},gn=(n,r)=>{n.post(on.UPLOAD,async n=>{try{const i=n.req.raw.headers.get("content-type")||"",s=(e,t)=>r.i18n?.translate(e,t)??String(e);if(i.includes("multipart/form-data")){const i=t.join(r.baseDir,"picgo-form-images"),o=[];try{await e.ensureDir(i);const a=(await n.req.formData()).getAll("files");if(0===a.length)return n.json({success:!1,result:[],message:s("SERVER_FORMDATA_NO_FILES_IN_FILES_FIELD")},400);for(const r of a){if(!un(r))return n.json({success:!1,result:[],message:s("SERVER_FORMDATA_FILES_MUST_BE_FILES")},400);const a=pn(r),c=t.basename(a),l=t.join(i,c),u=Buffer.from(await r.arrayBuffer());await e.writeFile(l,u),o.push(l)}const c=await r.upload(o);if(c instanceof Error)return n.json({success:!1,result:[],message:c.message},500);const l=c.map(e=>e.imgUrl).filter(e=>"string"==typeof e&&""!==e);return n.json({success:!0,result:l})}catch(e){return r.log.error(e),n.json({success:!1,result:[],message:cn(e)},500)}finally{await Promise.allSettled(o.map(t=>e.remove(t)))}}const o=await n.req.raw.text().catch(()=>"");if(""===o.trim()){const e=await r.upload();if(e instanceof Error)return n.json({success:!1,result:[],message:e.message},500);const t=e.map(e=>e.imgUrl).filter(e=>"string"==typeof e&&""!==e);return n.json({success:!0,result:t})}let a;try{a=JSON.parse(o)}catch{return n.json({success:!1,result:[],message:s("SERVER_INVALID_JSON_BODY")},400)}const c=(e=>{if("object"!=typeof e||null===e)return{kind:ln.Invalid,messageKey:"SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED"};if(!("list"in e))return{kind:ln.Clipboard};const t=e.list;return void 0===t?{kind:ln.Clipboard}:Array.isArray(t)?0===t.length?{kind:ln.Clipboard}:t.every(e=>"string"==typeof e&&""!==e.trim())?{kind:ln.List,list:t}:{kind:ln.Invalid,messageKey:"SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED"}:{kind:ln.Invalid,messageKey:"SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED"}})(a);if(c.kind===ln.Invalid)return n.json({success:!1,result:[],message:s(c.messageKey)},400);if(c.kind===ln.Clipboard){const e=await r.upload();if(e instanceof Error)return n.json({success:!1,result:[],message:e.message},500);const t=e.map(e=>e.imgUrl).filter(e=>"string"==typeof e&&""!==e);return n.json({success:!0,result:t})}const l=await r.upload(c.list);if(l instanceof Error)return n.json({success:!1,result:[],message:l.message},500);const u=l.map(e=>e.imgUrl).filter(e=>"string"==typeof e&&""!==e);return n.json({success:!0,result:u})}catch(e){return r.log.error(e),n.json({success:!1,result:[],message:cn(e)},500)}}),n.post(on.HEARTBEAT,e=>e.json({success:!0,result:"alive"}))};var En;!function(e){e.Authorization="authorization",e.Header="header",e.Query="query",e.None="none"}(En||(En={}));const dn=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&""!==e.trim()){const t=Number(e);if(Number.isFinite(t))return t}},hn=e=>{if("string"!=typeof e)return;const t=e.trim();return""===t?void 0:t};class _n{app;ctx;server;listeningPort;listeningHost;authSecret;warnedQuerySecret=!1;staticRoutePrefixes=[];constructor(e){this.ctx=e,this.app=new O.Hono,this.initMiddleware(),this.initCoreRoutes()}registerGet(e,t,n=!1){this.handleRegister("get",e,t,n)}registerPost(e,t,n=!1){this.handleRegister("post",e,t,n)}registerPut(e,t,n=!1){this.handleRegister("put",e,t,n)}registerDelete(e,t,n=!1){this.handleRegister("delete",e,t,n)}registerMiddleware(e,t){this.app.use(e,t)}registerStatic(e,t){const n=e.endsWith("/*")?e:`${e}/*`,r=n.replace(/\/\*$/,"")||"/";this.staticRoutePrefixes.includes(r)||this.staticRoutePrefixes.push(r),this.app.use(n,A.serveStatic({root:t}))}handleRegister(e,t,n,r){!an(t)||r?this.app[e](t,n):this.ctx.log.warn(`[PicGo Server] Plugin attempted to overwrite builtin route: ${t}. Action denied.`)}mount(e,t){const n=new O.Hono;t(n),this.app.route(e,n)}getServerInfo(){return this.server&&this.listeningHost&&void 0!==this.listeningPort?`http://${this.listeningHost}:${this.listeningPort}/`:""}isListening(){return void 0!==this.server}initMiddleware(){this.app.use(x.cors()),this.app.use((e,t)=>this.handleAuth(e,t)),this.app.use(R.logger())}initCoreRoutes(){gn(this.app,this.ctx)}t(e,t){return this.ctx.i18n?.translate(e,t)??String(e)}getRequestPath(e){return"string"==typeof e.req.path?e.req.path:new URL(e.req.url).pathname}isStaticPath(e){return this.staticRoutePrefixes.some(t=>!!t&&("/"===t?"/"===e:e===t||e.startsWith(`${t}/`)))}shouldSkipAuth(e,t){return"OPTIONS"===e.toUpperCase()||(""===t||"/"===t||(!!this.isStaticPath(t)||!(!an(t)||t===on.UPLOAD)))}extractAuthToken(e){const t=e.req.raw.headers;if(t.has("authorization")){const e=(t.get("authorization")??"").match(/^\s*Bearer\s+(.+)$/i);return{source:En.Authorization,token:e?.[1]}}if(t.has("x-picgo-secret"))return{source:En.Header,token:t.get("x-picgo-secret")??""};const n=new URL(e.req.url);return n.searchParams.has("secret")?{source:En.Query,token:n.searchParams.get("secret")??""}:{source:En.None}}warnQuerySecretOnce(){this.warnedQuerySecret||(this.warnedQuerySecret=!0,this.ctx.log.warn(this.t("SERVER_AUTH_QUERY_SECRET_WARNING")))}getClientIp(e){const t=e.req.raw.headers.get("x-forwarded-for");if(t){const e=t.split(",")[0]?.trim();if(e)return e}const n=e.env,r=n.server??n;return r?.incoming?.socket?.remoteAddress??"unknown"}logUnauthorized(e){const t=this.getClientIp(e);this.ctx.log.warn(this.t("SERVER_AUTH_UNAUTHORIZED_REQUEST",{ip:t}))}async handleAuth(e,t){if(!this.authSecret)return await t();const n=e.req.method,r=this.getRequestPath(e);if(this.shouldSkipAuth(n,r))return await t();const{source:i,token:s}=this.extractAuthToken(e);return i===En.Query&&this.warnQuerySecretOnce(),s&&s===this.authSecret?await t():(this.ctx.log.warn(`[PicGo Server] Unauthorized request to ${n} ${r} with token from ${i}`),this.logUnauthorized(e),e.json({success:!1,message:"Unauthorized"},401))}async startServer(e,t){return await new Promise((n,r)=>{const i=T.serve({fetch:this.app.fetch,port:e,hostname:t},e=>{i.off("error",s),n({server:i,port:e.port})});function s(e){i.off("error",s),r(e)}i.once("error",s)})}async isExistingPicGoServer(e,t){const n=`http://${"0.0.0.0"===e||"::"===e?"127.0.0.1":e}:${t}/heartbeat`;try{const e=await u.post(n,void 0,{timeout:1e3});return!0===e?.data?.success&&"alive"===e?.data?.result}catch{return!1}}async listen(e,t,n=!1,r){if(this.server&&void 0!==this.listeningPort)return t&&this.listeningHost&&t!==this.listeningHost&&this.ctx.log.warn(`Server is already listening at http://${this.listeningHost}:${this.listeningPort}`),this.listeningPort;const i=this.ctx.getConfig("settings.server.port"),s=this.ctx.getConfig("settings.server.host"),o=this.ctx.getConfig("settings.server.secret"),a=dn(e)??dn(i)??36677,c=t??("string"==typeof s?s:void 0)??"127.0.0.1";this.authSecret=hn(r)??hn(process.env.PICGO_SERVER_SECRET)??hn(o),this.warnedQuerySecret=!1,this.app=((e,t)=>{const n=new O.Hono,r=[],i=new Map;return e.routes.forEach(e=>{if("ALL"===e.method)return void r.push(e);const n=`${e.method}::${e.path}`,s=i.get(n);if(void 0!==s)an(e.path)||t.log.warn(`Route conflict detected for [${e.method}] ${e.path}. Overriding previous handler.`),r[s]=e;else{const t=r.push(e)-1;i.set(n,t)}}),r.forEach(e=>{n.on(e.method,e.path,e.handler)}),n})(this.app,this.ctx);const l=async e=>{try{const{server:t,port:n}=await this.startServer(e,c);return this.server=t,this.listeningPort=n,this.listeningHost=c,this.authSecret?this.ctx.log.info(this.t("SERVER_AUTH_ENABLED")):this.ctx.log.warn(this.t("SERVER_AUTH_DISABLED_WARNING")),this.ctx.log.info(`[PicGo Server] Listening at http://${c}:${n}`),n}catch(t){if("EADDRINUSE"===t?.code){if(!n){if(await this.isExistingPicGoServer(c,e))return this.ctx.log.info(`[PicGo Server] Detected existing instance at http://${c}:${e}`),e}return this.ctx.log.warn(`[PicGo Server] port ${e} is busy, trying with port ${e+1}`),await l(e+1)}this.ctx.log.error(t)}};return await l(a)}shutdown(){try{this.server?.close()}catch{}finally{this.server=void 0,this.listeningPort=void 0,this.listeningHost=void 0,this.authSecret=void 0,this.warnedQuerySecret=!1}}}const fn=e=>{let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")};class In{ctx;authState=null;pkceVerifier=null;pending;constructor(e){this.ctx=e,this.registerRoutes()}disposeLoginFlow(){const e=this.pending;if(!e)return;const t=this.ctx.i18n.translate("CLOUD_LOGIN_CANCELLED");e.abortController.abort(new Error(t))}async startLoginFlow(){if(this.pending)throw new Error(this.ctx.i18n.translate("CLOUD_LOGIN_IN_PROGRESS"));const e=this.ctx.server.isListening(),t=new AbortController,n=new Promise((n,r)=>{this.pending={resolve:n,reject:r,shouldShutdown:!e,abortController:t},t.signal.addEventListener("abort",()=>{const e=this.pending;if(!e||e.abortController!==t)return;this.pending=void 0,this.authState=null,this.pkceVerifier=null;const n=t.signal.reason,i=this.ctx.i18n.translate("CLOUD_LOGIN_CANCELLED"),s=n instanceof Error?n:new Error(String(n??i));r(s),e.shouldShutdown&&setTimeout(()=>{this.ctx.server.shutdown()},100)},{once:!0})});let r;try{r=await this.ctx.server.listen(void 0,"127.0.0.1",!0)}catch(e){const r=e instanceof Error?e:new Error(String(e));return t.abort(r),await n}if(void 0===r)return t.abort(new Error(this.ctx.i18n.translate("CLOUD_LOGIN_SERVER_START_FAILED"))),await n;if(t.signal.aborted)return await n;const i=encodeURIComponent(`http://127.0.0.1:${r}/auth/callback`);this.authState=B.randomUUID(),this.pkceVerifier=(()=>{const e=new Uint8Array(32);return _.webcrypto.getRandomValues(e),fn(e)})();const s=encodeURIComponent(await(async e=>{const t=(new TextEncoder).encode(e),n=await _.webcrypto.subtle.digest("SHA-256",t);return fn(new Uint8Array(n))})(this.pkceVerifier)),o=`${Ee}?callback=${i}&state=${encodeURIComponent(this.authState)}&challenge=${s}`;if(t.signal.aborted)return await n;try{await this.ctx.openUrl(o)}catch(e){const t=e instanceof Error?e.message:String(e);this.ctx.log.warn(this.ctx.i18n.translate("CLOUD_LOGIN_OPEN_BROWSER_FAILED",{message:t})),this.ctx.log.info(this.ctx.i18n.translate("CLOUD_LOGIN_OPEN_BROWSER_TIP",{url:o}))}return await n}renderResultPage(e,t){const n=e?"#2ecc71":"#e74c3c",r=e?this.ctx.i18n.translate("CLOUD_LOGIN_RESULT_SUCCESS_TITLE"):this.ctx.i18n.translate("CLOUD_LOGIN_RESULT_FAILED_TITLE"),i=e?"✓":"✕";return`\n <!DOCTYPE html>\n <html lang="en">\n <head>\n <title>${this.ctx.i18n.translate("CLOUD_LOGIN_PAGE_TITLE")}</title>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <style>\n body {\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100vh;\n margin: 0;\n background: #f0f2f5;\n }\n .card {\n background: white;\n padding: 40px;\n border-radius: 8px;\n box-shadow: 0 2px 10px rgba(0,0,0,0.1);\n text-align: center;\n max-width: 440px;\n width: calc(100% - 48px);\n }\n .icon {\n width: 64px;\n height: 64px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 16px;\n background: ${n};\n color: #fff;\n font-size: 36px;\n line-height: 1;\n }\n h1 {\n color: ${n};\n margin: 0 0 12px;\n font-size: 24px;\n }\n p {\n color: #666;\n margin: 0 0 24px;\n line-height: 1.5;\n }\n .btn {\n display: inline-block;\n padding: 10px 20px;\n background: #333;\n color: white;\n text-decoration: none;\n border-radius: 4px;\n font-size: 14px;\n cursor: pointer;\n user-select: none;\n }\n </style>\n </head>\n <body>\n <div class="card">\n <div class="icon">${i}</div>\n <h1>${r}</h1>\n <p>${t}</p>\n </div>\n </body>\n </html>\n `}abortPendingLogin(e,t){e.abortController.signal.aborted||e.abortController.abort(new Error(t))}async handleCallback(e){const t=e.req.query("code"),n=e.req.query("state");if(!n||n!==this.authState)return this.ctx.log.warn(this.ctx.i18n.translate("CLOUD_LOGIN_STATE_MISMATCH_WARN")),e.html(this.renderResultPage(!1,this.ctx.i18n.translate("CLOUD_LOGIN_STATE_INVALID")),403);if(!t){const t=this.ctx.i18n.translate("CLOUD_LOGIN_CODE_MISSING"),n=this.pending;return n&&this.abortPendingLogin(n,t),e.html(this.renderResultPage(!1,t),400)}const r=this.pending;if(!r||r.abortController.signal.aborted)return e.html(this.renderResultPage(!1,this.ctx.i18n.translate("CLOUD_LOGIN_NOT_IN_PROGRESS")),409);const i=this.pkceVerifier;if(!i){this.ctx.log.error("PKCE verifier is missing during callback handling");const t=this.ctx.i18n.translate("CLOUD_LOGIN_EXCHANGE_FAILED");return this.abortPendingLogin(r,t),e.html(this.renderResultPage(!1,t),500)}try{this.ctx.log.info("API_BASE_URL",ge,"Exchanging login code for token...");const n=await(async(e,t)=>(await u.post("/api/tokens/exchange",{code:e,verifier:t},{baseURL:ge})).data)(t,i);if(!n.token){this.ctx.log.error("Token exchange failed without throwing an error");const t=n.message??this.ctx.i18n.translate("CLOUD_LOGIN_EXCHANGE_FAILED");return this.abortPendingLogin(r,t),e.html(this.renderResultPage(!1,t),500)}return this.ctx.saveConfig({"settings.picgoCloud.token":n.token}),this.authState=null,this.pkceVerifier=null,this.pending=void 0,r.resolve(n.token),r.shouldShutdown&&setTimeout(()=>{this.ctx.server.shutdown()},100),e.html(this.renderResultPage(!0,this.ctx.i18n.translate("CLOUD_LOGIN_RESULT_SUCCESS_MESSAGE")),200)}catch(t){let n,i;if(u.isAxiosError(t)){i=t.response?.status;const e=t.response?.data;(e=>"object"==typeof e&&null!==e&&"message"in e&&"string"==typeof e.message)(e)&&(n=e.message)}const s=this.ctx.i18n.translate("CLOUD_LOGIN_EXCHANGE_FAILED"),o=n??s,a=400===i?400:500;return this.abortPendingLogin(r,o),this.ctx.log.error(`Token exchange failed: ${o} (status: ${a})`,t),e.html(this.renderResultPage(!1,o),a)}}registerRoutes(){this.ctx.server.registerGet(on.AUTH_CALLBACK,this.handleCallback.bind(this),!0)}}class Cn{client;ctx;constructor(e){this.client=new de(e),this.ctx=e}async whoami(e){return await this.client.request({method:"GET",url:"/api/whoami"},e)}async verifyToken(e){try{const t=await this.whoami(e);return this.ctx.log.success("Welcome:",t.user),!0}catch{return!1}}async getUserConfig(e){try{const t=await this.client.request({method:"GET",url:"/api/config"},e);return JSON.parse(t.config)}catch{throw new Error("Failed to fetch user config from server")}}}class mn{ctx;auth;user;constructor(e){this.ctx=e,this.user=new Cn(e),this.auth=new In(e)}async login(e){if(e){if(!await this.user.verifyToken(e))throw new Error(this.ctx.i18n.translate("CLOUD_LOGIN_INVALID_TOKEN"));return this.ctx.saveConfig({"settings.picgoCloud.token":e}),void this.ctx.log.success(this.ctx.i18n.translate("CLOUD_LOGIN_SUCCESS"))}const t=this.ctx.getConfig("settings.picgoCloud.token");if(t){if(await this.user.verifyToken(t))return void this.ctx.log.success(this.ctx.i18n.translate("CLOUD_LOGIN_SUCCESS"))}await this.auth.startLoginFlow(),this.ctx.log.success(this.ctx.i18n.translate("CLOUD_LOGIN_SUCCESS"))}logout(){this.ctx.removeConfig("settings.picgoCloud","token"),this.ctx.log.success(this.ctx.i18n.translate("CLOUD_LOGOUT_SUCCESS"))}disposeLoginFlow(){this.auth.disposeLoginFlow()}async getUserInfo(){const e=this.ctx.getConfig("settings.picgoCloud.token");if(!e)return null;try{return await this.user.whoami(e)}catch(e){if(u.isAxiosError(e)){const t=e.response?.status;if(401===t||403===t)return this.ctx.removeConfig("settings.picgoCloud","token"),null;const n=e.response?.data?.message??e.message;if(n)throw new Error(`${e.code?`Error code: ${e.code}`:""}, ${n}`)}throw e}}}const Sn=()=>_.randomUUID(),Nn=new Set(["current","uploader","transformer","proxy","list"]),Ln=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Pn=e=>e.trim(),Dn=e=>Pn(e).toLowerCase();class Un{ctx;constructor(e){this.ctx=e,this.init()}init(){const e=this.ctx.getConfig("picBed"),t=this.ctx.getConfig("uploader"),n=Ln(e)?e:{},r=Ln(t)?t:{},i=new Set;for(const e of Object.keys(n))Nn.has(e)||i.add(e);for(const e of Object.keys(r))i.add(e);for(const e of i)this.migrateNormalizeAndSync(e)}listUploaderTypes(){return this.ctx.helper.uploader.getIdList()}getConfigList(e){return this.readTypeStore(e).configList}getActiveConfig(e){const t=this.readTypeStore(e);return this.getActiveConfigFromStore(t)}use(e,t){this.assertUploaderTypeExists(e);const n=this.readTypeStore(e);if(0===n.configList.length)return this.ctx.log.warn(`[UploaderConfigManager] No existing configs for uploader type "${e}". Creating a new metadata-only config`+(t?` named "${Pn(t)}"`:"")+". Please configure it before uploading."),this.createOrUpdate(e,t,{});const r="string"==typeof t?Pn(t):"";if(r){const i=this.findConfigByName(n.configList,r);if(!i)throw new Error(`Config ${t} not found in type ${e}`);return this.activate(e,n,i._id)}const{store:i,changed:s}=this.normalizeTypeStore(n),o=this.getActiveConfigFromStore(i);return o?this.persistTypeAndMirror(e,i,o,{setCurrent:!0,persistStore:s}):this.createOrUpdate(e,t,{})}createOrUpdate(e,t,n={}){this.assertUploaderTypeExists(e);const r=this.readTypeStore(e),i=Date.now(),s="string"==typeof t?Pn(t):"",o=s?this.findConfigByName(r.configList,s):void 0;if(o){const t={...o,...n,_id:o._id,_configName:o._configName,_createdAt:o._createdAt,_updatedAt:i},s={configList:r.configList.map(e=>e._id===o._id?t:e),defaultId:t._id};return this.persistTypeAndMirror(e,s,t,{setCurrent:!0,persistStore:!0})}const a=s?this.ensureUniqueNameOrThrow(r.configList,s):this.generateDefaultName(r.configList),c={...n,_id:Sn(),_configName:a,_createdAt:i,_updatedAt:i},l={configList:[...r.configList,c],defaultId:c._id};return this.persistTypeAndMirror(e,l,c,{setCurrent:!0,persistStore:!0})}copy(e,t,n){this.assertUploaderTypeExists(e);const r=this.readTypeStore(e),i=this.normalizeTypeStore(r).store,s=Pn(t),o=this.findConfigByName(i.configList,s);if(!o)throw new Error(`Config ${t} not found in type ${e}`);const a=Pn(n);if(!a)throw new Error("Config name can not be empty");const l=this.ensureUniqueNameOrThrow(i.configList,a),u=Date.now(),p={...o,_id:Sn(),_configName:l,_createdAt:u,_updatedAt:u},g={configList:[...i.configList,p],defaultId:i.defaultId},E={[`uploader.${e}`]:g},d=this.getActiveConfigFromStore(g);if(d){const t=this.ctx.getConfig(`picBed.${e}`);c.isEqual(t,d)||(E[`picBed.${e}`]=d)}return this.ctx.saveConfig(E),p}rename(e,t,n){this.assertUploaderTypeExists(e);const r=this.readTypeStore(e),i=Pn(t),s=Pn(n);if(!s)throw new Error("Config name can not be empty");const o=this.findConfigByName(r.configList,i);if(!o)throw new Error(`Config ${t} not found in type ${e}`);this.ensureUniqueNameOrThrow(r.configList,s,o._id);const a=Date.now(),c={...o,_configName:s,_updatedAt:a},l={configList:r.configList.map(e=>e._id===o._id?c:e),defaultId:r.defaultId};return r.defaultId===o._id?(this.persistTypeAndMirror(e,l,c,{setCurrent:!1,persistStore:!0}),c):(this.ctx.saveConfig({[`uploader.${e}`]:l}),c)}remove(e,t){this.assertUploaderTypeExists(e);const n=this.readTypeStore(e),r=Pn(t),i=this.findConfigByName(n.configList,r);if(!i)throw new Error(`Config ${t} not found in type ${e}`);const s=n.configList.filter(e=>e._id!==i._id);if(0===s.length)return this.ctx.saveConfig({[`uploader.${e}`]:{configList:[],defaultId:""}}),this.ctx.removeConfig("picBed",e),void(this.ctx.getConfig("picBed.current")===e&&this.ctx.log.warn(`You are currently using ${e} but have deleted its last config. Please switch to another uploader or create a new config.`));const o={configList:s,defaultId:n.defaultId===i._id?s[0]._id:n.defaultId},a=this.getActiveConfigFromStore(o);a?this.persistTypeAndMirror(e,o,a,{setCurrent:!1,persistStore:!0}):this.ctx.saveConfig({[`uploader.${e}`]:o})}migrateNormalizeAndSync(e){const t=this.ctx.getConfig(`picBed.${e}`);let n=this.readTypeStore(e),r=!1;if(0===n.configList.length&&Ln(t)){const e=Date.now(),i={...t,_id:"string"==typeof t._id&&t._id.trim()?t._id:Sn(),_configName:"string"==typeof t._configName&&Pn(t._configName)?Pn(t._configName):"Default",_createdAt:"number"==typeof t._createdAt?t._createdAt:e,_updatedAt:"number"==typeof t._updatedAt?t._updatedAt:e};n={configList:[i],defaultId:i._id},r=!0}const i=this.normalizeTypeStore(n);n=i.store,r=r||i.changed;const s={};r&&(s[`uploader.${e}`]=n);const o=this.getActiveConfigFromStore(n);if(o){const t=this.ctx.getConfig(`picBed.${e}`);c.isEqual(t,o)||(s[`picBed.${e}`]=o)}Object.keys(s).length>0&&this.ctx.saveConfig(s)}assertUploaderTypeExists(e){if(!this.listUploaderTypes().includes(e))throw new Error(`Type ${e} not found`)}readTypeStore(e){const t=this.ctx.getConfig(`uploader.${e}`);if(!Ln(t))return{configList:[],defaultId:""};const n=t.configList,r=t.defaultId,i=[];if(Array.isArray(n))for(const e of n)Ln(e)&&i.push(e);return{configList:i,defaultId:"string"==typeof r?r:""}}normalizeTypeStore(e){const t=Date.now();let n=!1;const r=new Set,i=new Set,s=e.configList.map(e=>{const s={...e};let o="string"==typeof s._id&&s._id.trim()?s._id:Sn();for(;i.has(o);)o=Sn();o!==s._id&&(s._id=o,n=!0),i.add(o);const a="number"==typeof s._createdAt?s._createdAt:t,c="number"==typeof s._updatedAt?s._updatedAt:t;a!==s._createdAt&&(s._createdAt=a,n=!0),c!==s._updatedAt&&(s._updatedAt=c,n=!0);let l=("string"==typeof s._configName?Pn(s._configName):"")||this.generateDefaultNameFromUsed(r),u=Dn(l);if(r.has(u)){const e=l;let i=1;for(;r.has(Dn(`${e}-${i}`));)i++;l=`${e}-${i}`,u=Dn(l),s._updatedAt=t,n=!0}return l!==s._configName&&(s._configName=l,n=!0),r.add(u),s});let o=e.defaultId;if(s.length>0){s.some(e=>e._id===o)||(o=s[0]._id,n=!0)}else""!==o&&(o="",n=!0);return{store:{configList:s,defaultId:o},changed:n}}generateDefaultName(e){const t=new Set(e.map(e=>Dn(e._configName)));return this.generateDefaultNameFromUsed(t)}generateDefaultNameFromUsed(e){const t="Default";if(!e.has(Dn(t)))return t;let n=1;for(;e.has(Dn(`${t}-${n}`));)n++;return`${t}-${n}`}ensureUniqueNameOrThrow(e,t,n){const r=Pn(t);if(!r)throw new Error("Config name can not be empty");const i=Dn(r);if(e.some(e=>e._id!==n&&Dn(e._configName)===i))throw new Error(`Config name ${t} already exists`);return r}findConfigByName(e,t){const n=Dn(t);return e.find(e=>Dn(e._configName)===n)}getActiveConfigFromStore(e){if(!e.defaultId)return e.configList[0];return e.configList.find(t=>t._id===e.defaultId)??e.configList[0]}activate(e,t,n){const r=t.configList.find(e=>e._id===n);if(!r)throw new Error(`Config not found for type ${e}`);const i={configList:t.configList,defaultId:n};return this.persistTypeAndMirror(e,i,r,{setCurrent:!0,persistStore:!0})}persistTypeAndMirror(e,t,n,r){const i={};if(r.persistStore&&(i[`uploader.${e}`]=t),n&&(i[`picBed.${e}`]=n),r.setCurrent&&(i["picBed.current"]=e,i["picBed.uploader"]=e),this.ctx.saveConfig(i),n)return n;const s=t.configList[0];if(!s)throw new Error(`No configs found in type ${e}`);return s}}class yn extends n.EventEmitter{_config;lifecycle;db;_pluginLoader;configPath;baseDir;helper;log;cmd;output;input;pluginHandler;server;cloud;uploaderConfig;Request;i18n;VERSION="2.0.3";GUI_VERSION;get pluginLoader(){return this._pluginLoader}constructor(e=""){super(),this.configPath=e,this.output=[],this.input=[],this.helper={transformer:new st("transformer"),uploader:new st("uploader"),beforeTransformPlugins:new st("beforeTransformPlugins"),beforeUploadPlugins:new st("beforeUploadPlugins"),afterUploadPlugins:new st("afterUploadPlugins")},this.initConfigPath(),this.log=new ut(this),this.cmd=new at(this),this.pluginHandler=new tn(this),this.initConfig(),this.init()}initConfigPath(){if(""===this.configPath&&(this.configPath=r.homedir()+"/.picgo/config.json"),".JSON"!==t.extname(this.configPath).toUpperCase())throw this.configPath="",Error("The configuration file only supports JSON format.");this.baseDir=t.dirname(this.configPath);e.pathExistsSync(this.configPath)||e.ensureFileSync(`${this.configPath}`)}initConfig(){this.db=new en(this),this._config=this.db.read(!0)}init(){try{this.i18n=new sn(this),this.Request=new Zt(this),this.server=new _n(this),this.cloud=new mn(this),this._pluginLoader=new Yt(this),ot("picgo"),$t().register(this),{register(e){e.helper.transformer.register("path",Ht),e.helper.transformer.register("base64",kt)}}.register(this),ot(""),this._pluginLoader.load(),this.uploaderConfig=new Un(this),this.lifecycle=new pt(this)}catch(e){throw this.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,-1),this.log.error(e),e}}use(e,t){if(t)return this.pluginLoader.registerPlugin(t,e),this.pluginLoader.getPlugin(t);return e(this)}registerCommands(){""!==this.configPath&&(this.cmd.init(),this.cmd.loadCommands())}getConfig(e){return e?c.get(this._config,e):this._config}saveConfig(e){ee(e)?(this.setConfig(e),this.db.saveConfig(e)):this.log.warn("the format of config is invalid, please provide object")}removeConfig(e,t){e&&t&&(Z(e)?this.log.warn(`the config.${e} can't be removed`):(this.unsetConfig(e,t),this.db.unset(e,t)))}setConfig(e){ee(e)?Object.keys(e).forEach(t=>{Z(t)&&(this.log.warn(`the config.${t} can't be modified`),delete e[t]),c.set(this._config,t,e[t]),Wt.emit(exports.IBusEvent.CONFIG_CHANGE,{configName:t,value:e[t]})}):this.log.warn("the format of config is invalid, please provide object")}unsetConfig(e,t){e&&t&&(Z(e)?this.log.warn(`the config.${e} can't be unset`):c.unset(this.getConfig(e),t))}get request(){return this.Request.request.bind(this.Request)}async openUrl(e){const t=(await import("open")).default;this.log.info("Opening browser with URL:",e),await t(e)}async upload(t){if(""===this.configPath)return this.log.error("The configuration file only supports JSON format."),[];if(void 0!==t&&0!==t.length){const{output:e}=await this.lifecycle.start(t);return e}try{const{imgPath:t,shouldKeepAfterUploading:n}=await jt(this);if("no image"===t)throw new Error("image not found in clipboard");{this.once(exports.IBuildInEvent.FAILED,()=>{n||e.remove(t).catch(e=>{this.log.error(e)})}),this.once("finished",()=>{n||e.remove(t).catch(e=>{this.log.error(e)})});const{output:r}=await this.lifecycle.start([t]);return r}}catch(e){throw this.emit(exports.IBuildInEvent.FAILED,e),e}}}const Tn={...ie,applyUrlRewriteToImgInfo:G};exports.CloudManager=mn,exports.Commander=at,exports.ConfigMerger=me,exports.ConfigSyncManager=Fe,exports.CorruptedDataError=Ne,exports.DecryptionFailedError=Te,exports.InvalidPinError=Ue,exports.Lifecycle=pt,exports.LifecyclePlugins=st,exports.Logger=ut,exports.MaxRetryExceededError=ye,exports.MissingHandlerError=Pe,exports.PicGo=yn,exports.PicGoUtils=Tn,exports.PluginHandler=tn,exports.PluginLoader=Yt,exports.Request=Zt,exports.ServerManager=_n,exports.UnsupportedVersionError=Le;
|
|
1
|
+
"use strict";require("dotenv/config");var e=require("fs-extra"),t=require("path"),i=require("events"),r=require("os"),n=require("commander"),s=require("inquirer"),o=require("image-size"),a=require("url"),c=require("node:process"),l=require("node:util"),u=require("chalk"),p=require("lodash"),d=require("comment-json"),_=require("axios"),g=require("node:crypto"),h=require("crypto"),f=require("util"),E=require("node:fs/promises"),m=require("@picgo/store"),I=require("dayjs"),C=require("mime-types"),L=require("md5"),O=require("node:path"),U=require("node:fs"),P=require("write-file-atomic"),D=require("resolve"),S=require("child_process"),N=require("is-wsl"),T=require("form-data"),A=require("https"),y=require("tunnel"),R=require("cross-spawn"),w=require("js-yaml"),x=require("@picgo/i18n"),b=require("@hono/node-server"),M=require("@hono/node-server/serve-static"),B=require("hono"),v=require("hono/logger"),G=require("hono/cors");function $(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(i){if("default"!==i){var r=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:function(){return e[i]}})}}),t.default=e,Object.freeze(t)}var F=$(g);const k=e=>{const t=`${!0===e.global?"g":""}${!0===e.ignoreCase?"i":""}`;return new RegExp(e.match,t)},H=(e,t,i)=>{if(e.imgUrl)for(const r of t){if(!(!1!==r.enable))continue;let t;try{t=k(r)}catch(e){i.log.error(e);continue}if(!t.test(e.imgUrl))continue;const n=e.imgUrl,s=n.replace(t,r.replace);if(s!==n&&void 0===e.originImgUrl&&(e.originImgUrl=n),e.imgUrl=s,""===s){const e=i.i18n?.translate("URL_REWRITE_EMPTY_RESULT")??"URL_REWRITE_EMPTY_RESULT";i.log.warn(e)}break}};function Y(e,t){return e.map(e=>{const i={...e};if("function"==typeof e.choices){const r=e.choices;i.choices=i=>{try{return r(i)}catch(i){return t?.onError?.(e.name,"choices",i),[{name:e.name,value:null}]}}}if("function"==typeof e.default){const r=e.default;i.default=i=>{try{return r(i)}catch(i){return void t?.onError?.(e.name,"default",i)}}}return i})}const V={handle:e=>{const t=e.cmd;t.program.command("install <plugins...>").description("install picgo plugin").alias("add").option("-p, --proxy <proxy>","Add proxy for installing plugins").option("-r, --registry <registry>","Choose a registry for installing plugins").action((t,i)=>{const{proxy:r,registry:n}=i,s={npmProxy:r,npmRegistry:n};e.pluginHandler.install(t,s).catch(t=>{e.log.error(t)})}),t.program.command("uninstall <plugins...>").alias("rm").description("uninstall picgo plugin").action(t=>{e.pluginHandler.uninstall(t).catch(t=>{e.log.error(t)})}),t.program.command("update <plugins...>").description("update picgo plugin").option("-p, --proxy <proxy>","Add proxy for installing plugins").option("-r, --registry <registry>","Choose a registry for installing plugins").action((t,i)=>{const{proxy:r,registry:n}=i,s={npmProxy:r,npmRegistry:n};e.pluginHandler.update(t,s).catch(t=>{e.log.error(t)})})}},q={handle:e=>{e.cmd.program.option("-c, --config <path>","set config path")}},j=e=>e.startsWith("http://")||e.startsWith("https://"),K=e=>{if(!e)return"";try{return new a.URL(e).href}catch(t){if(e.startsWith("//"))try{return new a.URL("http:"+e).href.slice(5)}catch(e){}return encodeURI(e)}},W=(...e)=>e.join("").replace(/\/{2,}/g,"/").split("/").map(e=>encodeURIComponent(e)).join("/"),Q=e=>{try{const{width:t=0,height:i=0,type:r}=o.imageSize(e);return{real:!0,width:t,height:i,extname:r?`.${r}`:".png"}}catch(e){return{real:!1,width:200,height:200,extname:".png"}}},z=async i=>{try{return{extname:t.extname(i),fileName:t.basename(i),filePath:i,buffer:await e.readFile(i),success:!0}}catch{return{reason:`read file ${i} error`,success:!1}}},J=async(e,i)=>{e=K(e);let r,n=!1,s="";const o=new Promise((o,c)=>{(async()=>{try{const c=await i.request({method:"get",url:e,resolveWithFullResponse:!0,responseType:"arraybuffer"}).then(e=>{const t=e.headers["content-type"];return t?.includes("image")&&(n=!0,s=`.${t.split("image/")[1]}`),e.data});clearTimeout(r);const l=new a.URL(e).pathname,u=decodeURIComponent(t.basename(l));o(n?{buffer:c,fileName:u,extname:s||t.extname(u)||".png",success:!0}:{buffer:c,fileName:u,extname:t.extname(u)||".png",success:!0})}catch(t){clearTimeout(r),o({success:!1,reason:`request ${e} error, ${t?.message??""}`})}})().catch(c)}),c=new Promise(t=>{r=setTimeout(()=>{t({success:!1,reason:`request ${e} timeout`})},1e4)});return Promise.race([o,c])},X=e=>/^@[^/]+\/picgo-plugin-/.test(e)?"scope":e.startsWith("picgo-plugin-")?"normal":Z(e)?"simple":"unknown",Z=i=>{if(t.isAbsolute(i))return!1;const r=t.join(process.cwd(),i);return!e.existsSync(r)&&(!i.includes("/")&&!i.includes("\\"))},ee=(e,t="")=>t?`@${t}/picgo-plugin-${e}`:`picgo-plugin-${e}`,te=(i,r=console)=>{switch(X(i)){case"normal":case"scope":return i;case"simple":return ee(i);default:{let n=i;return t.isAbsolute(i)&&e.existsSync(i)?re(n):(n=t.join(process.cwd(),i),e.existsSync(n)?re(n):(r.warn(`Can't find plugin ${i}`),""))}}},ie=(i,r=console)=>{switch(X(i)){case"normal":return ne(i);case"scope":return ne(i,!0);case"simple":return ne(ee(i));default:{if(!e.existsSync(i))return r.warn(`Can't find plugin: ${i}`),"";const n=t.posix.join(i,"package.json");if(e.existsSync(n)){const t=e.readJSONSync(n)||{};return t.name?.includes("picgo-plugin-")?t.name:(r.warn(`The plugin package.json's name filed is ${t.name||"empty"}, need to include the prefix: picgo-plugin-`),"")}return r.warn(`Can't find plugin: ${i}`),""}}},re=e=>e.split(t.sep).join("/"),ne=(e,t=!1)=>{if(e.includes("@")){let i=/(.+\/)?(picgo-plugin-\w+)(@.+)*/;t&&(i=/(.+\/)?(^@[^/]+\/picgo-plugin-\w+)(@.+)*/);const r=e.match(i);return r?r[2]:(console.warn("can not remove plugin version"),e)}return e},se=[],oe=e=>se.some(t=>e.startsWith(t)),ae=e=>"object"==typeof e&&!Array.isArray(e)&&Object.keys(e).length>0;function ce(e){try{return JSON.parse(e)}catch(t){return e}}const le=(e=0)=>isNaN(Number(e))?0:Number(e),ue=()=>"development"===process.env.NODE_ENV;var pe,de,_e,ge,he,fe,Ee=Object.freeze({__proto__:null,configBlackList:se,forceNumber:le,getFSFile:z,getImageSize:Q,getNormalPluginName:ie,getPluginNameType:X,getProcessPluginName:te,getURLFile:J,handleCompletePluginName:ee,handleStreamlinePluginName:e=>/^@[^/]+\/picgo-plugin-/.test(e)?e.replace(/^@[^/]+\/picgo-plugin-/,""):e.replace(/picgo-plugin-/,""),handleUnixStylePath:re,handleUrlEncode:K,handleUrlPathSafeEncode:W,isConfigKeyInBlackList:oe,isDev:ue,isInputConfigValid:ae,isProd:()=>"production"===process.env.NODE_ENV,isSimpleName:Z,isUrl:j,removePluginVersion:ne,safeParse:ce});exports.AlbumListOrder=void 0,(pe=exports.AlbumListOrder||(exports.AlbumListOrder={})).ASC="asc",pe.DESC="desc",exports.AlbumListSort=void 0,(de=exports.AlbumListSort||(exports.AlbumListSort={})).NEWEST="newest",de.OLDEST="oldest",de.FILE_NAME="fileName",exports.OutputFormat=void 0,(_e=exports.OutputFormat||(exports.OutputFormat={})).PRETTY="pretty",_e.JSON="json",exports.ILogType=void 0,(ge=exports.ILogType||(exports.ILogType={})).success="success",ge.info="info",ge.warn="warn",ge.error="error",ge.debug="debug",exports.IBuildInEvent=void 0,(he=exports.IBuildInEvent||(exports.IBuildInEvent={})).UPLOAD_PROGRESS="uploadProgress",he.FILE_UPLOAD_PROGRESS="fileUploadProgress",he.FAILED="failed",he.BEFORE_TRANSFORM="beforeTransform",he.BEFORE_UPLOAD="beforeUpload",he.AFTER_UPLOAD="afterUpload",he.CLOUD_IMPORT_PROGRESS="cloudImportProgress",he.CLOUD_ALBUM_UPDATED="cloudAlbumUpdated",he.FINISHED="finished",he.INSTALL="install",he.UNINSTALL="uninstall",he.UPDATE="update",he.NOTIFICATION="notification",exports.LifecycleStep=void 0,(fe=exports.LifecycleStep||(exports.LifecycleStep={})).IDLE="idle",fe.BEFORE_TRANSFORM="beforeTransform",fe.TRANSFORM="transform",fe.BEFORE_UPLOAD="beforeUpload",fe.UPLOAD="upload",fe.AFTER_UPLOAD="afterUpload",exports.IBusEvent=void 0,(exports.IBusEvent||(exports.IBusEvent={})).CONFIG_CHANGE="CONFIG_CHANGE";const me="picgo-clipboard-images",Ie="picgo-cloud",Ce="picgoCloudAutoImport",Le=1048576,Oe=(e,t,i,r)=>{if("length"===i||"prototype"===i)return;if("arguments"===i||"caller"===i)return;const n=Object.getOwnPropertyDescriptor(e,i),s=Object.getOwnPropertyDescriptor(t,i);!Ue(n,s)&&r||Object.defineProperty(e,i,s)},Ue=function(e,t){return void 0===e||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},Pe=(e,t)=>`/* Wrapped ${e}*/\n${t}`,De=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Se=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name");function Ne(e,t,{ignoreNonConfigurable:i=!1}={}){const{name:r}=e;for(const r of Reflect.ownKeys(t))Oe(e,t,r,i);return((e,t)=>{const i=Object.getPrototypeOf(t);i!==Object.getPrototypeOf(e)&&Object.setPrototypeOf(e,i)})(e,t),((e,t,i)=>{const r=""===i?"":`with ${i.trim()}() `,n=Pe.bind(null,r,t.toString());Object.defineProperty(n,"name",Se);const{writable:s,enumerable:o,configurable:a}=De;Object.defineProperty(e,"toString",{value:n,writable:s,enumerable:o,configurable:a})})(e,t,r),e}const Te=new WeakMap,Ae=(e,t={})=>{if("function"!=typeof e)throw new TypeError("Expected a function");let i,r=0;const n=e.displayName||e.name||"<anonymous>",s=function(...o){if(Te.set(s,++r),1===r)i=e.apply(this,o),e=void 0;else if(!0===t.throw)throw new Error(`Function \`${n}\` can only be called once`);return i};return Ne(s,e),Te.set(s,r),s};Ae.callCount=e=>{if(!Te.has(e))throw new Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Te.get(e)};const ye=[];ye.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&ye.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&ye.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");const Re=e=>!!e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on,we=Symbol.for("signal-exit emitter"),xe=globalThis,be=Object.defineProperty.bind(Object);class Me{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(xe[we])return xe[we];be(xe,we,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){const i=this.listeners[e],r=i.indexOf(t);-1!==r&&(0===r&&1===i.length?i.length=0:i.splice(r,1))}emit(e,t,i){if(this.emitted[e])return!1;this.emitted[e]=!0;let r=!1;for(const n of this.listeners[e])r=!0===n(t,i)||r;return"exit"===e&&(r=this.emit("afterExit",t,i)||r),r}}class Be{}const ve=globalThis.process,{onExit:Ge}=($e=Re(ve)?new class extends Be{#e="win32"===ve.platform?"SIGINT":"SIGHUP";#t=new Me;#i;#r;#n;#s={};#o=!1;constructor(e){super(),this.#i=e,this.#s={};for(const t of ye)this.#s[t]=()=>{const i=this.#i.listeners(t);let{count:r}=this.#t;const n=e;if("object"==typeof n.__signal_exit_emitter__&&"number"==typeof n.__signal_exit_emitter__.count&&(r+=n.__signal_exit_emitter__.count),i.length===r){this.unload();const i=this.#t.emit("exit",null,t),r="SIGHUP"===t?this.#e:t;i||e.kill(e.pid,r)}};this.#n=e.reallyExit,this.#r=e.emit}onExit(e,t){if(!Re(this.#i))return()=>{};!1===this.#o&&this.load();const i=t?.alwaysLast?"afterExit":"exit";return this.#t.on(i,e),()=>{this.#t.removeListener(i,e),0===this.#t.listeners.exit.length&&0===this.#t.listeners.afterExit.length&&this.unload()}}load(){if(!this.#o){this.#o=!0,this.#t.count+=1;for(const e of ye)try{const t=this.#s[e];t&&this.#i.on(e,t)}catch(e){}this.#i.emit=(e,...t)=>this.#a(e,...t),this.#i.reallyExit=e=>this.#c(e)}}unload(){this.#o&&(this.#o=!1,ye.forEach(e=>{const t=this.#s[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#i.removeListener(e,t)}catch(e){}}),this.#i.emit=this.#r,this.#i.reallyExit=this.#n,this.#t.count-=1)}#c(e){return Re(this.#i)?(this.#i.exitCode=e||0,this.#t.emit("exit",this.#i.exitCode,null),this.#n.call(this.#i,this.#i.exitCode)):0}#a(e,...t){const i=this.#r;if("exit"===e&&Re(this.#i)){"number"==typeof t[0]&&(this.#i.exitCode=t[0]);const r=i.call(this.#i,e,...t);return this.#t.emit("exit",this.#i.exitCode,null),r}return i.call(this.#i,e,...t)}}(ve):new class extends Be{onExit(){return()=>{}}load(){}unload(){}},{onExit:(e,t)=>$e.onExit(e,t),load:()=>$e.load(),unload:()=>$e.unload()});var $e;const Fe=c.stderr.isTTY?c.stderr:c.stdout.isTTY?c.stdout:void 0,ke=Fe?Ae(()=>{Ge(()=>{Fe.write("[?25h")},{alwaysLast:!0})}):()=>{};let He=!1;const Ye={show:(e=c.stderr)=>{e.isTTY&&(He=!1,e.write("[?25h"))},hide:(e=c.stderr)=>{e.isTTY&&(ke(),He=!0,e.write("[?25l"))},toggle:(e,t)=>{void 0!==e&&(He=e),He?Ye.show(t):Ye.hide(t)}};var Ve={dots:{interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]},dots2:{interval:80,frames:["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"]},dots3:{interval:80,frames:["⠋","⠙","⠚","⠞","⠖","⠦","⠴","⠲","⠳","⠓"]},dots4:{interval:80,frames:["⠄","⠆","⠇","⠋","⠙","⠸","⠰","⠠","⠰","⠸","⠙","⠋","⠇","⠆"]},dots5:{interval:80,frames:["⠋","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋"]},dots6:{interval:80,frames:["⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠴","⠲","⠒","⠂","⠂","⠒","⠚","⠙","⠉","⠁"]},dots7:{interval:80,frames:["⠈","⠉","⠋","⠓","⠒","⠐","⠐","⠒","⠖","⠦","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈"]},dots8:{interval:80,frames:["⠁","⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈","⠈"]},dots9:{interval:80,frames:["⢹","⢺","⢼","⣸","⣇","⡧","⡗","⡏"]},dots10:{interval:80,frames:["⢄","⢂","⢁","⡁","⡈","⡐","⡠"]},dots11:{interval:100,frames:["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]},dots12:{interval:80,frames:["⢀⠀","⡀⠀","⠄⠀","⢂⠀","⡂⠀","⠅⠀","⢃⠀","⡃⠀","⠍⠀","⢋⠀","⡋⠀","⠍⠁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⢈⠩","⡀⢙","⠄⡙","⢂⠩","⡂⢘","⠅⡘","⢃⠨","⡃⢐","⠍⡐","⢋⠠","⡋⢀","⠍⡁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⠈⠩","⠀⢙","⠀⡙","⠀⠩","⠀⢘","⠀⡘","⠀⠨","⠀⢐","⠀⡐","⠀⠠","⠀⢀","⠀⡀"]},dots13:{interval:80,frames:["⣼","⣹","⢻","⠿","⡟","⣏","⣧","⣶"]},dots14:{interval:80,frames:["⠉⠉","⠈⠙","⠀⠹","⠀⢸","⠀⣰","⢀⣠","⣀⣀","⣄⡀","⣆⠀","⡇⠀","⠏⠀","⠋⠁"]},dots8Bit:{interval:80,frames:["⠀","⠁","⠂","⠃","⠄","⠅","⠆","⠇","⡀","⡁","⡂","⡃","⡄","⡅","⡆","⡇","⠈","⠉","⠊","⠋","⠌","⠍","⠎","⠏","⡈","⡉","⡊","⡋","⡌","⡍","⡎","⡏","⠐","⠑","⠒","⠓","⠔","⠕","⠖","⠗","⡐","⡑","⡒","⡓","⡔","⡕","⡖","⡗","⠘","⠙","⠚","⠛","⠜","⠝","⠞","⠟","⡘","⡙","⡚","⡛","⡜","⡝","⡞","⡟","⠠","⠡","⠢","⠣","⠤","⠥","⠦","⠧","⡠","⡡","⡢","⡣","⡤","⡥","⡦","⡧","⠨","⠩","⠪","⠫","⠬","⠭","⠮","⠯","⡨","⡩","⡪","⡫","⡬","⡭","⡮","⡯","⠰","⠱","⠲","⠳","⠴","⠵","⠶","⠷","⡰","⡱","⡲","⡳","⡴","⡵","⡶","⡷","⠸","⠹","⠺","⠻","⠼","⠽","⠾","⠿","⡸","⡹","⡺","⡻","⡼","⡽","⡾","⡿","⢀","⢁","⢂","⢃","⢄","⢅","⢆","⢇","⣀","⣁","⣂","⣃","⣄","⣅","⣆","⣇","⢈","⢉","⢊","⢋","⢌","⢍","⢎","⢏","⣈","⣉","⣊","⣋","⣌","⣍","⣎","⣏","⢐","⢑","⢒","⢓","⢔","⢕","⢖","⢗","⣐","⣑","⣒","⣓","⣔","⣕","⣖","⣗","⢘","⢙","⢚","⢛","⢜","⢝","⢞","⢟","⣘","⣙","⣚","⣛","⣜","⣝","⣞","⣟","⢠","⢡","⢢","⢣","⢤","⢥","⢦","⢧","⣠","⣡","⣢","⣣","⣤","⣥","⣦","⣧","⢨","⢩","⢪","⢫","⢬","⢭","⢮","⢯","⣨","⣩","⣪","⣫","⣬","⣭","⣮","⣯","⢰","⢱","⢲","⢳","⢴","⢵","⢶","⢷","⣰","⣱","⣲","⣳","⣴","⣵","⣶","⣷","⢸","⢹","⢺","⢻","⢼","⢽","⢾","⢿","⣸","⣹","⣺","⣻","⣼","⣽","⣾","⣿"]},dotsCircle:{interval:80,frames:["⢎ ","⠎⠁","⠊⠑","⠈⠱"," ⡱","⢀⡰","⢄⡠","⢆⡀"]},sand:{interval:80,frames:["⠁","⠂","⠄","⡀","⡈","⡐","⡠","⣀","⣁","⣂","⣄","⣌","⣔","⣤","⣥","⣦","⣮","⣶","⣷","⣿","⡿","⠿","⢟","⠟","⡛","⠛","⠫","⢋","⠋","⠍","⡉","⠉","⠑","⠡","⢁"]},line:{interval:130,frames:["-","\\","|","/"]},line2:{interval:100,frames:["⠂","-","–","—","–","-"]},rollingLine:{interval:80,frames:["/ "," - "," \\ "," |"," |"," \\ "," - ","/ "]},pipe:{interval:100,frames:["┤","┘","┴","└","├","┌","┬","┐"]},simpleDots:{interval:400,frames:[". ",".. ","..."," "]},simpleDotsScrolling:{interval:200,frames:[". ",".. ","..."," .."," ."," "]},star:{interval:70,frames:["✶","✸","✹","✺","✹","✷"]},star2:{interval:80,frames:["+","x","*"]},flip:{interval:70,frames:["_","_","_","-","`","`","'","´","-","_","_","_"]},hamburger:{interval:100,frames:["☱","☲","☴"]},growVertical:{interval:120,frames:["▁","▃","▄","▅","▆","▇","▆","▅","▄","▃"]},growHorizontal:{interval:120,frames:["▏","▎","▍","▌","▋","▊","▉","▊","▋","▌","▍","▎"]},balloon:{interval:140,frames:[" ",".","o","O","@","*"," "]},balloon2:{interval:120,frames:[".","o","O","°","O","o","."]},noise:{interval:100,frames:["▓","▒","░"]},bounce:{interval:120,frames:["⠁","⠂","⠄","⠂"]},boxBounce:{interval:120,frames:["▖","▘","▝","▗"]},boxBounce2:{interval:100,frames:["▌","▀","▐","▄"]},triangle:{interval:50,frames:["◢","◣","◤","◥"]},binary:{interval:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},arc:{interval:100,frames:["◜","◠","◝","◞","◡","◟"]},circle:{interval:120,frames:["◡","⊙","◠"]},squareCorners:{interval:180,frames:["◰","◳","◲","◱"]},circleQuarters:{interval:120,frames:["◴","◷","◶","◵"]},circleHalves:{interval:50,frames:["◐","◓","◑","◒"]},squish:{interval:100,frames:["╫","╪"]},toggle:{interval:250,frames:["⊶","⊷"]},toggle2:{interval:80,frames:["▫","▪"]},toggle3:{interval:120,frames:["□","■"]},toggle4:{interval:100,frames:["■","□","▪","▫"]},toggle5:{interval:100,frames:["▮","▯"]},toggle6:{interval:300,frames:["ဝ","၀"]},toggle7:{interval:80,frames:["⦾","⦿"]},toggle8:{interval:100,frames:["◍","◌"]},toggle9:{interval:100,frames:["◉","◎"]},toggle10:{interval:100,frames:["㊂","㊀","㊁"]},toggle11:{interval:50,frames:["⧇","⧆"]},toggle12:{interval:120,frames:["☗","☖"]},toggle13:{interval:80,frames:["=","*","-"]},arrow:{interval:100,frames:["←","↖","↑","↗","→","↘","↓","↙"]},arrow2:{interval:80,frames:["⬆️ ","↗️ ","➡️ ","↘️ ","⬇️ ","↙️ ","⬅️ ","↖️ "]},arrow3:{interval:120,frames:["▹▹▹▹▹","▸▹▹▹▹","▹▸▹▹▹","▹▹▸▹▹","▹▹▹▸▹","▹▹▹▹▸"]},bouncingBar:{interval:80,frames:["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},bouncingBall:{interval:80,frames:["( ● )","( ● )","( ● )","( ● )","( ●)","( ● )","( ● )","( ● )","( ● )","(● )"]},smiley:{interval:200,frames:["😄 ","😝 "]},monkey:{interval:300,frames:["🙈 ","🙈 ","🙉 ","🙊 "]},hearts:{interval:100,frames:["💛 ","💙 ","💜 ","💚 ","💗 "]},clock:{interval:100,frames:["🕛 ","🕐 ","🕑 ","🕒 ","🕓 ","🕔 ","🕕 ","🕖 ","🕗 ","🕘 ","🕙 ","🕚 "]},earth:{interval:180,frames:["🌍 ","🌎 ","🌏 "]},material:{interval:17,frames:["█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███████▁▁▁▁▁▁▁▁▁▁▁▁▁","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","██████████▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","█████████████▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁██████████████▁▁▁▁","▁▁▁██████████████▁▁▁","▁▁▁▁█████████████▁▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁▁▁████████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","██████▁▁▁▁▁▁▁▁▁▁▁▁▁█","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁▁█████████████▁▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁▁███████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁▁█████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁"]},moon:{interval:80,frames:["🌑 ","🌒 ","🌓 ","🌔 ","🌕 ","🌖 ","🌗 ","🌘 "]},runner:{interval:140,frames:["🚶 ","🏃 "]},pong:{interval:80,frames:["▐⠂ ▌","▐⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂▌","▐ ⠠▌","▐ ⡀▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐⠠ ▌"]},shark:{interval:120,frames:["▐|\\____________▌","▐_|\\___________▌","▐__|\\__________▌","▐___|\\_________▌","▐____|\\________▌","▐_____|\\_______▌","▐______|\\______▌","▐_______|\\_____▌","▐________|\\____▌","▐_________|\\___▌","▐__________|\\__▌","▐___________|\\_▌","▐____________|\\▌","▐____________/|▌","▐___________/|_▌","▐__________/|__▌","▐_________/|___▌","▐________/|____▌","▐_______/|_____▌","▐______/|______▌","▐_____/|_______▌","▐____/|________▌","▐___/|_________▌","▐__/|__________▌","▐_/|___________▌","▐/|____________▌"]},dqpb:{interval:100,frames:["d","q","p","b"]},weather:{interval:100,frames:["☀️ ","☀️ ","☀️ ","🌤 ","⛅️ ","🌥 ","☁️ ","🌧 ","🌨 ","🌧 ","🌨 ","🌧 ","🌨 ","⛈ ","🌨 ","🌧 ","🌨 ","☁️ ","🌥 ","⛅️ ","🌤 ","☀️ ","☀️ "]},christmas:{interval:400,frames:["🌲","🎄"]},grenade:{interval:80,frames:["، ","′ "," ´ "," ‾ "," ⸌"," ⸊"," |"," ⁎"," ⁕"," ෴ "," ⁓"," "," "," "]},point:{interval:125,frames:["∙∙∙","●∙∙","∙●∙","∙∙●","∙∙∙"]},layer:{interval:150,frames:["-","=","≡"]},betaWave:{interval:80,frames:["ρββββββ","βρβββββ","ββρββββ","βββρβββ","ββββρββ","βββββρβ","ββββββρ"]},fingerDance:{interval:160,frames:["🤘 ","🤟 ","🖖 ","✋ ","🤚 ","👆 "]},fistBump:{interval:80,frames:["🤜 🤛 ","🤜 🤛 ","🤜 🤛 "," 🤜 🤛 "," 🤜🤛 "," 🤜✨🤛 ","🤜 ✨ 🤛 "]},soccerHeader:{interval:80,frames:[" 🧑⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 ","🧑 ⚽️ 🧑 "]},mindblown:{interval:160,frames:["😐 ","😐 ","😮 ","😮 ","😦 ","😦 ","😧 ","😧 ","🤯 ","💥 ","✨ "," "," "," "]},speaker:{interval:160,frames:["🔈 ","🔉 ","🔊 ","🔉 "]},orangePulse:{interval:100,frames:["🔸 ","🔶 ","🟠 ","🟠 ","🔶 "]},bluePulse:{interval:100,frames:["🔹 ","🔷 ","🔵 ","🔵 ","🔷 "]},orangeBluePulse:{interval:100,frames:["🔸 ","🔶 ","🟠 ","🟠 ","🔶 ","🔹 ","🔷 ","🔵 ","🔵 ","🔷 "]},timeTravel:{interval:100,frames:["🕛 ","🕚 ","🕙 ","🕘 ","🕗 ","🕖 ","🕕 ","🕔 ","🕓 ","🕒 ","🕑 ","🕐 "]},aesthetic:{interval:80,frames:["▰▱▱▱▱▱▱","▰▰▱▱▱▱▱","▰▰▰▱▱▱▱","▰▰▰▰▱▱▱","▰▰▰▰▰▱▱","▰▰▰▰▰▰▱","▰▰▰▰▰▰▰","▰▱▱▱▱▱▱"]},dwarfFortress:{interval:80,frames:[" ██████£££ ","☺██████£££ ","☺██████£££ ","☺▓█████£££ ","☺▓█████£££ ","☺▒█████£££ ","☺▒█████£££ ","☺░█████£££ ","☺░█████£££ ","☺ █████£££ "," ☺█████£££ "," ☺█████£££ "," ☺▓████£££ "," ☺▓████£££ "," ☺▒████£££ "," ☺▒████£££ "," ☺░████£££ "," ☺░████£££ "," ☺ ████£££ "," ☺████£££ "," ☺████£££ "," ☺▓███£££ "," ☺▓███£££ "," ☺▒███£££ "," ☺▒███£££ "," ☺░███£££ "," ☺░███£££ "," ☺ ███£££ "," ☺███£££ "," ☺███£££ "," ☺▓██£££ "," ☺▓██£££ "," ☺▒██£££ "," ☺▒██£££ "," ☺░██£££ "," ☺░██£££ "," ☺ ██£££ "," ☺██£££ "," ☺██£££ "," ☺▓█£££ "," ☺▓█£££ "," ☺▒█£££ "," ☺▒█£££ "," ☺░█£££ "," ☺░█£££ "," ☺ █£££ "," ☺█£££ "," ☺█£££ "," ☺▓£££ "," ☺▓£££ "," ☺▒£££ "," ☺▒£££ "," ☺░£££ "," ☺░£££ "," ☺ £££ "," ☺£££ "," ☺£££ "," ☺▓££ "," ☺▓££ "," ☺▒££ "," ☺▒££ "," ☺░££ "," ☺░££ "," ☺ ££ "," ☺££ "," ☺££ "," ☺▓£ "," ☺▓£ "," ☺▒£ "," ☺▒£ "," ☺░£ "," ☺░£ "," ☺ £ "," ☺£ "," ☺£ "," ☺▓ "," ☺▓ "," ☺▒ "," ☺▒ "," ☺░ "," ☺░ "," ☺ "," ☺ &"," ☺ ☼&"," ☺ ☼ &"," ☺☼ &"," ☺☼ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & ","‼ & "," & "," & "," & ░ "," & ▒ "," & ▓ "," & £ "," & ░£ "," & ▒£ "," & ▓£ "," & ££ "," & ░££ "," & ▒££ ","& ▓££ ","& £££ "," ░£££ "," ▒£££ "," ▓£££ "," █£££ "," ░█£££ "," ▒█£££ "," ▓█£££ "," ██£££ "," ░██£££ "," ▒██£££ "," ▓██£££ "," ███£££ "," ░███£££ "," ▒███£££ "," ▓███£££ "," ████£££ "," ░████£££ "," ▒████£££ "," ▓████£££ "," █████£££ "," ░█████£££ "," ▒█████£££ "," ▓█████£££ "," ██████£££ "," ██████£££ "]},fish:{interval:80,frames:["~~~~~~~~~~~~~~~~~~~~","> ~~~~~~~~~~~~~~~~~~","º> ~~~~~~~~~~~~~~~~~","(º> ~~~~~~~~~~~~~~~~","((º> ~~~~~~~~~~~~~~~","<((º> ~~~~~~~~~~~~~~","><((º> ~~~~~~~~~~~~~"," ><((º> ~~~~~~~~~~~~","~ ><((º> ~~~~~~~~~~~","~~ <>((º> ~~~~~~~~~~","~~~ ><((º> ~~~~~~~~~","~~~~ <>((º> ~~~~~~~~","~~~~~ ><((º> ~~~~~~~","~~~~~~ <>((º> ~~~~~~","~~~~~~~ ><((º> ~~~~~","~~~~~~~~ <>((º> ~~~~","~~~~~~~~~ ><((º> ~~~","~~~~~~~~~~ <>((º> ~~","~~~~~~~~~~~ ><((º> ~","~~~~~~~~~~~~ <>((º> ","~~~~~~~~~~~~~ ><((º>","~~~~~~~~~~~~~~ <>((º","~~~~~~~~~~~~~~~ ><((","~~~~~~~~~~~~~~~~ <>(","~~~~~~~~~~~~~~~~~ ><","~~~~~~~~~~~~~~~~~~ <","~~~~~~~~~~~~~~~~~~~~"]}};const qe=function({onlyFirst:e=!1}={}){return new RegExp("(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]",e?void 0:"g")}();const je=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Ke=[12288,12288,65281,65376,65504,65510],We=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141],Qe=(e,t)=>{let i=0,r=Math.floor(e.length/2)-1;for(;i<=r;){const n=Math.floor((i+r)/2),s=2*n;if(t<e[s])r=n-1;else{if(!(t>e[s+1]))return!0;i=n+1}}return!1},ze=je[0],Je=je.at(-1),Xe=Ke[0],Ze=Ke.at(-1),et=We[0],tt=We.at(-1),[it,rt]=function(e){let t=e[0],i=e[1];for(let r=0;r<e.length;r+=2){const n=e[r],s=e[r+1];if(19968>=n&&19968<=s)return[n,s];s-n>i-t&&(t=n,i=s)}return[t,i]}(We);function nt(e,{ambiguousAsWide:t=!1}={}){return function(e){if(!Number.isSafeInteger(e))throw new TypeError(`Expected a code point, got \`${typeof e}\`.`)}(e),(e=>!(e<Xe||e>Ze)&&Qe(Ke,e))(e)||(e=>e>=it&&e<=rt||!(e<et||e>tt)&&Qe(We,e))(e)||t&&(e=>!(e<ze||e>Je)&&Qe(je,e))(e)?2:1}const st=new Intl.Segmenter,ot=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})+$/v,at=/^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v,ct=/^\p{RGI_Emoji}$/v,lt=/^[\d#*]\u20E3$/,ut=/\p{Extended_Pictographic}/gu;function pt(e){if(e.length>50)return!1;if(lt.test(e))return!0;if(e.includes("")){const t=e.match(ut);return null!==t&&t.length>=2}return!1}function dt(e){return e.replace(at,"")}function _t(e){return ot.test(e)}function gt(e,t){let i=0;if(e.length>1)for(const r of e.slice(1))r>=""&&r<=""&&(i+=nt(r.codePointAt(0),t));return i}function ht(e,t={}){if("string"!=typeof e||0===e.length)return 0;const{ambiguousIsNarrow:i=!0,countAnsiEscapeCodes:r=!1}=t;let n=e;if(r||!n.includes("")&&!n.includes("")||(n=function(e){if("string"!=typeof e)throw new TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(qe,"")}(n)),0===n.length)return 0;if(/^[\u0020-\u007E]*$/.test(n))return n.length;let s=0;const o={ambiguousAsWide:!i};for(const{segment:e}of st.segment(n)){if(_t(e))continue;if(ct.test(e)||pt(e)){s+=2;continue}s+=nt(dt(e).codePointAt(0),o),s+=gt(e,o)}return s}const ft=new class{#l=0;#u;#p=!1;#d=!1;#_=e=>{if(!e?.length)return;3===("string"==typeof e?e.codePointAt(0):e[0])&&(c.listenerCount("SIGINT")>0?c.emit("SIGINT"):c.kill(c.pid,"SIGINT"))};start(){this.#l++,1===this.#l&&this.#g()}stop(){0!==this.#l&&0===--this.#l&&this.#h()}#g(){const{stdin:e}=c;"win32"!==c.platform&&e?.isTTY&&"function"==typeof e.setRawMode?(this.#u=e,this.#p=e.isPaused(),this.#d=Boolean(e.isRaw),e.setRawMode(!0),e.prependListener("data",this.#_),this.#p&&e.resume()):this.#u=void 0}#h(){if(!this.#u)return;const e=this.#u;e.off("data",this.#_),e.isTTY&&e.setRawMode?.(this.#d),this.#p&&e.pause(),this.#u=void 0,this.#p=!1,this.#d=!1}};var Et=Object.freeze(ft);const mt=new Map;class It{#f=0;#E=-1;#m=0;#I;#C;#L;#O;#U=new Map;#P=!1;#D;#S;#N=!1;color;#T(e){this.#P=!0;try{return e()}finally{this.#P=!1}}#A(){this.isSpinning&&this.render()}#y(e,t){if(null==e)return"";if("string"==typeof e)return e;if(Buffer.isBuffer(e)||ArrayBuffer.isView(e)){const i="string"==typeof t&&t&&"buffer"!==t?t:"utf8";return Buffer.from(e).toString(i)}return String(e)}#R(e){if(!e)return!1;const t=e.at(-1);return"\n"===t||"\r"===t}#w(){this.#S||(this.#S=setTimeout(()=>{this.#S=void 0,this.isSpinning&&this.#A()},200),"function"==typeof this.#S?.unref&&this.#S.unref())}#x(){this.#S&&(clearTimeout(this.#S),this.#S=void 0)}#b(e,t,i,r){return this.#M(i," ")+e+("string"==typeof t?(e?" ":"")+t:"")+this.#B(r," ")}constructor(e){"string"==typeof e&&(e={text:e}),this.#I={color:"cyan",stream:c.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#I.color,this.#L=this.#I.stream,"boolean"!=typeof this.#I.isEnabled&&(this.#I.isEnabled=function({stream:e=process.stdout}={}){return Boolean(e&&e.isTTY&&"dumb"!==process.env.TERM&&!("CI"in process.env))}({stream:this.#L})),"boolean"!=typeof this.#I.isSilent&&(this.#I.isSilent=!1);const t=this.#I.interval;this.spinner=this.#I.spinner,this.#I.interval=t,this.text=this.#I.text,this.prefixText=this.#I.prefixText,this.suffixText=this.#I.suffixText,this.indent=this.#I.indent,"test"===c.env.NODE_ENV&&(this._stream=this.#L,this._isEnabled=this.#I.isEnabled,Object.defineProperty(this,"_linesToClear",{get(){return this.#f},set(e){this.#f=e}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#E}}),Object.defineProperty(this,"_lineCount",{get(){const e=this.#L.columns??80,t="function"==typeof this.#I.prefixText?"":this.#I.prefixText,i="function"==typeof this.#I.suffixText?"":this.#I.suffixText,r="string"==typeof t&&""!==t?t+" ":"",n="string"==typeof i&&""!==i?" "+i:"",s=" ".repeat(this.#I.indent)+r+"-"+("string"==typeof this.#I.text?" "+this.#I.text:"")+n;return this.#v(s,e)}}))}get indent(){return this.#I.indent}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw new Error("The `indent` option must be an integer from 0 and up");this.#I.indent=e}get interval(){return this.#I.interval??this.#C.interval??100}get spinner(){return this.#C}set spinner(e){if(this.#E=-1,this.#I.interval=void 0,"object"==typeof e){if(!Array.isArray(e.frames)||0===e.frames.length||e.frames.some(e=>"string"!=typeof e))throw new Error("The given spinner must have a non-empty `frames` array of strings");if(void 0!==e.interval&&!(Number.isInteger(e.interval)&&e.interval>0))throw new Error("`spinner.interval` must be a positive integer if provided");this.#C=e}else if(function(){const{env:e}=c,{TERM:t,TERM_PROGRAM:i}=e;return"win32"!==c.platform?"linux"!==t:Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||"{cmd::Cmder}"===e.ConEmuTask||"Terminus-Sublime"===i||"vscode"===i||"xterm-256color"===t||"alacritty"===t||"rxvt-unicode"===t||"rxvt-unicode-256color"===t||"JetBrains-JediTerm"===e.TERMINAL_EMULATOR}())if(void 0===e)this.#C=Ve.dots;else{if("default"===e||!Ve[e])throw new Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`);this.#C=Ve[e]}else this.#C=Ve.line}get text(){return this.#I.text}set text(e=""){this.#I.text=e}get prefixText(){return this.#I.prefixText}set prefixText(e=""){this.#I.prefixText=e}get suffixText(){return this.#I.suffixText}set suffixText(e=""){this.#I.suffixText=e}get isSpinning(){return void 0!==this.#O}#G(e,t,i=!1){const r="function"==typeof e?e():e;return"string"==typeof r&&""!==r?i?t+r:r+t:""}#M(e=this.#I.prefixText,t=" "){return this.#G(e,t,!1)}#B(e=this.#I.suffixText,t=" "){return this.#G(e,t,!0)}#v(e,t){let i=0;for(const r of l.stripVTControlCharacters(e).split("\n"))i+=Math.max(1,Math.ceil(ht(r)/t));return i}get isEnabled(){return this.#I.isEnabled&&!this.#I.isSilent}set isEnabled(e){if("boolean"!=typeof e)throw new TypeError("The `isEnabled` option must be a boolean");this.#I.isEnabled=e}get isSilent(){return this.#I.isSilent}set isSilent(e){if("boolean"!=typeof e)throw new TypeError("The `isSilent` option must be a boolean");this.#I.isSilent=e}frame(){const e=Date.now();(-1===this.#E||e-this.#m>=this.interval)&&(this.#E=(this.#E+1)%this.#C.frames.length,this.#m=e);const{frames:t}=this.#C;let i=t[this.#E];this.color&&(i=u[this.color](i));return this.#M(this.#I.prefixText," ")+i+("string"==typeof this.text?" "+this.text:"")+this.#B(this.#I.suffixText," ")}clear(){return this.isEnabled&&this.#L.isTTY?(this.#T(()=>{this.#L.cursorTo(0);for(let e=0;e<this.#f;e++)e>0&&this.#L.moveCursor(0,-1),this.#L.clearLine(1);this.#I.indent&&this.#L.cursorTo(this.#I.indent)}),this.#f=0,this):this}#$(e){if(!e||this.#U.has(e)||!e.isTTY||"function"!=typeof e.write)return;mt.has(e)&&console.warn("[ora] Multiple concurrent spinners detected. This may cause visual corruption. Use one spinner at a time.");const t=e.write;this.#U.set(e,t),mt.set(e,this),e.write=(i,r,n)=>this.#F(e,t,i,r,n)}#k(){if(!this.isEnabled||this.#U.size>0)return;const e=new Set([this.#L,c.stdout,c.stderr]);for(const t of e)this.#$(t)}#H(){for(const[e,t]of this.#U)e.write=t,mt.get(e)===this&&mt.delete(e);this.#U.clear()}#F(e,t,i,r,n){if("function"==typeof r&&(n=r,r=void 0),this.#P)return t.call(e,i,r,n);this.clear();const s=this.#y(i,r),o=this.#R(s),a=t.call(e,i,r,n);return o?this.#x():s.length>0&&this.#w(),this.isSpinning&&!this.#S&&this.render(),a}render(){if(!this.isEnabled||this.#D||this.#S)return this;const e=this.#L.isTTY;let t=!1;try{e&&(this.#T(()=>this.#L.write("[?2026h")),t=!0),this.clear();let i=this.frame();const r=this.#L.columns??80,n=this.#v(i,r),s=this.#L.rows;if(s&&s>1&&n>s){const e=i.split("\n"),t=s-1;i=[...e.slice(0,t),"... (content truncated to fit terminal)"].join("\n")}!1===this.#T(()=>this.#L.write(i))&&this.#L.isTTY&&(this.#D=()=>{this.#D=void 0,this.#A()},this.#L.once("drain",this.#D)),this.#f=this.#v(i,r)}finally{t&&this.#T(()=>this.#L.write("[?2026l"))}return this}start(e){if(e&&(this.text=e),this.isSilent)return this;if(!this.isEnabled){const e=this.text?"-":"",t=" ".repeat(this.#I.indent)+this.#b(e,this.text,this.#I.prefixText,this.#I.suffixText);return""!==t.trim()&&this.#T(()=>this.#L.write(t+"\n")),this}return this.isSpinning||(this.#I.hideCursor&&Ye.hide(this.#L),this.#I.discardStdin&&c.stdin.isTTY&&(Et.start(),this.#N=!0),this.#k(),this.render(),this.#O=setInterval(this.render.bind(this),this.interval)),this}stop(){return clearInterval(this.#O),this.#O=void 0,this.#E=-1,this.#m=0,this.#x(),this.#H(),this.#D&&(this.#L.removeListener("drain",this.#D),this.#D=void 0),this.isEnabled&&(this.clear(),this.#I.hideCursor&&Ye.show(this.#L)),this.#N&&(this.#N=!1,Et.stop()),this}succeed(e){return this.stopAndPersist({symbol:"✅",text:e})}fail(e){return this.stopAndPersist({symbol:"❌️",text:e})}warn(e){return this.stopAndPersist({symbol:"⚠️",text:e})}info(e){return this.stopAndPersist({symbol:"ℹ️",text:e})}stopAndPersist(e={}){if(this.isSilent)return this;const t=e.symbol??" ",i=e.text??this.text,r=e.prefixText??this.#I.prefixText,n=e.suffixText??this.#I.suffixText,s=this.#b(t,i,r,n)+"\n";return this.stop(),this.#T(()=>this.#L.write(s)),this}}function Ct(e){return new It(e)}const Lt=e=>{const t=Ct({text:""}),i=e.verbose||!process.stdout.isTTY,r=r=>{if(i)return t.isSpinning&&t.stop(),void console.log(e.formatVerboseText(r));const n=((e,t)=>{const i=t>0?Math.min(Math.max(e/t,0),1):0,r=Math.round(20*i),n=20-r;return"█".repeat(r)+"░".repeat(n)})(r.current,r.total);t.text=`${n} ${e.formatBarText(r)}`,t.isSpinning||t.start()};return e.ctx.on(e.event,r),{spinner:t,dispose:()=>{e.ctx.off(e.event,r),t.isSpinning&&t.stop()}}},Ot=e=>(e/Le).toFixed(1),Ut=(e,t)=>{const i=t.resumed?e.i18n.translate("PICGO_CLOUD_UPLOAD_RESUMED_SUFFIX"):"";return{fileName:t.fileName,loadedMB:Ot(t.current),totalMB:Ot(t.total),partsCompleted:String(t.partsCompleted),totalParts:String(t.totalParts),resumedSuffix:i}},Pt={handle:i=>{i.cmd.program.command("upload").description("upload, go go go").arguments("[input...]").alias("u").option("--format <format>","output format: pretty | json","pretty").option("--verbose","Force per-event progress lines (one console.log per progress tick) instead of an in-place spinner. Non-TTY stdout (pipes, CI) automatically falls back to this mode regardless of the flag — --verbose is for the niche case of wanting line-by-line history on an interactive TTY (debugging multipart retries, AI agents tailing output, etc.).",!1).action(async(r,n)=>{const s=r.map(e=>j(e)?e:t.resolve(e)).filter(t=>{const r=e.existsSync(t)||j(t);return r||i.log.warn(`${t} does not exist.`),r}),o=Lt({ctx:i,event:exports.IBuildInEvent.FILE_UPLOAD_PROGRESS,verbose:!0===n.verbose,formatBarText:e=>i.i18n.translate("PICGO_CLOUD_UPLOAD_PROGRESS_BAR",Ut(i,e)),formatVerboseText:e=>i.i18n.translate("PICGO_CLOUD_UPLOAD_VERBOSE",Ut(i,e))});try{await i.upload(s,{outputFormat:"json"===n.format?exports.OutputFormat.JSON:exports.OutputFormat.PRETTY})}catch(e){if(i.log.error(e instanceof Error?e:new Error(String(e))),process.argv.includes("--debug"))throw e}finally{o.dispose()}})}},Dt=e=>async t=>{try{await e.cloud.login(t)}catch(t){e.log.error(t)}},St=e=>async()=>{try{e.cloud.logout()}catch(t){e.log.error(t)}};var Nt,Tt,At,yt,Rt,wt,xt;exports.SyncStatus=void 0,(Nt=exports.SyncStatus||(exports.SyncStatus={})).SUCCESS="success",Nt.CONFLICT="conflict",Nt.FAILED="failed",exports.ConflictType=void 0,(Tt=exports.ConflictType||(exports.ConflictType={})).CLEAN="clean",Tt.CONFLICT="conflict",Tt.ADDED="added",Tt.DELETED="deleted",Tt.MODIFIED="modified",exports.E2EVersion=void 0,(At=exports.E2EVersion||(exports.E2EVersion={}))[At.NONE=0]="NONE",At[At.V1=1]="V1",exports.EncryptionMethod=void 0,(yt=exports.EncryptionMethod||(exports.EncryptionMethod={})).AUTO="auto",yt.SSE="sse",yt.E2EE="e2ee",exports.E2EAskPinReason=void 0,(Rt=exports.E2EAskPinReason||(exports.E2EAskPinReason={})).SETUP="setup",Rt.DECRYPT="decrypt",Rt.RETRY="retry",function(e){e.GUI="gui",e.CLI="cli"}(wt||(wt={})),function(e){e.AccountFrozen="ACCOUNT_FROZEN",e.ConfigConflict="CONFIG_CONFLICT",e.ConfigNotFound="CONFIG_NOT_FOUND",e.DuplicateId="DUPLICATE_ID",e.GraceRestricted="GRACE_RESTRICTED",e.ImportDisabled="IMPORT_DISABLED",e.PlanIneligible="PLAN_INELIGIBLE",e.PlanRequired="PLAN_REQUIRED",e.QuotaExceeded="QUOTA_EXCEEDED"}(xt||(xt={}));const bt=process.env.PICGO_API_URL||"https://api.picgo.app",Mt=process.env.PICGO_CLOUD_URL||"https://cloud.picgo.app",Bt=e=>"object"==typeof e&&null!==e,vt=(e,t)=>"number"==typeof e&&Number.isFinite(e)&&e>=0?Math.floor(e):t,Gt=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e||e instanceof Date){const t=new Date(e).getTime();return Number.isNaN(t)?void 0:t}},$t=e=>(e?.plan??0)>0,Ft=e=>{let t="";for(const i of e)t+=String.fromCharCode(i);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")},kt=e=>Bt(e),Ht=e=>{const t=e,i=t?.response?.data;return kt(i)?i:void 0},Yt=e=>{const t=e,i=t?.response?.status??t?.status;return"number"==typeof i?i:void 0},Vt=e=>{const t=e,i=t?.apiCode??Ht(e)?.code??t?.code;return"string"==typeof i?i:void 0},qt=(e,t="Request failed")=>{const i=Ht(e)?.message??(e instanceof Error?e.message:void 0)??(Bt(e)&&"string"==typeof e.message?e.message:void 0);return"string"==typeof i&&""!==i.trim()?i:t},jt=(e,t)=>{const i=new Error(e,void 0===t?void 0:{cause:t});return i.status=Yt(t),i.apiCode=Vt(t),i};class Kt{ctx;baseURL;constructor(e,t=bt){this.ctx=e,this.baseURL=t}resolveUrl(e){return new URL(e,this.baseURL).toString()}async request(e,t){const i=t??this.ctx.getConfig("settings.picgoCloud.token"),r={...e.headers||{}};i&&(r.Authorization=`Bearer ${i}`,process.env.ENABLE_PICGO_CLOUD_DEV_MODE&&(r["CF-Access-Client-Id"]=process.env.CF_ACCESS_CLIENT_ID||"",r["CF-Access-Client-Secret"]=process.env.CF_ACCESS_CLIENT_SECRET||""));try{return await this.ctx.request({...e,url:this.resolveUrl(e.url||""),headers:r})}catch(e){if((e=>"object"==typeof e&&null!==e&&("statusCode"in e||"response"in e||"message"in e))(e))throw(e=>{const t=e.response?.body,i=kt(t)&&"string"==typeof t.message?t.message:e.message||"Request failed",r=new Error(i),n=e.response?.status??e.statusCode??0;return r.name="AxiosError",r.isAxiosError=!0,r.status=n,kt(t)&&"string"==typeof t.code?r.code=t.code:"string"==typeof e.code&&(r.code=e.code),r.response={status:n,data:t},r})(e);throw e}}}class Wt{client;ctx;appType=wt.CLI;constructor(e){this.client=new Kt(e),this.ctx=e}async fetchConfig(){this.appType=this.ctx.GUI_VERSION?wt.GUI:wt.CLI;const e=Date.now();try{const t=await this.client.request({method:"GET",url:"/api/config",params:{appType:this.appType}});return t?.config&&""!==t.config.trim()?(this.ctx.log.debug(`[ConfigService] Config fetched successfully in ${Date.now()-e} ms, version: ${t.version}`),t):null}catch(t){if(this.ctx.log.debug(`[ConfigService] Failed to fetch config in ${Date.now()-e} ms`),_.isAxiosError(t)){const e=Yt(t),i=Vt(t);if(404===e||i===xt.ConfigNotFound)return null;const r=qt(t);throw this.ctx.log.warn("[ConfigService] Failed to fetch config:",r),jt(r,t)}throw t}}async updateConfig(e,t,i){this.appType=this.ctx.GUI_VERSION?wt.GUI:wt.CLI;const r=Date.now();try{const n=await this.client.request({method:"PUT",url:"/api/config",data:{appType:this.appType,config:e,baseVersion:t,historyLimit:10,...i??{}}});return this.ctx.log.debug(`[ConfigService] Config updated successfully in ${Date.now()-r} ms, new version: ${n.version}`),{success:!0,version:n.version}}catch(e){if(this.ctx.log.debug(`[ConfigService] Failed to update config in ${Date.now()-r} ms`),_.isAxiosError(e)){const i=e.response?.data;if(Vt(e)===xt.ConfigConflict)return{success:!1,conflict:!0,version:"number"==typeof i?.currentVersion?i.currentVersion:t};const r=qt(e);throw this.ctx.log.warn("[ConfigService] Failed to update config:",r),jt(r,e)}throw e}}}const Qt=(e,t)=>!(!e||"object"!=typeof e)&&Object.prototype.hasOwnProperty.call(e,t),zt=e=>{const t=Object.getPrototypeOf(e),i=Object.create(t);for(const t of Object.getOwnPropertySymbols(e)){const r=Object.getOwnPropertyDescriptor(e,t);r&&Object.defineProperty(i,t,r)}return i},Jt=(e,t)=>{const i=zt(e),r=[],n=new Set;for(const t of Object.keys(e))n.has(t)||(r.push(t),n.add(t));for(const e of Object.keys(t))n.has(e)||(r.push(e),n.add(e));for(const n of r){if(!Qt(t,n)){delete i[n];continue}const r=Qt(e,n)?e[n]:void 0,s=t[n];p.isPlainObject(r)&&p.isPlainObject(s)?i[n]=Jt(r,s):i[n]=s}return i},Xt=(e,t)=>p.isEqual(e,t)?exports.ConflictType.CLEAN:void 0===e&&void 0!==t?exports.ConflictType.ADDED:void 0!==e&&void 0===t?exports.ConflictType.DELETED:exports.ConflictType.MODIFIED;class Zt{static merge3Way(e,t,i,r="root"){if(p.isEqual(t,i)){const n=Xt(e,t);return{value:t,conflict:!1,diffNode:n===exports.ConflictType.CLEAN?void 0:{key:r,status:n,snapshotValue:e,localValue:t,remoteValue:i}}}const n=p.isPlainObject(t),s=p.isPlainObject(i),o=p.isPlainObject(e);if(p.isEqual(e,t)){if(n&&s){const n=Jt(t,i),s=Xt(e,n);return{value:n,conflict:!1,diffNode:s===exports.ConflictType.CLEAN?void 0:{key:r,status:s,snapshotValue:e,localValue:t,remoteValue:i}}}const o=Xt(e,i);return{value:i,conflict:!1,diffNode:o===exports.ConflictType.CLEAN?void 0:{key:r,status:o,snapshotValue:e,localValue:t,remoteValue:i}}}if(p.isEqual(e,i)){const n=Xt(e,t);return{value:t,conflict:!1,diffNode:n===exports.ConflictType.CLEAN?void 0:{key:r,status:n,snapshotValue:e,localValue:t,remoteValue:i}}}if(n&&s&&(o||null==e)){const n=o?e:{},s=t,a=i,c=[],l=new Set;for(const e of Object.keys(s))l.has(e)||(c.push(e),l.add(e));for(const e of Object.keys(a))l.has(e)||(c.push(e),l.add(e));for(const e of Object.keys(n))l.has(e)||(c.push(e),l.add(e));const u=zt(s),p=[];let d=!1;for(const e of c){const t=Qt(n,e)?n[e]:void 0,i=Qt(s,e)?s[e]:void 0,r=Qt(a,e)?a[e]:void 0,o=Zt.merge3Way(t,i,r,e);o.conflict&&(d=!0),void 0===o.value?delete u[e]:u[e]=o.value,o.diffNode&&o.diffNode.status!==exports.ConflictType.CLEAN&&p.push(o.diffNode)}const _=d?exports.ConflictType.CONFLICT:Xt(e,u);return{value:u,conflict:d,diffNode:_===exports.ConflictType.CLEAN?void 0:{key:r,status:_,snapshotValue:e,localValue:t,remoteValue:i,children:p.length?p:void 0}}}return{value:t,conflict:!0,diffNode:{key:r,status:exports.ConflictType.CONFLICT,snapshotValue:e,localValue:t,remoteValue:i}}}}class ei extends Error{constructor(e){super(e),this.name=new.target.name}}class ti extends ei{constructor(e="Encrypted config payload is corrupted"){super(e)}}class ii extends ei{constructor(e="Unsupported E2E version"){super(e)}}class ri extends ei{constructor(e="PIN handler is required for E2E operations"){super(e)}}class ni extends ei{constructor(e="Encryption switch confirmation handler is required"){super(e)}}class si extends ei{constructor(e="Invalid PIN input"){super(e)}}class oi extends ei{constructor(e="Maximum retry attempts exceeded"){super(e)}}class ai extends ei{constructor(e="Failed to decrypt payload"){super(e)}}class ci extends ei{value;constructor(e){super("Invalid encryption method"),this.value=e}}const li=12,ui="aes-256-gcm";class pi{generateE2EPayload(e,t){const i=h.randomBytes(16),r=h.randomBytes(32),n=this.wrapDEK(r,t,i),s=this.encryptConfig(e,r);return{payload:{e2eVersion:exports.E2EVersion.V1,clientKekSalt:i.toString("base64"),clientDekEncrypted:n,config:s},dek:r}}encryptConfig(e,t){return this.encryptWithKey(Buffer.from(e,"utf8"),t)}decryptConfig(e,t){return this.decryptWithKey(e,t).toString("utf8")}wrapDEK(e,t,i){const r=this.deriveKEK(t,i);return this.encryptWithKey(e,r)}unwrapDEK(e,t,i){const r=this.deriveKEK(t,i);return this.decryptWithKey(e,r)}decodeSalt(e){const t=Buffer.from(e,"base64");if(16!==t.length)throw new ti("Invalid salt length");return t}deriveKEK(e,t){return h.pbkdf2Sync(e,t,6e5,32,"sha256")}encryptWithKey(e,t){const i=h.randomBytes(li),r=h.createCipheriv(ui,t,i),n=Buffer.concat([r.update(e),r.final()]),s=r.getAuthTag();return Buffer.concat([i,s,n]).toString("base64")}decryptWithKey(e,t){const i=Buffer.from(e,"base64");if(i.length<28)throw new ti("Encrypted payload is too short");const r=i.subarray(0,li),n=i.subarray(li,28),s=i.subarray(28);try{const e=h.createDecipheriv(ui,t,r);return e.setAuthTag(n),Buffer.concat([e.update(s),e.final()])}catch(e){const t=e instanceof Error?e.message:"Failed to decrypt payload";throw new ai(t)}}}const di="settings.picgoCloud.encryptionMethod",_i=["settings.picgoCloud.token",di],gi=(e,t,i={})=>{const r=p.cloneDeep(e),n=!0===i.cleanupEmptyParents;return _i.forEach(e=>{const i=p.get(t,e);void 0!==i?p.set(r,e,i):(p.unset(r,e),n&&((e,t)=>{const i=t.split(".");for(let t=i.length-1;t>0;t-=1){const r=i.slice(0,t).join("."),n=p.get(e,r);if(!p.isPlainObject(n)||0!==Object.keys(n).length)break;p.unset(e,r)}})(r,e))}),r},hi=(e,t)=>{if(e)return e;const i=(e=>{const t=p.get(e,di);if(void 0!==t){if(t===exports.EncryptionMethod.AUTO||t===exports.EncryptionMethod.SSE||t===exports.EncryptionMethod.E2EE)return t;throw new ci(t)}})(t);return i??exports.EncryptionMethod.AUTO},fi=async t=>{if(await e.pathExists(t)){const i=await e.readFile(t,"utf8");return d.parse(i)}return{}},Ei=async t=>{if(!await e.pathExists(t))return{version:0,updatedAt:"",data:{}};const i=await fi(t);return(e=>{if(!p.isPlainObject(e))return!1;const t=e;return"number"==typeof t.version&&Object.prototype.hasOwnProperty.call(t,"data")})(i)?{version:i.version,updatedAt:"string"==typeof i.updatedAt?i.updatedAt:"",data:i.data??{}}:{version:0,updatedAt:"",data:i}},mi=async(t,i,r)=>{await(async(t,i)=>{const r=d.stringify(i,null,2);await e.writeFile(t,r,"utf8")})(t,{version:r,updatedAt:(new Date).toISOString(),data:i})};class Ii{ctx;snapshotPath;configService;onAskPin;onAskEncryptionSwitch;e2eService;currentRemoteVersion=0;originalRemote=null;remoteE2EVersion=exports.E2EVersion.NONE;remoteClientKekSalt;remoteClientDekEncrypted;cachedDEK;cachedClientDekEncrypted;constructor(e,i={}){this.ctx=e,this.snapshotPath=t.join(e.baseDir,"config.snapshot.json"),this.configService=new Wt(e),this.onAskPin=i.onAskPin,this.onAskEncryptionSwitch=i.onAskEncryptionSwitch,this.e2eService=new pi}async sync(t={},i=0){try{const r=await fi(this.ctx.configPath);if(!p.isPlainObject(r))return{status:exports.SyncStatus.FAILED,message:"Local config is not a valid JSON object"};const n=r,s=hi(t.encryptionMethod,n),o=await e.pathExists(this.snapshotPath),a=await Ei(this.snapshotPath),c=await this.fetchRemoteConfig();if(c&&!p.isPlainObject(c))return{status:exports.SyncStatus.FAILED,message:"Remote config is not a valid JSON object"};if(this.originalRemote=c||null,!this.originalRemote){const e=!o;e?this.ctx.log.info("First time sync detected. Initializing remote config..."):this.ctx.log.warn("Remote config missing (sync chain broken). Re-initializing from Local...");try{const e=await this.buildPushPayload(n,s);await this.pushRemoteConfig(e.configStr,e.e2eFields)}catch(e){if("Remote config modified by another device"===(e instanceof Error?e.message:String(e)))return i<1?(this.ctx.log.warn("Conflict detected during sync. Retrying automatically..."),this.sync(t,i+1)):{status:exports.SyncStatus.FAILED,message:"Sync failed: Remote config is changing too frequently. Please try again later."};throw e}return await mi(this.snapshotPath,n,this.currentRemoteVersion),{status:exports.SyncStatus.SUCCESS,message:e?"Config sync initialized":"Remote config restored from local",mergedConfig:n}}if(this.originalRemote&&this.isEncryptionModeSwitch(s)&&!t.skipEncryptionSwitchConfirm){if(!await this.confirmEncryptionSwitch(s))return{status:exports.SyncStatus.FAILED,message:this.ctx.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_CANCELLED")}}const l=gi(this.originalRemote,n);this.ctx.log.info("Merging configs for sync...");const u=Zt.merge3Way(a.data,n,l);if(u.conflict)return{status:exports.SyncStatus.CONFLICT,message:"Config sync conflict detected",diffTree:u.diffNode};const d=u.value;!p.isEqual(n,d)&&this.ctx.saveConfig(d);const _=gi(d,this.originalRemote,{cleanupEmptyParents:!0});if(this.isEncryptionModeSwitch(s)||!p.isEqual(this.originalRemote,_))try{const e=await this.buildPushPayload(_,s);await this.pushRemoteConfig(e.configStr,e.e2eFields)}catch(e){if("Remote config modified by another device"===(e instanceof Error?e.message:String(e)))return i<1?(this.ctx.log.warn("Conflict detected during sync. Retrying automatically..."),this.sync(t,i+1)):{status:exports.SyncStatus.FAILED,message:"Sync failed: Remote config is changing too frequently. Please try again later."};throw e}return await mi(this.snapshotPath,d,this.currentRemoteVersion),{status:exports.SyncStatus.SUCCESS,message:"Config sync success",mergedConfig:d}}catch(e){if(e instanceof ci)return{status:exports.SyncStatus.FAILED,message:this.ctx.i18n.translate("CONFIG_SYNC_INVALID_ENCRYPTION_METHOD",{value:`"${String(e.value)}"`})};if(e instanceof ni)return{status:exports.SyncStatus.FAILED,message:this.ctx.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_MISSING_HANDLER")};const t=e instanceof Error?e.message:String(e);return{status:exports.SyncStatus.FAILED,message:t}}}async applyResolvedConfig(e,t={}){try{if(!p.isPlainObject(e))return{status:exports.SyncStatus.FAILED,message:"Resolved config is not a valid JSON object"};const i=await fi(this.ctx.configPath);if(!p.isPlainObject(i))return{status:exports.SyncStatus.FAILED,message:"Local config is not a valid JSON object"};const r=gi(e,i);if(this.ctx.saveConfig(r),!this.originalRemote){const e=await this.fetchRemoteConfig();if(e&&!p.isPlainObject(e))return{status:exports.SyncStatus.FAILED,message:"Remote config is not a valid JSON object"};this.originalRemote=e||null}const n=this.originalRemote?gi(r,this.originalRemote,{cleanupEmptyParents:!0}):r,s=t.useE2E??this.remoteE2EVersion===exports.E2EVersion.V1?exports.EncryptionMethod.E2EE:exports.EncryptionMethod.SSE,o=await this.buildPushPayload(n,s);return await this.pushRemoteConfig(o.configStr,o.e2eFields),await mi(this.snapshotPath,r,this.currentRemoteVersion),{status:exports.SyncStatus.SUCCESS,message:"Config conflict resolved",mergedConfig:r}}catch(e){const t=e instanceof Error?e.message:String(e);return{status:exports.SyncStatus.FAILED,message:t}}}async fetchRemoteConfig(){this.ctx.log.info("Fetching remote config for sync...");const e=await this.configService.fetchConfig();if(!e)return this.currentRemoteVersion=0,this.setRemoteE2EState(exports.E2EVersion.NONE),null;this.currentRemoteVersion=e.version;if((e=>{if(e===exports.E2EVersion.V1)return exports.E2EVersion.V1;if(e===exports.E2EVersion.NONE||void 0===e)return exports.E2EVersion.NONE;if("number"==typeof e)throw new ii(`Unsupported E2E version: ${e}`);return exports.E2EVersion.NONE})(e.encryption?.e2eVersion)===exports.E2EVersion.V1){const t=(e=>{if(!e.encryption?.clientKekSalt)throw new ti("Missing clientKekSalt for encrypted config");return e.encryption.clientKekSalt})(e),i=(e=>{if(!e.encryption?.clientDekEncrypted)throw new ti("Missing clientDekEncrypted for encrypted config");return e.encryption.clientDekEncrypted})(e);this.setRemoteE2EState(exports.E2EVersion.V1,t,i);const r=await this.decryptRemoteConfig(e.config,t,i);return d.parse(r)}return this.setRemoteE2EState(exports.E2EVersion.NONE),d.parse(e.config)}async pushRemoteConfig(e,t){this.ctx.log.info("Pushing merged config to remote...");const i=await this.configService.updateConfig(e,this.currentRemoteVersion,t);if(i.conflict)throw this.currentRemoteVersion=i.version,new Error("Remote config modified by another device");this.currentRemoteVersion=i.version,this.applyE2EStateAfterPush(t)}applyE2EStateAfterPush(e){e.e2eVersion===exports.E2EVersion.V1&&e.clientKekSalt&&e.clientDekEncrypted?this.setRemoteE2EState(exports.E2EVersion.V1,e.clientKekSalt,e.clientDekEncrypted):e.e2eVersion===exports.E2EVersion.NONE&&this.setRemoteE2EState(exports.E2EVersion.NONE)}setRemoteE2EState(e,t,i){this.remoteE2EVersion=e,this.remoteClientKekSalt=t,this.remoteClientDekEncrypted=i,i&&i===this.cachedClientDekEncrypted||(this.cachedDEK=void 0,this.cachedClientDekEncrypted=void 0)}async confirmEncryptionSwitch(e){if(!this.onAskEncryptionSwitch)throw new ni;const t=this.remoteE2EVersion===exports.E2EVersion.V1?exports.EncryptionMethod.E2EE:exports.EncryptionMethod.SSE,i=this.shouldUseE2E(e)?exports.EncryptionMethod.E2EE:exports.EncryptionMethod.SSE;return this.onAskEncryptionSwitch({from:t,to:i})}async buildPushPayload(e,t){const i=d.stringify(e);if(!this.shouldUseE2E(t))return{configStr:i,e2eFields:{e2eVersion:exports.E2EVersion.NONE}};if(this.remoteE2EVersion===exports.E2EVersion.V1&&this.remoteClientKekSalt&&this.remoteClientDekEncrypted){const e=await this.ensureDEK(this.remoteClientKekSalt,this.remoteClientDekEncrypted);return{configStr:this.e2eService.encryptConfig(i,e),e2eFields:{e2eVersion:exports.E2EVersion.V1,clientKekSalt:this.remoteClientKekSalt,clientDekEncrypted:this.remoteClientDekEncrypted}}}const r=await this.askPin(exports.E2EAskPinReason.SETUP,0),{payload:n,dek:s}=this.e2eService.generateE2EPayload(i,r);return this.cachedDEK=s,this.cachedClientDekEncrypted=n.clientDekEncrypted,{configStr:n.config,e2eFields:{e2eVersion:n.e2eVersion,clientKekSalt:n.clientKekSalt,clientDekEncrypted:n.clientDekEncrypted}}}shouldUseE2E(e){return e===exports.EncryptionMethod.E2EE||e!==exports.EncryptionMethod.SSE&&this.remoteE2EVersion===exports.E2EVersion.V1}isEncryptionModeSwitch(e){return this.shouldUseE2E(e)!==(this.remoteE2EVersion===exports.E2EVersion.V1)}async decryptRemoteConfig(e,t,i){const r=await this.ensureDEK(t,i);try{return this.e2eService.decryptConfig(e,r)}catch(e){if(e instanceof ai)throw new ti("Failed to decrypt remote config payload");throw e}}async ensureDEK(e,t){if(this.cachedDEK&&this.cachedClientDekEncrypted===t)return this.cachedDEK;const i=this.e2eService.decodeSalt(e);for(let e=0;e<4;e+=1){const r=0===e?exports.E2EAskPinReason.DECRYPT:exports.E2EAskPinReason.RETRY,n=await this.askPin(r,e);try{const e=this.e2eService.unwrapDEK(t,n,i);return this.cachedDEK=e,this.cachedClientDekEncrypted=t,e}catch(e){if(e instanceof ai)continue;throw e}}throw new oi}async askPin(e,t){if(!this.onAskPin)throw new ri;const i=await this.onAskPin(e,t);if(null==i||0===i.length)throw new si;return i}}const Ci=e=>{if(void 0===e)return"undefined";try{return JSON.stringify(e)}catch{return f.inspect(e,{depth:4,breakLength:120,maxArrayLength:50})}},Li=(e,t=0)=>{const i=" ".repeat(2*t),r=e.status===exports.ConflictType.CONFLICT?u.red:e.status===exports.ConflictType.ADDED?u.green:e.status===exports.ConflictType.DELETED?u.gray:e.status===exports.ConflictType.MODIFIED?u.yellow:u.white;if(console.log(`${i}${r(`[${e.status}]`)} ${e.key}`),e.status!==exports.ConflictType.CONFLICT||e.children&&0!==e.children.length||(console.log(`${i} ${u.gray("snapshot:")} ${Ci(e.snapshotValue)}`),console.log(`${i} ${u.cyan("local :")} ${Ci(e.localValue)}`),console.log(`${i} ${u.magenta("remote:")} ${Ci(e.remoteValue)}`)),e.children?.length)for(const i of e.children)Li(i,t+1)},Oi=e=>e.option("--encrypt [method]","encryption method (auto|sse|e2ee)").option("--skip-encryption-switch-confirm","skip encryption switch confirmation"),Ui=e=>async t=>{const i=t.encrypt;let r;if(void 0!==i){const t="string"==typeof i?i:void 0;if(t!==exports.EncryptionMethod.AUTO&&t!==exports.EncryptionMethod.SSE&&t!==exports.EncryptionMethod.E2EE){const i=t??"undefined";return void e.log.error(e.i18n.translate("CONFIG_SYNC_INVALID_ENCRYPTION_METHOD",{value:`"${i}"`}))}r=t,e.saveConfig({"settings.picgoCloud.encryptionMethod":t})}const n=new Ii(e,{onAskPin:async(t,i)=>{if(t===exports.E2EAskPinReason.SETUP){for(let t=0;t<3;t+=1){const{pin:t}=await e.cmd.inquirer.prompt([{type:"password",name:"pin",message:"Set up E2E encryption. Enter PIN",mask:"*"}]),{confirmPin:i}=await e.cmd.inquirer.prompt([{type:"password",name:"confirmPin",message:"Confirm PIN",mask:"*"}]);if(t===i)return t;e.log.warn("PIN confirmation does not match. Please try again.")}return null}const r=t===exports.E2EAskPinReason.DECRYPT?"Enter PIN to decrypt config":`Incorrect PIN. Retry (${i}/3)`,{pin:n}=await e.cmd.inquirer.prompt([{type:"password",name:"pin",message:r,mask:"*"}]);return n},onAskEncryptionSwitch:async({from:t,to:i})=>{const r=e.i18n.translate(t===exports.EncryptionMethod.E2EE?"CONFIG_SYNC_ENCRYPTION_METHOD_E2EE":"CONFIG_SYNC_ENCRYPTION_METHOD_SSE"),n=e.i18n.translate(i===exports.EncryptionMethod.E2EE?"CONFIG_SYNC_ENCRYPTION_METHOD_E2EE":"CONFIG_SYNC_ENCRYPTION_METHOD_SSE"),s=e.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_TITLE"),o=e.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_BODY",{from:r,to:n}),{confirm:a}=await e.cmd.inquirer.prompt([{type:"list",name:"confirm",message:`${s}\n\n${o}`,choices:[{name:e.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_CONFIRM"),value:!0},{name:e.i18n.translate("CONFIG_SYNC_ENCRYPTION_SWITCH_CANCEL"),value:!1}]}]);return a}}),s=await n.sync({encryptionMethod:r,skipEncryptionSwitchConfirm:t.skipEncryptionSwitchConfirm});if(s.status!==exports.SyncStatus.SUCCESS){if(s.status===exports.SyncStatus.CONFLICT){e.log.warn(s.message||"Config sync conflict detected."),s.diffTree&&Li(s.diffTree);const{strategy:t}=await e.cmd.inquirer.prompt([{type:"list",name:"strategy",message:"Choose a strategy to resolve conflicts",choices:[{name:"Use Local",value:"local"},{name:"Use Remote",value:"remote"},{name:"Abort",value:"abort"}]}]);if("abort"===t)return void e.log.warn("Config sync aborted.");const i="local"===t?s.diffTree?.localValue:s.diffTree?.remoteValue;if(!i||!p.isPlainObject(i))return void e.log.error("Invalid resolved config, please resolve it manually.");let o;if(r===exports.EncryptionMethod.E2EE)o={useE2E:!0};else if(r===exports.EncryptionMethod.SSE)o={useE2E:!1};else{const t=e.getConfig("settings.picgoCloud.encryptionMethod");t===exports.EncryptionMethod.E2EE?o={useE2E:!0}:t===exports.EncryptionMethod.SSE&&(o={useE2E:!1})}const a=await n.applyResolvedConfig(i,o);return a.status===exports.SyncStatus.SUCCESS?void e.log.success(a.message||"Config sync resolved!"):void e.log.error(a.message||"Failed to apply resolved config")}e.log.error(s.message||"Config sync failed")}else e.log.success(s.message||"Config sync success!")},Pi={handle:e=>{const t=e.cmd.program.command("config").description("manage picgo config");Oi(t.command("sync").description("sync config with picgo cloud (shortcut for cloud config sync)")).action(Ui(e))}},Di=e=>e.trim(),Si=e=>Di(e).toLowerCase(),Ni=(e,t)=>{const i=Si(t);return e.find(e=>Si(e)===i)},Ti=async(e,t,i,r)=>{const n=Y(t,{onError:(t,i,r)=>{const n=r instanceof Error?r.message:String(r);e.log.warn(`[plugin-config] ${t}.${i} threw during CLI prompt: ${n}`)}}),s=await e.cmd.inquirer.prompt(n),o="transformer"===i?`transformer.${r}`:r;e.saveConfig({[o]:s}),"transformer"===i&&e.saveConfig({"picBed.transformer":r})},Ai={handle:e=>{e.cmd.program.command("set").arguments("<module> [name] [configName]").description("configure config of picgo modules (uploader/transformer/plugin)").action(async(t,i,r)=>{try{switch(t){case"uploader":{const t=i||(await e.cmd.inquirer.prompt([{type:"list",name:"uploaderType",choices:e.helper.uploader.getIdList(),message:"Choose an uploader",default:e.getConfig("picBed.uploader")||e.getConfig("picBed.current")||"smms"}])).uploaderType,n=e.helper.uploader.get(t);if(!n)return e.log.error(`No uploader named ${t}`);if(!n.config)return e.log.error(`Uploader ${t} has no config`);const s=e.uploaderConfig.getConfigList(t),o=s.map(e=>e._configName);let a="string"==typeof r?Di(r):"";if(!a)if(o.length>0){const t=await e.cmd.inquirer.prompt([{type:"list",name:"configChoice",message:"Choose a config",choices:[{name:"[Create New Config]",value:"__CREATE__"},...o]}]);if("__CREATE__"===t.configChoice){const t=await e.cmd.inquirer.prompt([{type:"input",name:"newConfigName",message:"Enter config name",validate:e=>{const t=Di(e);return t?!Ni(o,t)||`Config name ${t} already exists`:"Config name can not be empty"}}]);a=Di(t.newConfigName)}else a=String(t.configChoice)}else{const t=await e.cmd.inquirer.prompt([{type:"input",name:"newConfigName",message:"Enter config name",validate:e=>!!Di(e)||"Config name can not be empty"}]);a=Di(t.newConfigName)}const c=Ni(o,a);if(c){const i=s.find(e=>Si(e._configName)===Si(c));i&&e.setConfig({[`picBed.${t}`]:i})}const l=Y(n.config(e),{onError:(t,i,r)=>{const n=r instanceof Error?r.message:String(r);e.log.warn(`[plugin-config] ${t}.${i} threw during CLI prompt: ${n}`)}}),u=await e.cmd.inquirer.prompt(l);e.uploaderConfig.createOrUpdate(t,a,u)}break;case"transformer":if(i){const r=e.helper.transformer.get(i);if(!r)return e.log.error(`No transformer named ${i}`);r.config&&await Ti(e,r.config(e),t,i)}else{const i=[{type:"list",name:"transformer",choices:e.helper.transformer.getIdList(),message:"Choose a transformer"}],r=await e.cmd.inquirer.prompt(i),n=e.helper.transformer.get(r.transformer);n?.config&&await Ti(e,n.config(e),t,r.transformer)}break;case"plugin":if(i){if(i.includes("picgo-plugin-")||(i=`picgo-plugin-${i}`),!Object.keys(e.getConfig("picgoPlugins")).includes(i))return e.log.error(`No plugin named ${i}`);e.pluginLoader.getPlugin(i)?.config&&await Ti(e,e.pluginLoader.getPlugin(i).config(e),"plugin",i)}else{const t=[{type:"list",name:"plugin",choices:e.pluginLoader.getFullList(),message:"Choose a plugin"}],i=await e.cmd.inquirer.prompt(t);e.pluginLoader.getPlugin(i.plugin)?.config&&await Ti(e,e.pluginLoader.getPlugin(i.plugin).config(e),"plugin",i.plugin)}break;default:return e.log.warn(`No module named ${t}`),e.log.warn("Available modules are uploader|transformer|plugin")}e.log.success("Configure config successfully!"),"plugin"===t&&e.log.info("If you want to use this config, please run 'picgo use plugins'")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}})}},yi={handle:async e=>{const t=e.cmd;t.program.command("use").arguments("[module] [name] [configName]").description("use a module (uploader/transformer/plugin) of picgo").action(async(i,r,n)=>{try{if("uploader"===i&&r)return e.uploaderConfig.use(r,n),void e.log.success("Activated config successfully!");const s=["uploader","transformer","plugins"];let o=[];const a={uploader:{type:"list",name:"uploader",message:"Use an uploader",choices:e.helper.uploader.getIdList(),default:e.getConfig("picBed.uploader")||e.getConfig("picBed.current")||"smms"},transformer:{type:"list",name:"transformer",message:"Use a transformer",choices:e.helper.transformer.getIdList(),default:e.getConfig("picBed.transformer")||"path"},plugins:{type:"checkbox",name:"plugins",message:"Use plugins",choices:e.pluginLoader.getFullList(),default:Object.keys(e.getConfig("picgoPlugins")).filter(t=>e.getConfig(`picgoPlugins.${t}`))}};if(i){if("uploader"!==i&&"transformer"!==i&&"plugins"!==i)return e.log.warn(`No module named ${i}`),e.log.warn(`Available modules are ${s.join("|")}`);o.push(a[i])}else o=s.map(e=>a[e]);const c=await t.inquirer.prompt(o);if(c.plugins){const t=c.plugins,i=e.getConfig("picgoPlugins");Object.keys(i).forEach(e=>{i[e]=t.includes(e)}),e.saveConfig({picgoPlugins:i})}if(c.uploader){const i=c.uploader,r=e.uploaderConfig.getConfigList(i);if(r.length>1){const n=e.uploaderConfig.getActiveConfig(i),s=await t.inquirer.prompt([{type:"list",name:"uploaderConfigName",message:"Use an uploader config",choices:r.map(e=>e._configName),default:n?._configName}]);e.uploaderConfig.use(i,s.uploaderConfigName)}else e.uploaderConfig.use(i)}void 0!==c.transformer&&e.saveConfig({"picBed.transformer":c.transformer||"path"}),e.log.success("Configure config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}})}},Ri={handle:e=>{e.cmd.program.option("-p, --proxy <url>","set proxy for uploading",t=>{e.setConfig({"picBed.proxy":t})})}},wi={handle:e=>{e.cmd.program.command("i18n").arguments("[lang]").description("change picgo language").action(async(t="")=>{const i=e.i18n.getLanguageList();if(!t){const t=[{type:"list",name:"i18n",choices:i,message:"Choose a language",default:e.getConfig("settings.language")||"zh-CN"}],r=await e.cmd.inquirer.prompt(t);return e.i18n.setLanguage(r.i18n),void e.log.success(`Language set to ${r.i18n}`)}if(!i.includes(t))return e.log.warn("No such language");e.i18n.setLanguage(t),e.log.success(`Language set to ${t}`)})}},xi={handle:e=>{e.cmd.program.command("server").description("run PicGo as a standalone server").helpOption("--help","display help for command").option("-p, --port <n>","server port").option("-h, --host <s>","server host").option("-i, --ignore-existing-external-server","ignore existing PicGo server instance").option("--secret <s>","server authentication secret").action(async t=>{try{e.setConfig({"picgoInternal.serverMode":!0});const i=t.port?Number(t.port):void 0,r=t.host;await e.server.listen(i,r,t.ignoreExistingExternalServer,t.secret)}catch(t){e.unsetConfig("picgoInternal","serverMode"),e.log.error(t)}})}},bi={handle:e=>{e.cmd.program.command("login").description("login to cloud.picgo.app (shortcut for cloud login)").arguments("[token]").action(Dt(e))}},Mi={handle:e=>{e.cmd.program.command("logout").description("logout from cloud.picgo.app (shortcut for cloud logout)").action(St(e))}},Bi=e=>e.trim(),vi=e=>Bi(e).toLowerCase(),Gi=(e,t)=>{const i=e.getConfig("picBed.current"),r=[];for(const n of t){i===n?r.push(u.green.bold(`+ ${n} [Current Uploader]`)):r.push(`+ ${n}`);const t=e.uploaderConfig.getConfigList(n);if(0===t.length){r.push(u.grey(" (No configs found)"));continue}const s=e.getConfig(`uploader.${n}.defaultId`);for(const e of t)e._id===s?r.push(u.blue(` * ${e._configName} [Default Config]`)):r.push(` ${e._configName}`)}return`\n${r.join("\n")}`},$i={handle:e=>{const t=e.cmd,i=t.program.command("uploader").description("manage uploader configurations").action(async()=>{try{const i=[{name:"List all configurations",value:"list"},{name:"Rename config",value:"rename"},{name:"Copy config",value:"copy"},{name:"Delete config",value:"delete"}],r=await t.inquirer.prompt([{type:"list",name:"operation",message:"Choose an operation:",choices:i}]);if("list"===r.operation){const t=e.uploaderConfig.listUploaderTypes();return void console.log(Gi(e,t))}const n=e.uploaderConfig.listUploaderTypes().filter(t=>e.uploaderConfig.getConfigList(t).length>0);if(0===n.length)return void e.log.warn("No configs found");const s=await t.inquirer.prompt([{type:"list",name:"type",message:"Choose an uploader:",choices:n}]),o=String(s.type),a=e.uploaderConfig.getConfigList(o).map(e=>e._configName),c=await t.inquirer.prompt([{type:"list",name:"configName",message:"rename"===r.operation?"Choose a config to rename:":"copy"===r.operation?"Choose a config to copy:":"Choose a config to delete:",choices:a}]),l=String(c.configName);if("rename"===r.operation){const i=await t.inquirer.prompt([{type:"input",name:"newName",message:"Enter new name:",validate:e=>{const t=Bi(e);if(!t)return"Config name can not be empty";return!a.some(e=>vi(e)===vi(t)&&vi(e)!==vi(l))||`Config name ${t} already exists`}}]);return e.uploaderConfig.rename(o,l,String(i.newName)),void e.log.success("Rename config successfully!")}if("copy"===r.operation){const i=await t.inquirer.prompt([{type:"input",name:"newName",message:"Enter new name:",validate:e=>{const t=Bi(e);if(!t)return"Config name can not be empty";return!a.some(e=>vi(e)===vi(t))||`Config name ${t} already exists`}}]);return e.uploaderConfig.copy(o,l,String(i.newName)),void e.log.success("Copy config successfully!")}if(!(await t.inquirer.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete ${l}?`,default:!1}])).confirm)return;e.uploaderConfig.remove(o,l),e.log.success("Delete config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}});i.command("list [type]").description("list uploader configurations").action(async t=>{try{const i=e.uploaderConfig.listUploaderTypes();if("string"==typeof t&&t)return i.includes(t)?void console.log(Gi(e,[t])):void e.log.error(`Type ${t} not found`);console.log(Gi(e,i))}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}}),i.command("rename <type> <oldName> <newName>").description("rename a config").action(async(t,i,r)=>{try{e.uploaderConfig.rename(t,i,r),e.log.success("Rename config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}}),i.command("copy <type> <configName> <newConfigName>").description("copy a config (does not switch current uploader)").action(async(t,i,r)=>{try{e.uploaderConfig.copy(t,i,r),e.log.success("Copy config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}}),i.command("rm <type> <configName>").description("remove a config").action(async(t,i)=>{try{e.uploaderConfig.remove(t,i),e.log.success("Delete config successfully!")}catch(t){if(e.log.error(t),process.argv.includes("--debug"))throw t}})}},Fi=e=>Ct({text:e}).start(),ki=async(e,t)=>{try{(e=>{const t=e.getConfig("settings.picgoCloud.token")?.trim();if(!t)throw new Error([e.i18n.translate("CLOUD_COMMAND_LOGIN_REQUIRED"),e.i18n.translate("CLOUD_COMMAND_LOGIN_HINT")].join("\n"))})(e),await t()}catch(t){e.log.error(t instanceof Error?t:new Error(String(t)))}},Hi=e=>Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e)),Yi=e=>{if("string"!=typeof e||""===e.trim())return;const t=Number(e);return Number.isFinite(t)?t:void 0},Vi=e=>({current:String(e.current),total:String(e.total),batchIndex:String(e.batchIndex),batchTotal:String(e.batchTotal),created:String(e.created),skipped:String(e.skipped),failed:String(e.failed)}),qi=(e,t)=>Lt({ctx:e,event:exports.IBuildInEvent.CLOUD_IMPORT_PROGRESS,verbose:t,formatBarText:t=>e.i18n.translate("CLOUD_ALBUM_IMPORT_PROGRESS_BAR",Vi(t)),formatVerboseText:t=>e.i18n.translate("CLOUD_ALBUM_IMPORT_VERBOSE_BATCH",Vi(t))}),ji=(e,t)=>{console.log(e.i18n.translate("CLOUD_ALBUM_IMPORT_SUMMARY_TITLE"));const i=[["CLOUD_ALBUM_IMPORT_SUMMARY_TOTAL",t.total],["CLOUD_ALBUM_IMPORT_SUMMARY_CREATED",t.created],["CLOUD_ALBUM_IMPORT_SUMMARY_SKIPPED",t.skipped],["CLOUD_ALBUM_IMPORT_SUMMARY_INVALID",t.invalid],["CLOUD_ALBUM_IMPORT_SUMMARY_FAILED",t.failed],["CLOUD_ALBUM_IMPORT_SUMMARY_PENDING",t.pending]];for(const[t,r]of i)console.log(`${e.i18n.translate(t)}: ${r}`);t.pending>0&&console.log(e.i18n.translate("CLOUD_ALBUM_IMPORT_RETRY_HINT"))},Ki=e=>{console.log(JSON.stringify(e,null,2))},Wi=e=>{console.log(JSON.stringify(e))},Qi=["active-pro","active-pro-yearly","active-pro-cancel","active-grant","active-grant-lifetime","grace","frozen","pending-cleanup"];function zi(){const e=process.env.PICGO_MOCK_LIFECYCLE;if(e)return Qi.includes(e)?e:void 0}const Ji=e=>new Date(Date.now()+864e5*e).toISOString();class Xi{client;ctx;constructor(e){this.client=new Kt(e),this.ctx=e}async whoami(e){const t=zi();return t?(this.ctx.log.warn(`[MOCK] UserService.whoami scenario=${t}`),{user:"Mock User",avatar:null,plan:2,autoImport:"active-pro"===(i=t)||"active-pro-yearly"===i||"active-pro-cancel"===i}):await this.client.request({method:"GET",url:"/api/whoami"},e);var i}async setAutoImport(e,t){const i=await this.client.request({method:"PUT",url:"/api/profile/me",data:{extra:{autoImport:e}}},t);return{user:i.user.name,avatar:i.user.image,autoImport:e}}async verifyToken(e){try{const t=await this.whoami(e);return this.ctx.log.success("Welcome:",t.user??"Unknown user"),!0}catch{return!1}}async getUserConfig(e){try{const t=await this.client.request({method:"GET",url:"/api/config"},e);return JSON.parse(t.config)}catch{throw new Error("Failed to fetch user config from server")}}}const Zi=e=>e.argument("[dbPath]","path to the local PicGo album database, usually called picgo.db").option("--json-file <path>","read import data from a JSON file").option("--data <json>","read import data from an inline JSON string").option("--verbose","print batch details instead of the progress bar").option("--enable-auto-import","enable auto import before importing when needed").option("--format <format>","output format: pretty | json","pretty"),er=e=>async(t,i)=>{await ki(e,async()=>{const r=Fi(e.i18n.translate("CLOUD_ALBUM_IMPORT_LOADING_SOURCE"));let n;try{n=await tr(e,t,i),r.succeed(e.i18n.translate("CLOUD_ALBUM_IMPORT_LOADING_SOURCE_DONE",{count:String(n.items.length)}))}catch(e){throw r.fail(e instanceof Error?e.message:String(e)),e}const s=Fi(e.i18n.translate("CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT"));await or(e,!0===i.enableAutoImport,s);const o=qi(e,!0===i.verbose);o.spinner.text=e.i18n.translate("CLOUD_ALBUM_IMPORT_UPLOADING"),o.spinner.start();try{const t=await e.cloud.album.import(n.items);o.spinner.succeed(e.i18n.translate("CLOUD_ALBUM_IMPORT_UPLOADING_DONE")),n.galleryStore&&await sr(n.galleryStore,t.items),"json"===i.format?Wi(t):ji(e,t)}catch(e){throw o.spinner.fail(e instanceof Error?e.message:String(e)),e}finally{o.dispose()}})},tr=async(e,t,i)=>{const r=[t,i.jsonFile,i.data].filter(e=>"string"==typeof e&&""!==e.trim());if(0===r.length)throw new Error(e.i18n.translate("CLOUD_ALBUM_IMPORT_SOURCE_REQUIRED"));if(r.length>1)throw new Error(e.i18n.translate("CLOUD_ALBUM_IMPORT_SOURCE_CONFLICT"));return"string"==typeof t&&""!==t.trim()?await ir(e,t):"string"==typeof i.jsonFile&&""!==i.jsonFile.trim()?{items:await rr(e,i.jsonFile)}:{items:nr(e,i.data??"")}},ir=async(i,r)=>{const n=t.resolve(r);if(!await e.pathExists(n))throw new Error(i.i18n.translate("CLOUD_ALBUM_IMPORT_INVALID_JSON_FILE",{path:n}));const s=new m.DBStore(n,"gallery"),o=await s.get();return{galleryStore:s,items:o.data.filter(e=>!0!==e._importToPicGoCloud)}},rr=async(e,i)=>{const r=t.resolve(i);try{const t=await E.readFile(r,"utf8");return nr(e,t)}catch{throw new Error(e.i18n.translate("CLOUD_ALBUM_IMPORT_INVALID_JSON_FILE",{path:r}))}},nr=(e,t)=>{const i=e.i18n.translate("CLOUD_ALBUM_IMPORT_INVALID_JSON");let r;try{r=JSON.parse(t)}catch{throw new Error(i)}if(!Array.isArray(r))throw new Error(i);return r},sr=async(e,t)=>{const i=t.map(e=>e.id).filter(e=>"string"==typeof e&&""!==e.trim());0!==i.length&&await e.updateMany(i.map(e=>({id:e,_importToPicGoCloud:!0})))},or=async(e,t,i)=>{const r=await e.cloud.getUserInfo();if(!$t(r))throw new Error(e.i18n.translate("CLOUD_ALBUM_IMPORT_PLAN_REQUIRED"));if(r?.autoImport)return void i.succeed(e.i18n.translate("CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT_DONE"));if(t)return i.text=e.i18n.translate("CLOUD_ALBUM_IMPORT_ENABLING_AUTO_IMPORT"),await ar(e),void i.succeed(e.i18n.translate("CLOUD_ALBUM_IMPORT_AUTO_IMPORT_ENABLED"));i.stop();if(!(await e.cmd.inquirer.prompt([{type:"confirm",name:"enableAutoImport",message:e.i18n.translate("CLOUD_ALBUM_IMPORT_PROMPT_ENABLE_AUTO_IMPORT"),default:!0}])).enableAutoImport)throw new Error(e.i18n.translate("CLOUD_ALBUM_IMPORT_AUTO_IMPORT_DISABLED"));const n=Fi(e.i18n.translate("CLOUD_ALBUM_IMPORT_ENABLING_AUTO_IMPORT"));try{await ar(e),n.succeed(e.i18n.translate("CLOUD_ALBUM_IMPORT_AUTO_IMPORT_ENABLED"))}catch(e){throw n.fail(e instanceof Error?e.message:String(e)),e}},ar=async e=>{const t=new Xi(e);await t.setAutoImport(!0),await e.cloud.refreshUserInfo()},cr={asc:exports.AlbumListOrder.ASC,desc:exports.AlbumListOrder.DESC},lr={newest:exports.AlbumListSort.NEWEST,oldest:exports.AlbumListSort.OLDEST,fileName:exports.AlbumListSort.FILE_NAME},ur=e=>e.option("--content-type <contentType>","filter by content type").option("--type <uploader-type>",'filter by uploader type. For example: "picgo-cloud", "smms", "imgur"').option("--ext <ext>","filter by extension").option("--search <keyword>","filter by keyword").option("--file-name <fileName>","filter by file name").option("--limit <limit>","set the page size").option("--offset <offset>","set the page offset").option("--sort <field>","sort by newest, oldest, or fileName").option("--order <order>","sort order: asc or desc").option("--format <format>","output format: pretty | json","pretty"),pr=e=>{const t=e.url;return"string"==typeof t&&""!==t.trim()?t:e.imgUrl??""},dr=e=>async t=>{await ki(e,async()=>{const i=Hi({contentType:t.contentType,type:t.type,ext:t.ext,search:t.search,fileName:t.fileName,limit:Yi(t.limit),offset:Yi(t.offset),sort:gr(t.sort),order:_r(t.order)}),r=Fi(e.i18n.translate("CLOUD_ALBUM_LIST_LOADING")),n=await e.cloud.album.list(i);if(r.succeed(e.i18n.translate("CLOUD_ALBUM_LIST_DONE")),"json"===t.format)return void Wi(n);const s=Math.max(2,...n.items.map(e=>(e.id??"").length));console.log(`${"ID".padEnd(s)} URL`);for(const e of n.items){const t=(e.id??"").padEnd(s),i=pr(e);console.log(`${t} ${i}`)}console.log(`\nTotal: ${n.total} Limit: ${n.limit} Offset: ${n.offset}`)})},_r=e=>e?cr[e]:void 0,gr=e=>e?lr[e]:void 0,hr={logged_in:0,logged_out:1,invalid:2,error:3},fr=e=>async(t={})=>{const i=await(async e=>{const t=e.getConfig("settings.picgoCloud.token")?.trim();if(!t)return{status:"logged_out",loggedIn:!1};try{const t=await e.cloud.getUserInfo();return t?{status:"logged_in",loggedIn:!0,user:t.user,plan:t.plan}:{status:"invalid",loggedIn:!1}}catch(e){return{status:"error",loggedIn:!1,message:e instanceof Error?e.message:String(e)}}})(e);return"json"===t.format?Wi((e=>{const t={status:e.status,loggedIn:e.loggedIn};return"logged_in"===e.status&&(t.user=e.user??null,"number"==typeof e.plan&&(t.plan=e.plan)),"error"===e.status&&e.message&&(t.message=e.message),t})(i)):((e,t)=>{switch(t.status){case"logged_in":e.log.success(e.i18n.translate("CLOUD_AUTH_STATUS_LOGGED_IN",{user:t.user??""}));break;case"logged_out":e.log.warn(e.i18n.translate("CLOUD_AUTH_STATUS_LOGGED_OUT")),e.log.info(e.i18n.translate("CLOUD_COMMAND_LOGIN_HINT"));break;case"invalid":e.log.warn(e.i18n.translate("CLOUD_AUTH_STATUS_INVALID")),e.log.info(e.i18n.translate("CLOUD_COMMAND_LOGIN_HINT"));break;case"error":e.log.error(e.i18n.translate("CLOUD_AUTH_STATUS_ERROR",{message:t.message??""}))}})(e,i),process.exitCode=hr[i.status],i},Er={handle:e=>{const t=e.cmd.program.command("cloud").description("manage PicGo Cloud");t.command("login").description("login to cloud.picgo.app (alias: picgo login)").arguments("[token]").action(Dt(e)),t.command("logout").description("logout from cloud.picgo.app (alias: picgo logout)").action(St(e));const i=t.command("album").description("manage cloud album data");((e,t)=>{Zi(t.command("import").description("import local album data into PicGo Cloud")).action(er(e))})(e,i),((e,t)=>{ur(t.command("list").description("list cloud album items")).action(dr(e))})(e,i),((e,t)=>{t.command("get").description("get one cloud album item").argument("<id>").option("--format <format>","output format: pretty | json","pretty").action(async(t,i)=>{await ki(e,async()=>{const r=Fi(e.i18n.translate("CLOUD_ALBUM_GET_LOADING")),n=await e.cloud.album.get(t);r.succeed(e.i18n.translate("CLOUD_ALBUM_GET_DONE")),"json"===i.format?Wi(n):Ki(n)})})})(e,i),((e,t)=>{t.command("update").description("update one cloud album item").argument("<id>").option("--fileName <fileName>","update the file name").option("--imgUrl <imgUrl>","update the image url").option("--originImgUrl <originImgUrl>","update the original image url").option("--contentType <contentType>","update the content type").option("--width <width>","update the width").option("--height <height>","update the height").option("--format <format>","output format: pretty | json","pretty").action(async(t,i)=>{await ki(e,async()=>{const r=Hi({fileName:i.fileName,imgUrl:i.imgUrl,originImgUrl:i.originImgUrl,contentType:i.contentType,width:Yi(i.width),height:Yi(i.height)}),n=Fi(e.i18n.translate("CLOUD_ALBUM_UPDATE_LOADING")),s=await e.cloud.album.update(t,r);n.succeed(e.i18n.translate("CLOUD_ALBUM_UPDATE_DONE")),"json"===i.format?Wi(s):Ki(s)})})})(e,i),((e,t)=>{t.command("delete").description("delete cloud album items").argument("<id...>").option("--force","skip the confirmation prompt").option("--format <format>","output format: pretty | json","pretty").action(async(t,i)=>{await ki(e,async()=>{if(!0!==i.force&&!(await e.cmd.inquirer.prompt([{type:"confirm",name:"confirm",message:e.i18n.translate("CLOUD_ALBUM_DELETE_CONFIRM",{count:String(t.length)}),default:!1}])).confirm)return;const r=Fi(e.i18n.translate("CLOUD_ALBUM_DELETE_LOADING"));await e.cloud.album.delete(1===t.length?t[0]:t),r.succeed(e.i18n.translate("CLOUD_ALBUM_DELETE_DONE"));const n={deleted:t};"json"===i.format?Wi(n):Ki(n)})})})(e,i),((e,t)=>{t.command("retry").description("retry pending cloud album imports").option("--verbose","print batch details instead of the progress bar").option("--format <format>","output format: pretty | json","pretty").action(async t=>{await ki(e,async()=>{const i=Fi(e.i18n.translate("CLOUD_ALBUM_RETRY_LOADING_PENDING")),r=await e.cloud.album.getPending();if(0===r.length)return void i.succeed(e.i18n.translate("CLOUD_ALBUM_IMPORT_NO_PENDING"));i.succeed(e.i18n.translate("CLOUD_ALBUM_RETRY_LOADING_PENDING_DONE",{count:String(r.length)}));const n=qi(e,!0===t.verbose);n.spinner.text=e.i18n.translate("CLOUD_ALBUM_RETRY_UPLOADING"),n.spinner.start();try{const i=await e.cloud.album.retryPending();n.spinner.succeed(e.i18n.translate("CLOUD_ALBUM_RETRY_UPLOADING_DONE")),"json"===t.format?Wi(i):ji(e,i)}catch(e){throw n.spinner.fail(e instanceof Error?e.message:String(e)),e}finally{n.dispose()}})})})(e,i);((e,t)=>{const i=fr(e);t.command("status").description("check PicGo Cloud login status (non-blocking)").option("--format <format>","output format: pretty | json","pretty").action(async e=>{await i(e)})})(e,t.command("auth").description("manage PicGo Cloud auth"));const r=t.command("config").description("manage cloud config");Oi(r.command("sync").description("sync config with picgo cloud (alias: picgo config sync)")).action(Ui(e)),ur(t.command("list").description("list cloud album items (shortcut for cloud album list)")).action(dr(e)),Zi(t.command("import").description("import local album data (shortcut for cloud album import)")).action(er(e))}},mr=e=>"json"===e.format,Ir=e=>t=>{const i=(e=>e.getConfig("picBed.uploader")||e.getConfig("picBed.current")||Ie)(e);return mr(t)?console.log(JSON.stringify({uploader:i})):console.log(i),i},Cr=e=>t=>{const i=(e=>{const t=e.getConfig("picgoPlugins")||{};return Object.keys(t).map(e=>({name:e,enabled:!!t[e]}))})(e);return mr(t)?console.log(JSON.stringify({plugins:i})):0===i.length?console.log(e.i18n.translate("GET_PLUGINS_EMPTY")):i.forEach(({name:e,enabled:t})=>{console.log(`${e}\t${t?"enabled":"disabled"}`)}),i},Lr={handle:e=>{const t=e.cmd.program.command("get").description("get current picgo module config (uploader/transformer/plugins)");t.command("uploader").description("get current uploader type").option("--format <format>","output format: pretty | json","pretty").action(t=>{Ir(e)(t)}),t.command("transformer").description("get current transformer").option("--format <format>","output format: pretty | json","pretty").action(t=>{(e=>t=>{const i=(e=>e.getConfig("picBed.transformer")||"path")(e);return mr(t)?console.log(JSON.stringify({transformer:i})):console.log(i),i})(e)(t)}),t.command("plugins").description("list installed plugins with enabled/disabled state").option("--format <format>","output format: pretty | json","pretty").action(t=>{Cr(e)(t)})}};class Or{static currentPlugin;list;pluginIdMap;name;constructor(e){this.name=e,this.list=new Map,this.pluginIdMap=new Map}register(e,t){if(!e)throw new TypeError("id is required!");if("function"!=typeof t.handle)throw new TypeError("plugin.handle must be a function!");if(this.list.has(e))throw new TypeError(`${this.name} duplicate id: ${e}!`);this.list.set(e,t),Or.currentPlugin&&(this.pluginIdMap.has(Or.currentPlugin)?this.pluginIdMap.get(Or.currentPlugin)?.push(e):this.pluginIdMap.set(Or.currentPlugin,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);t?.forEach(e=>{this.list.delete(e)})}}getName(){return this.name}get(e){return this.list.get(e)}getList(){return[...this.list.values()]}getIdList(){return[...this.list.keys()]}}const Ur=(e=null)=>{Or.currentPlugin=e};class Pr{name="commander";static currentPlugin;list=new Map;pluginIdMap=new Map;ctx;program;inquirer;constructor(e){this.program=new n.Command,this.inquirer=s,this.ctx=e}getName(){return this.name}init(){var e;this.program.version("3.0.0","-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",V),e.cmd.register("configPath",q),e.cmd.register("config",Pi),e.cmd.register("setting",Ai),e.cmd.register("upload",Pt),e.cmd.register("use",yi),e.cmd.register("proxy",Ri),e.cmd.register("i18n",wi),e.cmd.register("server",xi),e.cmd.register("login",bi),e.cmd.register("logout",Mi),e.cmd.register("cloud",Er),e.cmd.register("uploader",$i),e.cmd.register("get",Lr)}register(e,t){if(!e)throw new TypeError("name is required!");if("function"!=typeof t.handle)throw new TypeError("plugin.handle must be a function!");if(this.list.has(e))throw new TypeError(`${this.name} plugin duplicate id: ${e}!`);this.list.set(e,t);const i=Or.currentPlugin;null!==i&&(this.pluginIdMap.has(i)?this.pluginIdMap.get(i)?.push(e):this.pluginIdMap.set(i,[e]))}unregister(e){if(this.pluginIdMap.has(e)){const t=this.pluginIdMap.get(e);t?.forEach(e=>{this.list.delete(e)})}}loadCommands(){this.getList().forEach(e=>{try{e.handle(this.ctx)}catch(e){this.ctx.log.error(e)}})}get(e){return this.list.get(e)}getList(){return[...this.list.values()]}getIdList(){return[...this.list.keys()]}}class Dr{level={[exports.ILogType.success]:"green",[exports.ILogType.info]:"blue",[exports.ILogType.warn]:"yellow",[exports.ILogType.error]:"red",[exports.ILogType.debug]:"magenta"};ctx;consoleOutput;respectSilent;logLevel;logPath;logPathOverride;constructor(e,t={}){this.ctx=e,this.consoleOutput=t.consoleOutput??!0,this.respectSilent=t.respectSilent??!0,this.logPathOverride=t.logPath}handleLog(e,...i){this.logLevel=this.ctx.getConfig("settings.logLevel");const r=this.ctx.getConfig("silent");if((!this.respectSilent||!r)&&this.checkLogLevel(e,this.logLevel)){const n=u[this.level[e]](`[PicGo ${e.toUpperCase()}]:`);this.consoleOutput&&!r&&console.log(n,...i),this.logPath=this.logPathOverride||this.ctx.getConfig("settings.logPath")||t.join(this.ctx.baseDir,"./picgo.log"),setTimeout(()=>{try{const t=this.checkLogFileIsLarge(this.logPath);if(t.isLarge){const e=`Log file is too large (> ${t.logFileSizeLimit/1024/1024||"10"} MB), recreate log file`;this.consoleOutput&&!r&&console.log(u.yellow("[PicGo WARN]:"),e),this.recreateLogFile(this.logPath),i.unshift(e)}this.handleWriteLog(this.logPath,e,...i)}catch(e){console.error("[PicGo Error] on checking log file size",e)}},0)}}checkLogFileIsLarge(t){if(e.existsSync(t)){const i=e.statSync(t).size,r=1024*le(this.ctx.getConfig("settings.logFileSizeLimit")||10)*1024;return{isLarge:i>r,logFileSize:i,logFileSizeLimit:r}}return{isLarge:!1}}recreateLogFile(t){e.existsSync(t)&&(e.unlinkSync(t),e.createFileSync(t))}handleWriteLog(t,i,...r){try{let n=`${I().format("YYYY-MM-DD HH:mm:ss")} [PicGo ${i.toUpperCase()}] `;r.forEach(e=>{e instanceof Error&&"error"===i?n+=`\n------Error Stack Begin------\n${f.format(e?.stack)}\n-------Error Stack End------- `:("object"==typeof e&&(e=JSON.stringify(e,null,2)),n+=`${e} `)}),n+="\n",e.appendFileSync(t,n)}catch(e){console.error("[PicGo Error] on writing log file",e)}}checkLogLevel(e,t){return void 0===t||"all"===t||(Array.isArray(t)?t.some(t=>t===e||"all"===t):e===t)}success(...e){return this.handleLog(exports.ILogType.success,...e)}info(...e){return this.handleLog(exports.ILogType.info,...e)}error(...e){return this.handleLog(exports.ILogType.error,...e)}warn(...e){return this.handleLog(exports.ILogType.warn,...e)}debug(...e){ue()&&this.handleLog(exports.ILogType.debug,...e)}createLogger(e={}){return new Dr(this.ctx,e)}}const Sr=new Set([Ce]);class Nr extends i.EventEmitter{ctx;step=exports.LifecycleStep.IDLE;constructor(e){super(),this.ctx=e}async start(e,t){const i=(e=>({configPath:e.configPath,baseDir:e.baseDir,log:e.log,cmd:e.cmd,server:e.server,cloud:e.cloud,uploaderConfig:e.uploaderConfig,output:[],input:[],pluginLoader:e.pluginLoader,pluginHandler:e.pluginHandler,Request:e.Request,helper:e.helper,VERSION:e.VERSION,GUI_VERSION:e.GUI_VERSION,request:e.request,openUrl:e.openUrl.bind(e),i18n:e.i18n,getConfig:e.getConfig.bind(e),saveConfig:e.saveConfig.bind(e),removeConfig:e.removeConfig.bind(e),setConfig:e.setConfig.bind(e),unsetConfig:e.unsetConfig.bind(e),upload:e.upload.bind(e),addListener:e.addListener.bind(e),on:e.on.bind(e),once:e.once.bind(e),removeListener:e.removeListener.bind(e),off:e.off.bind(e),removeAllListeners:e.removeAllListeners.bind(e),setMaxListeners:e.setMaxListeners.bind(e),getMaxListeners:e.getMaxListeners.bind(e),listeners:e.listeners.bind(e),rawListeners:e.rawListeners.bind(e),emit:e.emit.bind(e),listenerCount:e.listenerCount.bind(e),prependListener:e.prependListener.bind(e),prependOnceListener:e.prependOnceListener.bind(e),eventNames:e.eventNames.bind(e)}))(this.ctx);this.step=exports.LifecycleStep.IDLE;try{if(!Array.isArray(e))throw new Error("Input must be an array.");return i.input=e,i.output=[],this.step=exports.LifecycleStep.BEFORE_TRANSFORM,await this.beforeTransform(i),this.step=exports.LifecycleStep.TRANSFORM,await this.doTransform(i),this.step=exports.LifecycleStep.BEFORE_UPLOAD,await this.beforeUpload(i),this.step=exports.LifecycleStep.UPLOAD,await this.doUpload(i),this.step=exports.LifecycleStep.AFTER_UPLOAD,await this.afterUpload(i,t),i}catch(e){if(this.step===exports.LifecycleStep.UPLOAD&&i.output.some(e=>void 0!==e.imgUrl))try{this.step=exports.LifecycleStep.AFTER_UPLOAD,await this.afterUpload(i,t)}catch{}if(i.log.warn(exports.IBuildInEvent.FAILED),i.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,-1),i.emit(exports.IBuildInEvent.FAILED,e),i.log.error(e),i.getConfig("debug"))throw e;return i}}async beforeTransform(e){return e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,0),e.emit(exports.IBuildInEvent.BEFORE_TRANSFORM,e),e.log.info("Before transform"),await this.handlePlugins(e.helper.beforeTransformPlugins,e),e}async doTransform(e){e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,30);const t=e.getConfig("picBed.transformer")||"path";let i=t,r=e.helper.transformer.get(t);return r||(r=e.helper.transformer.get("path"),i="path",e.log.warn(`Can't find transformer - ${t}, switch to default transformer - path`)),e.log.info(`Transforming... Current transformer is [${i}]`),await(r?.handle(e)),e}async beforeUpload(e){return e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,60),e.log.info("Before upload"),e.emit(exports.IBuildInEvent.BEFORE_UPLOAD,e),await this.handlePlugins(e.helper.beforeUploadPlugins,e),e}async doUpload(e){let t=e.getConfig("picBed.uploader")||e.getConfig("picBed.current")||Ie,i=e.helper.uploader.get(t),r=t;i||(t=Ie,r=Ie,i=e.helper.uploader.get(Ie),e.log.warn(`Can't find uploader - ${t}, switch to default uploader - ${Ie}`)),e.log.info(`Uploading... Current uploader is [${r}]`),await(i?.handle(e));for(const i of e.output)i.type=t;return e}async afterUpload(e,t){e.emit(exports.IBuildInEvent.AFTER_UPLOAD,e),e.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,100),(e=>{const t=e.getConfig("settings.urlRewrite.rules");if(Array.isArray(t)&&0!==t.length)for(const i of e.output)H(i,t,e)})(e),await this.handlePlugins(e.helper.afterUploadPlugins,e);const i=this.buildSuccessMessage(e,t);for(const t of e.output)delete t.base64Image,delete t.buffer;return e.emit(exports.IBuildInEvent.FINISHED,e),e.log.success(`\n${i}`),await this.handlePlugins(e.helper.afterFinishPlugins,e,{consoleOutput:!1}),e}buildSuccessMessage(e,t){if(t?.outputFormat===exports.OutputFormat.JSON)return JSON.stringify(e.output.map(e=>({imgUrl:e.imgUrl,origin:e.origin,fileName:e.fileName,type:e.type,contentType:e.contentType,size:e.size,width:e.width,height:e.height,extname:e.extname})));let i="";const r=e.output.length,n=!0===e.getConfig("settings.encodeOutputURL");for(let t=0;t<r;t++)void 0!==e.output[t].imgUrl&&(i+=n?K(e.output[t].imgUrl):e.output[t].imgUrl,t!==r-1&&(i+="\n"));return i}async handlePlugins(e,t,i){const r=e.getList(),n=e.getIdList(),s=e.getName();if(!1===i?.consoleOutput){const e=t.log.createLogger?.({consoleOutput:!1});e&&(t.log=e)}return await Promise.all(r.map(async(e,i)=>{try{Sr.has(n[i])||t.log.info(`${s}: ${n[i]} running`),await e.handle(t)}catch(e){throw t.log.error(`${s}: ${n[i]} error`),e}})),t}}const Tr=(e,t,i,r="")=>{const n=r||"s.ee";return{method:"POST",url:`https://${n}${"s.ee"===n?"/api/v1/file/upload":"/api/v2/upload"}`,headers:{contentType:"multipart/form-data","User-Agent":"PicGo",Authorization:i},formData:{smfile:{value:t,options:{filename:e}}}}},Ar=async e=>{const t=e.getConfig("picBed.smms");if(!t)throw new Error("Can not find smms config!");const i=e.output;for(const r of i)if(r.fileName&&r.buffer){let i=r.buffer;!i&&r.base64Image&&(i=Buffer.from(r.base64Image,"base64"));const n=Tr(r.fileName,i,t?.token,t?.backupDomain);try{const t=await e.request(n),i=JSON.parse(t);if(200!==i.code&&"success"!==i.message)throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:i.message}),new Error(i.message);delete r.base64Image,delete r.buffer,r.imgUrl=i.data.url}catch(t){throw e.log.error(t),t}}return e},yr=e=>{const t=e.getConfig("picBed.smms")||{};return[{name:"token",message:"api token",type:"password",get alias(){return e.i18n.translate("PICBED_SMMS_TOKEN")},default:t.token||"",required:!0},{name:"backupDomain",type:"input",get prefix(){return e.i18n.translate("PICBED_SMMS_BACKUP_DOMAIN")},get message(){return e.i18n.translate("PICBED_SMMS_MESSAGE_BACKUP_DOMAIN")},get alias(){return e.i18n.translate("PICBED_SMMS_BACKUP_DOMAIN")},default:t.backupDomain||"",required:!1}]};const Rr=e=>C.lookup(e)||"application/octet-stream",wr=(e,t,i,r)=>{const n=e.secretId,s=e.secretKey,o=e.appId,a=e.bucket;let c,l="";if(e.version&&"v4"!==e.version){const n=Math.floor((new Date).getTime()/1e3);l=`${n};${n+86400}`;const o=h.createHmac("sha1",s).update(l).digest("hex"),a=e.endpoint?e.endpoint:`cos.${e.area}.myqcloud.com`,p=`put\n/${e.path}${t}\n\ncontent-length=${r}&content-type=${u=i,encodeURIComponent(u).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A")}&host=${e.bucket}.${a}\n`,d=`sha1\n${l}\n${h.createHash("sha1").update(p).digest("hex")}\n`;c=h.createHmac("sha1",o).update(d).digest("hex")}else{const e=Math.floor(1e10*Math.random()),t=Math.floor((new Date).getTime()/1e3)-1,i=`a=${o}&b=${a}&k=${n}&e=${t+3600}&t=${t}&r=${e}&f=`,r=h.createHmac("sha1",s).update(i).digest(),l=Buffer.concat([r,Buffer.from(i)]);c=Buffer.from(l).toString("base64")}var u;return{signature:c,appId:o,bucket:a,signTime:l}},xr=(e,t,i,r,n)=>{const s=e.area,o=e.path;if(e.version&&"v4"!==e.version){const s=e.endpoint?e.endpoint:`cos.${e.area}.myqcloud.com`;return{method:"PUT",url:`http://${e.bucket}.${s}/${W(o,t)}`,headers:{Host:`${e.bucket}.${s}`,Authorization:`q-sign-algorithm=sha1&q-ak=${e.secretId}&q-sign-time=${i.signTime}&q-key-time=${i.signTime}&q-header-list=content-length;content-type;host&q-url-param-list=&q-signature=${i.signature}`,contentType:Rr(t),contentLength:r.byteLength,"User-Agent":`PicGo;${n};null;null`},body:r,resolveWithFullResponse:!0}}return{method:"POST",url:`http://${s}.file.myqcloud.com/files/v2/${i.appId}/${i.bucket}/${W(o,t)}`,headers:{Host:`${s}.file.myqcloud.com`,Authorization:i.signature,contentType:"multipart/form-data","User-Agent":`PicGo;${n};null;null`},formData:{op:"upload",filecontent:r},resolveWithFullResponse:!0}},br=async e=>{const t=e.getConfig("picBed.tcyun");if(!t)throw new Error("Can't find tencent COS config");try{const i=e.output,r=t.customUrl,n=t.path,s=!t.version||"v4"===t.version;for(const o of i)if(o.fileName&&o.buffer){let i=o.buffer;!i&&o.base64Image&&(i=Buffer.from(o.base64Image,"base64"));const a=wr(t,o.fileName,Rr(o.fileName),i.byteLength);if(!a)return!1;const c=xr(t,o.fileName,a,i,e.GUI_VERSION||e.VERSION),l=await e.request(c).then(e=>e).catch(t=>({statusCode:400,body:{msg:e.i18n.translate("AUTH_FAILED"),err:t}}));let u;if(u=s&&"string"==typeof l?JSON.parse(l):l,400===u.statusCode)throw u?.body?.err?u.body.err:new Error(u?.body?.msg||u?.body?.message);const p=t.options||"",d=t.slim||"";if(s&&"SUCCESS"===u.message)delete o.base64Image,delete o.buffer,o.imgUrl=r?`${r}/${n}${o.fileName}`:`${u.data.source_url}${p}`;else{if(s||!u||200!==u.statusCode)throw new Error(l.body.msg);if(delete o.base64Image,delete o.buffer,r)o.imgUrl=`${r}/${encodeURI(n)}${W(o.fileName)}${p}`;else{const e=t.endpoint?t.endpoint:`cos.${t.area}.myqcloud.com`;o.imgUrl=`https://${t.bucket}.${e}/${encodeURI(n)}${W(o.fileName)}${p}`}}d&&(o.imgUrl+=p?"&imageSlim":"?imageSlim")}return e}catch(i){if(!t.version||"v4"===t.version)try{const t=JSON.parse(i.error);e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("UPLOAD_FAILED_REASON",{code:t.code}),text:"https://cloud.tencent.com/document/product/436/8432"})}catch(e){}throw i}},Mr=e=>{const t=e.getConfig("picBed.tcyun")||{};return[{name:"version",type:"list",alias:e.i18n.translate("PICBED_TENCENTCLOUD_VERSION"),choices:["v4","v5"],default:"v5",required:!1},{name:"secretId",type:"input",get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_SECRETID")},default:t.secretId||"",required:!0},{name:"secretKey",type:"password",get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_SECRETKEY")},default:t.secretKey||"",required:!0},{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_BUCKET")},default:t.bucket||"",required:!0},{name:"appId",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_APPID")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_APPID")},default:t.appId||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_APPID")},required:!0},{name:"area",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_AREA")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_AREA")},default:t.area||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_AREA")},required:!0},{name:"endpoint",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_ENDPOINT")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_ENDPOINT")},default:t.endpoint||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT")},required:!1},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_PATH")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_PATH")},default:t.path||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_PATH")},required:!1},{name:"customUrl",type:"input",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_CUSTOMURL")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_CUSTOMURL")},default:t.customUrl||"",get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL")},required:!1},{name:"options",type:"input",default:t.options||"",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_OPTIONS")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_OPTIONS")},get message(){return e.i18n.translate("PICBED_TENCENTCLOUD_MESSAGE_OPTIONS")},required:!1},{name:"slim",type:"confirm",default:t.options||"",get prefix(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM")},get alias(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM")},required:!1,get confirmText(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM_CONFIRM")},get cancelText(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM_CANCEL")},get tips(){return e.i18n.translate("PICBED_TENCENTCLOUD_SLIM_TIP")}}]};const Br=(e,t,i)=>{const r=t.path||"",{token:n,repo:s}=t;return{method:"PUT",url:`https://api.github.com/repos/${s}/contents/${W(r,e)}`,headers:{Authorization:`token ${n}`,"User-Agent":"PicGo","Content-Type":C.lookup(e)},body:i,json:!0}},vr=async e=>{const t=e.getConfig("picBed.github");if(!t)throw new Error("Can't find github config");try{const i=e.output;for(const r of i)if(r.fileName&&r.buffer){const i=r.base64Image||Buffer.from(r.buffer).toString("base64"),n={message:"Upload by PicGo",branch:t.branch,content:i,path:t.path+encodeURI(r.fileName)},s=Br(r.fileName,t,n);try{const i=await e.request(s);if(!i)throw new Error("Server error, please try again");delete r.base64Image,delete r.buffer,t.customUrl?r.imgUrl=`${t.customUrl}/${W(t.path||"",r.fileName)}`:r.imgUrl=i.content.download_url}catch(e){if(422!==e.statusCode)throw e;delete r.base64Image,delete r.buffer,t.customUrl?r.imgUrl=`${t.customUrl}/${W(t.path||"",r.fileName)}`:r.imgUrl=`https://raw.githubusercontent.com/${t.repo}/${t.branch}/${W(t.path||"",r.fileName)}`}}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK")}),t}},Gr=e=>{const t=e.getConfig("picBed.github")||{};return[{name:"repo",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_REPO")},get alias(){return e.i18n.translate("PICBED_GITHUB_REPO")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_REPO")},default:t.repo||"",required:!0},{name:"branch",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_BRANCH")},get alias(){return e.i18n.translate("PICBED_GITHUB_BRANCH")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_BRANCH")},default:t.branch||"master",required:!0},{name:"token",type:"password",get alias(){return e.i18n.translate("PICBED_GITHUB_TOKEN")},default:t.token||"",required:!0},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_PATH")},get alias(){return e.i18n.translate("PICBED_GITHUB_PATH")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_PATH")},default:t.path||"",required:!1},{name:"customUrl",type:"input",get prefix(){return e.i18n.translate("PICBED_GITHUB_CUSTOMURL")},get alias(){return e.i18n.translate("PICBED_GITHUB_CUSTOMURL")},get message(){return e.i18n.translate("PICBED_GITHUB_MESSAGE_CUSTOMURL")},default:t.customUrl||"",required:!1}]};function $r(e,t,i,r){const n=function(e){return"z0"===e?"":"-"+e}(e.area||"z0"),s=e.path||"";return{method:"POST",url:`http://upload${n}.qiniup.com/putb64/-1/key/${Buffer.from(s+t,"utf-8").toString("base64").replace(/\+/g,"-").replace(/\//g,"_")}`,headers:{Authorization:`UpToken ${i}`,"Content-Type":C.lookup(t)||"application/octet-stream"},body:r}}function Fr(e){return e.replace(/\//g,"_").replace(/\+/g,"-")}function kr(e){const t=e.accessKey,i=e.secretKey,r={scope:e.bucket,deadline:3600+Math.floor(Date.now()/1e3)},n=(s=JSON.stringify(r),Fr(Buffer.from(s).toString("base64")));var s;const o=Fr(function(e,t){const i=g.createHmac("sha1",t);return i.update(e),i.digest("base64")}(n,i));return[t,o,n].join(":")}const Hr=async e=>{const t=e.getConfig("picBed.qiniu");if(!t)throw new Error("Can't find qiniu config");try{const i=e.output;for(const r of i)if(r.fileName&&r.buffer){const i=r.base64Image||Buffer.from(r.buffer).toString("base64"),n=$r(t,r.fileName,kr(t),i),s=await e.request(n),o=JSON.parse(s);if(!o?.key)throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:o.msg}),e.log.error("qiniu error",o),new Error("Upload failed");{delete r.base64Image,delete r.buffer;const e=t.url,i=t.options;r.imgUrl=`${e}/${o.key}${i}`}}return e}catch(t){if("Upload failed"!==t.message&&t.response){const i=t.response.body;e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:i.error})}throw t}},Yr=e=>{const t=e.getConfig("picBed.qiniu")||{};return[{name:"accessKey",type:"input",get alias(){return e.i18n.translate("PICBED_QINIU_ACCESSKEY")},default:t.accessKey||"",required:!0},{name:"secretKey",type:"password",get alias(){return e.i18n.translate("PICBED_QINIU_SECRETKEY")},default:t.secretKey||"",required:!0},{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_QINIU_BUCKET")},default:t.bucket||"",required:!0},{name:"url",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_URL")},get alias(){return e.i18n.translate("PICBED_QINIU_URL")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_URL")},default:t.url||"",required:!0},{name:"area",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_AREA")},get alias(){return e.i18n.translate("PICBED_QINIU_AREA")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_AREA")},default:t.area||"",required:!0},{name:"options",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_OPTIONS")},get alias(){return e.i18n.translate("PICBED_QINIU_OPTIONS")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_OPTIONS")},default:t.options||"",required:!1},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_QINIU_PATH")},get alias(){return e.i18n.translate("PICBED_QINIU_PATH")},get message(){return e.i18n.translate("PICBED_QINIU_MESSAGE_PATH")},default:t.path||"",required:!1}]};const Vr=(e,t,i)=>{const r={method:"POST",url:"https://api.imgur.com/3/image",headers:{Authorization:`Client-ID ${e.clientId}`,"content-type":"multipart/form-data",Host:"api.imgur.com","User-Agent":"PicGo"},formData:{image:i,type:"base64",name:t}};return e.proxy&&(r.proxy=e.proxy),r},qr=async e=>{const t=e.getConfig("picBed.imgur");if(!t)throw new Error("Can't find imgur config");try{const i=e.output;for(const r of i)if(r.fileName&&r.buffer){const i=r.base64Image||Buffer.from(r.buffer).toString("base64"),n=Vr(t,r.fileName,i),s=await e.request(n),o="string"==typeof s?JSON.parse(s):s;if(!o.success)throw new Error("Server error, please try again");delete r.base64Image,delete r.buffer,r.imgUrl=o.data.link}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS_AND_NETWORK"),text:"http://docs.imgur.com/api/errno/"}),t?.response?.data||t}},jr=e=>{const t=e.getConfig("picBed.imgur")||{};return[{name:"clientId",type:"input",get alias(){return e.i18n.translate("PICBED_IMGUR_CLIENTID")},default:t.clientId||"",required:!0},{name:"proxy",type:"input",get prefix(){return e.i18n.translate("PICBED_IMGUR_PROXY")},get alias(){return e.i18n.translate("PICBED_IMGUR_PROXY")},get message(){return e.i18n.translate("PICBED_IMGUR_MESSAGE_PROXY")},default:t.proxy||"",required:!1}]};const Kr=(e,t)=>{const i=(new Date).toUTCString(),r=C.lookup(t);if(!r)throw Error(`No mime type found for file ${t}`);const n=`PUT\n\n${r}\n${i}\n/${e.bucket}/${e.path}${t}`,s=h.createHmac("sha1",e.accessKeySecret).update(n).digest("base64");return`OSS ${e.accessKeyId}:${s}`},Wr=(e,t,i,r)=>{const n=e.path||"";return{method:"PUT",url:`https://${e.bucket}.${e.area}.aliyuncs.com/${W(n,t)}`,headers:{Host:`${e.bucket}.${e.area}.aliyuncs.com`,Authorization:i,Date:(new Date).toUTCString(),"Content-Type":C.lookup(t)},body:r,resolveWithFullResponse:!0}},Qr=async e=>{const t=e.getConfig("picBed.aliyun");if(!t)throw new Error("Can't find aliYun OSS config");try{const i=e.output,r=t.customUrl,n=t.path||"";for(const s of i)if(s.fileName&&s.buffer){const i=Kr(t,s.fileName);let o=s.buffer;!o&&s.base64Image&&(o=Buffer.from(s.base64Image,"base64"));const a=Wr(t,s.fileName,i,o);if(200!==(await e.request(a)).statusCode)throw new Error("Upload failed");{delete s.base64Image,delete s.buffer;const e=t.options||"";s.imgUrl=r?`${r}/${W(n,s.fileName)}${e}`:`https://${t.bucket}.${t.area}.aliyuncs.com/${W(n,s.fileName)}${e}`}}return e}catch(t){throw e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")}),t}},zr=e=>{const t=e.getConfig("picBed.aliyun")||{};return[{name:"accessKeyId",type:"input",get alias(){return e.i18n.translate("PICBED_ALICLOUD_ACCESSKEYID")},default:t.accessKeyId||"",required:!0},{name:"accessKeySecret",type:"password",get alias(){return e.i18n.translate("PICBED_ALICLOUD_ACCESSKEYSECRET")},default:t.accessKeySecret||"",required:!0},{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_ALICLOUD_BUCKET")},default:t.bucket||"",required:!0},{name:"area",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_AREA")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_AREA")},default:t.area||"",get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_AREA")},required:!0},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_PATH")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_PATH")},get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_PATH")},default:t.path||"",required:!1},{name:"customUrl",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_CUSTOMURL")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_CUSTOMURL")},get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_CUSTOMURL")},default:t.customUrl||"",required:!1},{name:"options",type:"input",get prefix(){return e.i18n.translate("PICBED_ALICLOUD_OPTIONS")},get alias(){return e.i18n.translate("PICBED_ALICLOUD_OPTIONS")},get message(){return e.i18n.translate("PICBED_ALICLOUD_MESSAGE_OPTIONS")},default:t.options||"",required:!1}]};const Jr=(e,t)=>{const i=e.path||"",r=e.operator,n=e.password,s=L(n),o=(new Date).toUTCString(),a=`PUT&${`/${e.bucket}/${W(i,t)}`}&${o}`;return`UPYUN ${r}:${h.createHmac("sha1",s).update(a).digest("base64")}`},Xr=(e,t,i,r)=>{const n=e.bucket,s=e.path||"";return{method:"PUT",url:`https://v0.api.upyun.com/${n}/${W(s,t)}`,headers:{Authorization:i,Date:(new Date).toUTCString(),"Content-Type":C.lookup(t)||"application/octet-stream"},body:r,resolveWithFullResponse:!0}},Zr=async e=>{const t=e.getConfig("picBed.upyun");if(!t)throw new Error("Can't find upYun config");try{const i=e.output,r=t.path||"";for(const n of i)if(n.fileName&&n.buffer){let i=n.buffer;!i&&n.base64Image&&(i=Buffer.from(n.base64Image,"base64"));const s=Jr(t,n.fileName),o=Xr(t,n.fileName,s,i);if(200!==(await e.request(o)).statusCode)throw new Error("Upload failed");delete n.base64Image,delete n.buffer,n.imgUrl=`${t.url}/${W(r,n.fileName)}${t.options}`}return e}catch(t){if("Upload failed"===t.message)e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("CHECK_SETTINGS")});else{const i=ce(t.error);e.emit(exports.IBuildInEvent.NOTIFICATION,{title:e.i18n.translate("UPLOAD_FAILED"),body:e.i18n.translate("UPLOAD_FAILED_REASON",{code:"object"==typeof i?i.code:i}),text:"http://docs.upyun.com/api/errno/"})}throw t}},en=e=>{const t=e.getConfig("picBed.upyun")||{};return[{name:"bucket",type:"input",get alias(){return e.i18n.translate("PICBED_UPYUN_BUCKET")},default:t.bucket||"",required:!0},{name:"operator",type:"input",get alias(){return e.i18n.translate("PICBED_UPYUN_OPERATOR")},get prefix(){return e.i18n.translate("PICBED_UPYUN_OPERATOR")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_OPERATOR")},default:t.operator||"",required:!0},{name:"password",type:"password",get prefix(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_PASSWORD")},get alias(){return e.i18n.translate("PICBED_UPYUN_PASSWORD")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_PASSWORD")},default:t.password||"",required:!0},{name:"url",type:"input",get alias(){return e.i18n.translate("PICBED_UPYUN_URL")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_URL")},default:t.url||"",required:!0},{name:"options",type:"input",get prefix(){return e.i18n.translate("PICBED_UPYUN_OPTIONS")},get alias(){return e.i18n.translate("PICBED_UPYUN_OPTIONS")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_OPTIONS")},default:t.options||"",required:!1},{name:"path",type:"input",get prefix(){return e.i18n.translate("PICBED_UPYUN_PATH")},get alias(){return e.i18n.translate("PICBED_UPYUN_PATH")},get message(){return e.i18n.translate("PICBED_UPYUN_MESSAGE_PATH")},default:t.path||"",required:!1}]};const tn=(e,t)=>`${e}:${t}`,rn=e=>{const t=e.indexOf(":");return-1===t?null:{userId:e.slice(0,t),fingerprint:e.slice(t+1)}};class nn{ctx;constructor(e){this.ctx=e}get(e,t){return this.read().sessions[tn(e,t)]??null}set(e,t,i){const r=this.read();r.sessions[tn(e,t)]=i,this.write(r)}remove(e,t){const i=this.read(),r=tn(e,t);r in i.sessions&&(delete i.sessions[r],this.write(i))}appendCompletedPart(e,t,i){const r=this.read(),n=tn(e,t),s=r.sessions[n];if(!s)return;const o=[...s.completedParts.filter(e=>e.partNumber!==i.partNumber),i];r.sessions[n]={...s,completedParts:o},this.write(r)}sweepExpired(e=Date.now()){const t=this.read();let i=!1;for(const[r,n]of Object.entries(t.sessions))e-n.createdAt>6048e5&&(delete t.sessions[r],i=!0);i&&this.write(t)}listForUser(e){const t=this.read(),i=`${e}:`,r=[];for(const[e,n]of Object.entries(t.sessions)){if(!e.startsWith(i))continue;const t=rn(e);t&&r.push({fingerprint:t.fingerprint,session:n})}return r}getFilePath(){return O.join(this.ctx.baseDir,"picgo-cloud-multipart-pending.json")}read(){const e=this.getFilePath();if(!U.existsSync(e))return{v:1,sessions:{}};try{const t=U.readFileSync(e,"utf8"),i=JSON.parse(t);return(e=>{if("object"!=typeof e||null===e)return!1;const t=e.v,i=e.sessions;return 1===t&&"object"==typeof i&&null!==i})(i)?i:{v:1,sessions:{}}}catch{return{v:1,sessions:{}}}}write(e){const t=this.getFilePath();try{P.sync(t,JSON.stringify(e,null,2)+"\n")}catch{}}}const sn=[1e3,2e3,4e3];class on extends Error{status;constructor(e,t){super(e),this.name="PartHttpError",this.status=t}}const an=(e,t)=>new Promise((i,r)=>{const n=setTimeout(()=>{t.removeEventListener("abort",s),i()},e),s=()=>{clearTimeout(n),r(new Error("Aborted"))};t.addEventListener("abort",s,{once:!0})}),cn=e=>g.createHash("sha1").update(e).digest("hex").slice(0,16),ln=e=>{const t=new Map;for(const i of e)t.set(i.partNumber,i);return t};class un{ctx;authClient;storage;diagLogger;constructor(e){this.ctx=e,this.authClient=new Kt(e),this.storage=new nn(e),this.diagLogger=e.log.createLogger?.({consoleOutput:!1,respectSilent:!1})}async abort(e,t){const i=this.ctx.getConfig("settings.picgoCloud.token")?.trim();if(i)try{await this.authClient.request({method:"POST",url:"/api/upload/multipart/abort",data:{uploadId:e,objectKey:t}},i)}catch(t){this.diagLogger?.warn(`[multipart-abort] failed for ${e}: ${qt(t)}`)}}listPending(){const e=this.ctx.getConfig("settings.picgoCloud.token")?.trim();if(!e)return[];const t=cn(e);return this.storage.listForUser(t).map(e=>e.session)}removePending(e){const t=this.ctx.getConfig("settings.picgoCloud.token")?.trim();if(!t)return;const i=cn(t);this.storage.remove(i,e)}getInternals(){return{ctx:this.ctx,authClient:this.authClient,storage:this.storage,diagLogger:this.diagLogger}}}async function pn(e,t){const i=e.getConfig("settings.picgoCloud.token")?.trim();if(!i)throw new Error(e.i18n.translate("PICGO_CLOUD_UPLOAD_LOGIN_REQUIRED"));const r=t.fileName?.trim();if(!r)throw new Error(e.i18n.translate("PICGO_CLOUD_UPLOAD_MISSING_FILE_NAME"));let n;try{n=(e=>{if(e.buffer)return e.buffer;if(e.base64Image)return Buffer.from(e.base64Image,"base64");throw new Error("missing-file-data")})(t)}catch{throw new Error(e.i18n.translate("PICGO_CLOUD_UPLOAD_MISSING_FILE_DATA"))}const s=((e,t)=>{const i=e.contentType?.trim()||e.mimeType?.trim();if(i)return i;const r=C.lookup(t);return"string"==typeof r?r:"application/octet-stream"})(t,r),o=cn(i),a=(e=>g.createHash("sha1").update(e).digest("hex"))(n),c=e.cloud.uploader,{authClient:l,storage:u,diagLogger:p}=c.getInternals();u.sweepExpired();const d=u.get(o,a),_=null!==d;let h,f;if(_)h=d,p?.info(`[multipart] resuming ${r}: ${h.completedParts.length}/${h.partCount} parts done`),f=await fn(e,l,i,h,p);else{const t=await hn(e,l,i,n.length,r,s,p);h=t.session,f=t.partUrls,u.set(o,a,h)}const E=await In({state:h,userId:o,fingerprint:a,fileName:r,buffer:n,partUrls:f,completed:new Map(h.completedParts.map(e=>[e.partNumber,e])),emitProgress:t=>gn(e,r,h,dn(h),t),refreshUrls:()=>mn(e,l,i,h,f,p),diagLogger:p,internalAbort:new AbortController,authClient:l,ctx:e,token:i,resumed:_});h.completedParts=[...E.values()];const m=await On(e,l,i,h,r,t,p);return u.remove(o,a),m}const dn=e=>e.completedParts,_n=(e,t,i)=>{const r=qt(i,"").trim();return""!==r?r:e.i18n.translate(t)},gn=(e,t,i,r,n)=>{const s=r.reduce((e,t)=>{const r=(t.partNumber-1)*i.partSize;return e+(Math.min(r+i.partSize,i.size)-r)},0),o=i.size>0?Math.min(s/i.size,1):0,a={fileName:t,current:s,total:i.size,fraction:o,partsCompleted:r.length,totalParts:i.partCount,resumed:n};e.emit(exports.IBuildInEvent.FILE_UPLOAD_PROGRESS,a)},hn=async(e,t,i,r,n,s,o)=>{try{const o=await t.request({method:"POST",url:"/api/upload/multipart/initiate",data:{filename:n,contentType:s,sizeBytes:r}},i);if(!(o.success&&o.uploadId&&o.objectKey&&o.publicId&&o.url&&o.partSize&&o.partCount&&o.parts))throw new Error(o.message||e.i18n.translate("PICGO_CLOUD_UPLOAD_INVALID_INITIATE_RESPONSE"));return{session:{v:1,uploadId:o.uploadId,objectKey:o.objectKey,publicId:o.publicId,url:o.url,filename:n,size:r,contentType:s,partSize:o.partSize,partCount:o.partCount,completedParts:[],createdAt:Date.now()},partUrls:ln(o.parts)}}catch(t){throw Un(e,t),o?.error(`[multipart-initiate] status=${Yt(t)??"?"} code=${Vt(t)??"-"} server="${qt(t)}"`),jt(_n(e,"PICGO_CLOUD_UPLOAD_INVALID_INITIATE_RESPONSE",t),t)}},fn=async(e,t,i,r,n)=>{const s=new Set(r.completedParts.map(e=>e.partNumber)),o=[];for(let e=1;e<=r.partCount;e++)s.has(e)||o.push(e);return 0===o.length?new Map:En(e,t,i,r,o,n)},En=async(e,t,i,r,n,s)=>{try{const e=await t.request({method:"POST",url:"/api/upload/multipart/part-urls",data:{uploadId:r.uploadId,objectKey:r.objectKey,partNumbers:n}},i);if(!e.success||!e.parts)throw new Error(e.message||"invalid part-urls response");return ln(e.parts)}catch(t){throw Un(e,t),s?.error(`[multipart-part-urls] status=${Yt(t)??"?"} code=${Vt(t)??"-"} server="${qt(t)}"`),jt(_n(e,"PICGO_CLOUD_UPLOAD_MULTIPART_PART_FAILED",t),t)}},mn=async(e,t,i,r,n,s)=>{const o=new Set(r.completedParts.map(e=>e.partNumber)),a=[];for(let e=1;e<=r.partCount;e++)o.has(e)||a.push(e);const c=await En(e,t,i,r,a,s);for(const[e,t]of c)n.set(e,t)},In=async e=>{const{state:t,userId:i,fingerprint:r,buffer:n,partUrls:s,completed:o,diagLogger:a,internalAbort:c,ctx:l,resumed:u}=e,p=new Set(o.keys()),d=[];for(let e=1;e<=t.partCount;e++)p.has(e)||d.push(e);if(gn(l,e.fileName,t,[...o.values()],u),0===d.length)return o;let _=null;const g=async()=>{if(_)await _;else{_=e.refreshUrls();try{await _}finally{_=null}}},h={value:null},f=async d=>{const _=(d-1)*t.partSize,h=Math.min(_+t.partSize,t.size),f=n.subarray(_,h);for(let n=0;n<=sn.length;n++){if(c.signal.aborted)throw new Error("Aborted");const _=s.get(d);if(!_)throw new Error(`missing presign for part ${d}`);try{const n=await Ln(l,_,f,d),s={partNumber:d,etag:n};o.set(d,s),p.add(d),e.diagLogger?.info(`[multipart] part ${d} done etag=${n}`);return e.ctx.cloud.uploader.getInternals().storage.appendCompletedPart(i,r,s),void gn(l,e.fileName,t,[...o.values()],u)}catch(s){if(c.signal.aborted)throw s;if(s instanceof on&&403===s.status){a?.info(`[multipart] part ${d} presign expired (403), refreshing`),await g();continue}if(s instanceof on&&404===s.status){a?.warn(`[multipart] session ${t.uploadId} not found on server (404); clearing local entry`);throw e.ctx.cloud.uploader.getInternals().storage.remove(i,r),jt(l.i18n.translate("PICGO_CLOUD_UPLOAD_MULTIPART_NOT_FOUND"),s)}if(a?.warn(`[multipart] part ${d} attempt ${n} failed: ${Yt(s)??"?"} ${qt(s)}`),n<sn.length){try{await an(sn[n],c.signal)}catch{throw s}continue}throw a?.error(`[multipart-part] part ${d} failed after retries: status=${Yt(s)??"?"} server="${qt(s)}"`),jt(l.i18n.translate("PICGO_CLOUD_UPLOAD_MULTIPART_PART_FAILED"),s)}}throw jt(l.i18n.translate("PICGO_CLOUD_UPLOAD_MULTIPART_PART_FAILED"),new Error("exhausted attempts"))},E=[],m=Math.min(3,d.length);for(let e=0;e<m;e++)E.push((async()=>{for(;d.length>0;){if(c.signal.aborted)return;const e=d.shift();if(void 0===e)return;try{await f(e)}catch(e){return null!==h.value||Cn(e)||(h.value=e instanceof Error?e:new Error(String(e))),void c.abort()}}})());await Promise.all(E);const I=h.value;if(null!==I)throw I;return o},Cn=e=>e instanceof Error&&"Aborted"===e.message,Ln=async(e,t,i,r)=>{try{const n={method:t.method,url:t.url,data:i,headers:t.headers??{},resolveWithFullResponse:!0,maxContentLength:1/0,maxBodyLength:1/0},s=(await e.request(n)).headers??{},o=s.etag??s.ETag??s.Etag;if(!o)throw new Error(`part ${r} response missing ETag header`);return o}catch(e){const t=Yt(e);if("number"==typeof t)throw new on(`part ${r} HTTP ${t}`,t);throw e}},On=async(e,t,i,r,n,s,o)=>{if(r.completedParts.length!==r.partCount)throw jt(e.i18n.translate("PICGO_CLOUD_UPLOAD_MULTIPART_COMPLETE_FAILED"),new Error("part count mismatch at complete"));const a=[...r.completedParts].sort((e,t)=>e.partNumber-t.partNumber);try{await t.request({method:"POST",url:"/api/upload/multipart/complete",data:{uploadId:r.uploadId,objectKey:r.objectKey,parts:a}},i)}catch(t){throw Un(e,t),o?.error(`[multipart-complete] status=${Yt(t)??"?"} code=${Vt(t)??"-"} server="${qt(t)}"`),jt(_n(e,"PICGO_CLOUD_UPLOAD_MULTIPART_COMPLETE_FAILED",t),t)}try{const e=await t.request({method:"POST",url:"/api/album-items/complete",data:{objectKey:r.objectKey,publicId:r.publicId,filename:n,..."number"==typeof s.width?{width:s.width}:{},..."number"==typeof s.height?{height:s.height}:{}}},i),o=e.data?.item,a=o?.imgUrl;if(!e.success||"string"!=typeof a||0===a.length)throw new Error(e.message||"invalid album-items complete response");return{imgUrl:a,..."number"==typeof o?.width?{width:o.width}:{},..."number"==typeof o?.height?{height:o.height}:{},..."number"==typeof o?.size?{size:o.size}:{},..."string"==typeof o?.contentType?{contentType:o.contentType}:{}}}catch(t){throw Un(e,t),o?.error(`[album-items-complete] status=${Yt(t)??"?"} code=${Vt(t)??"-"} server="${qt(t)}"`),jt(_n(e,"PICGO_CLOUD_UPLOAD_INVALID_COMPLETE_RESPONSE",t),t)}},Un=(e,t)=>{if(!_.isAxiosError(t))return;if(401===Yt(t))throw e.removeConfig("settings.picgoCloud","token"),jt(e.i18n.translate("PICGO_CLOUD_UPLOAD_RELOGIN_REQUIRED"),t)};class Pn{ctx;client;constructor(e){this.ctx=e,this.client=new Kt(e)}async upload(e){const t=this.getToken(),i=this.getFileName(e),r=this.getImageBuffer(e),n=this.getContentType(e,i);if(r.length>=10485760)return await pn(this.ctx,e);const s=Date.now(),o=await this.callAuthenticatedStep(async()=>await this.client.request({method:"POST",url:"/api/upload/presign",data:{filename:i,...n?{contentType:n}:{}}},t));if(this.ctx.log.debug("Presign duration",Date.now()-s,"ms"),!(o.success&&o.objectKey&&o.publicId&&o.uploadUrl))throw new Error(o.message||this.ctx.i18n.translate("PICGO_CLOUD_UPLOAD_INVALID_PRESIGN_RESPONSE"));const a=this.buildUploadHeaders(o.headers,n),c=Date.now();await async function(e,t,i){const r=t.onUploadProgress,n=i.partsCompleted??-1,s=i.totalParts??-1,o=i.resumed??!1,a={...t,onUploadProgress:t=>{r?.(t);const a=("number"==typeof t.total?t.total:void 0)??i.totalBytes??0,c=t.loaded,l=a>0?Math.min(c/a,1):0,u={fileName:i.fileName,current:c,total:a,fraction:l,partsCompleted:n,totalParts:s,resumed:o};e.emit(exports.IBuildInEvent.FILE_UPLOAD_PROGRESS,u)}};return e.request(a)}(this.ctx,{method:"PUT",url:o.uploadUrl,data:r,headers:a,resolveWithFullResponse:!0},{fileName:i,totalBytes:r.length}),this.ctx.log.debug("Upload duration",Date.now()-c,"ms");const l=Date.now(),u=await this.callAuthenticatedStep(async()=>await this.client.request({method:"POST",url:"/api/album-items/complete",data:{objectKey:o.objectKey,publicId:o.publicId,filename:i,..."number"==typeof e.width?{width:e.width}:{},..."number"==typeof e.height?{height:e.height}:{}}},t)),p=Date.now();this.ctx.log.debug("Complete duration",p-l,"ms"),this.ctx.log.debug("All duration",p-s,"ms");const d=u.data?.item,_=d?.imgUrl;if(!u.success||"string"!=typeof _||0===_.length)throw new Error(u.message||this.ctx.i18n.translate("PICGO_CLOUD_UPLOAD_INVALID_COMPLETE_RESPONSE"));return{imgUrl:_,..."number"==typeof d?.width?{width:d.width}:{},..."number"==typeof d?.height?{height:d.height}:{},..."number"==typeof d?.size?{size:d.size}:{},..."string"==typeof d?.contentType?{contentType:d.contentType}:{}}}getToken(){const e=this.ctx.getConfig("settings.picgoCloud.token")?.trim();if(!e)throw new Error(this.ctx.i18n.translate("PICGO_CLOUD_UPLOAD_LOGIN_REQUIRED"));return e}getFileName(e){const t=e.fileName?.trim();if(!t)throw new Error(this.ctx.i18n.translate("PICGO_CLOUD_UPLOAD_MISSING_FILE_NAME"));return t}getImageBuffer(e){if(e.buffer)return e.buffer;if(e.base64Image)return Buffer.from(e.base64Image,"base64");throw new Error(this.ctx.i18n.translate("PICGO_CLOUD_UPLOAD_MISSING_FILE_DATA"))}getContentType(e,t){const i=e.contentType?.trim()||e.mimeType?.trim();if(i)return i;const r=C.lookup(t);return"string"==typeof r?r:void 0}buildUploadHeaders(e,t){const i={...e||{}};if(!t)return i;return Object.keys(i).some(e=>"content-type"===e.toLowerCase())||(i["Content-Type"]=t),i}async callAuthenticatedStep(e){try{return await e()}catch(e){if(_.isAxiosError(e)){if(401===Yt(e))throw this.ctx.removeConfig("settings.picgoCloud","token"),jt(this.ctx.i18n.translate("PICGO_CLOUD_UPLOAD_RELOGIN_REQUIRED"),e);const t=qt(e);if(""!==t.trim())throw jt(t,e)}throw e}}}const Dn=e=>O.join(e.baseDir,"picgo-cloud-import-list.log"),Sn=e=>({total:e.total,created:e.created,skipped:e.skipped,invalid:e.invalid,failed:e.failed,pending:e.pending}),Nn=async(e,t)=>{const i={...t,source:"upload",timestamp:(new Date).toISOString()},r=e.log.createLogger?.({logPath:Dn(e),consoleOutput:!1,respectSilent:!1});r?.info(JSON.stringify(i))},Tn=()=>[],An=async e=>{const t=new Pn(e);for(const i of e.output)try{const e=await t.upload(i);delete i.base64Image,delete i.buffer,i.imgUrl=e.imgUrl,void 0!==e.width&&(i.width=e.width),void 0!==e.height&&(i.height=e.height),void 0!==e.size&&(i.size=e.size),void 0!==e.contentType&&(i.contentType=e.contentType)}catch(t){if(t instanceof Error)throw e.log.error(t),t;throw new Error(e.i18n.translate("UPLOAD_FAILED"))}return e},yn=e=>{const t="string"==typeof e.GUI_VERSION&&""!==e.GUI_VERSION.trim(),i=!0===e.getConfig("picgoInternal.serverMode");return t||i},Rn=async e=>{const t=e.getConfig("settings.picgoCloud.token")?.trim(),i=e.output.filter(e=>e.type!==Ie);if(!t||0===i.length)return(e=>e.some(e=>e.type===Ie))(e.output)&&e.emit(exports.IBuildInEvent.CLOUD_ALBUM_UPDATED,{items:[]}),void await Nn(e,{status:"skipped",itemCount:i.length,reason:t?"no_eligible_items":"missing_token"});try{const t=await e.cloud.getUserInfo();if(!$t(t))return void await Nn(e,{status:"skipped",itemCount:i.length,reason:"plan_required"});if(!t?.autoImport)return void await Nn(e,{status:"skipped",itemCount:i.length,reason:"auto_import_disabled"});(e=>{for(const t of e)"string"==typeof t.id&&""!==t.id.trim()||(t.id=g.randomUUID())})(i);const r=await e.cloud.album.import(i);if(r.failed>0)return await Nn(e,{status:"partial",itemCount:i.length,result:Sn(r)}),void e.emit(exports.IBuildInEvent.CLOUD_ALBUM_UPDATED,{items:r.items});const n=await e.cloud.album.retryPending();await Nn(e,{status:"success",itemCount:i.length,result:Sn(r),retryPending:Sn(n)});const s=[...r.items,...n.items];e.emit(exports.IBuildInEvent.CLOUD_ALBUM_UPDATED,{items:s})}catch(t){const r=qt(t),n=Yt(t),s=Vt(t);if(!(401===n||403===n||s===xt.DuplicateId))try{await e.cloud.album.addToPending(i)}catch{}await Nn(e,{status:"failed",itemCount:i.length,error:{message:r,..."number"==typeof n?{status:n}:{},..."string"==typeof s?{code:s}:{}}})}},wn=e=>{(e=>{const t=e.getConfig("settings.picgoCloud.token")?.trim();t&&e.cloud.getUserInfo().catch(()=>{})})(e)},xn=e=>{yn(e)&&setImmediate(()=>{(()=>Rn(e))().catch(()=>{})})},bn=async e=>{yn(e)||await Rn(e)};const Mn=()=>({register(e){!function(e){e.helper.uploader.register("aliyun",{get name(){return e.i18n.translate("PICBED_ALICLOUD")},handle:Qr,config:zr})}(e),function(e){e.helper.uploader.register("tcyun",{get name(){return e.i18n.translate("PICBED_TENCENTCLOUD")},handle:br,config:Mr})}(e),function(e){e.helper.uploader.register("smms",{get name(){return e.i18n.translate("PICBED_SMMS")},handle:Ar,config:yr})}(e),function(e){e.helper.uploader.register("github",{get name(){return e.i18n.translate("PICBED_GITHUB")},handle:vr,config:Gr})}(e),function(e){e.helper.uploader.register("qiniu",{get name(){return e.i18n.translate("PICBED_QINIU")},handle:Hr,config:Yr})}(e),function(e){e.helper.uploader.register("imgur",{get name(){return e.i18n.translate("PICBED_IMGUR")},handle:qr,config:jr})}(e),function(e){e.helper.uploader.register("upyun",{get name(){return e.i18n.translate("PICBED_UPYUN")},handle:Zr,config:en})}(e),function(e){e.helper.uploader.register(Ie,{name:"PicGo Cloud",handle:An,config:Tn}),e.on(exports.IBuildInEvent.BEFORE_UPLOAD,wn),e.on(exports.IBuildInEvent.AFTER_UPLOAD,xn),e.helper.afterFinishPlugins.register(Ce,{handle:bn})}(e)}}),Bn=(e,t,i)=>{const r=Q(t);return r.real||("string"==typeof i?e.log.warn(`can't get ${i}'s image size`):e.log.warn("can't get image size"),e.log.warn("fallback to 200 * 200")),r};var vn={handle:async e=>{const t=e.output;return await Promise.all(e.input.map(async(i,r)=>{let n;if(n=Buffer.isBuffer(i)?{success:!0,buffer:i,fileName:"",extname:""}:j(i)?await J(i,e):await z(i),n.success&&n.buffer){const s=Bn(e,n.buffer,i),o=n.extname||s.extname||".png";t[r]={buffer:n.buffer,fileName:n.fileName||`${I().format("YYYYMMDDHHmmssSSS")}${o}`,width:s.width,height:s.height,filePath:n.filePath,extname:o,size:n.buffer?.length||0,contentType:C.lookup(o)||"application/octet-stream",origin:"string"==typeof i?i:void 0}}else e.log.error(n.reason)})),e.output=t.filter(e=>e),e}};var Gn={handle:async e=>(e.output.push(...e.input),e)};class $n{ctx;list=[];fullList=new Set;pluginMap=new Map;constructor(e){this.ctx=e,this.init()}init(){const i=t.join(this.ctx.baseDir,"package.json");if(!e.existsSync(i)){const t={name:"picgo-plugins",description:"picgo-plugins",repository:"https://github.com/PicGo/PicGo-Core",license:"MIT"};e.writeFileSync(i,JSON.stringify(t),"utf8")}}resolvePlugin(e,i){try{return D.sync(i,{basedir:e.baseDir})}catch(r){return t.join(e.baseDir,"node_modules",i)}}load(){const i=t.join(this.ctx.baseDir,"package.json"),r=t.join(this.ctx.baseDir,"node_modules/");if(!e.existsSync(r))return!1;const n=e.readJSONSync(i),s=Object.keys(n.dependencies||{}),o=Object.keys(n.devDependencies||{}),a=s.concat(o).filter(t=>{if(!/^picgo-plugin-|^@[^/]+\/picgo-plugin-/.test(t))return!1;const i=this.resolvePlugin(this.ctx,t);return e.existsSync(i)});for(const e of a)this.registerPlugin(e);return!0}registerPlugin(e,t){if(e&&"string"==typeof e){this.fullList.add(e);try{if(t){this.list.push(e),Ur(e);const i=t(this.ctx);this.pluginMap.set(e,i),i.register(this.ctx)}else if(!0===this.ctx.getConfig(`picgoPlugins.${e}`)||void 0===this.ctx.getConfig(`picgoPlugins.${e}`)){this.list.push(e),Ur(e),this.getPlugin(e).register(this.ctx);const t=`picgoPlugins[${e}]`;this.ctx.saveConfig({[t]:!0})}}catch(t){this.pluginMap.delete(e),this.list=this.list.filter(t=>t!==e),this.fullList.delete(e),this.ctx.log.error(t),this.ctx.emit(exports.IBuildInEvent.NOTIFICATION,{title:`Plugin ${e} Load Error`,body:t})}}else this.ctx.log.warn("Please provide valid plugin")}unregisterPlugin(e){this.list=this.list.filter(t=>t!==e),this.fullList.delete(e),this.pluginMap.delete(e),Ur(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.helper.afterFinishPlugins.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 i=t.join(this.ctx.baseDir,"node_modules/"),r=require(i+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 Fn={darwin:'-- From https://github.com/mushanshitiancai/vscode-paste-image\nproperty fileTypes : {{«class PNGf», ".png"}}\n\non run argv\n\tif argv is {} then\n\t\treturn ""\n\tend if\n\n\tif ((clipboard info) as string) contains "«class furl»" then\n\t\treturn POSIX path of (the clipboard as «class furl»)\n\telse\n\t\tset imagePath to (item 1 of argv)\n\t\tset theType to getType()\n\n\t\tif theType is not missing value then\n\t\t\ttry\n\t\t\t\tset myFile to (open for access imagePath with write permission)\n\t\t\t\tset eof myFile to 0\n\t\t\t\twrite (the clipboard as (first item of theType)) to myFile\n\t\t\t\tclose access myFile\n\t\t\t\treturn (POSIX path of imagePath)\n\t\t\ton error\n\t\t\t\ttry\n\t\t\t\t\tclose access myFile\n\t\t\t\tend try\n\t\t\t\treturn "no image"\n\t\t\tend try\n\t\telse\n\t\t\treturn "no image"\n\t\tend if\n\tend if\nend run\n\non getType()\n\trepeat with aType in fileTypes\n\t\trepeat with theInfo in (clipboard info)\n\t\t\tif (first item of theInfo) is equal to (first item of aType) then return aType\n\t\tend repeat\n\tend repeat\n\treturn missing value\nend getType\n',win32:'\nparam($imagePath)\n\n# Adapted from https://github.com/octan3/img-clipboard-dump/blob/master/dump-clipboard-png.ps1\n\nAdd-Type -Assembly PresentationCore\n$img = [Windows.Clipboard]::GetImage()\n\nif ($img -eq $null) {\n "no image"\n Exit 1\n}\n\nif (-not $imagePath) {\n "no image"\n Exit 1\n}\n\n$fcb = new-object Windows.Media.Imaging.FormatConvertedBitmap($img, [Windows.Media.PixelFormats]::Rgb24, $null, 0)\n$stream = [IO.File]::Open($imagePath, "OpenOrCreate")\n$encoder = New-Object Windows.Media.Imaging.PngBitmapEncoder\n$encoder.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($fcb)) | out-null\n$encoder.Save($stream) | out-null\n$stream.Dispose() | out-null\n\n$imagePath\n',win10:'# Adapted from https://github.com/octan3/img-clipboard-dump/blob/master/dump-clipboard-png.ps1\nparam($imagePath)\n\n# https://github.com/PowerShell/PowerShell/issues/7233\n# fix the output encoding bug\n[console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding\n\nAdd-Type -Assembly PresentationCore\nfunction main {\n $img = [Windows.Clipboard]::GetImage()\n\n if ($img -eq $null) {\n "no image"\n Exit 1\n }\n\n if (-not $imagePath) {\n "no image"\n Exit 1\n }\n\n $fcb = new-object Windows.Media.Imaging.FormatConvertedBitmap($img, [Windows.Media.PixelFormats]::Rgb24, $null, 0)\n $stream = [IO.File]::Open($imagePath, "OpenOrCreate")\n $encoder = New-Object Windows.Media.Imaging.PngBitmapEncoder\n $encoder.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($fcb)) | out-null\n $encoder.Save($stream) | out-null\n $stream.Dispose() | out-null\n\n $imagePath\n # fix windows 10 native cmd crash bug when "picgo upload"\n # https://github.com/PicGo/PicGo-Core/issues/32\n Exit 1\n}\n\ntry {\n # For WIN10\n $file = Get-Clipboard -Format FileDropList\n if ($file -ne $null) {\n Convert-Path $file\n Exit 1\n }\n} catch {\n # For WIN7 WIN8 WIN10\n main\n}\n\nmain',linux:'#!/bin/sh\nif [ "$XDG_SESSION_TYPE" = "x11" ]; then\n # require xclip(see http://stackoverflow.com/questions/592620/check-if-a-program-exists-from-a-bash-script/677212#677212)\n command -v xclip >/dev/null 2>&1 || { echo >&1 "no xclip"; exit 1; }\n # write image in clipboard to file (see http://unix.stackexchange.com/questions/145131/copy-image-from-clipboard-to-file)\n filePath=`xclip -selection clipboard -o 2>/dev/null | grep ^file:// | cut -c8-`\n if [ ! -n "$filePath" ] ;then\n if\n xclip -selection clipboard -target image/png -o >/dev/null 2>&1\n then\n xclip -selection clipboard -target image/png -o >$1 2>/dev/null\n echo $1\n else\n echo "no image"\n fi\n else\n echo $filePath\n fi\nelif [ "$XDG_SESSION_TYPE" = "wayland" ]; then\n command -v wl-paste >/dev/null 2>&1 || { echo >&1 "no wl-clipboard"; exit 1; }\n isImage=`wl-paste --list-types | grep image`\n if [ -n "$isImage" ]; then\n wl-paste --type image/png > $1 2>/dev/null\n echo $1\n else\n echo "no image"\n exit 1\n fi\nelse\n # fallback for unsupported session types\n echo >&2 "Error: Unsupported session type \'$XDG_SESSION_TYPE\'."\n echo >&2 "Solution: The variable of XDG_SESSION_TYPE must set as \'x11\' or \'wayland\'."\n exit 1\nfi\n',wsl:'#!/bin/sh\n# grab the paths\nscriptPath=$(echo $0 | awk \'{ print substr( $0, 1, length($0)-6 ) }\')"windows10.ps1"\nimagePath=$(echo $1 | awk \'{ print substr( $0, 1, length($0)-18 ) }\')\nimageName=$(echo $1 | awk \'{ print substr( $0, length($0)-17, length($0) ) }\')\n\n# run the powershell script\nres=$(powershell.exe -noprofile -noninteractive -nologo -sta -executionpolicy unrestricted -file $(wslpath -w $scriptPath) $(wslpath -w $imagePath)"\\\\"$imageName)\n\n# note that there is a return symbol in powershell result\nnoImage=$(echo "no image\\r")\n\n# check whether image exists\nif [ "$res" = "$noImage" ] ;then\n echo "no image"\nelse\n echo $(wslpath -u -a "${res}")\nfi\n'},kn={darwin:"mac.applescript",win32:"windows.ps1",win10:"windows10.ps1",linux:"linux.sh",wsl:"wsl.sh"};const Hn=async i=>{!function(i){const r=t.join(i.baseDir,me);e.existsSync(r)||e.mkdirSync(r)}(i);const n=t.join(i.baseDir,me,`${I().format("YYYYMMDDHHmmssSSS")}.png`);return await new Promise((s,o)=>{const a=(()=>{const e=process.platform;if(N)return"wsl";if("win32"===e)return"10"===r.release().split(".")[0]?"win10":"win32";return"darwin"===e?"darwin":"linux"})(),c=t.join(i.baseDir,kn[a]);let l;e.existsSync(c)||e.writeFileSync(c,Fn[a],"utf8"),l="darwin"===a?S.spawn("osascript",[c,n]):"win32"===a||"win10"===a?S.spawn("powershell",["-noprofile","-noninteractive","-nologo","-sta","-executionpolicy","unrestricted","-file",c,n]):S.spawn("sh",[c,n]),l.stdout.on("data",r=>{if("linux"===a&&"no xclip or wl-clipboard"===r.toString().trim())return i.emit(exports.IBuildInEvent.NOTIFICATION,{title:"xclip or wl-clipboard not found",body:"Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"}),o(new Error("Please install xclip(for x11) or wl-clipboard(for wayland) before run picgo"));const c=r.toString().trim();let l=!1;if(t.basename(c)!==t.basename(n)&&e.existsSync(c)&&(l=!0),"no image"!==c&&!e.existsSync(c))return o(new Error(`Can't find ${c}`));s({imgPath:c,shouldKeepAfterUploading:l})})})},Yn=new i.EventEmitter,Vn=new A.Agent({maxVersion:"TLSv1.2",minVersion:"TLSv1.2"});function qn(e,t,i){"object"==typeof i&&"value"in i&&"options"in i?e.append(t,i.value,i.options):e.append(t,i)}function jn(e){return{...e,statusCode:e.status,body:e.data}}function Kn(e){const t={method:e?.config?.method?.toUpperCase()||"",url:e?.config?.url||"",statusCode:e?.response?.status||0,message:e?.message||"",stack:e?.stack||{},response:{status:e?.response?.status||0,statusCode:e?.response?.status||0,body:e?.response?.data||""}};return Promise.reject(t)}class Wn{ctx;proxy="";options={};constructor(e){this.ctx=e,this.init(),Yn.on(exports.IBusEvent.CONFIG_CHANGE,e=>{switch(e.configName){case"picBed":e.value?.proxy&&(this.proxy=e.value.proxy);break;case"picBed.proxy":this.proxy=e.value}})}init(){const e=this.ctx.getConfig("picBed.proxy");e&&(this.proxy=e)}handleProxy(){if(this.proxy)try{const e=new a.URL(this.proxy);return{host:e.hostname,port:parseInt(e.port||"0",10),protocol:e.protocol}}catch(e){}return!1}request(e){this.options.proxy=this.handleProxy(),this.options.headers=e.headers||{},this.options.maxBodyLength=1/0,this.options.maxContentLength=1/0,this.options.withCredentials=!0,this.options.proxy&&e.url?.startsWith("https://")?(this.options.httpsAgent=y.httpsOverHttp({proxy:{host:this.options.proxy.host,port:this.options.proxy.port}}),this.options.proxy=!1):this.options.httpsAgent=Vn;const t=_.create(this.options);t.interceptors.response.use(jn,Kn);const i=function(e){let t=!1;const i={...e,url:e.url||"",headers:e.headers||{}};if(e.proxy){let r=e.proxy;if("string"==typeof r){try{r=new a.URL(e.proxy)}catch(e){r=!1,i.proxy=!1,console.error(e)}t=!0}r&&(e.url?.startsWith("https://")?(i.proxy=!1,i.httpsAgent=y.httpsOverHttp({proxy:{host:r?.hostname,port:parseInt(r?.port,10)}})):i.proxy={host:r.hostname,port:parseInt(r.port,10),protocol:"http"})}if("formData"in e){const r=new T;for(const t in e.formData)qn(r,t,e.formData[t]);i.data=r,i.headers=Object.assign(i.headers||{},r.getHeaders()),t=!0,delete i.formData}return"body"in e&&(i.data=e.body,t=!0,delete i.body),"qs"in e&&(i.params=e.qs,t=!0),i.__isOldOptions=t,i}(e);return t.interceptors.request.use(function(e){let t="";return e?.headers?.contentType?(t=e.headers.contentType,delete e.headers.contentType):e?.headers?.ContentType?(t=e.headers.ContentType,delete e.headers.ContentType):e?.headers?.["content-type"]&&(t=e.headers["content-type"],delete e.headers["content-type"]),""!==t&&e.headers&&(e.headers["Content-Type"]=t),e}),"resolveWithFullResponse"in e&&e.resolveWithFullResponse?t.request(i):t.request(i).then(t=>i.__isOldOptions?"json"in e?e.json?t.data:void 0:JSON.stringify(t.data):t.data)}}class Qn{ctx;db;constructor(e){if(this.ctx=e,this.db=new m.JSONStore(this.ctx.configPath),!this.db.has("picBed"))try{this.db.set("picBed",{uploader:Ie,current:Ie})}catch(e){throw this.ctx.log.error(e),e}if(!this.db.has("picgoPlugins"))try{this.db.set("picgoPlugins",{})}catch(e){throw this.ctx.log.error(e),e}}read(e){return this.db.read(e)}get(e=""){return this.read(!0),this.db.get(e)}set(e,t){return this.read(!0),this.db.set(e,t)}has(e){return this.read(!0),this.db.has(e)}unset(e,t){return this.read(!0),this.db.unset(e,t)}saveConfig(e){Object.keys(e).forEach(t=>{this.set(t,e[t])})}removeConfig(e){Object.keys(e).forEach(t=>{this.unset(t,e[t])})}}class zn{ctx;constructor(e){this.ctx=e}async install(e,t={},i){const r=[],n=e.map(e=>Jn(this.ctx,e)).filter(e=>this.ctx.pluginLoader.hasPlugin(e.pkgName)?(r.push(e.pkgName),this.ctx.log.success(`PicGo has already installed ${e.pkgName}`),!1):!!e.success),s=n.map(e=>e.fullName),o=n.map(e=>e.pkgName);if(s.length>0){const e=await this.execCommand("install",s,this.ctx.baseDir,t,i);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}}o.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:[...o,...r]});return{success:!0,body:[...o,...r]}}if(0===r.length){const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("installFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED"),body:e});return{success:!1,body:e}}this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS")),this.ctx.emit("installSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS"),body:[...o,...r]});return{success:!0,body:[...o,...r]}}async uninstall(e,t){const i=e.map(e=>Jn(this.ctx,e)).filter(e=>e.success).map(e=>e.pkgName);if(i.length>0){const e=await this.execCommand("uninstall",i,this.ctx.baseDir,void 0,t);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}}i.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:i});return{success:!0,body:i}}{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={},i){const r=e.map(e=>Jn(this.ctx,e)).filter(e=>e.success).map(e=>e.pkgName);if(r.length>0){const e=await this.execCommand("update",r,this.ctx.baseDir,t,i);if(e.code){const t=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON",{code:`${e.code}`,data:e.data});this.ctx.log.error(t),this.ctx.emit("updateFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED"),body:t});return{success:!1,body:t}}this.ctx.log.success(this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS")),this.ctx.emit("updateSuccess",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS"),body:r});return{success:!0,body:r}}{const e=this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID");this.ctx.log.error(e),this.ctx.emit("updateFailed",{title:this.ctx.i18n.translate("PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED"),body:e});return{success:!1,body:e}}}async execCommand(e,t,i,r={},n={}){const s=r.npmRegistry||this.ctx.getConfig("settings.npmRegistry"),o=r.npmProxy||this.ctx.getConfig("settings.npmProxy");return await new Promise(r=>{let a=[e].concat(t).concat("--color=always").concat("--save");s&&(a=a.concat(`--registry=${s}`)),o&&(a=a.concat(`--proxy=${o}`));try{const e=R("npm",a,{cwd:i,env:Object.assign({},process.env,n)});let t="";e.stdout?.on("data",e=>{t+=e}).pipe(process.stdout),e.stderr?.on("data",e=>{t+=e}).pipe(process.stderr),e.on("close",e=>{r(e?{code:e,data:t}:{code:0,data:t})}),e.on("error",e=>{this.ctx.log.error(e),this.ctx.log.error("NPM is not installed"),this.ctx.emit(exports.IBuildInEvent.FAILED,"NPM is not installed")})}catch(e){this.ctx.log.error(e),this.ctx.emit(exports.IBuildInEvent.FAILED,e)}})}}const Jn=(e,t)=>{const i={success:!1,fullName:"",pkgName:""},r=te(t,e.log);if(!r)return i;const n=ie(r,e.log);return n?{success:!0,fullName:r,pkgName:n}:i},Xn={"zh-CN":{UPLOAD_FAILED:"上传失败",CHECK_SETTINGS:"请检查你的配置项是否正确",CHECK_SETTINGS_AND_NETWORK:"请检查你的配置项以及网络",UPLOAD_FAILED_REASON:"错误码:${code},请打开浏览器粘贴地址查看相关原因",SERVER_ERROR:"服务端出错,请重试",AUTH_FAILED:"认证失败",CLOUD_LOGIN_CANCELLED:"登录已取消",CLOUD_LOGIN_IN_PROGRESS:"登录正在进行中",CLOUD_LOGIN_INVALID_TOKEN:"无效的 token",CLOUD_LOGIN_SUCCESS:"登录成功!",CLOUD_LOGOUT_SUCCESS:"退出登录成功!",CLOUD_LOGIN_SERVER_START_FAILED:"启动登录服务失败",CLOUD_LOGIN_OPEN_BROWSER_FAILED:"无法自动打开浏览器:${message}",CLOUD_LOGIN_OPEN_BROWSER_TIP:"请在浏览器中打开该链接:${url}",CLOUD_LOGIN_STATE_MISMATCH_WARN:"State 校验失败或缺失,请求已拦截",CLOUD_LOGIN_STATE_INVALID:"State 无效,请重新登录。",CLOUD_LOGIN_TOKEN_MISSING:"回调中缺少 token。",CLOUD_LOGIN_CODE_MISSING:"回调中缺少 code。",CLOUD_LOGIN_EXCHANGE_FAILED:"登录 code 交换失败。",CLOUD_LOGIN_NOT_IN_PROGRESS:"当前没有进行中的登录流程。",CLOUD_LOGIN_PAGE_TITLE:"PicGo 登录",CLOUD_LOGIN_RESULT_SUCCESS_TITLE:"授权成功!",CLOUD_LOGIN_RESULT_FAILED_TITLE:"授权失败",CLOUD_LOGIN_RESULT_SUCCESS_MESSAGE:"你可以关闭此窗口并返回 PicGo。",PICGO_CLOUD_UPLOAD_LOGIN_REQUIRED:"请先登录 PicGo Cloud 后再使用该图床。",PICGO_CLOUD_UPLOAD_RELOGIN_REQUIRED:"PicGo Cloud 登录状态已失效,请重新登录后再试。",PICGO_CLOUD_UPLOAD_INVALID_PRESIGN_RESPONSE:"PicGo Cloud 返回的上传凭证无效。",PICGO_CLOUD_UPLOAD_INVALID_COMPLETE_RESPONSE:"PicGo Cloud 返回的完成上传响应无效。",PICGO_CLOUD_UPLOAD_MISSING_FILE_NAME:"缺少文件名,无法上传到 PicGo Cloud。",PICGO_CLOUD_UPLOAD_MISSING_FILE_DATA:"缺少图片数据,无法上传到 PicGo Cloud。",PICGO_CLOUD_UPLOAD_INVALID_INITIATE_RESPONSE:"PicGo Cloud 返回的分片上传初始化响应无效。",PICGO_CLOUD_UPLOAD_MULTIPART_NOT_FOUND:"分片上传会话已失效,请重新上传。",PICGO_CLOUD_UPLOAD_MULTIPART_PART_FAILED:"分片上传中某个分片重试多次仍失败。",PICGO_CLOUD_UPLOAD_MULTIPART_COMPLETE_FAILED:"分片上传完成请求失败。",PICGO_CLOUD_UPLOAD_PROGRESS_BAR:"上传 ${fileName} ${loadedMB}/${totalMB} MB${resumedSuffix}",PICGO_CLOUD_UPLOAD_VERBOSE:"上传 ${fileName}: ${loadedMB}/${totalMB} MB (${partsCompleted}/${totalParts} parts)${resumedSuffix}",PICGO_CLOUD_UPLOAD_RESUMED_SUFFIX:"(续传)",CLOUD_ALBUM_PENDING_INVALID_FILE:"待重试队列文件无效,已按空队列处理:${path}",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_DISABLED:"云端相册导入功能未开启,请先启用自动导入。",CLOUD_ALBUM_IMPORT_PLAN_REQUIRED:"云端相册导入需要 PicGo Cloud 付费套餐。",CLOUD_ALBUM_AUTO_IMPORT_PENDING_WARNING:"自动导入未完全完成,当前待重试队列共有 ${count} 条记录。",CLOUD_COMMAND_LOGIN_REQUIRED:"请先登录 PicGo Cloud。",CLOUD_COMMAND_LOGIN_HINT:"请先执行 `picgo login`(或 `picgo cloud login`)后再重试。",CLOUD_AUTH_STATUS_LOGGED_IN:"已登录 PicGo Cloud(用户:${user})",CLOUD_AUTH_STATUS_LOGGED_OUT:"未登录 PicGo Cloud。",CLOUD_AUTH_STATUS_INVALID:"PicGo Cloud 登录状态已失效,请重新登录。",CLOUD_AUTH_STATUS_ERROR:"无法检测 PicGo Cloud 登录状态:${message}",GET_PLUGINS_EMPTY:"没有已安装的插件。",CLOUD_ALBUM_IMPORT_PROMPT_ENABLE_AUTO_IMPORT:"云端相册导入功能未开启,是否立即开启?",CLOUD_ALBUM_IMPORT_ENABLING_AUTO_IMPORT:"正在开启云端相册自动导入...",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_ENABLED:"已开启云端相册自动导入。",CLOUD_ALBUM_IMPORT_DUPLICATE_ID:"这些数据已经导入过 PicGo Cloud。",CLOUD_ALBUM_IMPORT_PROGRESS_BAR:"正在导入 ${current}/${total}(批次 ${batchIndex}/${batchTotal})",CLOUD_ALBUM_IMPORT_VERBOSE_BATCH:"批次 ${batchIndex}/${batchTotal}:已处理 ${current}/${total},成功 ${created},跳过 ${skipped},失败 ${failed}",CLOUD_ALBUM_IMPORT_SUMMARY_TITLE:"导入结果",CLOUD_ALBUM_IMPORT_SUMMARY_TOTAL:"总数",CLOUD_ALBUM_IMPORT_SUMMARY_CREATED:"成功创建",CLOUD_ALBUM_IMPORT_SUMMARY_SKIPPED:"跳过",CLOUD_ALBUM_IMPORT_SUMMARY_INVALID:"无效",CLOUD_ALBUM_IMPORT_SUMMARY_FAILED:"失败",CLOUD_ALBUM_IMPORT_SUMMARY_PENDING:"待重试",CLOUD_ALBUM_IMPORT_RETRY_HINT:"你可以执行 `picgo cloud album retry` 继续重试待处理条目。",CLOUD_ALBUM_IMPORT_NO_PENDING:"没有待重试的条目。",CLOUD_ALBUM_LIST_LOADING:"正在获取云端相册列表...",CLOUD_ALBUM_LIST_DONE:"已获取云端相册列表",CLOUD_ALBUM_GET_LOADING:"正在获取云端相册数据...",CLOUD_ALBUM_GET_DONE:"已获取云端相册数据",CLOUD_ALBUM_UPDATE_LOADING:"正在更新云端相册数据...",CLOUD_ALBUM_UPDATE_DONE:"已更新云端相册数据",CLOUD_ALBUM_DELETE_LOADING:"正在删除云端相册数据...",CLOUD_ALBUM_DELETE_DONE:"已删除云端相册数据",CLOUD_ALBUM_DELETE_CONFIRM:"确定从云端相册删除 ${count} 条记录?",CLOUD_ALBUM_IMPORT_SOURCE_REQUIRED:"请提供导入来源:数据库路径、`--json-file` 或 `--data`。",CLOUD_ALBUM_IMPORT_SOURCE_CONFLICT:"数据库路径、`--json-file` 和 `--data` 只能选择一种。",CLOUD_ALBUM_IMPORT_INVALID_JSON:"导入数据不是合法的 JSON 数组。",CLOUD_ALBUM_IMPORT_INVALID_JSON_FILE:"读取导入 JSON 文件失败:${path}",CLOUD_ALBUM_IMPORT_LOADING_SOURCE:"正在加载导入数据...",CLOUD_ALBUM_IMPORT_LOADING_SOURCE_DONE:"已加载 ${count} 条数据",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT:"正在检查云端导入状态...",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT_DONE:"云端导入状态检查完毕",CLOUD_ALBUM_IMPORT_UPLOADING:"正在导入到云端...",CLOUD_ALBUM_IMPORT_UPLOADING_DONE:"云端导入完成",CLOUD_ALBUM_RETRY_LOADING_PENDING:"正在加载待重试队列...",CLOUD_ALBUM_RETRY_LOADING_PENDING_DONE:"已加载 ${count} 条待重试数据",CLOUD_ALBUM_RETRY_UPLOADING:"正在重试导入...",CLOUD_ALBUM_RETRY_UPLOADING_DONE:"重试导入完成",SERVER_INVALID_JSON_BODY:"JSON 请求体无效",SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED:"请求体无效:需要 { list: string[] }",SERVER_FORMDATA_NO_FILES_IN_FILES_FIELD:"form-data 的 files 字段未找到文件",SERVER_FORMDATA_FILES_MUST_BE_FILES:"form-data 无效:files 必须是文件",SERVER_AUTH_ENABLED:"[PicGo Server] 认证已启用。",SERVER_AUTH_DISABLED_WARNING:"[PicGo Server] 警告:认证已关闭,任何人都可以上传图片。",SERVER_AUTH_UNAUTHORIZED_REQUEST:"[PicGo Server] 未授权的请求,来源 ${ip}",SERVER_AUTH_QUERY_SECRET_WARNING:"[PicGo Server] 警告:通过 URL 参数传递 secret 不安全,请使用 Authorization Header。",URL_REWRITE_EMPTY_RESULT:"URL 重写结果为空,请检查你的规则配置",PICBED_SMMS:"SM.MS(S.EE)",PICBED_SMMS_TOKEN:"设定Token",PICBED_SMMS_BACKUP_DOMAIN:"备用上传域名",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例如 sm.ms",PICBED_ALICLOUD:"阿里云OSS",PICBED_ALICLOUD_ACCESSKEYID:"设定KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"设定KeySecret",PICBED_ALICLOUD_BUCKET:"设定Bucket",PICBED_ALICLOUD_AREA:"设定存储区域",PICBED_ALICLOUD_PATH:"设定存储路径",PICBED_ALICLOUD_CUSTOMURL:"设定自定义域名",PICBED_ALICLOUD_OPTIONS:"设定网址后缀",PICBED_ALICLOUD_MESSAGE_AREA:"例如:oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例如:test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例如:?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD:"腾讯云COS",PICBED_TENCENTCLOUD_VERSION:"COS版本",PICBED_TENCENTCLOUD_SECRETID:"设定SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"设定SecretKey",PICBED_TENCENTCLOUD_APPID:"设定AppId",PICBED_TENCENTCLOUD_BUCKET:"设定Bucket",PICBED_TENCENTCLOUD_AREA:"设定存储区域",PICBED_TENCENTCLOUD_ENDPOINT:"设定Endpoint",PICBED_TENCENTCLOUD_PATH:"设定存储路径",PICBED_TENCENTCLOUD_OPTIONS:"设定网址后缀",PICBED_TENCENTCLOUD_CUSTOMURL:"设定自定义域名",PICBED_TENCENTCLOUD_SLIM:"极智压缩",PICBED_TENCENTCLOUD_SLIM_TIP:"图片极智压缩,详情请参考[文档说明](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"开启",PICBED_TENCENTCLOUD_SLIM_CANCEL:"关闭",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例如:1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例如:ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例如:cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例如:test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例如:?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"设定Token",PICBED_GITHUB_REPO:"设定仓库名",PICBED_GITHUB_PATH:"设定存储路径",PICBED_GITHUB_BRANCH:"设定分支名",PICBED_GITHUB_CUSTOMURL:"设定自定义域名",PICBED_GITHUB_MESSAGE_REPO:"格式:username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例如:main",PICBED_GITHUB_MESSAGE_PATH:"例如:test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_QINIU:"七牛云",PICBED_QINIU_ACCESSKEY:"设定AccessKey",PICBED_QINIU_SECRETKEY:"设定SecretKey",PICBED_QINIU_BUCKET:"设定Bucket",PICBED_QINIU_PATH:"设定存储路径",PICBED_QINIU_URL:"设定访问网址",PICBED_QINIU_OPTIONS:"设定网址后缀",PICBED_QINIU_AREA:"设定存储区域",PICBED_QINIU_MESSAGE_PATH:"例如:test/",PICBED_QINIU_MESSAGE_AREA:"例如:z0",PICBED_QINIU_MESSAGE_OPTIONS:"例如:?imageslim",PICBED_QINIU_MESSAGE_URL:"例如:https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"设定ClientId",PICBED_IMGUR_PROXY:"设定代理",PICBED_IMGUR_MESSAGE_PROXY:"例如:http://127.0.0.1:1080",PICBED_UPYUN:"又拍云",PICBED_UPYUN_BUCKET:"设定Bucket",PICBED_UPYUN_OPERATOR:"设定操作员",PICBED_UPYUN_PASSWORD:"设定操作员密码",PICBED_UPYUN_PATH:"设定存储路径",PICBED_UPYUN_URL:"设定加速域名",PICBED_UPYUN_OPTIONS:"设定网址后缀",PICBED_UPYUN_MESSAGE_OPERATOR:"例如:me",PICBED_UPYUN_MESSAGE_PASSWORD:"输入操作员密码",PICBED_UPYUN_MESSAGE_URL:"例如:http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例如:!imgslim",PICBED_UPYUN_MESSAGE_PATH:"例如:test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"插件安装成功",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"插件安装失败",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"插件安装失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"插件安装失败,请输入合法插件名或合法安装路径",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"插件卸载成功",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"插件卸载失败",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"插件卸载失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"插件卸载失败,请输入合法插件名",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"插件更新成功",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"插件更新失败",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"插件更新失败,失败码为${code},错误日志为 \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"插件更新失败,请输入合法插件名",CONFIG_SYNC_INVALID_ENCRYPTION_METHOD:'配置无效:settings.picgoCloud.encryptionMethod 必须是 "auto"、"sse" 或 "e2ee" 之一,当前为:${value}',CONFIG_SYNC_ENCRYPTION_METHOD_E2EE:"端到端加密",CONFIG_SYNC_ENCRYPTION_METHOD_SSE:"服务端加密",CONFIG_SYNC_ENCRYPTION_SWITCH_TITLE:"确认切换加密方式吗?",CONFIG_SYNC_ENCRYPTION_SWITCH_BODY:"您正在从“${from}”切换为“${to}”。\n\n注意:切换加密模式将清空您所有的云端历史版本记录。\n这是因为旧的历史版本无法在新模式下被解密或验证。\n切换后,系统将立即为您创建一份新的备份作为起点。",CONFIG_SYNC_ENCRYPTION_SWITCH_CONFIRM:"确认切换并清空历史",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCEL:"取消",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCELLED:"已取消切换加密方式",CONFIG_SYNC_ENCRYPTION_SWITCH_MISSING_HANDLER:"需要提供加密方式切换确认处理器"},"zh-TW":{UPLOAD_FAILED:"上傳失敗",CHECK_SETTINGS:"請檢查你的設定是否正確",CHECK_SETTINGS_AND_NETWORK:"請檢查你的設定及網路",UPLOAD_FAILED_REASON:"錯誤碼:${code},請打開瀏覽器貼上地址查看相關原因",SERVER_ERROR:"伺服器出錯,請重試",AUTH_FAILED:"認證失敗",CLOUD_LOGIN_CANCELLED:"登入已取消",CLOUD_LOGIN_IN_PROGRESS:"登入正在進行中",CLOUD_LOGIN_INVALID_TOKEN:"無效的 token",CLOUD_LOGIN_SUCCESS:"登入成功!",CLOUD_LOGOUT_SUCCESS:"登出成功!",CLOUD_LOGIN_SERVER_START_FAILED:"啟動登入服務失敗",CLOUD_LOGIN_OPEN_BROWSER_FAILED:"無法自動打開瀏覽器:${message}",CLOUD_LOGIN_OPEN_BROWSER_TIP:"請在瀏覽器中打開此連結:${url}",CLOUD_LOGIN_STATE_MISMATCH_WARN:"State 驗證失敗或缺失,請求已攔截",CLOUD_LOGIN_STATE_INVALID:"State 無效,請重新登入。",CLOUD_LOGIN_TOKEN_MISSING:"回呼中缺少 token。",CLOUD_LOGIN_CODE_MISSING:"回呼中缺少 code。",CLOUD_LOGIN_EXCHANGE_FAILED:"登入 code 交換失敗。",CLOUD_LOGIN_NOT_IN_PROGRESS:"目前沒有進行中的登入流程。",CLOUD_LOGIN_PAGE_TITLE:"PicGo 登入",CLOUD_LOGIN_RESULT_SUCCESS_TITLE:"授權成功!",CLOUD_LOGIN_RESULT_FAILED_TITLE:"授權失敗",CLOUD_LOGIN_RESULT_SUCCESS_MESSAGE:"你可以關閉此視窗並返回 PicGo。",PICGO_CLOUD_UPLOAD_LOGIN_REQUIRED:"請先登入 PicGo Cloud 後再使用此圖床。",PICGO_CLOUD_UPLOAD_RELOGIN_REQUIRED:"PicGo Cloud 登入狀態已失效,請重新登入後再試。",PICGO_CLOUD_UPLOAD_INVALID_PRESIGN_RESPONSE:"PicGo Cloud 回傳的上傳憑證無效。",PICGO_CLOUD_UPLOAD_INVALID_COMPLETE_RESPONSE:"PicGo Cloud 回傳的完成上傳回應無效。",PICGO_CLOUD_UPLOAD_MISSING_FILE_NAME:"缺少檔名,無法上傳到 PicGo Cloud。",PICGO_CLOUD_UPLOAD_MISSING_FILE_DATA:"缺少圖片資料,無法上傳到 PicGo Cloud。",PICGO_CLOUD_UPLOAD_INVALID_INITIATE_RESPONSE:"PicGo Cloud 回傳的分片上傳初始化回應無效。",PICGO_CLOUD_UPLOAD_MULTIPART_NOT_FOUND:"分片上傳工作階段已失效,請重新上傳。",PICGO_CLOUD_UPLOAD_MULTIPART_PART_FAILED:"分片上傳中某個分片重試多次仍失敗。",PICGO_CLOUD_UPLOAD_MULTIPART_COMPLETE_FAILED:"分片上傳完成請求失敗。",PICGO_CLOUD_UPLOAD_PROGRESS_BAR:"上傳 ${fileName} ${loadedMB}/${totalMB} MB${resumedSuffix}",PICGO_CLOUD_UPLOAD_VERBOSE:"上傳 ${fileName}: ${loadedMB}/${totalMB} MB (${partsCompleted}/${totalParts} parts)${resumedSuffix}",PICGO_CLOUD_UPLOAD_RESUMED_SUFFIX:"(續傳)",CLOUD_ALBUM_PENDING_INVALID_FILE:"待重試佇列檔案無效,已視為空佇列處理:${path}",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_DISABLED:"雲端相簿匯入功能未開啟,請先啟用自動匯入。",CLOUD_ALBUM_IMPORT_PLAN_REQUIRED:"雲端相簿匯入需要 PicGo Cloud 付費方案。",CLOUD_ALBUM_AUTO_IMPORT_PENDING_WARNING:"自動匯入未完全完成,目前待重試佇列共有 ${count} 筆記錄。",CLOUD_COMMAND_LOGIN_REQUIRED:"請先登入 PicGo Cloud。",CLOUD_COMMAND_LOGIN_HINT:"請先執行 `picgo login`(或 `picgo cloud login`)後再重試。",CLOUD_AUTH_STATUS_LOGGED_IN:"已登入 PicGo Cloud(使用者:${user})",CLOUD_AUTH_STATUS_LOGGED_OUT:"未登入 PicGo Cloud。",CLOUD_AUTH_STATUS_INVALID:"PicGo Cloud 登入狀態已失效,請重新登入。",CLOUD_AUTH_STATUS_ERROR:"無法檢測 PicGo Cloud 登入狀態:${message}",GET_PLUGINS_EMPTY:"沒有已安裝的外掛。",CLOUD_ALBUM_IMPORT_PROMPT_ENABLE_AUTO_IMPORT:"雲端相簿匯入功能未開啟,是否立即開啟?",CLOUD_ALBUM_IMPORT_ENABLING_AUTO_IMPORT:"正在開啟雲端相簿自動匯入...",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_ENABLED:"已開啟雲端相簿自動匯入。",CLOUD_ALBUM_IMPORT_DUPLICATE_ID:"這些資料已經匯入過 PicGo Cloud。",CLOUD_ALBUM_IMPORT_PROGRESS_BAR:"正在匯入 ${current}/${total}(批次 ${batchIndex}/${batchTotal})",CLOUD_ALBUM_IMPORT_VERBOSE_BATCH:"批次 ${batchIndex}/${batchTotal}:已處理 ${current}/${total},成功 ${created},跳過 ${skipped},失敗 ${failed}",CLOUD_ALBUM_IMPORT_SUMMARY_TITLE:"匯入結果",CLOUD_ALBUM_IMPORT_SUMMARY_TOTAL:"總數",CLOUD_ALBUM_IMPORT_SUMMARY_CREATED:"成功建立",CLOUD_ALBUM_IMPORT_SUMMARY_SKIPPED:"跳過",CLOUD_ALBUM_IMPORT_SUMMARY_INVALID:"無效",CLOUD_ALBUM_IMPORT_SUMMARY_FAILED:"失敗",CLOUD_ALBUM_IMPORT_SUMMARY_PENDING:"待重試",CLOUD_ALBUM_IMPORT_RETRY_HINT:"你可以執行 `picgo cloud album retry` 繼續重試待處理項目。",CLOUD_ALBUM_IMPORT_NO_PENDING:"沒有待重試的項目。",CLOUD_ALBUM_LIST_LOADING:"正在取得雲端相簿列表...",CLOUD_ALBUM_LIST_DONE:"已取得雲端相簿列表",CLOUD_ALBUM_GET_LOADING:"正在取得雲端相簿資料...",CLOUD_ALBUM_GET_DONE:"已取得雲端相簿資料",CLOUD_ALBUM_UPDATE_LOADING:"正在更新雲端相簿資料...",CLOUD_ALBUM_UPDATE_DONE:"已更新雲端相簿資料",CLOUD_ALBUM_DELETE_LOADING:"正在刪除雲端相簿資料...",CLOUD_ALBUM_DELETE_DONE:"已刪除雲端相簿資料",CLOUD_ALBUM_DELETE_CONFIRM:"確定要從雲端相簿刪除 ${count} 筆記錄嗎?",CLOUD_ALBUM_IMPORT_SOURCE_REQUIRED:"請提供一種匯入來源:資料庫路徑、`--json-file` 或 `--data`。",CLOUD_ALBUM_IMPORT_SOURCE_CONFLICT:"資料庫路徑、`--json-file` 和 `--data` 只能擇一使用。",CLOUD_ALBUM_IMPORT_INVALID_JSON:"匯入資料必須是合法的 JSON 陣列。",CLOUD_ALBUM_IMPORT_INVALID_JSON_FILE:"讀取匯入 JSON 檔案失敗:${path}",CLOUD_ALBUM_IMPORT_LOADING_SOURCE:"正在載入匯入資料...",CLOUD_ALBUM_IMPORT_LOADING_SOURCE_DONE:"已載入 ${count} 筆資料",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT:"正在檢查雲端匯入狀態...",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT_DONE:"雲端匯入狀態檢查完畢",CLOUD_ALBUM_IMPORT_UPLOADING:"正在匯入至雲端...",CLOUD_ALBUM_IMPORT_UPLOADING_DONE:"雲端匯入完成",CLOUD_ALBUM_RETRY_LOADING_PENDING:"正在載入待重試佇列...",CLOUD_ALBUM_RETRY_LOADING_PENDING_DONE:"已載入 ${count} 筆待重試資料",CLOUD_ALBUM_RETRY_UPLOADING:"正在重試匯入...",CLOUD_ALBUM_RETRY_UPLOADING_DONE:"重試匯入完成",SERVER_INVALID_JSON_BODY:"JSON 請求內容無效",SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED:"請求內容無效:需要 { list: string[] }",SERVER_FORMDATA_NO_FILES_IN_FILES_FIELD:"form-data 的 files 欄位未找到檔案",SERVER_FORMDATA_FILES_MUST_BE_FILES:"form-data 無效:files 必須是檔案",SERVER_AUTH_ENABLED:"[PicGo Server] 認證已啟用。",SERVER_AUTH_DISABLED_WARNING:"[PicGo Server] 警告:認證已關閉,任何人都可以上傳圖片。",SERVER_AUTH_UNAUTHORIZED_REQUEST:"[PicGo Server] 未授權的請求,來源 ${ip}",SERVER_AUTH_QUERY_SECRET_WARNING:"[PicGo Server] 警告:透過 URL 參數傳遞 secret 不安全,請使用 Authorization Header。",URL_REWRITE_EMPTY_RESULT:"URL 重寫結果為空,請檢查你的規則設定",PICBED_SMMS:"SM.MS(S.EE)",PICBED_SMMS_TOKEN:"設定Token",PICBED_SMMS_BACKUP_DOMAIN:"備用上傳網址",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"例如 sm.ms",PICBED_ALICLOUD:"阿里云OSS",PICBED_ALICLOUD_ACCESSKEYID:"設定KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"設定KeySecret",PICBED_ALICLOUD_BUCKET:"設定Bucket",PICBED_ALICLOUD_AREA:"設定儲存區域",PICBED_ALICLOUD_PATH:"設定儲存路徑",PICBED_ALICLOUD_CUSTOMURL:"設定自訂網址",PICBED_ALICLOUD_OPTIONS:"設定網址後綴",PICBED_ALICLOUD_MESSAGE_AREA:"例如:oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"例如:test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"例如:?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD:"騰訊云COS",PICBED_TENCENTCLOUD_VERSION:"COS版本",PICBED_TENCENTCLOUD_SECRETID:"設定SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"設定SecretKey",PICBED_TENCENTCLOUD_APPID:"設定AppId",PICBED_TENCENTCLOUD_BUCKET:"設定Bucket",PICBED_TENCENTCLOUD_AREA:"設定儲存區域",PICBED_TENCENTCLOUD_ENDPOINT:"設定Endpoint",PICBED_TENCENTCLOUD_PATH:"設定儲存路徑",PICBED_TENCENTCLOUD_OPTIONS:"設定網址後綴",PICBED_TENCENTCLOUD_SLIM:"極智壓縮",PICBED_TENCENTCLOUD_SLIM_CANCEL:"關閉",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"開啓",PICBED_TENCENTCLOUD_SLIM_TIP:"圖片極智壓縮,詳情請參考[文檔說明](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_CUSTOMURL:"設定自訂網址",PICBED_TENCENTCLOUD_MESSAGE_APPID:"例如:1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"例如:ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"例如:cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"例如:test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"例如:?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"設定Token",PICBED_GITHUB_REPO:"設定倉庫名稱",PICBED_GITHUB_PATH:"設定儲存路徑",PICBED_GITHUB_BRANCH:"設定分支名稱",PICBED_GITHUB_CUSTOMURL:"設定自訂網址",PICBED_GITHUB_MESSAGE_REPO:"格式:username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"例如:main",PICBED_GITHUB_MESSAGE_PATH:"例如:test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"例如:https://test.com",PICBED_QINIU:"七牛云",PICBED_QINIU_ACCESSKEY:"設定AccessKey",PICBED_QINIU_SECRETKEY:"設定SecretKey",PICBED_QINIU_BUCKET:"設定Bucket",PICBED_QINIU_PATH:"設定儲存路徑",PICBED_QINIU_URL:"設定訪問網址",PICBED_QINIU_OPTIONS:"設定網址後綴",PICBED_QINIU_AREA:"設定儲存區域",PICBED_QINIU_MESSAGE_PATH:"例如:test/",PICBED_QINIU_MESSAGE_AREA:"例如:z0",PICBED_QINIU_MESSAGE_OPTIONS:"例如:?imageslim",PICBED_QINIU_MESSAGE_URL:"例如:https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"設定ClientId",PICBED_IMGUR_PROXY:"設定PROXY",PICBED_IMGUR_MESSAGE_PROXY:"例如:http://127.0.0.1:1080",PICBED_UPYUN:"又拍云",PICBED_UPYUN_BUCKET:"設定Bucket",PICBED_UPYUN_OPERATOR:"設定操作員",PICBED_UPYUN_PASSWORD:"設定操作員密碼",PICBED_UPYUN_PATH:"設定儲存路徑",PICBED_UPYUN_URL:"設定加速網址",PICBED_UPYUN_OPTIONS:"設定網址後綴",PICBED_UPYUN_MESSAGE_OPERATOR:"例如:me",PICBED_UPYUN_MESSAGE_PASSWORD:"輸入操作員密碼",PICBED_UPYUN_MESSAGE_URL:"例如:http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"例如:!imgslim",PICBED_UPYUN_MESSAGE_PATH:"例如:test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"插件安裝成功",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"插件安裝失敗",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"插件安裝失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"插件安裝失敗,請輸入正確的插件名稱或正確的安裝路徑",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"插件卸載成功",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"插件卸載失敗",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"插件卸載失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"插件卸載失敗,請輸入正確的插件名稱",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"插件更新成功",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"插件更新失敗",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"插件更新失敗,失敗碼為${code},錯誤紀錄為 \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"插件更新失敗,請輸入正確的插件名稱",CONFIG_SYNC_INVALID_ENCRYPTION_METHOD:"設定無效:settings.picgoCloud.encryptionMethod 必須是「auto」、「sse」或「e2ee」之一,目前為:${value}",CONFIG_SYNC_ENCRYPTION_METHOD_E2EE:"端對端加密",CONFIG_SYNC_ENCRYPTION_METHOD_SSE:"伺服器端加密",CONFIG_SYNC_ENCRYPTION_SWITCH_TITLE:"確認切換加密方式嗎?",CONFIG_SYNC_ENCRYPTION_SWITCH_BODY:"您正在從「${from}」切換為「${to}」。\n\n注意:切換加密模式將清空您所有的雲端歷史版本記錄。\n這是因為舊的歷史版本無法在新模式下被解密或驗證。\n切換後,系統將立即為您建立一份新的備份作為起點。",CONFIG_SYNC_ENCRYPTION_SWITCH_CONFIRM:"確認切換並清空歷史",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCEL:"取消",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCELLED:"已取消切換加密方式",CONFIG_SYNC_ENCRYPTION_SWITCH_MISSING_HANDLER:"需要提供加密方式切換確認處理器"},en:{UPLOAD_FAILED:"Upload failed",CHECK_SETTINGS:"Please check your settings",CHECK_SETTINGS_AND_NETWORK:"Please check your settings and network",UPLOAD_FAILED_REASON:"Error code: ${code}, please open the browser and paste the address to see the reason",SERVER_ERROR:"Server error, please try again later",AUTH_FAILED:"Authentication failed",CLOUD_LOGIN_CANCELLED:"Login cancelled",CLOUD_LOGIN_IN_PROGRESS:"Login is already in progress",CLOUD_LOGIN_INVALID_TOKEN:"Invalid token",CLOUD_LOGIN_SUCCESS:"Login success!",CLOUD_LOGOUT_SUCCESS:"Logout success!",CLOUD_LOGIN_SERVER_START_FAILED:"Failed to start PicGo server for login",CLOUD_LOGIN_OPEN_BROWSER_FAILED:"Failed to open browser automatically: ${message}",CLOUD_LOGIN_OPEN_BROWSER_TIP:"Please open this url in browser: ${url}",CLOUD_LOGIN_STATE_MISMATCH_WARN:"State mismatch or missing. Request blocked.",CLOUD_LOGIN_STATE_INVALID:"Invalid state. Please try logging in again.",CLOUD_LOGIN_TOKEN_MISSING:"Token missing in callback.",CLOUD_LOGIN_CODE_MISSING:"Code missing in callback.",CLOUD_LOGIN_EXCHANGE_FAILED:"Failed to exchange login code.",CLOUD_LOGIN_NOT_IN_PROGRESS:"Login flow is not in progress.",CLOUD_LOGIN_PAGE_TITLE:"PicGo Auth",CLOUD_LOGIN_RESULT_SUCCESS_TITLE:"Authorization Successful!",CLOUD_LOGIN_RESULT_FAILED_TITLE:"Authorization Failed",CLOUD_LOGIN_RESULT_SUCCESS_MESSAGE:"You can now close this window and return to PicGo.",PICGO_CLOUD_UPLOAD_LOGIN_REQUIRED:"Please log in to PicGo Cloud before using this uploader.",PICGO_CLOUD_UPLOAD_RELOGIN_REQUIRED:"Your PicGo Cloud session has expired. Please log in again and retry.",PICGO_CLOUD_UPLOAD_INVALID_PRESIGN_RESPONSE:"PicGo Cloud returned an invalid upload presign response.",PICGO_CLOUD_UPLOAD_INVALID_COMPLETE_RESPONSE:"PicGo Cloud returned an invalid upload completion response.",PICGO_CLOUD_UPLOAD_MISSING_FILE_NAME:"Missing file name. Unable to upload to PicGo Cloud.",PICGO_CLOUD_UPLOAD_MISSING_FILE_DATA:"Missing image data. Unable to upload to PicGo Cloud.",PICGO_CLOUD_UPLOAD_INVALID_INITIATE_RESPONSE:"PicGo Cloud returned an invalid multipart upload initiate response.",PICGO_CLOUD_UPLOAD_MULTIPART_NOT_FOUND:"Multipart upload session has expired. Please upload again.",PICGO_CLOUD_UPLOAD_MULTIPART_PART_FAILED:"A part failed to upload after multiple retries.",PICGO_CLOUD_UPLOAD_MULTIPART_COMPLETE_FAILED:"Multipart upload completion request failed.",PICGO_CLOUD_UPLOAD_PROGRESS_BAR:"Uploading ${fileName} ${loadedMB}/${totalMB} MB${resumedSuffix}",PICGO_CLOUD_UPLOAD_VERBOSE:"Uploading ${fileName}: ${loadedMB}/${totalMB} MB (${partsCompleted}/${totalParts} parts)${resumedSuffix}",PICGO_CLOUD_UPLOAD_RESUMED_SUFFIX:" (resumed)",CLOUD_ALBUM_PENDING_INVALID_FILE:"Pending import queue file is invalid and has been treated as empty: ${path}",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_DISABLED:"Cloud album auto import is disabled. Please enable auto import first.",CLOUD_ALBUM_IMPORT_PLAN_REQUIRED:"Cloud album import requires a paid PicGo Cloud plan.",CLOUD_ALBUM_AUTO_IMPORT_PENDING_WARNING:"Automatic import did not finish completely. The pending queue now contains ${count} item(s).",CLOUD_COMMAND_LOGIN_REQUIRED:"Please log in to PicGo Cloud first.",CLOUD_COMMAND_LOGIN_HINT:"Run `picgo login` (or `picgo cloud login`) and try again.",CLOUD_AUTH_STATUS_LOGGED_IN:"Logged in to PicGo Cloud (user: ${user})",CLOUD_AUTH_STATUS_LOGGED_OUT:"Not logged in to PicGo Cloud.",CLOUD_AUTH_STATUS_INVALID:"PicGo Cloud session is invalid. Please log in again.",CLOUD_AUTH_STATUS_ERROR:"Failed to check PicGo Cloud status: ${message}",GET_PLUGINS_EMPTY:"No installed plugins.",CLOUD_ALBUM_IMPORT_PROMPT_ENABLE_AUTO_IMPORT:"Cloud album auto import is disabled. Enable it now?",CLOUD_ALBUM_IMPORT_ENABLING_AUTO_IMPORT:"Enabling cloud album auto import...",CLOUD_ALBUM_IMPORT_AUTO_IMPORT_ENABLED:"Cloud album auto import has been enabled.",CLOUD_ALBUM_IMPORT_DUPLICATE_ID:"These items have already been imported to PicGo Cloud.",CLOUD_ALBUM_IMPORT_PROGRESS_BAR:"Importing ${current}/${total} (batch ${batchIndex}/${batchTotal})",CLOUD_ALBUM_IMPORT_VERBOSE_BATCH:"Batch ${batchIndex}/${batchTotal}: processed ${current}/${total}, created ${created}, skipped ${skipped}, failed ${failed}",CLOUD_ALBUM_IMPORT_SUMMARY_TITLE:"Import summary",CLOUD_ALBUM_IMPORT_SUMMARY_TOTAL:"Total",CLOUD_ALBUM_IMPORT_SUMMARY_CREATED:"Created",CLOUD_ALBUM_IMPORT_SUMMARY_SKIPPED:"Skipped",CLOUD_ALBUM_IMPORT_SUMMARY_INVALID:"Invalid",CLOUD_ALBUM_IMPORT_SUMMARY_FAILED:"Failed",CLOUD_ALBUM_IMPORT_SUMMARY_PENDING:"Pending",CLOUD_ALBUM_IMPORT_RETRY_HINT:"Run `picgo cloud album retry` to retry the pending items.",CLOUD_ALBUM_IMPORT_NO_PENDING:"There are no pending items to retry.",CLOUD_ALBUM_LIST_LOADING:"Fetching cloud album list...",CLOUD_ALBUM_LIST_DONE:"Fetched cloud album list",CLOUD_ALBUM_GET_LOADING:"Fetching cloud album item...",CLOUD_ALBUM_GET_DONE:"Fetched cloud album item",CLOUD_ALBUM_UPDATE_LOADING:"Updating cloud album item...",CLOUD_ALBUM_UPDATE_DONE:"Updated cloud album item",CLOUD_ALBUM_DELETE_LOADING:"Deleting cloud album item(s)...",CLOUD_ALBUM_DELETE_DONE:"Deleted cloud album item(s)",CLOUD_ALBUM_DELETE_CONFIRM:"Delete ${count} item(s) from the cloud album?",CLOUD_ALBUM_IMPORT_SOURCE_REQUIRED:"Provide one import source: a database path, `--json-file`, or `--data`.",CLOUD_ALBUM_IMPORT_SOURCE_CONFLICT:"Only one import source is allowed: database path, `--json-file`, or `--data`.",CLOUD_ALBUM_IMPORT_INVALID_JSON:"Import data must be a valid JSON array.",CLOUD_ALBUM_IMPORT_INVALID_JSON_FILE:"Failed to read the import JSON file: ${path}",CLOUD_ALBUM_IMPORT_LOADING_SOURCE:"Loading import data...",CLOUD_ALBUM_IMPORT_LOADING_SOURCE_DONE:"Loaded ${count} item(s)",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT:"Checking cloud import status...",CLOUD_ALBUM_IMPORT_CHECKING_AUTO_IMPORT_DONE:"Cloud import status verified",CLOUD_ALBUM_IMPORT_UPLOADING:"Importing to cloud...",CLOUD_ALBUM_IMPORT_UPLOADING_DONE:"Cloud import finished",CLOUD_ALBUM_RETRY_LOADING_PENDING:"Loading pending items...",CLOUD_ALBUM_RETRY_LOADING_PENDING_DONE:"Loaded ${count} pending item(s)",CLOUD_ALBUM_RETRY_UPLOADING:"Retrying import...",CLOUD_ALBUM_RETRY_UPLOADING_DONE:"Retry import finished",SERVER_INVALID_JSON_BODY:"Invalid JSON body",SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED:"Invalid request body: { list: string[] } required",SERVER_FORMDATA_NO_FILES_IN_FILES_FIELD:"No files found in form-data: files",SERVER_FORMDATA_FILES_MUST_BE_FILES:"Invalid form-data: files must be file(s)",SERVER_AUTH_ENABLED:"[PicGo Server] Authentication enabled.",SERVER_AUTH_DISABLED_WARNING:"[PicGo Server] Warning: Authentication disabled. Anyone can upload images.",SERVER_AUTH_UNAUTHORIZED_REQUEST:"[PicGo Server] Unauthorized request from ${ip}",SERVER_AUTH_QUERY_SECRET_WARNING:"[PicGo Server] Warning: Passing secret via URL query is insecure. Please use Authorization header.",URL_REWRITE_EMPTY_RESULT:"URL rewrite produced an empty result, please check your rule config",PICBED_SMMS:"SM.MS(S.EE)",PICBED_SMMS_TOKEN:"Set Token",PICBED_SMMS_BACKUP_DOMAIN:"Set Backup Upload Domain",PICBED_SMMS_MESSAGE_BACKUP_DOMAIN:"Ex. sm.ms",PICBED_ALICLOUD:"Ali Cloud",PICBED_ALICLOUD_ACCESSKEYID:"Set KeyId",PICBED_ALICLOUD_ACCESSKEYSECRET:"Set KeySecret",PICBED_ALICLOUD_BUCKET:"Set Bucket",PICBED_ALICLOUD_AREA:"Set Area",PICBED_ALICLOUD_PATH:"Set Path",PICBED_ALICLOUD_CUSTOMURL:"Set Custom URL",PICBED_ALICLOUD_OPTIONS:"Set URL Suffix",PICBED_ALICLOUD_MESSAGE_AREA:"Ex. oss-cn-beijing",PICBED_ALICLOUD_MESSAGE_PATH:"Ex. test/",PICBED_ALICLOUD_MESSAGE_OPTIONS:"Ex. ?x-oss-process=xxx",PICBED_ALICLOUD_MESSAGE_CUSTOMURL:"Ex. https://test.com",PICBED_TENCENTCLOUD:"Tencent Cloud",PICBED_TENCENTCLOUD_VERSION:"Choose COS version",PICBED_TENCENTCLOUD_SECRETID:"Set SecretId",PICBED_TENCENTCLOUD_SECRETKEY:"Set SecretKey",PICBED_TENCENTCLOUD_APPID:"Set AppId",PICBED_TENCENTCLOUD_BUCKET:"Set Bucket",PICBED_TENCENTCLOUD_AREA:"Set Area",PICBED_TENCENTCLOUD_ENDPOINT:"Set Endpoint",PICBED_TENCENTCLOUD_PATH:"Set Path",PICBED_TENCENTCLOUD_OPTIONS:"Set URL Suffix",PICBED_TENCENTCLOUD_SLIM:"Set ImageSlim",PICBED_TENCENTCLOUD_SLIM_TIP:"Image extremely intelligent compression, please refer to the [document description](https://cloud.tencent.com/document/product/436/49259)",PICBED_TENCENTCLOUD_SLIM_CONFIRM:"OPEN",PICBED_TENCENTCLOUD_SLIM_CANCEL:"CLOSE",PICBED_TENCENTCLOUD_CUSTOMURL:"Set Custom URL",PICBED_TENCENTCLOUD_MESSAGE_APPID:"Ex. 1234567890",PICBED_TENCENTCLOUD_MESSAGE_AREA:"Ex. ap-beijing",PICBED_TENCENTCLOUD_MESSAGE_ENDPOINT:"Ex. cos-internal.accelerate.tencentcos.cn",PICBED_TENCENTCLOUD_MESSAGE_PATH:"Ex. test/",PICBED_TENCENTCLOUD_MESSAGE_CUSTOMURL:"Ex. http://test.com",PICBED_TENCENTCLOUD_MESSAGE_OPTIONS:"Ex. ?imageMogr2",PICBED_GITHUB:"GitHub",PICBED_GITHUB_TOKEN:"Set Token",PICBED_GITHUB_REPO:"Set Repo Name",PICBED_GITHUB_PATH:"Set Path",PICBED_GITHUB_BRANCH:"Set Branch",PICBED_GITHUB_CUSTOMURL:"Set Custom URL",PICBED_GITHUB_MESSAGE_REPO:"Ex. username/repo",PICBED_GITHUB_MESSAGE_BRANCH:"Ex. main",PICBED_GITHUB_MESSAGE_PATH:"Ex. test/",PICBED_GITHUB_MESSAGE_CUSTOMURL:"Ex. https://test.com",PICBED_QINIU:"Qiniu",PICBED_QINIU_ACCESSKEY:"Set AccessKey",PICBED_QINIU_SECRETKEY:"Set SecretKey",PICBED_QINIU_BUCKET:"Set Bucket",PICBED_QINIU_PATH:"Set Path",PICBED_QINIU_URL:"Set URL",PICBED_QINIU_OPTIONS:"Set URL Suffix",PICBED_QINIU_AREA:"Set Area",PICBED_QINIU_MESSAGE_PATH:"Ex. test/",PICBED_QINIU_MESSAGE_AREA:"Ex. z0",PICBED_QINIU_MESSAGE_OPTIONS:"Ex. ?imageslim",PICBED_QINIU_MESSAGE_URL:"Ex. https://xxx.yyy.glb.clouddn.com",PICBED_IMGUR:"Imgur",PICBED_IMGUR_CLIENTID:"Set ClientId",PICBED_IMGUR_PROXY:"Set Proxy",PICBED_IMGUR_MESSAGE_PROXY:"Ex. http://127.0.0.1:1080",PICBED_UPYUN:"Upyun",PICBED_UPYUN_BUCKET:"Set Bucket",PICBED_UPYUN_OPERATOR:"Set Operator",PICBED_UPYUN_PASSWORD:"Set Operator Password",PICBED_UPYUN_PATH:"Set Path",PICBED_UPYUN_URL:"Set URL",PICBED_UPYUN_OPTIONS:"Set URL Suffix",PICBED_UPYUN_MESSAGE_OPERATOR:"Ex. me",PICBED_UPYUN_MESSAGE_PASSWORD:"Please type the operator password",PICBED_UPYUN_MESSAGE_URL:"Ex. http://xxx.test.upcdn.net",PICBED_UPYUN_MESSAGE_OPTIONS:"Ex. !imgslim",PICBED_UPYUN_MESSAGE_PATH:"Ex. test/",PLUGIN_HANDLER_PLUGIN_INSTALL_SUCCESS:"Plugin installed successfully",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED:"Plugin installation failed",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_REASON:"Plugin installation failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_INSTALL_FAILED_PATH:"Plugin installation failed, please enter a valid plugin name or valid installation path",PLUGIN_HANDLER_PLUGIN_UNINSTALL_SUCCESS:"Plugin uninstalled successfully",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED:"Plugin uninstall failed",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_REASON:"Plugin uninstall failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_UNINSTALL_FAILED_VALID:"Plugin uninstall failed, please enter a valid plugin name",PLUGIN_HANDLER_PLUGIN_UPDATE_SUCCESS:"Plugin updated successfully",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED:"Plugin update failed",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_REASON:"Plugin update failed, error code is ${code}, error log is \n ${data}",PLUGIN_HANDLER_PLUGIN_UPDATE_FAILED_VALID:"Plugin update failed, please enter a valid plugin name",CONFIG_SYNC_INVALID_ENCRYPTION_METHOD:"Invalid configuration: settings.picgoCloud.encryptionMethod must be one of 'auto', 'sse', 'e2ee'. Found: ${value}",CONFIG_SYNC_ENCRYPTION_METHOD_E2EE:"End-to-end encryption",CONFIG_SYNC_ENCRYPTION_METHOD_SSE:"Server-side encryption",CONFIG_SYNC_ENCRYPTION_SWITCH_TITLE:"Confirm switch encryption method?",CONFIG_SYNC_ENCRYPTION_SWITCH_BODY:'You are switching from "${from}" to "${to}".\n\nNote: Switching encryption modes will clear all your cloud history versions.\nThis is because older history versions cannot be decrypted or verified under the new mode.\nAfter switching, the system will immediately create a new backup as the starting point.',CONFIG_SYNC_ENCRYPTION_SWITCH_CONFIRM:"Confirm switch and clear history",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCEL:"Cancel",CONFIG_SYNC_ENCRYPTION_SWITCH_CANCELLED:"Encryption switch cancelled by user",CONFIG_SYNC_ENCRYPTION_SWITCH_MISSING_HANDLER:"Encryption switch confirmation handler is required"}};class Zn{i18n;objectAdapter;ctx;constructor(e){this.ctx=e,this.objectAdapter=new x.ObjectAdapter(Xn);let t=this.ctx.getConfig("settings.language")||"en";Xn[t]||(t="en"),this.i18n=new x.I18n({adapter:this.objectAdapter,defaultLanguage:t}),this.loadOutsideI18n()}loadOutsideI18n(){const i=this.getOutsideI18nFolder();e.readdirSync(i,{withFileTypes:!0}).forEach(r=>{if(r.isFile()&&r.name.endsWith(".yml")){const n=t.join(i,r.name),s=e.readFileSync(n,"utf8");try{const e=w.load(s);Xn[r.name.replace(/\.yml$/,"")]=e}catch(e){console.error(e)}}})}getOutsideI18nFolder(){const i=t.join(this.ctx.baseDir,"i18n-cli");return e.pathExistsSync(i)||e.ensureDirSync(i),i}translate(e,t){return this.i18n.translate(e,t)||e}setLanguage(e){this.i18n.setLanguage(e),this.ctx.saveConfig({"settings.language":e})}addLocale(e,t){const i=this.objectAdapter.getLocale(e);if(!i)return!1;const r=p.merge(i,t);return this.objectAdapter.setLocale(e,r),!0}addLanguage(e,t){return!this.objectAdapter.getLocale(e)&&(this.objectAdapter.setLocale(e,t),Xn[e]=t,!0)}getLanguageList(){return Object.keys(Xn)}}var es;function ts(e){return Object.values(es).includes(e)}!function(e){e.AUTH_CALLBACK="/auth/callback",e.UPLOAD="/upload",e.HEARTBEAT="/heartbeat"}(es||(es={}));const is=e=>{if(e instanceof Error)return e.message;if("string"==typeof e)return e;try{return JSON.stringify(e)}catch{return String(e)}};var rs;!function(e){e[e.Clipboard=0]="Clipboard",e[e.List=1]="List",e[e.Invalid=2]="Invalid"}(rs||(rs={}));const ns=e=>"object"==typeof e&&null!==e&&("arrayBuffer"in e&&"function"==typeof e.arrayBuffer),ss=e=>{const t=e.name;return"string"==typeof t&&""!==t.trim()?t:`${g.randomUUID()}.png`},os=e=>{if(e instanceof Error)return{success:!1,result:[],items:[],message:e.message};const t=e.map(e=>e.imgUrl).filter(e=>"string"==typeof e&&""!==e),i=e.map(e=>({origin:e.origin,imgUrl:e.imgUrl,fileName:e.fileName,type:e.type,contentType:e.contentType,size:e.size,width:e.width,height:e.height,extname:e.extname}));return 0===t.length?{success:!1,result:t,items:i,message:"All uploads failed"}:{success:!0,result:t,items:i}},as=(i,r,n)=>{i.post(es.UPLOAD,async i=>{try{const s=i.req.raw.headers.get("content-type")||"",o=(e,t)=>r.i18n?.translate(e,t)??String(e),a=n?.()??(e=>({uploadClipboard:async()=>await e.upload(),uploadPaths:async t=>await e.upload(t),getTempDir:()=>t.join(e.baseDir,"picgo-form-images")}))(r);if(s.includes("multipart/form-data")){const n=a.getTempDir?.()??t.join(r.baseDir,"picgo-form-images"),s=[];try{await e.ensureDir(n);const r=(await i.req.formData()).getAll("files");if(0===r.length)return i.json({success:!1,result:[],items:[],message:o("SERVER_FORMDATA_NO_FILES_IN_FILES_FIELD")},400);for(const a of r){if(!ns(a))return i.json({success:!1,result:[],items:[],message:o("SERVER_FORMDATA_FILES_MUST_BE_FILES")},400);const r=ss(a),c=t.basename(r),l=t.join(n,c),u=Buffer.from(await a.arrayBuffer());await e.writeFile(l,u),s.push(l)}const c=await a.uploadPaths(s),l=os(c);return i.json(l,l.success?200:500)}catch(e){return r.log.error(e),i.json({success:!1,result:[],items:[],message:is(e)},500)}finally{await Promise.allSettled(s.map(t=>e.remove(t)))}}const c=await i.req.raw.text().catch(()=>"");if(""===c.trim()){const e=await a.uploadClipboard(),t=os(e);return i.json(t,t.success?200:500)}let l;try{l=JSON.parse(c)}catch{return i.json({success:!1,result:[],items:[],message:o("SERVER_INVALID_JSON_BODY")},400)}const u=(e=>{if("object"!=typeof e||null===e)return{kind:rs.Invalid,messageKey:"SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED"};if(!("list"in e))return{kind:rs.Clipboard};const t=e.list;return void 0===t?{kind:rs.Clipboard}:Array.isArray(t)?0===t.length?{kind:rs.Clipboard}:t.every(e=>"string"==typeof e&&""!==e.trim())?{kind:rs.List,list:t}:{kind:rs.Invalid,messageKey:"SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED"}:{kind:rs.Invalid,messageKey:"SERVER_INVALID_REQUEST_BODY_LIST_REQUIRED"}})(l);if(u.kind===rs.Invalid)return i.json({success:!1,result:[],items:[],message:o(u.messageKey)},400);if(u.kind===rs.Clipboard){const e=await a.uploadClipboard(),t=os(e);return i.json(t,t.success?200:500)}const p=await a.uploadPaths(u.list),d=os(p);return i.json(d,d.success?200:500)}catch(e){return r.log.error(e),i.json({success:!1,result:[],items:[],message:is(e)},500)}}),i.post(es.HEARTBEAT,e=>e.json({success:!0,result:"alive"}))};var cs;!function(e){e.Authorization="authorization",e.Header="header",e.Query="query",e.None="none"}(cs||(cs={}));const ls=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e&&""!==e.trim()){const t=Number(e);if(Number.isFinite(t))return t}},us=e=>{if("string"!=typeof e)return;const t=e.trim();return""===t?void 0:t};class ps{app;ctx;server;listeningPort;listeningHost;authSecret;warnedQuerySecret=!1;staticRoutePrefixes=[];uploadAdapter;constructor(e){this.ctx=e,this.app=new B.Hono,this.initMiddleware(),this.initCoreRoutes()}registerGet(e,t,i=!1){this.handleRegister("get",e,t,i)}registerPost(e,t,i=!1){this.handleRegister("post",e,t,i)}registerPut(e,t,i=!1){this.handleRegister("put",e,t,i)}registerDelete(e,t,i=!1){this.handleRegister("delete",e,t,i)}registerMiddleware(e,t){this.app.use(e,t)}setUploadAdapter(e){this.uploadAdapter=e}registerStatic(e,t){const i=e.endsWith("/*")?e:`${e}/*`,r=i.replace(/\/\*$/,"")||"/";this.staticRoutePrefixes.includes(r)||this.staticRoutePrefixes.push(r),this.app.use(i,M.serveStatic({root:t}))}handleRegister(e,t,i,r){!ts(t)||r?this.app[e](t,i):this.ctx.log.warn(`[PicGo Server] Plugin attempted to overwrite builtin route: ${t}. Action denied.`)}mount(e,t){const i=new B.Hono;t(i),this.app.route(e,i)}getServerInfo(){return this.server&&this.listeningHost&&void 0!==this.listeningPort?`http://${this.listeningHost}:${this.listeningPort}/`:""}isListening(){return void 0!==this.server}initMiddleware(){this.app.use(G.cors()),this.app.use((e,t)=>this.handleAuth(e,t)),this.app.use(v.logger())}initCoreRoutes(){as(this.app,this.ctx,()=>this.uploadAdapter)}t(e,t){return this.ctx.i18n?.translate(e,t)??String(e)}getRequestPath(e){return"string"==typeof e.req.path?e.req.path:new URL(e.req.url).pathname}isStaticPath(e){return this.staticRoutePrefixes.some(t=>!!t&&("/"===t?"/"===e:e===t||e.startsWith(`${t}/`)))}shouldSkipAuth(e,t){return"OPTIONS"===e.toUpperCase()||(""===t||"/"===t||(!!this.isStaticPath(t)||!(!ts(t)||t===es.UPLOAD)))}extractAuthToken(e){const t=e.req.raw.headers;if(t.has("authorization")){const e=(t.get("authorization")??"").match(/^\s*Bearer\s+(.+)$/i);return{source:cs.Authorization,token:e?.[1]}}if(t.has("x-picgo-secret"))return{source:cs.Header,token:t.get("x-picgo-secret")??""};const i=new URL(e.req.url);return i.searchParams.has("secret")?{source:cs.Query,token:i.searchParams.get("secret")??""}:{source:cs.None}}warnQuerySecretOnce(){this.warnedQuerySecret||(this.warnedQuerySecret=!0,this.ctx.log.warn(this.t("SERVER_AUTH_QUERY_SECRET_WARNING")))}getClientIp(e){const t=e.req.raw.headers.get("x-forwarded-for");if(t){const e=t.split(",")[0]?.trim();if(e)return e}const i=e.env,r=i.server??i;return r?.incoming?.socket?.remoteAddress??"unknown"}logUnauthorized(e){const t=this.getClientIp(e);this.ctx.log.warn(this.t("SERVER_AUTH_UNAUTHORIZED_REQUEST",{ip:t}))}async handleAuth(e,t){if(!this.authSecret)return await t();const i=e.req.method,r=this.getRequestPath(e);if(this.shouldSkipAuth(i,r))return await t();const{source:n,token:s}=this.extractAuthToken(e);return n===cs.Query&&this.warnQuerySecretOnce(),s&&s===this.authSecret?await t():(this.ctx.log.warn(`[PicGo Server] Unauthorized request to ${i} ${r} with token from ${n}`),this.logUnauthorized(e),e.json({success:!1,message:"Unauthorized"},401))}async startServer(e,t){return await new Promise((i,r)=>{const n=b.serve({fetch:this.app.fetch,port:e,hostname:t},e=>{n.off("error",s),i({server:n,port:e.port})});function s(e){n.off("error",s),r(e)}n.once("error",s)})}async isExistingPicGoServer(e,t){const i=`http://${"0.0.0.0"===e||"::"===e?"127.0.0.1":e}:${t}/heartbeat`;try{const e=await _.post(i,void 0,{timeout:1e3});return!0===e?.data?.success&&"alive"===e?.data?.result}catch{return!1}}async listen(e,t,i=!1,r){if(this.server&&void 0!==this.listeningPort)return t&&this.listeningHost&&t!==this.listeningHost&&this.ctx.log.warn(`Server is already listening at http://${this.listeningHost}:${this.listeningPort}`),this.listeningPort;const n=this.ctx.getConfig("settings.server.port"),s=this.ctx.getConfig("settings.server.host"),o=this.ctx.getConfig("settings.server.secret"),a=ls(e)??ls(n)??36677,c=t??("string"==typeof s?s:void 0)??"127.0.0.1";this.authSecret=us(r)??us(process.env.PICGO_SERVER_SECRET)??us(o),this.warnedQuerySecret=!1,this.app=((e,t)=>{const i=new B.Hono,r=[],n=new Map;return e.routes.forEach(e=>{if("ALL"===e.method)return void r.push(e);const i=`${e.method}::${e.path}`,s=n.get(i);if(void 0!==s)ts(e.path)||t.log.warn(`Route conflict detected for [${e.method}] ${e.path}. Overriding previous handler.`),r[s]=e;else{const t=r.push(e)-1;n.set(i,t)}}),r.forEach(e=>{i.on(e.method,e.path,e.handler)}),i})(this.app,this.ctx);const l=async e=>{try{const{server:t,port:i}=await this.startServer(e,c);return this.server=t,this.listeningPort=i,this.listeningHost=c,this.authSecret?this.ctx.log.info(this.t("SERVER_AUTH_ENABLED")):this.ctx.log.warn(this.t("SERVER_AUTH_DISABLED_WARNING")),this.ctx.log.info(`[PicGo Server] Listening at http://${c}:${i}`),i}catch(t){if("EADDRINUSE"===t?.code){if(!i){if(await this.isExistingPicGoServer(c,e))return this.ctx.log.info(`[PicGo Server] Detected existing instance at http://${c}:${e}`),e}return this.ctx.log.warn(`[PicGo Server] port ${e} is busy, trying with port ${e+1}`),await l(e+1)}this.ctx.log.error(t)}};return await l(a)}shutdown(){try{this.server?.close()}catch{}finally{this.server=void 0,this.listeningPort=void 0,this.listeningHost=void 0,this.authSecret=void 0,this.warnedQuerySecret=!1}}}class ds{ctx;authState=null;pkceVerifier=null;pending;constructor(e){this.ctx=e,this.registerRoutes()}disposeLoginFlow(){const e=this.pending;if(!e)return;const t=this.ctx.i18n.translate("CLOUD_LOGIN_CANCELLED");e.abortController.abort(new Error(t))}async startLoginFlow(){if(this.pending)throw new Error(this.ctx.i18n.translate("CLOUD_LOGIN_IN_PROGRESS"));const e=this.ctx.server.isListening(),t=new AbortController,i=new Promise((i,r)=>{this.pending={resolve:i,reject:r,shouldShutdown:!e,abortController:t},t.signal.addEventListener("abort",()=>{const e=this.pending;if(!e||e.abortController!==t)return;this.pending=void 0,this.authState=null,this.pkceVerifier=null;const i=t.signal.reason,n=this.ctx.i18n.translate("CLOUD_LOGIN_CANCELLED"),s=i instanceof Error?i:new Error(String(i??n));r(s),e.shouldShutdown&&setTimeout(()=>{this.ctx.server.shutdown()},100)},{once:!0})});let r;try{r=await this.ctx.server.listen(void 0,"127.0.0.1",!0)}catch(e){const r=e instanceof Error?e:new Error(String(e));return t.abort(r),await i}if(void 0===r)return t.abort(new Error(this.ctx.i18n.translate("CLOUD_LOGIN_SERVER_START_FAILED"))),await i;if(t.signal.aborted)return await i;const n=encodeURIComponent(`http://127.0.0.1:${r}/auth/callback`);this.authState=F.randomUUID(),this.pkceVerifier=(()=>{const e=new Uint8Array(32);return g.webcrypto.getRandomValues(e),Ft(e)})();const s=encodeURIComponent(await(async e=>{const t=(new TextEncoder).encode(e),i=await g.webcrypto.subtle.digest("SHA-256",t);return Ft(new Uint8Array(i))})(this.pkceVerifier)),o=`${Mt}?callback=${n}&state=${encodeURIComponent(this.authState)}&challenge=${s}`;if(t.signal.aborted)return await i;try{await this.ctx.openUrl(o)}catch(e){const t=e instanceof Error?e.message:String(e);this.ctx.log.warn(this.ctx.i18n.translate("CLOUD_LOGIN_OPEN_BROWSER_FAILED",{message:t})),this.ctx.log.info(this.ctx.i18n.translate("CLOUD_LOGIN_OPEN_BROWSER_TIP",{url:o}))}return await i}renderResultPage(e,t){const i=e?"#2ecc71":"#e74c3c",r=e?this.ctx.i18n.translate("CLOUD_LOGIN_RESULT_SUCCESS_TITLE"):this.ctx.i18n.translate("CLOUD_LOGIN_RESULT_FAILED_TITLE"),n=e?"✓":"✕";return`\n <!DOCTYPE html>\n <html lang="en">\n <head>\n <title>${this.ctx.i18n.translate("CLOUD_LOGIN_PAGE_TITLE")}</title>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <style>\n body {\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100vh;\n margin: 0;\n background: #f0f2f5;\n }\n .card {\n background: white;\n padding: 40px;\n border-radius: 8px;\n box-shadow: 0 2px 10px rgba(0,0,0,0.1);\n text-align: center;\n max-width: 440px;\n width: calc(100% - 48px);\n }\n .icon {\n width: 64px;\n height: 64px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n margin: 0 auto 16px;\n background: ${i};\n color: #fff;\n font-size: 36px;\n line-height: 1;\n }\n h1 {\n color: ${i};\n margin: 0 0 12px;\n font-size: 24px;\n }\n p {\n color: #666;\n margin: 0 0 24px;\n line-height: 1.5;\n }\n .btn {\n display: inline-block;\n padding: 10px 20px;\n background: #333;\n color: white;\n text-decoration: none;\n border-radius: 4px;\n font-size: 14px;\n cursor: pointer;\n user-select: none;\n }\n </style>\n </head>\n <body>\n <div class="card">\n <div class="icon">${n}</div>\n <h1>${r}</h1>\n <p>${t}</p>\n </div>\n </body>\n </html>\n `}abortPendingLogin(e,t){e.abortController.signal.aborted||e.abortController.abort(new Error(t))}async handleCallback(e){const t=e.req.query("code"),i=e.req.query("state");if(!i||i!==this.authState)return this.ctx.log.warn(this.ctx.i18n.translate("CLOUD_LOGIN_STATE_MISMATCH_WARN")),e.html(this.renderResultPage(!1,this.ctx.i18n.translate("CLOUD_LOGIN_STATE_INVALID")),403);if(!t){const t=this.ctx.i18n.translate("CLOUD_LOGIN_CODE_MISSING"),i=this.pending;return i&&this.abortPendingLogin(i,t),e.html(this.renderResultPage(!1,t),400)}const r=this.pending;if(!r||r.abortController.signal.aborted)return e.html(this.renderResultPage(!1,this.ctx.i18n.translate("CLOUD_LOGIN_NOT_IN_PROGRESS")),409);const n=this.pkceVerifier;if(!n){this.ctx.log.error("PKCE verifier is missing during callback handling");const t=this.ctx.i18n.translate("CLOUD_LOGIN_EXCHANGE_FAILED");return this.abortPendingLogin(r,t),e.html(this.renderResultPage(!1,t),500)}try{this.ctx.log.info("API_BASE_URL",bt,"Exchanging login code for token...");const i=await(async(e,t)=>(await _.post("/api/tokens/exchange",{code:e,verifier:t},{baseURL:bt})).data)(t,n);if(!i.token){this.ctx.log.error("Token exchange failed without throwing an error");const t=i.message??this.ctx.i18n.translate("CLOUD_LOGIN_EXCHANGE_FAILED");return this.abortPendingLogin(r,t),e.html(this.renderResultPage(!1,t),500)}return this.ctx.saveConfig({"settings.picgoCloud.token":i.token}),this.authState=null,this.pkceVerifier=null,this.pending=void 0,r.resolve(i.token),r.shouldShutdown&&setTimeout(()=>{this.ctx.server.shutdown()},100),e.html(this.renderResultPage(!0,this.ctx.i18n.translate("CLOUD_LOGIN_RESULT_SUCCESS_MESSAGE")),200)}catch(t){let i,n;if(_.isAxiosError(t)){n=t.response?.status;const e=t.response?.data;(e=>Bt(e)&&"string"==typeof e.message)(e)&&(i=e.message)}const s=this.ctx.i18n.translate("CLOUD_LOGIN_EXCHANGE_FAILED"),o=i??s,a=400===n?400:500;return this.abortPendingLogin(r,o),this.ctx.log.error(`Token exchange failed: ${o} (status: ${a})`,t),e.html(this.renderResultPage(!1,o),a)}}registerRoutes(){this.ctx.server.registerGet(es.AUTH_CALLBACK,this.handleCallback.bind(this),!0)}}class _s{static DEFAULT_LIMIT=20;static DEFAULT_OFFSET=0;static IMPORT_BATCH_SIZE=100;static MAX_IMPORT_ATTEMPTS=3;ctx;client;pendingFilePath;constructor(e,t=new Kt(e)){this.ctx=e,this.client=t,this.pendingFilePath=O.join(e.baseDir,"picgo-cloud-import-list-pending.json")}async list(e={}){const t={limit:_s.DEFAULT_LIMIT,offset:_s.DEFAULT_OFFSET,...e},i=(r=t,Object.fromEntries(Object.entries(r).filter(([,e])=>null!=e)));var r;const n=await this.client.request({method:"GET",url:"/api/album-items",params:i});return{success:n.success,...n.data}}async get(e){return(await this.client.request({method:"GET",url:`/api/album-items/${e}`})).data.item}async update(e,t){const{extname:i,size:r,...n}=t;return(await this.client.request({method:"PATCH",url:`/api/album-items/${e}`,data:n})).data.item}async batchUpdate(e){if(0===e.length)return{updated:0,skipped:0,items:[]};const t=e.map(({id:e,data:t})=>{const{extname:i,size:r,...n}=t;return{id:e,...n}});return(await this.client.request({method:"PATCH",url:"/api/album-items",data:{items:t}})).data}async delete(e){if(Array.isArray(e)){if(0===e.length)return;await this.client.request({method:"DELETE",url:"/api/album-items",data:{ids:e}})}else await this.client.request({method:"DELETE",url:`/api/album-items/${e}`})}async getStats(){return(await this.client.request({method:"GET",url:"/api/album-items/stats"})).data}async getFilters(){const e=await this.client.request({method:"GET",url:"/api/album-items/filters"});return{success:e.success,...e.data}}async import(e){const t=await this.getPending(),i={total:e.length,created:0,skipped:0,invalid:0,failed:0,pending:t.length,items:[]},r=this.normalizeImportItems(e);if(i.invalid=e.length-r.length,0===r.length)return i;const n=((e,t)=>{const i=[];for(let r=0;r<e.length;r+=t)i.push(e.slice(r,r+t));return i})(r,_s.IMPORT_BATCH_SIZE);let s=0;for(const[e,t]of n.entries()){const o=await this.importBatchWithRetry(t);if(!o.ok){i.failed+=t.length,s+=t.length;const a=n.slice(e).flat(),c=await this.addToPending(a);return i.pending=c.length,this.emitImportProgress({total:r.length,current:s,batchIndex:e+1,batchTotal:n.length,created:i.created,skipped:i.skipped,failed:i.failed}),this.ctx.log.warn(qt(o.error)),i}i.created+=o.created,i.skipped+=o.skipped,i.items.push(...o.items),s+=t.length,this.emitImportProgress({total:r.length,current:s,batchIndex:e+1,batchTotal:n.length,created:i.created,skipped:i.skipped,failed:i.failed})}return i.pending=(await this.getPending()).length,i}async getPending(){try{const e=await E.readFile(this.pendingFilePath,"utf8"),t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>this.isImgInfoLike(e)):(this.warnInvalidPendingFile(),[])}catch(e){if(this.isFileMissing(e))return[];if(e instanceof SyntaxError)return this.warnInvalidPendingFile(),[];throw e}}async addToPending(e){if(0===e.length)return await this.getPending();const t=[...await this.getPending(),...e];return await this.writePending(t),t}async retryPending(){const e=await this.getPending();if(0===e.length)return{total:0,created:0,skipped:0,invalid:0,failed:0,pending:0,items:[]};await this.writePending([]);try{return await this.import(e)}catch(t){throw await this.writePending(e),t}}normalizeImportItems(e){return e.flatMap(e=>{const t="string"==typeof e.imgUrl?e.imgUrl.trim():"";if(""===t)return[];const i="string"==typeof e.id&&""!==e.id.trim()?e.id.trim():g.randomUUID(),r=this.resolveContentType(e),{mimeType:n,createdAt:s,updatedAt:o,origin:a,filePath:c,buffer:l,base64Image:u,_importToPicGoCloud:p,...d}=e,_=Gt(s),h=Gt(o),f=this.buildExtra(e);return[{...d,id:i,imgUrl:t,...r?{contentType:r}:{},...void 0!==_?{createdAt:_}:{},...void 0!==h?{updatedAt:h}:{},...f?{extra:f}:{}}]})}async importBatchWithRetry(e){let t;for(let i=0;i<_s.MAX_IMPORT_ATTEMPTS;i++)try{const t=await this.client.request({method:"POST",url:"/api/album-items",data:{items:e}});return{ok:!0,...this.normalizeBatchSummary(t,e.length),items:Array.isArray(t.data?.items)?t.data.items:[]}}catch(e){if(this.hasApiErrorCode(e,xt.DuplicateId))throw jt(this.ctx.i18n.translate("CLOUD_ALBUM_IMPORT_DUPLICATE_ID"),e);if(this.hasApiErrorCode(e,xt.ImportDisabled))throw jt(this.ctx.i18n.translate("CLOUD_ALBUM_IMPORT_AUTO_IMPORT_DISABLED"),e);if(this.isUnauthorizedError(e))throw jt(this.ctx.i18n.translate("PICGO_CLOUD_UPLOAD_RELOGIN_REQUIRED"),e);if(this.hasApiErrorCode(e,xt.PlanRequired))throw jt(qt(e),e);if(!this.shouldRetry(e))throw e;t=e}return{ok:!1,error:t}}normalizeBatchSummary(e,t){const i=e.data?.created,r=e.data?.skipped;if(void 0===i&&void 0===r)return{created:t,skipped:0};let n=vt(i,0),s=vt(r,0);const o=n+s-t;return o>0&&(s>=o?s-=o:(n=Math.max(0,n-(o-s)),s=0)),0===n&&0===s&&(n=t),{created:n,skipped:s}}resolveContentType(e){const t=e.contentType?.trim()||e.mimeType?.trim();if(t&&""!==t)return t;const i=e.extname?.trim();return i&&C.lookup(i)||void 0}buildExtra(e){const t="object"==typeof e.extra&&null!==e.extra?e.extra:{},i="string"==typeof e.origin&&""!==e.origin.trim()?e.origin.trim():void 0,r={...t,...i?{origin:i}:{}};return Object.keys(r).length>0?r:void 0}emitImportProgress(e){const t=e.total>0?Math.min(e.current/e.total,1):0,i={...e,fraction:t};this.ctx.emit(exports.IBuildInEvent.CLOUD_IMPORT_PROGRESS,i)}shouldRetry(e){if(_.isAxiosError(e)){const t=Yt(e);return void 0===t||t>=500}return!0}isUnauthorizedError(e){return 401===Yt(e)}hasApiErrorCode(e,t){return Vt(e)===t}async writePending(e){await P(this.pendingFilePath,`${JSON.stringify(e,null,2)}\n`,{encoding:"utf8"})}warnInvalidPendingFile(){this.ctx.log.warn(this.ctx.i18n.translate("CLOUD_ALBUM_PENDING_INVALID_FILE",{path:this.pendingFilePath}))}isFileMissing(e){return Bt(e)&&"ENOENT"===e.code}isImgInfoLike(e){return Bt(e)&&"string"==typeof e.id&&""!==e.id.trim()&&"string"==typeof e.imgUrl&&""!==e.imgUrl.trim()}}class gs{client;ctx;constructor(e){this.client=new Kt(e),this.ctx=e}async getUsage(e){const t=this.ctx.GUI_VERSION?wt.GUI:wt.CLI,i=zi();if(i)return this.ctx.log.warn(`[MOCK] BillingService.getUsage scenario=${i}`),function(e,t){const i="grace"===e||"frozen"===e||"pending-cleanup"===e,r=53687091200,n=524288e3;return{plan:"pro",effectiveQuotaPlan:i?"free":"pro",storage:{used:i?Math.round(734003200):Math.round(17179869184),limit:i?n:r},mediaCount:{used:i?5e3:8120,limit:i?200:5e4},monthlyServes:{used:12345,periodStart:Ji(-15),periodEnd:Ji(15)},configHistory:{used:5,limit:i?3:50,appType:t}}}(i,t===wt.GUI?"gui":"cli");const r=(await this.client.request({method:"GET",url:"/api/billing/usage",params:{appType:t}},e)).data;return{plan:r.plan,effectiveQuotaPlan:r.effectiveQuotaPlan,storage:r.storage,mediaCount:r.mediaCount,monthlyServes:r.monthlyServes,configHistory:r.configHistory}}async getOverview(e){const t=zi();if(t)return this.ctx.log.warn(`[MOCK] BillingService.getOverview scenario=${t}`),function(e){switch(e){case"active-pro":return{plan:{paid:"pro",capability:"pro",billingPeriod:"monthly",source:"entitlement"},lifecycle:{phase:"active",daysRemaining:20,graceEndsAt:null,freezeEndsAt:null,currentPhaseEndsAt:Ji(20),flags:{customDomainDisabledByLifecycle:!1,autoImportDisabledByLifecycle:!1}},subscription:{status:"active",currentPeriodEnd:Ji(20)}};case"active-pro-yearly":return{plan:{paid:"pro",capability:"pro",billingPeriod:"yearly",source:"entitlement"},lifecycle:{phase:"active",daysRemaining:180,graceEndsAt:null,freezeEndsAt:null,currentPhaseEndsAt:Ji(180),flags:{customDomainDisabledByLifecycle:!1,autoImportDisabledByLifecycle:!1}},subscription:{status:"active",currentPeriodEnd:Ji(180)}};case"active-pro-cancel":return{plan:{paid:"pro",capability:"pro",billingPeriod:"monthly",source:"entitlement"},lifecycle:{phase:"active",daysRemaining:20,graceEndsAt:null,freezeEndsAt:null,currentPhaseEndsAt:Ji(20),flags:{customDomainDisabledByLifecycle:!1,autoImportDisabledByLifecycle:!1}},subscription:{status:"scheduled_cancel",currentPeriodEnd:Ji(20)}};case"active-grant":return{plan:{paid:"free",capability:"pro",billingPeriod:null,source:"admin_grant"},lifecycle:{phase:"active",daysRemaining:30,graceEndsAt:null,freezeEndsAt:null,currentPhaseEndsAt:Ji(30),flags:{customDomainDisabledByLifecycle:!1,autoImportDisabledByLifecycle:!1}},subscription:null};case"active-grant-lifetime":return{plan:{paid:"free",capability:"pro",billingPeriod:null,source:"admin_grant"},lifecycle:{phase:"active",daysRemaining:null,graceEndsAt:null,freezeEndsAt:null,currentPhaseEndsAt:null,flags:{customDomainDisabledByLifecycle:!1,autoImportDisabledByLifecycle:!1}},subscription:null};case"grace":return{plan:{paid:"pro",capability:"pro",billingPeriod:"monthly",source:"entitlement"},lifecycle:{phase:"grace",daysRemaining:30,graceEndsAt:Ji(30),freezeEndsAt:Ji(90),currentPhaseEndsAt:Ji(30),flags:{customDomainDisabledByLifecycle:!0,autoImportDisabledByLifecycle:!0}},subscription:{status:"past_due",currentPeriodEnd:Ji(-3)}};case"frozen":return{plan:{paid:"pro",capability:"pro",billingPeriod:"monthly",source:"entitlement"},lifecycle:{phase:"frozen",daysRemaining:60,graceEndsAt:Ji(-30),freezeEndsAt:Ji(60),currentPhaseEndsAt:Ji(60),flags:{customDomainDisabledByLifecycle:!0,autoImportDisabledByLifecycle:!0}},subscription:{status:"canceled",currentPeriodEnd:Ji(-30)}};case"pending-cleanup":return{plan:{paid:"pro",capability:"pro",billingPeriod:"monthly",source:"entitlement"},lifecycle:{phase:"pending_cleanup",daysRemaining:null,graceEndsAt:Ji(-90),freezeEndsAt:Ji(-30),currentPhaseEndsAt:null,flags:{customDomainDisabledByLifecycle:!0,autoImportDisabledByLifecycle:!0}},subscription:null}}}(t);const i=(await this.client.request({method:"GET",url:"/api/billing/me"},e)).data;return{plan:i.plan,lifecycle:i.lifecycle,subscription:i.subscription}}}class hs{ctx;auth;billingService;albumService;uploaderService;userInfoCache;userInfoPromise;user;constructor(e){this.ctx=e,this.user=new Xi(e),this.auth=new ds(e),this.billingService=new gs(e)}get album(){return this.albumService||(this.albumService=new _s(this.ctx)),this.albumService}get uploader(){return this.uploaderService||(this.uploaderService=new un(this.ctx)),this.uploaderService}async login(e){if(e){if(!await this.user.verifyToken(e))throw new Error(this.ctx.i18n.translate("CLOUD_LOGIN_INVALID_TOKEN"));return this.ctx.saveConfig({"settings.picgoCloud.token":e}),this.clearUserInfoCache(),void this.ctx.log.success(this.ctx.i18n.translate("CLOUD_LOGIN_SUCCESS"))}const t=this.ctx.getConfig("settings.picgoCloud.token");if(t){if(await this.user.verifyToken(t))return void this.ctx.log.success(this.ctx.i18n.translate("CLOUD_LOGIN_SUCCESS"))}await this.auth.startLoginFlow(),this.clearUserInfoCache(),this.ctx.log.success(this.ctx.i18n.translate("CLOUD_LOGIN_SUCCESS"))}logout(){this.clearUserInfoCache(),this.ctx.removeConfig("settings.picgoCloud","token"),this.ctx.log.success(this.ctx.i18n.translate("CLOUD_LOGOUT_SUCCESS"))}disposeLoginFlow(){this.auth.disposeLoginFlow()}async getUserInfo(){const e=this.ctx.getConfig("settings.picgoCloud.token");if(!e)return this.clearUserInfoCache(),null;if(void 0!==this.userInfoCache)return this.userInfoCache;this.userInfoPromise||(this.userInfoPromise=this.fetchUserInfo(e));try{return await this.userInfoPromise}finally{this.userInfoPromise=void 0}}async refreshUserInfo(){return this.clearUserInfoCache(),await this.getUserInfo()}async getUsage(){const e=this.ctx.getConfig("settings.picgoCloud.token");if(!e)return null;try{return await this.billingService.getUsage(e)}catch(e){if(_.isAxiosError(e)){if(401===Yt(e))return this.clearUserInfoCache(),this.ctx.removeConfig("settings.picgoCloud","token"),null;const t=qt(e);if(""!==t.trim())throw jt(t,e)}throw e}}async getBillingOverview(){const e=this.ctx.getConfig("settings.picgoCloud.token");if(!e)return null;try{return await this.billingService.getOverview(e)}catch(e){if(_.isAxiosError(e)){if(401===Yt(e))return this.clearUserInfoCache(),this.ctx.removeConfig("settings.picgoCloud","token"),null;const t=qt(e);if(""!==t.trim())throw jt(t,e)}throw e}}async setAutoImport(e){const t=this.ctx.getConfig("settings.picgoCloud.token")?.trim();if(!t)throw new Error(this.ctx.i18n.translate("CLOUD_COMMAND_LOGIN_REQUIRED"));if(e){const e=await this.refreshUserInfo();if(!$t(e))throw jt(this.ctx.i18n.translate("CLOUD_ALBUM_IMPORT_PLAN_REQUIRED"),{status:403,apiCode:xt.PlanRequired})}const i=await this.user.setAutoImport(e,t),r={...this.userInfoCache,...i};return this.userInfoCache=r,r}async fetchUserInfo(e){try{const t=await this.user.whoami(e);return this.userInfoCache=t,t}catch(e){if(_.isAxiosError(e)){if(401===Yt(e))return this.clearUserInfoCache(),this.ctx.removeConfig("settings.picgoCloud","token"),null;const t=qt(e);if(""!==t.trim())throw jt(t,e)}throw e}}clearUserInfoCache(){this.userInfoCache=void 0,this.userInfoPromise=void 0}}const fs=()=>g.randomUUID(),Es=new Set(["current","uploader","transformer","proxy","list"]),ms=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Is=e=>e.trim(),Cs=e=>Is(e).toLowerCase();class Ls{ctx;constructor(e){this.ctx=e,this.init()}init(){const e=this.ctx.getConfig("picBed"),t=this.ctx.getConfig("uploader"),i=ms(e)?e:{},r=ms(t)?t:{},n=new Set;for(const e of Object.keys(i))Es.has(e)||n.add(e);for(const e of Object.keys(r))n.add(e);for(const e of n)this.migrateNormalizeAndSync(e)}listUploaderTypes(){return this.ctx.helper.uploader.getIdList()}getConfigList(e){return this.readTypeStore(e).configList}getActiveConfig(e){const t=this.readTypeStore(e);return this.getActiveConfigFromStore(t)}use(e,t){this.assertUploaderTypeExists(e);const i=this.readTypeStore(e);if(0===i.configList.length)return e!==Ie&&this.ctx.log.warn(`[UploaderConfigManager] No existing configs for uploader type "${e}". Creating a new metadata-only config`+(t?` named "${Is(t)}"`:"")+". Please configure it before uploading."),this.createOrUpdate(e,t,{});const r="string"==typeof t?Is(t):"";if(r){const n=this.findConfigByName(i.configList,r);if(!n)throw new Error(`Config ${t} not found in type ${e}`);return this.activate(e,i,n._id)}const{store:n,changed:s}=this.normalizeTypeStore(i),o=this.getActiveConfigFromStore(n);return o?this.persistTypeAndMirror(e,n,o,{setCurrent:!0,persistStore:s}):this.createOrUpdate(e,t,{})}createOrUpdate(e,t,i={}){this.assertUploaderTypeExists(e);const r=this.readTypeStore(e),n=Date.now(),s="string"==typeof t?Is(t):"",o=s?this.findConfigByName(r.configList,s):void 0;if(o){const t={...o,...i,_id:o._id,_configName:o._configName,_createdAt:o._createdAt,_updatedAt:n},s={configList:r.configList.map(e=>e._id===o._id?t:e),defaultId:t._id};return this.persistTypeAndMirror(e,s,t,{setCurrent:!0,persistStore:!0})}const a=s?this.ensureUniqueNameOrThrow(r.configList,s):this.generateDefaultName(r.configList),c={...i,_id:fs(),_configName:a,_createdAt:n,_updatedAt:n},l={configList:[...r.configList,c],defaultId:c._id};return this.persistTypeAndMirror(e,l,c,{setCurrent:!0,persistStore:!0})}copy(e,t,i){this.assertUploaderTypeExists(e);const r=this.readTypeStore(e),n=this.normalizeTypeStore(r).store,s=Is(t),o=this.findConfigByName(n.configList,s);if(!o)throw new Error(`Config ${t} not found in type ${e}`);const a=Is(i);if(!a)throw new Error("Config name can not be empty");const c=this.ensureUniqueNameOrThrow(n.configList,a),l=Date.now(),u={...o,_id:fs(),_configName:c,_createdAt:l,_updatedAt:l},d={configList:[...n.configList,u],defaultId:n.defaultId},_={[`uploader.${e}`]:d},g=this.getActiveConfigFromStore(d);if(g){const t=this.ctx.getConfig(`picBed.${e}`);p.isEqual(t,g)||(_[`picBed.${e}`]=g)}return this.ctx.saveConfig(_),u}rename(e,t,i){this.assertUploaderTypeExists(e);const r=this.readTypeStore(e),n=Is(t),s=Is(i);if(!s)throw new Error("Config name can not be empty");const o=this.findConfigByName(r.configList,n);if(!o)throw new Error(`Config ${t} not found in type ${e}`);this.ensureUniqueNameOrThrow(r.configList,s,o._id);const a=Date.now(),c={...o,_configName:s,_updatedAt:a},l={configList:r.configList.map(e=>e._id===o._id?c:e),defaultId:r.defaultId};return r.defaultId===o._id?(this.persistTypeAndMirror(e,l,c,{setCurrent:!1,persistStore:!0}),c):(this.ctx.saveConfig({[`uploader.${e}`]:l}),c)}remove(e,t){this.assertUploaderTypeExists(e);const i=this.readTypeStore(e),r=Is(t),n=this.findConfigByName(i.configList,r);if(!n)throw new Error(`Config ${t} not found in type ${e}`);const s=i.configList.filter(e=>e._id!==n._id);if(0===s.length)return this.ctx.saveConfig({[`uploader.${e}`]:{configList:[],defaultId:""}}),this.ctx.removeConfig("picBed",e),void(this.ctx.getConfig("picBed.current")===e&&this.ctx.log.warn(`You are currently using ${e} but have deleted its last config. Please switch to another uploader or create a new config.`));const o={configList:s,defaultId:i.defaultId===n._id?s[0]._id:i.defaultId},a=this.getActiveConfigFromStore(o);a?this.persistTypeAndMirror(e,o,a,{setCurrent:!1,persistStore:!0}):this.ctx.saveConfig({[`uploader.${e}`]:o})}migrateNormalizeAndSync(e){const t=this.ctx.getConfig(`picBed.${e}`);let i=this.readTypeStore(e),r=!1;if(0===i.configList.length&&ms(t)){const e=Date.now(),n={...t,_id:"string"==typeof t._id&&t._id.trim()?t._id:fs(),_configName:"string"==typeof t._configName&&Is(t._configName)?Is(t._configName):"Default",_createdAt:"number"==typeof t._createdAt?t._createdAt:e,_updatedAt:"number"==typeof t._updatedAt?t._updatedAt:e};i={configList:[n],defaultId:n._id},r=!0}const n=this.normalizeTypeStore(i);i=n.store,r=r||n.changed;const s={};r&&(s[`uploader.${e}`]=i);const o=this.getActiveConfigFromStore(i);if(o){const t=this.ctx.getConfig(`picBed.${e}`);p.isEqual(t,o)||(s[`picBed.${e}`]=o)}Object.keys(s).length>0&&this.ctx.saveConfig(s)}assertUploaderTypeExists(e){if(!this.listUploaderTypes().includes(e))throw new Error(`Type ${e} not found`)}readTypeStore(e){const t=this.ctx.getConfig(`uploader.${e}`);if(!ms(t))return{configList:[],defaultId:""};const i=t.configList,r=t.defaultId,n=[];if(Array.isArray(i))for(const e of i)ms(e)&&n.push(e);return{configList:n,defaultId:"string"==typeof r?r:""}}normalizeTypeStore(e){const t=Date.now();let i=!1;const r=new Set,n=new Set,s=e.configList.map(e=>{const s={...e};let o="string"==typeof s._id&&s._id.trim()?s._id:fs();for(;n.has(o);)o=fs();o!==s._id&&(s._id=o,i=!0),n.add(o);const a="number"==typeof s._createdAt?s._createdAt:t,c="number"==typeof s._updatedAt?s._updatedAt:t;a!==s._createdAt&&(s._createdAt=a,i=!0),c!==s._updatedAt&&(s._updatedAt=c,i=!0);let l=("string"==typeof s._configName?Is(s._configName):"")||this.generateDefaultNameFromUsed(r),u=Cs(l);if(r.has(u)){const e=l;let n=1;for(;r.has(Cs(`${e}-${n}`));)n++;l=`${e}-${n}`,u=Cs(l),s._updatedAt=t,i=!0}return l!==s._configName&&(s._configName=l,i=!0),r.add(u),s});let o=e.defaultId;if(s.length>0){s.some(e=>e._id===o)||(o=s[0]._id,i=!0)}else""!==o&&(o="",i=!0);return{store:{configList:s,defaultId:o},changed:i}}generateDefaultName(e){const t=new Set(e.map(e=>Cs(e._configName)));return this.generateDefaultNameFromUsed(t)}generateDefaultNameFromUsed(e){const t="Default";if(!e.has(Cs(t)))return t;let i=1;for(;e.has(Cs(`${t}-${i}`));)i++;return`${t}-${i}`}ensureUniqueNameOrThrow(e,t,i){const r=Is(t);if(!r)throw new Error("Config name can not be empty");const n=Cs(r);if(e.some(e=>e._id!==i&&Cs(e._configName)===n))throw new Error(`Config name ${t} already exists`);return r}findConfigByName(e,t){const i=Cs(t);return e.find(e=>Cs(e._configName)===i)}getActiveConfigFromStore(e){if(!e.defaultId)return e.configList[0];return e.configList.find(t=>t._id===e.defaultId)??e.configList[0]}activate(e,t,i){const r=t.configList.find(e=>e._id===i);if(!r)throw new Error(`Config not found for type ${e}`);const n={configList:t.configList,defaultId:i};return this.persistTypeAndMirror(e,n,r,{setCurrent:!0,persistStore:!0})}persistTypeAndMirror(e,t,i,r){const n={};if(r.persistStore&&(n[`uploader.${e}`]=t),i&&(n[`picBed.${e}`]=i),r.setCurrent&&(n["picBed.current"]=e,n["picBed.uploader"]=e),this.ctx.saveConfig(n),i)return i;const s=t.configList[0];if(!s)throw new Error(`No configs found in type ${e}`);return s}}class Os extends i.EventEmitter{_config;lifecycle;db;_pluginLoader;configPath;baseDir;helper;log;cmd;output;input;pluginHandler;server;cloud;uploaderConfig;Request;i18n;VERSION="3.0.0";GUI_VERSION;get pluginLoader(){return this._pluginLoader}constructor(e=""){super(),this.configPath=e,this.output=[],this.input=[],this.helper={transformer:new Or("transformer"),uploader:new Or("uploader"),beforeTransformPlugins:new Or("beforeTransformPlugins"),beforeUploadPlugins:new Or("beforeUploadPlugins"),afterUploadPlugins:new Or("afterUploadPlugins"),afterFinishPlugins:new Or("afterFinishPlugins")},this.initConfigPath(),this.log=new Dr(this),this.cmd=new Pr(this),this.pluginHandler=new zn(this),this.initConfig(),this.init()}initConfigPath(){if(""===this.configPath&&(this.configPath=r.homedir()+"/.picgo/config.json"),".JSON"!==t.extname(this.configPath).toUpperCase())throw this.configPath="",Error("The configuration file only supports JSON format.");this.baseDir=t.dirname(this.configPath);e.pathExistsSync(this.configPath)||e.ensureFileSync(`${this.configPath}`)}initConfig(){this.db=new Qn(this),this._config=this.db.read(!0)}init(){try{this.i18n=new Zn(this),this.Request=new Wn(this),this.server=new ps(this),this.cloud=new hs(this),this._pluginLoader=new $n(this),Ur("picgo"),Mn().register(this),{register(e){e.helper.transformer.register("path",vn),e.helper.transformer.register("base64",Gn)}}.register(this),Ur(""),this._pluginLoader.load(),this.uploaderConfig=new Ls(this),this.lifecycle=new Nr(this)}catch(e){throw this.emit(exports.IBuildInEvent.UPLOAD_PROGRESS,-1),this.log.error(e),e}}use(e,t){if(t)return this.pluginLoader.registerPlugin(t,e),this.pluginLoader.getPlugin(t);return e(this)}registerCommands(){""!==this.configPath&&(this.cmd.init(),this.cmd.loadCommands())}getConfig(e){return e?p.get(this._config,e):this._config}saveConfig(e){ae(e)?(this.setConfig(e),this.db.saveConfig(e)):this.log.warn("the format of config is invalid, please provide object")}removeConfig(e,t){e&&t&&(oe(e)?this.log.warn(`the config.${e} can't be removed`):(this.unsetConfig(e,t),this.db.unset(e,t)))}setConfig(e){ae(e)?Object.keys(e).forEach(t=>{oe(t)&&(this.log.warn(`the config.${t} can't be modified`),delete e[t]),p.set(this._config,t,e[t]),Yn.emit(exports.IBusEvent.CONFIG_CHANGE,{configName:t,value:e[t]})}):this.log.warn("the format of config is invalid, please provide object")}unsetConfig(e,t){e&&t&&(oe(e)?this.log.warn(`the config.${e} can't be unset`):p.unset(this.getConfig(e),t))}get request(){return this.Request.request.bind(this.Request)}async openUrl(e){const t=(await import("open")).default;this.log.info("Opening browser with URL:",e),await t(e)}async upload(t,i){if(""===this.configPath)return this.log.error("The configuration file only supports JSON format."),[];if(void 0!==t&&0!==t.length){const{output:e}=await this.lifecycle.start(t,i);return e}try{const{imgPath:t,shouldKeepAfterUploading:r}=await Hn(this);if("no image"===t)throw new Error("image not found in clipboard");{this.once(exports.IBuildInEvent.FAILED,()=>{r||e.remove(t).catch(e=>{this.log.error(e)})}),this.once("finished",()=>{r||e.remove(t).catch(e=>{this.log.error(e)})});const{output:n}=await this.lifecycle.start([t],i);return n}}catch(e){throw this.emit(exports.IBuildInEvent.FAILED,e),e}}}const Us={...Ee,applyUrlRewriteToImgInfo:H};exports.CloudManager=hs,exports.Commander=Pr,exports.ConfigMerger=Zt,exports.ConfigSyncManager=Ii,exports.CorruptedDataError=ti,exports.DecryptionFailedError=ai,exports.InvalidPinError=si,exports.Lifecycle=Nr,exports.LifecyclePlugins=Or,exports.Logger=Dr,exports.MaxRetryExceededError=oi,exports.MissingHandlerError=ri,exports.PicGo=Os,exports.PicGoUtils=Us,exports.PluginHandler=zn,exports.PluginLoader=$n,exports.Request=Wn,exports.ServerManager=ps,exports.UnsupportedVersionError=ii,exports.evaluatePluginConfig=function(e,t,i){const r={...t??{}};return e.map(e=>{const t={...e};if("function"==typeof e.default)try{t.default=e.default({...r})}catch(r){t.default=void 0,i?.onError?.(e.name,"default",r)}if("function"==typeof e.choices)try{t.choices=e.choices({...r})}catch(r){t.choices=[],i?.onError?.(e.name,"choices",r)}return void 0===r[e.name]&&void 0!==t.default&&(r[e.name]=t.default),t})};
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|