UNPKG

@snazzah/emoji-sync

Version:

Sync Discord emojis with your app

9 lines (8 loc) 11.9 kB
"use strict";var mt=Object.create;var A=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var X=s=>{throw TypeError(s)};var gt=(s,e)=>{for(var t in e)A(s,t,{get:e[t],enumerable:!0})},Z=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ut(e))!ft.call(s,r)&&r!==t&&A(s,r,{get:()=>e[r],enumerable:!(i=ct(e,r))||i.enumerable});return s};var Q=(s,e,t)=>(t=s!=null?mt(dt(s)):{},Z(e||!s||!s.__esModule?A(t,"default",{value:s,enumerable:!0}):t,s)),pt=s=>Z(A({},"__esModule",{value:!0}),s);var F=(s,e,t)=>e.has(s)||X("Cannot "+t);var a=(s,e,t)=>(F(s,e,"read from private field"),t?t.call(s):e.get(s)),m=(s,e,t)=>e.has(s)?X("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,t),b=(s,e,t,i)=>(F(s,e,"write to private field"),i?i.call(s,t):e.set(s,t),t),c=(s,e,t)=>(F(s,e,"access private method"),t);var Rt={};gt(Rt,{API_BASE_URL:()=>G,API_VERSION:()=>Ut,CDN_URL:()=>wt,DiscordHTTPError:()=>x,DiscordRESTError:()=>q,EmojiManager:()=>V,VERSION:()=>W,extensionToMimeType:()=>S,getCreatedAt:()=>K,getDiscordEpoch:()=>it,getFiles:()=>L,toDataUri:()=>P,toMarkdown:()=>N});module.exports=pt(Rt);var k=require("path");var p,j,C,y=class{constructor(){m(this,j);m(this,p,[])}get locked(){return a(this,p).length>0}acquire(e){let t=this.locked,i=new Promise(r=>{if(e)return a(this,p).unshift(r);a(this,p).push(r)});return t||c(this,j,C).call(this),i}static wait(e){return new Promise(t=>{setTimeout(t,e)})}};p=new WeakMap,j=new WeakSet,C=function(){let e=a(this,p).shift();if(!e)return;let t=!1;e(()=>{t||(t=!0,c(this,j,C).call(this))})};var x=class s extends Error{constructor(e,t,i){super(`${t.status} ${t.statusText||"Unknown error"} on ${e.method} ${e.path}`),this.req=e,this.res=t,this.code=t.status,this.stack="",i?this.stack=this.name+": "+this.message+` `+i:Error.captureStackTrace(this,s)}get headers(){return this.res.headers}get name(){return this.constructor.name}};var q=class s extends Error{constructor(e,t,i,r){super(),this.req=e,this.res=t,this.response=i,this.code=t.status;let n=i?.message||"Unknown error";if(i?.errors)n+=` `+this.flattenErrors(i.errors).join(` `);else if(i){let l=this.flattenErrors(i);l.length>0&&(n+=` `+l.join(` `))}this.message=n,r?this.stack=this.name+": "+this.message+` `+r:(this.stack="",Error.captureStackTrace(this,s))}get name(){return`${this.constructor.name} [${this.code}]`}flattenErrors(e,t=""){let i=[];for(let r in e)if(!(!(r in e)||r==="message"||r==="code")){if(r==="_errors"){i=i.concat(e._errors.map(n=>`${t?`${t}: `:""}${n.message}`));continue}e[r]._errors?i=i.concat(e[r]._errors.map(n=>`${t+r}: ${n.message}`)):Array.isArray(e[r])?i=i.concat(e[r].map(n=>`${t+r}: ${n}`)):typeof e[r]=="object"&&(i=i.concat(this.flattenErrors(e[r],t+r+".")))}return i}};async function Y(s){return s.headers.get("content-type")==="application/json"?await s.json():null}function yt(s){switch(s){case"user":return"User";case"global":return"Global";case"shared":return"Shared";default:return"Unexpected"}}var o,w,D,O,f,T,tt,et,v=class{constructor(e,t,i){m(this,f);this.limit=1;this.remaining=1;this.reset=0;m(this,o);m(this,w);m(this,D);m(this,O,new y);b(this,o,e),b(this,w,t),b(this,D,i)}get id(){return`${a(this,w)}:${a(this,D)}`}get inactive(){return!this.limited&&!a(this,o).limited&&!a(this,O).locked}get limited(){return this.remaining<=0&&Date.now()<this.reset}async add(e,t){let i=await a(this,O).acquire(t);try{return await c(this,f,T).call(this,e)}finally{i()}}};o=new WeakMap,w=new WeakMap,D=new WeakMap,O=new WeakMap,f=new WeakSet,T=async function(e,t=0){let i={};for(Error.captureStackTrace(i),i.stack.startsWith(`Error `)&&(i.stack=i.stack.substring(6));this.limited||a(this,o).limited;){if(a(this,o).limited){let u=a(this,o).globalReset-Date.now();a(this,o).globalTimeout||c(this,f,et).call(this,u),await a(this,o).globalTimeout;continue}let h=this.reset-Date.now();await y.wait(h)}a(this,o).globalReset<Date.now()&&(a(this,o).globalReset=Date.now()+1e3,a(this,o).globalBlock=!1);let r,n=Date.now();try{r=await e.send(),n=Date.now()-n}catch(h){if(t>=a(this,o).options.retryLimit)throw h.name==="AbortError"?new Error(`Request timed out (>${a(this,o).options.requestTimeout}ms) on ${e.method} ${e.path}`):h;return c(this,f,T).call(this,e,++t)}a(this,o).manager?.listenerCount("rawREST")&&a(this,o).manager.emit("rawREST",{auth:e.options.auth??!1,body:e.options.body,files:e.options.files,latency:n,url:e.url,method:e.method,request:e,response:r});let l=c(this,f,tt).call(this,e,r,n);if(a(this,o).manager?.emit("debug",`${e.method} ${e.route} (${this.id}) ${r.status}: ${n}ms | ${this.remaining}/${this.limit} left | Reset ${this.reset} (${this.reset-Date.now()}ms left)`),r.status>=200&&r.status<300)return Y(r);if(r.status>=400&&r.status<500){let h=await Y(r);if(r.status===429){let u=h.retry_after?h.retry_after*1e3:l;return a(this,o).manager?.emit("debug",`${yt(r.headers.get("x-ratelimit-scope"))} 429. Retrying in ${u}ms (${this.id})`),u&&await y.wait(u),c(this,f,T).call(this,e,t)}throw new q(e,r,h,i.stack)}if(r.status>=500&&r.status<600){if(t>=a(this,o).options.retryLimit)throw new x(e,r,i.stack);return c(this,f,T).call(this,e,++t)}return null},tt=function(e,t,i){let r=t.headers.get("x-ratelimit-bucket"),n=t.headers.get("x-ratelimit-limit"),l=t.headers.get("x-ratelimit-remaining"),h=t.headers.get("x-ratelimit-reset-after")||t.headers.get("retry-after"),u=Date.now();if(r)if(a(this,w)!==r)a(this,o).hashes.set(e.id,{value:r,lastAccess:u}),a(this,o).manager?.emit("debug",`Updated bucket hash (${a(this,w)}) to ${r}`);else{let J=a(this,o).hashes.get(e.id);J&&(J.lastAccess=u)}n&&(this.limit=+n),this.remaining=l?+l:1;let d=0;if(h&&(d=+h*1e3+a(this,o).options.ratelimiterOffset),d>0)return t.headers.get("x-ratelimit-global")?(a(this,o).globalReset=u+d,a(this,o).globalBlock=!0):this.reset=u+d,d;let g=t.headers.has("date")?Date.parse(t.headers.get("date")):u,U=u-g+i;this.reset=Math.max(+(t.headers.get("x-ratelimit-reset")||0)*1e3+U,u)+a(this,o).options.ratelimiterOffset},et=function(e){a(this,o).globalTimeout=y.wait(e).then(()=>{a(this,o).globalTimeout=void 0})};var rt=Q(require("path")),B=require("fs/promises");async function L(s,e=!1){let t=await(0,B.readdir)(s),i=[];for(let r of t){let n=rt.default.join(s,r),l=await(0,B.lstat)(n);l.isDirectory()&&e?i.push(...await L(n)):l.isFile()&&i.push(n)}return i}function K(s){return it(s)+14200704e5}function it(s){return Math.floor(Math.floor(Number(BigInt(s)/4194304n)))}function N(s){return`<${s.animated?"a":""}:${s.name}:${s.id}>`}function P(s,e){let t=("Buffer"in globalThis&&s instanceof Buffer?s:Buffer.from(s)).toString("base64");return`data:${e};base64,${t}`}function S(s){switch((s.startsWith(".")?s.slice(1):s).toLowerCase()){case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"gif":return"image/gif";case"webp":return"image/webp";default:return null}}var W="0.1.2",Ut=10,G="https://discord.com/api/v10",wt="https://cdn.discordapp.com";var bt=`DiscordBot (https://github.com/Snazzah/emoji-sync, ${W})`,R,st,nt,M=class{constructor(e,t,i,r){m(this,R);this.headers={"User-Agent":bt};if(this.handler=e,this.method=t,this.path=i,this.options=r,this.url=new URL(e.options.baseURL+i),typeof r.query=="object")for(let n in r.query)r.query[n]!==void 0&&this.url.searchParams.append(n,r.query[n]);if(typeof r.headers=="object")for(let n in r.headers)this.headers[n]=r.headers[n];r.reason&&(this.headers["X-Audit-Log-Reason"]=encodeURIComponent(r.reason)),this.setBody(r.body,r.files),this.majorParameter=c(this,R,st).call(this),this.route=c(this,R,nt).call(this)}get id(){return`${this.method}:${this.route}`}async send(){let e=new AbortController;return setTimeout(()=>e.abort(),this.handler.options.requestTimeout),fetch(this.url,{body:this.data,dispatcher:this.handler.options.dispatcher,headers:this.headers,method:this.method,signal:e.signal})}setBody(e,t){if(t?.length){let i=new FormData;for(let r=0;r<t.length;r++)if(t[r]){let n=t[r].file;"Buffer"in globalThis&&n instanceof Buffer&&(n=new Blob([n])),i.append(`files[${r}]`,n,t[r].name)}e&&i.append("payload_json",JSON.stringify(e)),this.data=i}else e&&(this.data=JSON.stringify(e,(i,r)=>typeof r=="bigint"?r.toString():r),this.headers["Content-Type"]="application/json");return this}};R=new WeakSet,st=function(){return/^\/(?:channels|guilds|webhooks)\/(\d{16,19})/.exec(this.path)?.[1]??"global"},nt=function(){let e=this.path.replace(/\/reactions\/.*/g,"/reactions/:id").replace(/\d{16,19}/g,":id").replace(/[a-zA-Z0-9]{150,300}/g,":token"),t="";if(this.method==="DELETE"&&e==="/channels/:id/messages/:id"){let i=this.path.slice(this.path.lastIndexOf("/")+1),r=K(i),n=Date.now()-r;n>=12096e5?t+=";old":n<=1e4&&(t+=";new")}return e+t};var E,I,at,_=class{constructor(e,t={}){m(this,I);this.buckets=new Map;this.globalBlock=!1;this.globalReset=0;this.hashes=new Map;m(this,E);this.manager=e,this.options={baseURL:t.baseURL??G,ratelimiterOffset:t.ratelimiterOffset??0,requestTimeout:t.requestTimeout??15e3,retryLimit:t.retryLimit??3},t.token&&b(this,E,t.token)}get limited(){return this.globalBlock&&Date.now()<this.globalReset}async request(e,t,i={}){let r=new M(this,e,t,i);if(i.auth){if(!a(this,E))throw new Error("Missing required token");r.headers.Authorization=a(this,E)}let n=this.hashes.get(r.id)?.value??r.id;return c(this,I,at).call(this,n,r.majorParameter).add(r)}};E=new WeakMap,I=new WeakSet,at=function(e,t){let i=this.buckets.get(`${e}:${t}`);if(i)return i;let r=new v(this,e,t);return this.buckets.set(r.id,r),r};var ot=require("url"),z=require("fs/promises"),lt=Q(require("eventemitter3"));var $,H,ht,V=class extends lt.default{constructor(t){super();m(this,H);this.emojis=new Map;m(this,$,new Map);let i=t.token&&!t.token.startsWith("Bot ")&&!t.token.startsWith("Bearer ")?"Bot "+t.token:t.token;this.requestHandler=new _(this,{...t.rest??{},token:i})}get(t){return this.emojis.get(t)??null}getPartial(t){let i=this.emojis.get(t);return i?{id:i.id,name:i.name,animated:i.animated}:null}getMarkdown(t){let i=this.get(t);return i?N(i):null}load(t){for(let i in t)a(this,$).set(i,t[i])}async loadFromFolder(t,i){let r=await L(t,i?.recursive??!1);for(let n of r){let l=(0,k.parse)(n).name;a(this,$).set(l,n)}}async sync(){let i=`/applications/${await c(this,H,ht).call(this)}/emojis`,r=await this.requestHandler.request("GET",i,{auth:!0});for(let n of r.items)this.emojis.set(n.name,n);for(let[n,l]of a(this,$)){if(this.emojis.has(n))continue;let h;if(l.startsWith("data:"))h=l;else if(l.startsWith("file:")){let d=(0,ot.fileURLToPath)(l),g=await(0,z.readFile)(d),U=S((0,k.extname)(d));if(!U)throw new Error(`[${n}] Unknown file type for file: ${d}`);h=P(g,U)}else if(l.startsWith("https://")||l.startsWith("http://")){let d=await fetch(l);if(!d.ok)throw new Error(`[${n}] URL returned ${d.status}: ${l}`);let g=d.headers.get("content-type")||S((0,k.extname)(l));if(!g)throw new Error(`[${n}] URL response does not have a Content-Type and URL does not have a known extension: ${l}`);h=P(await d.arrayBuffer(),g)}else{let d=await(0,z.readFile)(l),g=S((0,k.extname)(l));if(!g)throw new Error(`[${n}] Unknown file type for file: ${l}`);h=P(d,g)}this.emit("debug",`Uploading emoji ${n} from path "${l}"...`);let u=await this.requestHandler.request("POST",i,{auth:!0,body:{name:n,image:h}});this.emojis.set(u.name,u)}}loadFromDiscord(t){for(let i of t)this.emojis.set(i.name,i)}};$=new WeakMap,H=new WeakSet,ht=async function(){if(this.applicationId)return this.applicationId;let t=await this.requestHandler.request("GET","/applications/@me",{auth:!0});return this.applicationId=t.id,this.applicationId};0&&(module.exports={API_BASE_URL,API_VERSION,CDN_URL,DiscordHTTPError,DiscordRESTError,EmojiManager,VERSION,extensionToMimeType,getCreatedAt,getDiscordEpoch,getFiles,toDataUri,toMarkdown});