simply-xp 2.0.0-beta.0 → 2.0.0-beta.0-fix.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/README.md CHANGED
@@ -25,15 +25,15 @@
25
25
  ## 🖥️ <b>[DEV] Installation</b>
26
26
 
27
27
  ```shell
28
- npm install simply-xp@dev
28
+ npm install simply-xp@beta
29
29
  ```
30
30
 
31
31
  ```shell
32
- pnpm install simply-xp@dev
32
+ pnpm install simply-xp@beta
33
33
  ```
34
34
 
35
35
  ```shell
36
- yarn add simply-xp@dev
36
+ yarn add simply-xp@beta
37
37
  ```
38
38
 
39
39
  <br>
package/lib/src/add.js CHANGED
@@ -9,7 +9,7 @@
9
9
  * @link `Documentation:` https://simplyxp.js.org/docs/next/functions/addlevel
10
10
  * @returns {Promise<UserResult>} - Object of user data on success
11
11
  * @throws {XpFatal} - If parameters are not provided correctly
12
- */async function addLevel(userId,guildId,level,username){if(!userId)throw new xplogs_1.XpFatal({function:"addLevel()",message:"User ID was not provided"});if(!guildId)throw new xplogs_1.XpFatal({function:"addLevel()",message:"Guild ID was not provided"});if(isNaN(level))throw new xplogs_1.XpFatal({function:"addLevel()",message:"Level was not provided"});var e=await database_1.db.findOne({collection:"simply-xps",data:{user:userId,guild:guildId}});if(e)return database_1.db.updateOne({collection:"simply-xps",data:{user:userId,guild:guildId}},{collection:"simply-xps",data:{name:username||e?.name||userId,user:userId,guild:guildId,level:e.level+level,xp:(0,xp_1.convertFrom)(level+e.level),xp_rate:xp_1.xp.xp_rate}});if(xp_1.xp.auto_create&&username)return database_1.db.createOne({collection:"simply-xps",data:{guild:guildId,user:userId,name:username,level:level,xp:(0,xp_1.convertFrom)(level),xp_rate:xp_1.xp.xp_rate}});throw new xplogs_1.XpFatal({function:"addLevel()",message:"User does not exist"})}
12
+ */async function addLevel(e,a,t,l){if(!e)throw new xplogs_1.XpFatal({function:"addLevel()",message:"User ID was not provided"});if(!a)throw new xplogs_1.XpFatal({function:"addLevel()",message:"Guild ID was not provided"});if(isNaN(t))throw new xplogs_1.XpFatal({function:"addLevel()",message:"Level was not provided"});var o=await database_1.db.findOne({collection:"simply-xps",data:{user:e,guild:a}});if(o)return database_1.db.updateOne({collection:"simply-xps",data:{user:e,guild:a}},{collection:"simply-xps",data:{name:l||o?.name||e,user:e,guild:a,level:o.level+t,xp:(0,xp_1.convertFrom)(t+o.level),xp_rate:xp_1.xp.xp_rate}});if(xp_1.xp.auto_create&&l)return database_1.db.createOne({collection:"simply-xps",data:{guild:a,user:e,name:l,level:t,xp:(0,xp_1.convertFrom)(t),xp_rate:xp_1.xp.xp_rate}});throw new xplogs_1.XpFatal({function:"addLevel()",message:"User does not exist"})}
13
13
  /**
14
14
  * Add XP to a user.
15
15
  * @async
@@ -20,4 +20,4 @@
20
20
  * @link `Documentation:` https://simplyxp.js.org/docs/next/functions/addxp
21
21
  * @returns {Promise<XPResult>} - Object of user data on success.
22
22
  * @throws {XpFatal} - If parameters are not provided correctly.
23
- */async function addXP(userId,guildId,xpData,username){var e;if(!("number"==typeof xpData||"object"==typeof xp_1.xp&&xpData.min&&xpData.max))throw new xplogs_1.XpFatal({function:"addXP()",message:"XP is not a number or object, make sure you are using the correct syntax"});if("object"==typeof xpData&&(xpData=Math.floor(Math.random()*(xpData.max-xpData.min)+xpData.min)),!userId)throw new xplogs_1.XpFatal({function:"addXP()",message:"User ID was not provided"});if(!guildId)throw new xplogs_1.XpFatal({function:"addXP()",message:"Guild ID was not provided"});let a;if(e=await database_1.db.findOne({collection:"simply-xps",data:{user:userId,guild:guildId}}))a=await database_1.db.updateOne({collection:"simply-xps",data:{user:userId,guild:guildId}},{collection:"simply-xps",data:{user:userId,guild:guildId,name:username||e?.name||userId,level:(0,xp_1.convertFrom)(e.xp+xpData,"xp"),xp:e.xp+xpData,xp_rate:xp_1.xp.xp_rate}}).catch(err=>{throw new xplogs_1.XpFatal({function:"addXP()",message:err.stack})});else{if(!xp_1.xp.auto_create||!username)throw new xplogs_1.XpFatal({function:"addXP()",message:"User does not exist"});a=await database_1.db.createOne({collection:"simply-xps",data:{guild:guildId,user:userId,name:username,level:(0,xp_1.convertFrom)(xpData,"xp"),xp:xpData,xp_rate:xp_1.xp.xp_rate}}).catch(err=>{throw new xplogs_1.XpFatal({function:"addXP()",message:err.stack})})}return username=xplogs_1.XpEvents.eventCallback,(xpData=e?.level&&a?.level?a.level!==e.level?a.level-e.level:0:0<a?.level?a.level:0)<0&&username?.levelDown&&"function"==typeof username.levelDown&&username.levelDown(a,await xp_1.roleSetup.getRoles(userId,guildId,{includeNextRoles:!0})),0<xpData&&username?.levelUp&&"function"==typeof username.levelUp&&username.levelUp(a,await xp_1.roleSetup.getRoles(userId,guildId)),{...a,levelDifference:xpData}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.addXP=exports.addLevel=void 0;const xplogs_1=require("./functions/xplogs"),database_1=require("./functions/database"),xp_1=require("../xp");exports.addLevel=addLevel,exports.addXP=addXP;
23
+ */async function addXP(e,a,t,l){var o;if(!("number"==typeof t||"object"==typeof xp_1.xp&&t.min&&t.max))throw new xplogs_1.XpFatal({function:"addXP()",message:"XP is not a number or object, make sure you are using the correct syntax"});if("object"==typeof t&&(t=Math.floor(Math.random()*(t.max-t.min)+t.min)),!e)throw new xplogs_1.XpFatal({function:"addXP()",message:"User ID was not provided"});if(!a)throw new xplogs_1.XpFatal({function:"addXP()",message:"Guild ID was not provided"});let s;if(o=await database_1.db.findOne({collection:"simply-xps",data:{user:e,guild:a}}))s=await database_1.db.updateOne({collection:"simply-xps",data:{user:e,guild:a}},{collection:"simply-xps",data:{user:e,guild:a,name:l||o?.name||e,level:(0,xp_1.convertFrom)(o.xp+t,"xp"),xp:o.xp+t,xp_rate:xp_1.xp.xp_rate}}).catch(e=>{throw new xplogs_1.XpFatal({function:"addXP()",message:e.stack})});else{if(!xp_1.xp.auto_create||!l)throw new xplogs_1.XpFatal({function:"addXP()",message:"User does not exist"});s=await database_1.db.createOne({collection:"simply-xps",data:{guild:a,user:e,name:l,level:(0,xp_1.convertFrom)(t,"xp"),xp:t,xp_rate:xp_1.xp.xp_rate}}).catch(e=>{throw new xplogs_1.XpFatal({function:"addXP()",message:e.stack})})}return l=xplogs_1.XpEvents.eventCallback,(t=o?.level&&s?.level?s.level!==o.level?s.level-o.level:0:0<s?.level?s.level:0)<0&&l?.levelDown&&"function"==typeof l.levelDown&&l.levelDown(s,await xp_1.roleSetup.getRoles(e,a,{includeNextRoles:!0})),0<t&&l?.levelUp&&"function"==typeof l.levelUp&&l.levelUp(s,await xp_1.roleSetup.getRoles(e,a)),{...s,levelDifference:t}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.addXP=exports.addLevel=void 0;const xplogs_1=require("./functions/xplogs"),database_1=require("./functions/database"),xp_1=require("../xp");exports.addLevel=addLevel,exports.addXP=addXP;
@@ -19,6 +19,7 @@ export interface CompareCardOptions {
19
19
  color?: HexColor;
20
20
  centerBar?: HexColor;
21
21
  centerBarBg?: HexColor;
22
+ fallbackFont?: string;
22
23
  font?: string;
23
24
  light?: boolean;
24
25
  }
@@ -44,8 +45,9 @@ export interface LeaderboardCardOptions {
44
45
  borderColors?: [HexColor, HexColor];
45
46
  backgroundColor?: HexColor;
46
47
  backgroundImage?: URL;
47
- primaryFont?: string;
48
+ fallbackFont?: string;
48
49
  light?: boolean;
50
+ primaryFont?: string;
49
51
  rowColors?: [HexColor, HexColor];
50
52
  rowOpacity?: number;
51
53
  secondaryFont?: string;
@@ -70,6 +72,7 @@ export interface RankCardOptions {
70
72
  light?: boolean;
71
73
  lvlbar?: HexColor;
72
74
  lvlbarBg?: HexColor;
75
+ fallbackFont?: string;
73
76
  font?: string;
74
77
  }
75
78
  export type CardUserOptions = {
@@ -137,7 +140,6 @@ export declare function rankCard(guild: {
137
140
  name: string;
138
141
  }>;
139
142
  /**
140
- * @constructor
141
143
  * @private
142
144
  */
143
145
  export declare function RoundedBox(ctx: SKRSContext2D, x: number, y: number, width: number, height: number, radius: number, options?: {
package/lib/src/cards.js CHANGED
@@ -10,7 +10,7 @@
10
10
  * @link `Documentation` https://simplyxp.js.org/docs/next/functions/compareCard
11
11
  * @returns {Promise<{attachment: Buffer, description: string, name: string}>}
12
12
  * @throws {XpFatal} - If parameters are not provided correctly or if the user is not found in the database
13
- */async function compareCard(guild,user1,user2,options={},locales={}){var e,o,a,t,l,r,i;if(!guild?.id||!guild?.name)throw new xplogs_1.XpFatal({function:"compareCard()",message:"Please provide a guild"});if(!(user1?.id&&user1?.username&&user2?.id&&user2?.username))throw new xplogs_1.XpFatal({function:"compareCard()",message:"Please provide two valid users!"});if(!user1?.avatarURL.endsWith(".png")&&!user1.avatarURL.endsWith(".jpg")&&!user1.avatarURL.endsWith(".webp"))throw new xplogs_1.XpFatal({function:"compareCard()",message:"[USER 1] Avatar image must be a png, jpg, or webp"});if(!user2?.avatarURL.endsWith(".png")&&!user2.avatarURL.endsWith(".jpg")&&!user2.avatarURL.endsWith(".webp"))throw new xplogs_1.XpFatal({function:"compareCard()",message:"[USER 2] Avatar image, avatar image must be a png, jpg, or webp"});await(0,xp_1.registerFont)(options?.font||"https://fonts.cdnfonts.com/s/14539/Baloo-Regular.woff","Baloo"),await(0,xp_1.registerFont)("https://cdn.jsdelivr.net/fontsource/fonts/mochiy-pop-one@latest/japanese-400-normal.woff2","MochiyPopOne"),locales?.level||(locales.level="Level"),locales?.versus||(locales.versus="vs"),t=await(0,canvas_1.loadImage)(options?.background||"https://i.ibb.co/WnfXZjc/clouds.jpg").catch(()=>{throw new xplogs_1.XpFatal({function:"compareCard()",message:"Unable to load background image, is it valid?"})}),e=await(0,canvas_1.loadImage)(user1.avatarURL).catch(()=>{throw new xplogs_1.XpFatal({function:"compareCard()",message:"[USER 1] Unable to load user's AvatarURL, is it reachable?"})}),o=await(0,canvas_1.loadImage)(user2.avatarURL).catch(()=>{throw new xplogs_1.XpFatal({function:"compareCard()",message:"[USER 2] Unable to load user's AvatarURL, is it reachable?"})});let s=await xp_1.db.findOne({collection:"simply-xps",data:{guild:guild.id,user:user1.id}});if(!s){if(!xp_1.xp.auto_create||!user2?.username)throw new xplogs_1.XpFatal({function:"compareCard()",message:"[USER 1] User not found in database"});s=await(0,xp_1.create)(user1.id,guild.id,user1.username)}let n=await xp_1.db.findOne({collection:"simply-xps",data:{guild:guild.id,user:user2.id}});if(!n){if(!xp_1.xp.auto_create||!user2?.username)throw new xplogs_1.XpFatal({function:"compareCard()",message:"[USER 2] User not found in database"});n=await(0,xp_1.create)(user2.id,guild.id,user2.username)}return RoundedBox(a=(guild=(0,canvas_1.createCanvas)(1080,400)).getContext("2d"),0,0,guild.width,guild.height,25),a.clip(),a.fillStyle=options?.light?"#ffffff":"#000000",a.fill(),a.globalAlpha=.5,a.drawImage(t,-5,0,1090,400),a.restore(),a.globalAlpha=1,t=user1.username.replace(/[^\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FBF\u0041-\u005A\u0061-\u007A\u0030-\u0039]/g,""),user1=user2.username.replace(/[^\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FBF\u0041-\u005A\u0061-\u007A\u0030-\u0039]/g,""),user2=options?.color||options?.light?"rgba(0,0,0,0.5)":"rgba(255,255,255,0.5)",l=options?.centerBarBg||options?.light?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.4)",r=locales.level+(" "+shortener(s.level,!0)),i=locales.level+(" "+shortener(n.level,!0)),a.save(),a.textAlign="center",a.fillStyle="#ffffff",a.shadowColor="#000000",a.shadowBlur=6,a.shadowOffsetX=1,a.shadowOffsetY=1,a.font="40px Baloo, MochiyPopOne",a.fillText(`${t} ${locales.versus} `+user1,540,60),a.restore(),a.save(),a.beginPath(),a.arc(160,200,105,0,2*Math.PI,!0),a.closePath(),a.strokeStyle=user2,a.lineWidth=5,a.stroke(),a.beginPath(),a.arc(160,200,100,0,2*Math.PI,!0),a.closePath(),a.clip(),a.fillStyle=user2,a.fill(),a.drawImage(e,50,90,220,220),a.restore(),a.save(),a.beginPath(),a.arc(920,200,105,0,2*Math.PI,!0),a.closePath(),a.strokeStyle=user2,a.lineWidth=5,a.stroke(),a.beginPath(),a.arc(920,200,100,0,2*Math.PI,!0),a.closePath(),a.clip(),a.fillStyle=user2,a.fill(),a.drawImage(o,810,90,220,220),a.restore(),a.save(),a.globalAlpha=1,a.fillStyle="#ffffff",a.textAlign="center",a.font="25px Baloo, MochiyPopOne",options?.light&&(a.shadowColor="#000000",a.shadowBlur=5,a.shadowOffsetX=1,a.shadowOffsetY=1),a.fillText(r,160,350),a.fillText(i,920,350),a.restore(),a.save(),a.globalAlpha=1,RoundedBox(a,265,330,540,25,10),a.clip(),a.fillStyle=l,a.fill(),a.fillStyle="#ffffff",a.textAlign="center",a.font="22px Baloo, MochiyPopOne",a.fillText((s.xp>n.xp?"+":"-")+Math.abs(s.level-n.level),540,350),xp_1.xp.auto_clean&&(0,xp_1.clean)(),{attachment:guild.toBuffer("image/png"),description:"Simply-XP Comparison Card",name:"compareCard.png"}}
13
+ */async function compareCard(e,a,l,o={},t={}){var r,n,i,s,f,d,c;if(!e?.id||!e?.name)throw new xplogs_1.XpFatal({function:"compareCard()",message:"Please provide a guild"});if(!(a?.id&&a?.username&&l?.id&&l?.username))throw new xplogs_1.XpFatal({function:"compareCard()",message:"Please provide two valid users!"});if(!a?.avatarURL.endsWith(".png")&&!a.avatarURL.endsWith(".jpg")&&!a.avatarURL.endsWith(".webp"))throw new xplogs_1.XpFatal({function:"compareCard()",message:"[USER 1] Avatar image must be a png, jpg, or webp"});await(0,xp_1.registerFont)(o?.font||(0,path_1.join)(__dirname,"fonts","Baloo2-ExtraBold.woff2"),"Baloo"),o?.fallbackFont&&await(0,xp_1.registerFont)(o.fallbackFont,"FallbackFont"),t?.level||(t.level="Level"),t?.versus||(t.versus="vs"),s=await(0,canvas_1.loadImage)(o?.background||"https://i.ibb.co/WnfXZjc/clouds.jpg").catch(()=>{throw new xplogs_1.XpFatal({function:"compareCard()",message:"Unable to load background image, is it valid and reachable?"})}),r=await(0,canvas_1.loadImage)(a.avatarURL).catch(()=>{throw new xplogs_1.XpFatal({function:"compareCard()",message:"[USER 1] Unable to load user's AvatarURL, is it valid and reachable?"})}),n=await(0,canvas_1.loadImage)(l.avatarURL).catch(()=>{throw new xplogs_1.XpFatal({function:"compareCard()",message:"[USER 2] Unable to load user's AvatarURL, is it valid and reachable?"})});let p=await xp_1.db.findOne({collection:"simply-xps",data:{guild:e.id,user:a.id}});if(!p){if(!xp_1.xp.auto_create||!l?.username)throw new xplogs_1.XpFatal({function:"compareCard()",message:"[USER 1] User not found in database"});p=await(0,xp_1.create)(a.id,e.id,a.username)}let g=await xp_1.db.findOne({collection:"simply-xps",data:{guild:e.id,user:l.id}});if(!g){if(!xp_1.xp.auto_create||!l?.username)throw new xplogs_1.XpFatal({function:"compareCard()",message:"[USER 2] User not found in database"});g=await(0,xp_1.create)(l.id,e.id,l.username)}return RoundedBox(i=(e=(0,canvas_1.createCanvas)(1080,400)).getContext("2d"),0,0,e.width,e.height,25),i.clip(),i.fillStyle=o?.light?"#ffffff":"#000000",i.fill(),i.globalAlpha=.6,i.drawImage(s,-5,0,1090,400),i.restore(),i.globalAlpha=1,s=o?.color||o?.light?"rgba(0,0,0,0.5)":"rgba(255,255,255,0.5)",f=o?.centerBarBg||o?.light?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.4)",d=t.level+(" "+shortener(p.level,!0)),c=t.level+(" "+shortener(g.level,!0)),i.save(),i.textAlign="center",i.fillStyle="#ffffff",i.shadowColor="#000000",i.shadowBlur=6,i.shadowOffsetX=1,i.shadowOffsetY=1,i.font="40px Baloo, FallbackFont",i.fillText(`${a.username} ${t.versus} `+l.username,540,60),i.restore(),i.save(),i.beginPath(),i.arc(160,200,105,0,2*Math.PI,!0),i.closePath(),i.strokeStyle=s,i.lineWidth=5,i.stroke(),i.beginPath(),i.arc(160,200,100,0,2*Math.PI,!0),i.closePath(),i.clip(),i.fillStyle=s,i.fill(),i.drawImage(r,50,90,220,220),i.restore(),i.save(),i.beginPath(),i.arc(920,200,105,0,2*Math.PI,!0),i.closePath(),i.strokeStyle=s,i.lineWidth=5,i.stroke(),i.beginPath(),i.arc(920,200,100,0,2*Math.PI,!0),i.closePath(),i.clip(),i.fillStyle=s,i.fill(),i.drawImage(n,810,90,220,220),i.restore(),i.save(),i.globalAlpha=1,i.fillStyle="#ffffff",i.textAlign="center",i.font="25px Baloo, FallbackFont",o?.light&&(i.shadowColor="#000000",i.shadowBlur=5,i.shadowOffsetX=1,i.shadowOffsetY=1),i.fillText(d,160,350),i.fillText(c,920,350),i.restore(),i.save(),i.globalAlpha=1,RoundedBox(i,265,330,540,25,10),i.clip(),i.fillStyle=f,i.fill(),i.fillStyle="#ffffff",i.textAlign="center",i.font="22px Baloo, FallbackFont",i.fillText((p.xp>g.xp?"+":"-")+Math.abs(p.level-g.level),540,350),xp_1.xp.auto_clean&&(0,xp_1.clean)(),{attachment:e.toBuffer("image/png"),description:"Simply-XP Comparison Card",name:"compareCard.png"}}
14
14
  /**
15
15
  * Generate a simple leaderboard card
16
16
  * @async
@@ -21,7 +21,7 @@
21
21
  * @link `Documentation` https://simplyxp.js.org/docs/next/functions/leaderboard
22
22
  * @returns {Promise<{attachment: Buffer, description: string, name: string}>}
23
23
  * @throws {XpFatal} - If parameters are not provided correctly
24
- */async function leaderboardCard(data,options={},guildInfo,locales={}){var o,e,a,t,l,r;if(!data||data.length<1)throw new xplogs_1.XpFatal({function:"leaderboardCard()",message:"There must be at least 1 user in the data array"});let i=void 0,s=void 0,n,d=(options?.artworkImage&&(i=await(0,canvas_1.loadImage)(options.artworkImage).catch(()=>{throw new xplogs_1.XpFatal({function:"leaderboardCard()",message:"Unable to load artwork image, is it valid?"})})),options?.backgroundImage&&(s=await(0,canvas_1.loadImage)(options.backgroundImage).catch(()=>{throw new xplogs_1.XpFatal({function:"leaderboardCard()",message:"Unable to load background image, is it valid?"})})),await(0,xp_1.registerFont)(options?.primaryFont||"https://fonts.cdnfonts.com/s/14539/Baloo-Regular.woff","Baloo"),options?.secondaryFont&&await(0,xp_1.registerFont)(options.secondaryFont,"SecondaryFont"),await(0,xp_1.registerFont)("https://cdn.jsdelivr.net/fontsource/fonts/mochiy-pop-one@latest/japanese-400-normal.woff2","MochiyPopOne"),locales.level||(locales.level="LEVEL"),locales.members||(locales.members="Members"),data=data.slice(0,8),o=options?.secondaryFont?"SecondaryFont, MochiyPopOne":"Baloo, MochiyPopOne",n=options?.light?{artworkColors:options?.artworkColors||["#997fe1","#616bff"],backgroundColor:"#FFFFFF",borderColors:options?.borderColors||["#e0d440","#fffa6b"],evenColor:"#f0f0f0",oddColor:"#dcdcdc",primaryTextColor:"#000000",secondaryTextColor:"rgba(0,0,0,0.5)"}:{artworkColors:options?.artworkColors||["#6B46D4","#2e3cff"],backgroundColor:"#141414",borderColors:options?.borderColors||["#e0d440","#fffa6b"],evenColor:"#1e1e1e",oddColor:"#282828",primaryTextColor:"#ffffff",secondaryTextColor:"rgba(255,255,255,0.5)"},RoundedBox(a=(e=(0,canvas_1.createCanvas)(1350,1080)).getContext("2d"),0,0,e.width,e.height,20,{clip:!0}),(t=a.createLinearGradient(0,0,e.width,0)).addColorStop(.4,n.artworkColors[0]),t.addColorStop(1,n.artworkColors[1]),a.fillStyle=t,a.fillRect(0,0,e.width,220),i&&(a.fillStyle="#000000",a.fillRect(0,0,e.width,220),a.globalAlpha=.5,a.drawImage(i,0,0,e.width,220),a.globalAlpha=1),a.fillStyle=options.backgroundColor||n.backgroundColor,a.fillRect(0,220,e.width,1080),s&&(a.globalAlpha=.9,a.drawImage(s,0,220,e.width,1080),a.globalAlpha=1),guildInfo&&guildInfo?.imageURL&&guildInfo?.name&&(t=await(0,canvas_1.loadImage)(guildInfo.imageURL),a.save(),a.beginPath(),a.arc(150,110,90,0,2*Math.PI,!0),a.closePath(),a.clip(),a.drawImage(t,60,20,180,180),a.restore(),(t=a.createLinearGradient(0,0,0,220)).addColorStop(0,n.borderColors[0]),t.addColorStop(1,n.borderColors[1]),a.strokeStyle=t,a.lineWidth=8,a.beginPath(),a.arc(150,110,90,0,2*Math.PI,!0),a.stroke(),a.fillStyle=n.primaryTextColor,a.font="60px Baloo, MochiyPopOne",guildInfo?.memberCount?(a.fillText(guildInfo.name,270,110),a.fillStyle=n.secondaryTextColor,a.font="40px Baloo, MochiyPopOne",a.fillText(guildInfo.memberCount+" "+locales.members,270,160)):a.fillText(guildInfo.name,270,130)),n.evenColor);l=options?.rowOpacity&&!isNaN(options?.rowOpacity)?options.rowOpacity:s?.5:1;for(let e=0;e<data.length;e++)r=300+90*e,a.globalAlpha=l,a.save(),1===data.length?RoundedBox(a,30,r,1290,90,20,{clip:!0,fill:{color:d}}):0===e?RoundedBox(a,30,r,1290,90,20,{clip:!0,fill:{color:d},roundCorners:{top:!0,bottom:!1}}):e===data.length-1?RoundedBox(a,30,r,1290,90,20,{clip:!0,fill:{color:d},roundCorners:{top:!1,bottom:!0}}):RoundedBox(a,30,r,1290,90,0,{fill:{color:d}}),a.restore(),a.globalAlpha=1,a.textAlign="left",a.font="30px "+o,a.fillStyle=n.secondaryTextColor,a.fillText(e+1+".",60,55+r),a.textAlign="left",a.font="40px "+o,a.fillStyle=n.primaryTextColor,a.fillText(data[e]?.name||data[e]?.user||"???",120,60+r),a.textAlign="right",a.font="30px "+o,a.fillStyle=n.primaryTextColor,a.fillText(shortener(data[e]?.level)||"???",1270,55+r),a.fillStyle=n.secondaryTextColor,a.fillText(locales.level,1270-a.measureText(shortener(data[e]?.level)||"???").width-15,55+r),d=d===n.evenColor?n.oddColor:n.evenColor;return xp_1.xp.auto_clean&&(0,xp_1.clean)(),{attachment:e.toBuffer("image/png"),description:"Simply-XP Leaderboard Card",name:"leaderboard.png"}}
24
+ */async function leaderboardCard(a,e={},l,o={}){var t,r,n,i,s,f;if(!a||a.length<1)throw new xplogs_1.XpFatal({function:"leaderboardCard()",message:"There must be at least 1 user in the data array"});let d=void 0,c=void 0,p,g=(e?.artworkImage&&(d=await(0,canvas_1.loadImage)(e.artworkImage).catch(()=>{throw new xplogs_1.XpFatal({function:"leaderboardCard()",message:"Unable to load artwork image, is it valid?"})})),e?.backgroundImage&&(c=await(0,canvas_1.loadImage)(e.backgroundImage).catch(()=>{throw new xplogs_1.XpFatal({function:"leaderboardCard()",message:"Unable to load background image, is it valid?"})})),await(0,xp_1.registerFont)(e?.primaryFont||(0,path_1.join)(__dirname,"fonts","Baloo2-ExtraBold.woff2"),"Baloo"),e?.secondaryFont&&await(0,xp_1.registerFont)(e.secondaryFont,"SecondaryFont"),e?.fallbackFont&&await(0,xp_1.registerFont)(e.fallbackFont,"FallbackFont"),o.level||(o.level="LEVEL"),o.members||(o.members="Members"),a=a.slice(0,8),t=e?.secondaryFont?"SecondaryFont, FallbackFont":"Baloo, FallbackFont",p=e?.light?{artworkColors:e?.artworkColors||["#997fe1","#616bff"],backgroundColor:"#FFFFFF",borderColors:e?.borderColors||["#e0d440","#fffa6b"],evenColor:"#f0f0f0",oddColor:"#dcdcdc",primaryTextColor:"#000000",secondaryTextColor:"rgba(0,0,0,0.5)"}:{artworkColors:e?.artworkColors||["#6B46D4","#2e3cff"],backgroundColor:"#141414",borderColors:e?.borderColors||["#e0d440","#fffa6b"],evenColor:"#1e1e1e",oddColor:"#282828",primaryTextColor:"#ffffff",secondaryTextColor:"rgba(255,255,255,0.5)"},RoundedBox(n=(r=(0,canvas_1.createCanvas)(1350,1080)).getContext("2d"),0,0,r.width,r.height,20,{clip:!0}),(i=n.createLinearGradient(0,0,r.width,0)).addColorStop(.4,p.artworkColors[0]),i.addColorStop(1,p.artworkColors[1]),n.fillStyle=i,n.fillRect(0,0,r.width,220),d&&(n.fillStyle="#000000",n.fillRect(0,0,r.width,220),n.globalAlpha=.5,n.drawImage(d,0,0,r.width,220),n.globalAlpha=1),n.fillStyle=e.backgroundColor||p.backgroundColor,n.fillRect(0,220,r.width,1080),c&&(n.globalAlpha=.9,n.drawImage(c,0,220,r.width,1080),n.globalAlpha=1),l&&l?.imageURL&&l?.name&&(i=await(0,canvas_1.loadImage)(l.imageURL),n.save(),n.beginPath(),n.arc(150,110,90,0,2*Math.PI,!0),n.closePath(),n.clip(),n.drawImage(i,60,20,180,180),n.restore(),(i=n.createLinearGradient(0,0,0,220)).addColorStop(0,p.borderColors[0]),i.addColorStop(1,p.borderColors[1]),n.strokeStyle=i,n.lineWidth=8,n.beginPath(),n.arc(150,110,90,0,2*Math.PI,!0),n.stroke(),n.fillStyle=p.primaryTextColor,n.font="60px Baloo, FallbackFont",l?.memberCount?(n.fillText(l.name,270,110),n.fillStyle=p.secondaryTextColor,n.font="40px Baloo, FallbackFont",n.fillText(l.memberCount+" "+o.members,270,160)):n.fillText(l.name,270,130)),p.evenColor);s=e?.rowOpacity&&!isNaN(e?.rowOpacity)?e.rowOpacity:c?.5:1;for(let e=0;e<a.length;e++)f=300+90*e,n.globalAlpha=s,n.save(),1===a.length?RoundedBox(n,30,f,1290,90,20,{clip:!0,fill:{color:g}}):0===e?RoundedBox(n,30,f,1290,90,20,{clip:!0,fill:{color:g},roundCorners:{top:!0,bottom:!1}}):e===a.length-1?RoundedBox(n,30,f,1290,90,20,{clip:!0,fill:{color:g},roundCorners:{top:!1,bottom:!0}}):RoundedBox(n,30,f,1290,90,0,{fill:{color:g}}),n.restore(),n.globalAlpha=1,n.textAlign="left",n.font="30px "+t,n.fillStyle=p.secondaryTextColor,n.fillText(e+1+".",60,55+f),n.textAlign="left",n.font="40px "+t,n.fillStyle=p.primaryTextColor,n.fillText(a[e]?.name||a[e]?.user||"???",120,60+f),n.textAlign="right",n.font="30px "+t,n.fillStyle=p.primaryTextColor,n.fillText(shortener(a[e]?.level)||"???",1270,55+f),n.fillStyle=p.secondaryTextColor,n.fillText(o.level,1270-n.measureText(shortener(a[e]?.level)||"???").width-15,55+f),g=g===p.evenColor?p.oddColor:p.evenColor;return xp_1.xp.auto_clean&&(0,xp_1.clean)(),{attachment:r.toBuffer("image/png"),description:"Simply-XP Leaderboard Card",name:"leaderboard.png"}}
25
25
  /**
26
26
  * Generate a simple user rank card
27
27
  * @async
@@ -32,4 +32,4 @@
32
32
  * @link `Documentation` https://simplyxp.js.org/docs/next/functions/rankCard
33
33
  * @returns {Promise<{attachment: Buffer, description: string, name: string}>}
34
34
  * @throws {XpFatal} - If parameters are not provided correctly
35
- */async function rankCard(guild,user,options={},locales={}){var e,o,a,t,l,r,i,s,n,d,f,c,p;if(!guild)throw new xplogs_1.XpFatal({function:"rankCard()",message:"No Guild Provided"});if(!user)throw new xplogs_1.XpFatal({function:"rankCard()",message:"No User Provided"});if(locales?.level||(locales.level="Level"),locales?.next_level||(locales.next_level="Next Level"),locales?.xp||(locales.xp="XP"),xplogs_1.XpLog.debug("rankCard()",`${options?.legacy?"LEGACY":"MODERN"} ENABLED`),!user?.avatarURL.endsWith(".png")&&!user.avatarURL.endsWith(".jpg")&&!user.avatarURL.endsWith(".webp"))throw new xplogs_1.XpFatal({function:"rankCard()",message:"Invalid avatar image, avatar image must be a png, jpg, or webp"});if(!user||!user.id||!user.username)throw new xplogs_1.XpFatal({function:"rankCard()",message:"Invalid User Provided, user must contain id, username, and avatarURL."});await(0,xp_1.registerFont)(options?.font||"https://fonts.cdnfonts.com/s/14539/Baloo-Regular.woff","Baloo"),await(0,xp_1.registerFont)("https://cdn.jsdelivr.net/fontsource/fonts/mochiy-pop-one@latest/japanese-400-normal.woff2","MochiyPopOne"),t=await(0,canvas_1.loadImage)(options?.background||(options?.legacy?"https://i.ibb.co/dck2Tnt/rank-card.webp":"https://i.ibb.co/WnfXZjc/clouds.jpg")).catch(()=>{throw new xplogs_1.XpFatal({function:"rankCard()",message:"Unable to load background image, is it valid?"})}),e=await(0,canvas_1.loadImage)(user.avatarURL).catch(()=>{throw new xplogs_1.XpFatal({function:"rankCard()",message:"Unable to load user's AvatarURL, is it reachable?"})});let g=await xp_1.db.findOne({collection:"simply-xps",data:{guild:guild.id,user:user.id}});if(!g){if(!xp_1.xp.auto_create)throw new xplogs_1.XpFatal({function:"rankCard()",message:"User not found in database"});g=await(0,xp_1.create)(user.id,guild.id,user.username)}return o=await xp_1.db.find({collection:"simply-xps",data:{guild:guild.id}}),g.position=o.sort((a,b)=>b.xp-a.xp).findIndex(u=>u.user===user.id)+1,(a=(o=(0,canvas_1.createCanvas)(1080,400)).getContext("2d")).save(),RoundedBox(a,0,0,o.width,o.height,25),a.clip(),a.fillStyle=options?.light?"#ffffff":"#000000",a.fill(),a.globalAlpha=options?.legacy?.8:.6,a.drawImage(t,-5,0,1090,400),a.restore(),t=user.username.replace(/[^\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FBF\u0041-\u005A\u0061-\u007A\u0030-\u0039]/g,""),l=options?.color||(options?.legacy?"#9900ff":options?.light?"rgba(0,0,0,0.5)":"rgba(255,255,255,0.5)"),r=options?.lvlbar||"#ffffff",i=options?.lvlbarBg||options?.legacy?"#FFFFFF":options?.light?"rgba(0,0,0,0.2)":"rgba(255,255,255,0.2)",s=shortener(g.xp)+(" "+locales.xp),n=locales.level+(" "+shortener(g.level)),d="{current} / {needed}",f=(0,xp_1.convertFrom)(g.level+1),c=(0,xp_1.convertFrom)(g.level),c=100*(g.xp-c)/(f-c)*(options?.legacy?660:530)/100,p="326815959358898189"===g.user?"#ade6d8":1===g.position?"#ADD8E6":2===g.position?"#C0C0C0":3===g.position?"#CD7F32":"#ffffff",options?.legacy?(a.save(),a.globalAlpha=.4,a.fillStyle=options?.light?"#ffffff":"#000000",a.fillRect(40,0,240,o.height),a.restore(),a.save(),RoundedBox(a,70,30,180,180,50,{clip:!0,fill:{color:l}}),RoundedBox(a,75,35,170,170,50,{clip:!0}),a.drawImage(e,70,30,180,180),a.restore(),a.save(),RoundedBox(a,70,320,180,50,20,{clip:!0}),a.fillStyle=l,a.fillRect(70,320,180,50),a.fillStyle="#ffffff",dynamicFont(a,s,160,358,160,32),a.restore(),a.save(),RoundedBox(a,70,240,180,50,20,{clip:!0}),a.fillStyle=l,a.fillRect(70,240,180,50),a.fillStyle="#ffffff",a.textAlign="center",dynamicFont(a,n,160,278,160,32),a.restore(),a.save(),a.textAlign="left",a.fillStyle="#ffffff",a.shadowColor="#000000",a.shadowBlur=15,a.shadowOffsetX=1,a.shadowOffsetY=1,a.font="39px Baloo, MochiyPopOne",a.fillText(t,395,80),a.restore(),a.save(),a.textAlign="right",a.fillStyle="#ffffff",a.shadowColor="#000000",a.shadowBlur=15,a.shadowOffsetX=1,a.shadowOffsetY=1,a.font="55px Baloo, MochiyPopOne",a.fillText("#"+g.position,o.width-55,80),a.restore(),a.save(),RoundedBox(a,390,305,660,70,20,{clip:!0}),a.fillStyle="#ffffff",dynamicFont(a,guild.name,720,355,700,45),a.globalAlpha=.2,a.fillRect(390,305,660,70),a.restore(),a.save(),RoundedBox(a,390,145,660,50,20,{clip:!0}),a.fillStyle=i,a.globalAlpha=.2,a.fillRect(390,145,660,50),a.restore(),a.save(),RoundedBox(a,390,145,c,50,20,{clip:!0}),a.fillStyle=r,a.globalAlpha=.5,a.fillRect(390,145,c,50),a.restore(),a.save(),a.textAlign="left",a.fillStyle="#ffffff",a.globalAlpha=.8,a.font="30px Baloo, MochiyPopOne",a.fillText(locales.next_level+": "+shortener(f)+" "+locales.xp,390,230),a.restore(),s=d.replace(/{needed}/g,shortener(f)).replace(/{current}/g,shortener(g.xp)),a.textAlign="center",a.fillStyle="#474747",a.globalAlpha=1,a.font="30px Baloo, MochiyPopOne",a.fillText(s,730,180)):(a.save(),a.textAlign="center",a.fillStyle="#ffffff",a.shadowColor="#000000",a.shadowBlur=5,a.shadowOffsetX=1,a.shadowOffsetY=1,a.font="40px Baloo, MochiyPopOne",a.fillText(t,540,80),a.restore(),a.save(),a.beginPath(),a.arc(160,200,105,0,2*Math.PI,!0),a.closePath(),a.lineWidth=5,a.strokeStyle=l,a.stroke(),a.beginPath(),a.arc(160,200,100,0,2*Math.PI,!0),a.closePath(),a.clip(),a.fillStyle=l,a.fill(),a.drawImage(e,50,90,220,220),a.restore(),a.save(),a.beginPath(),a.arc(230,130,30,0,2*Math.PI,!0),a.closePath(),a.strokeStyle=l,a.lineWidth=5,a.stroke(),a.beginPath(),a.arc(230,130,30,0,2*Math.PI,!0),a.closePath(),a.fillStyle=p,a.fill(),a.clip(),a.fillStyle="#000000",dynamicFont(a,shortener(g.position,!0),230,138,45,30),a.restore(),a.save(),a.fillStyle="#ffffff",options?.light&&(a.shadowColor="#000000",a.shadowBlur=5,a.shadowOffsetX=1,a.shadowOffsetY=1),a.textAlign="center",a.font="25px Baloo, MochiyPopOne",a.fillText(n,160,350),a.restore(),a.save(),RoundedBox(a,265,330,540,25,10,{clip:!0,fill:{color:i}}),RoundedBox(a,270,335,530,15,5,{clip:!0}),a.fillStyle=r,a.fillRect(270,335,c,15),a.restore(),a.save(),a.textAlign="center",a.fillStyle=options?.light?"rgba(0,0,0,0.6)":"rgba(255,255,255,0.6)",a.font="22px Baloo, MochiyPopOne",a.fillText(d.replace(/{needed}/g,shortener(f)).replace(/{current}/g,shortener(g.xp)),540,320),a.save(),a.fillStyle="#ffffff",a.textAlign="center",options?.light&&(a.shadowColor="#000000",a.shadowBlur=5,a.shadowOffsetX=1,a.shadowOffsetY=1),a.font="25px Baloo, MochiyPopOne",a.fillText(locales.level+" "+shortener(g.level+1),920,350),a.restore()),xp_1.xp.auto_clean&&(0,xp_1.clean)(),{attachment:o.toBuffer("image/png"),description:"Simply-XP Rank Card",name:"rank.png"}}function RoundedBox(ctx,x,y,width,height,radius,options){var e=options?.roundCorners||{top:!0,bottom:!0};ctx.beginPath(),ctx.moveTo(x+(e.top?radius:0),y),ctx.lineTo(x+width-(e.top?radius:0),y),e.top&&ctx.quadraticCurveTo(x+width,y,x+width,y+radius),ctx.lineTo(x+width,y+height-(e.bottom?radius:0)),e.bottom&&ctx.quadraticCurveTo(x+width,y+height,x+width-radius,y+height),ctx.lineTo(x+(e.bottom?radius:0),y+height),e.bottom&&ctx.quadraticCurveTo(x,y+height,x,y+height-radius),ctx.lineTo(x,y+(e.top?radius:0)),e.top&&ctx.quadraticCurveTo(x,y,x+radius,y),ctx.closePath(),options?.fill&&(options?.clip&&ctx.clip(),options.fill?.color&&(ctx.fillStyle=options.fill.color),options.fill?.alpha&&(ctx.globalAlpha=options.fill.alpha),ctx.fillRect(x,y,width,height)),options?.stroke&&(options.stroke?.color&&(ctx.strokeStyle=options.stroke.color),options.stroke?.width&&(ctx.lineWidth=options.stroke.width),ctx.stroke()),options?.clip&&ctx.clip()}function shortener(count,roundedNumber){let e="",o=0;if(!count||0===count)return"0";if(count>Number.MAX_SAFE_INTEGER)return"∞";for(;1e3<=count&&o<8;)count/=1e3,o++;switch(o){case 0:e="";break;case 1:e="K";break;case 2:e="M";break;case 3:e="B";break;case 4:e="T";break;case 5:e="Qa";break;case 6:e="Qi";break;default:e="S+"}return""+count.toFixed(0===o||roundedNumber?0:2)+e}function dynamicFont(context,text,x,y,maxWidth,maxSize){let e=maxSize;for(;0<e&&(context.font=e+'px "Baloo"',!(context.measureText(text).width<maxWidth));)e--;context.textAlign="center",context.fillText(text,x,y)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.RoundedBox=exports.rankCard=exports.leaderboardCard=exports.compareCard=void 0;const canvas_1=require("@napi-rs/canvas"),xp_1=require("../xp"),xplogs_1=require("./functions/xplogs");exports.compareCard=compareCard,exports.leaderboardCard=leaderboardCard,exports.rankCard=rankCard,exports.RoundedBox=RoundedBox;
35
+ */async function rankCard(e,a,l={},o={}){var t,r,n,i,s,f,d,c,p,g,h,x;if(!e)throw new xplogs_1.XpFatal({function:"rankCard()",message:"No Guild Provided"});if(!a)throw new xplogs_1.XpFatal({function:"rankCard()",message:"No User Provided"});if(o?.level||(o.level="Level"),o?.next_level||(o.next_level="Next Level"),o?.xp||(o.xp="XP"),xplogs_1.XpLog.debug("rankCard()",`${l?.legacy?"LEGACY":"MODERN"} ENABLED`),!a||!a.id||!a.username)throw new xplogs_1.XpFatal({function:"rankCard()",message:"Invalid User Provided, user must contain id, username, and avatarURL."});await(0,xp_1.registerFont)(l?.font||(0,path_1.join)(__dirname,"fonts","Baloo2-ExtraBold.woff2"),"Baloo"),l?.fallbackFont&&await(0,xp_1.registerFont)(l.fallbackFont,"FallbackFont"),i=await(0,canvas_1.loadImage)(l?.background||(l?.legacy?"https://i.ibb.co/dck2Tnt/rank-card.webp":"https://i.ibb.co/WnfXZjc/clouds.jpg")).catch(()=>{throw new xplogs_1.XpFatal({function:"rankCard()",message:"Unable to load background image, is it valid and reachable?"})}),t=await(0,canvas_1.loadImage)(a.avatarURL).catch(()=>{throw new xplogs_1.XpFatal({function:"rankCard()",message:"Unable to load user's AvatarURL, is it valid and reachable??"})});let b=await xp_1.db.findOne({collection:"simply-xps",data:{guild:e.id,user:a.id}});if(!b){if(!xp_1.xp.auto_create)throw new xplogs_1.XpFatal({function:"rankCard()",message:"User not found in database"});b=await(0,xp_1.create)(a.id,e.id,a.username)}return r=await xp_1.db.find({collection:"simply-xps",data:{guild:e.id}}),b.position=1+r.sort((e,a)=>a.xp-e.xp).findIndex(e=>e.user===a.id)||1,(n=(r=(0,canvas_1.createCanvas)(1080,400)).getContext("2d")).save(),RoundedBox(n,0,0,r.width,r.height,25),n.clip(),n.fillStyle=l?.light?"#ffffff":"#000000",n.fill(),n.globalAlpha=l?.legacy?.8:.6,n.drawImage(i,-5,0,1090,400),n.restore(),i=l?.color||(l?.legacy?"#9900ff":l?.light?"rgba(0,0,0,0.5)":"rgba(255,255,255,0.5)"),s=l?.lvlbar||"#ffffff",f=l?.lvlbarBg||l?.legacy?"#FFFFFF":l?.light?"rgba(0,0,0,0.2)":"rgba(255,255,255,0.2)",d=shortener(b.xp)+(" "+o.xp),c=o.level+(" "+shortener(b.level)),p="{current} / {needed}",g=(0,xp_1.convertFrom)(b.level+1),h=(0,xp_1.convertFrom)(b.level),h=100*(b.xp-h)/(g-h)*(l?.legacy?660:530)/100,x="326815959358898189"===b.user?"#ade6d8":1===b.position?"#ADD8E6":2===b.position?"#C0C0C0":3===b.position?"#CD7F32":"#ffffff",l?.legacy?(n.save(),n.globalAlpha=.4,n.fillStyle=l?.light?"#ffffff":"#000000",n.fillRect(40,0,240,r.height),n.restore(),n.save(),RoundedBox(n,70,30,180,180,50,{clip:!0,fill:{color:i}}),RoundedBox(n,75,35,170,170,50,{clip:!0}),n.drawImage(t,70,30,180,180),n.restore(),n.save(),RoundedBox(n,70,320,180,50,20,{clip:!0}),n.fillStyle=i,n.fillRect(70,320,180,50),n.fillStyle="#ffffff",dynamicFont(n,d,160,358,160,32),n.restore(),n.save(),RoundedBox(n,70,240,180,50,20,{clip:!0}),n.fillStyle=i,n.fillRect(70,240,180,50),n.fillStyle="#ffffff",n.textAlign="center",dynamicFont(n,c,160,278,160,32),n.restore(),n.save(),n.textAlign="left",n.fillStyle="#ffffff",n.shadowColor="#000000",n.shadowBlur=15,n.shadowOffsetX=1,n.shadowOffsetY=1,n.font="39px Baloo, FallbackFont",n.fillText(a.username,395,80),n.restore(),n.save(),n.textAlign="right",n.fillStyle="#ffffff",n.shadowColor="#000000",n.shadowBlur=15,n.shadowOffsetX=1,n.shadowOffsetY=1,n.font="55px Baloo, FallbackFont",n.fillText("#"+b.position,r.width-55,80),n.restore(),n.save(),RoundedBox(n,390,305,660,70,20,{clip:!0}),n.fillStyle="#ffffff",dynamicFont(n,e.name,720,355,700,45),n.globalAlpha=.2,n.fillRect(390,305,660,70),n.restore(),n.save(),RoundedBox(n,390,145,660,50,20,{clip:!0}),n.fillStyle=f,n.globalAlpha=.2,n.fillRect(390,145,660,50),n.restore(),n.save(),RoundedBox(n,390,145,h,50,20,{clip:!0}),n.fillStyle=s,n.globalAlpha=.5,n.fillRect(390,145,h,50),n.restore(),n.save(),n.textAlign="left",n.fillStyle="#ffffff",n.globalAlpha=.8,n.font="30px Baloo, FallbackFont",n.fillText(o.next_level+": "+shortener(g)+" "+o.xp,390,230),n.restore(),d=p.replace(/{needed}/g,shortener(g)).replace(/{current}/g,shortener(b.xp)),n.textAlign="center",n.fillStyle="#474747",n.globalAlpha=1,n.font="30px Baloo, FallbackFont",n.fillText(d,730,180)):(n.save(),n.textAlign="center",n.fillStyle="#ffffff",n.shadowColor="#000000",n.shadowBlur=5,n.shadowOffsetX=1,n.shadowOffsetY=1,n.font="40px Baloo, FallbackFont",n.fillText(a.username,540,80),n.restore(),n.save(),n.beginPath(),n.arc(160,200,105,0,2*Math.PI,!0),n.closePath(),n.lineWidth=5,n.strokeStyle=i,n.stroke(),n.beginPath(),n.arc(160,200,100,0,2*Math.PI,!0),n.closePath(),n.clip(),n.fillStyle=i,n.fill(),n.drawImage(t,50,90,220,220),n.restore(),n.save(),n.beginPath(),n.arc(230,130,30,0,2*Math.PI,!0),n.closePath(),n.strokeStyle=i,n.lineWidth=5,n.stroke(),n.beginPath(),n.arc(230,130,30,0,2*Math.PI,!0),n.closePath(),n.fillStyle=x,n.fill(),n.clip(),n.fillStyle="#000000",dynamicFont(n,shortener(b.position,!0),230,138,45,30),n.restore(),n.save(),n.fillStyle="#ffffff",l?.light&&(n.shadowColor="#000000",n.shadowBlur=5,n.shadowOffsetX=1,n.shadowOffsetY=1),n.textAlign="center",n.font="25px Baloo, FallbackFont",n.fillText(c,160,350),n.restore(),n.save(),RoundedBox(n,265,330,540,25,10,{clip:!0,fill:{color:f}}),RoundedBox(n,270,335,h,15,5,{clip:!0,fill:{color:s}}),n.restore(),n.save(),n.textAlign="center",n.fillStyle=l?.light?"rgba(0,0,0,0.6)":"rgba(255,255,255,0.6)",n.font="22px Baloo, FallbackFont",n.fillText(p.replace(/{needed}/g,shortener(g)).replace(/{current}/g,shortener(b.xp)),540,320),n.save(),n.fillStyle="#ffffff",n.textAlign="center",l?.light&&(n.shadowColor="#000000",n.shadowBlur=5,n.shadowOffsetX=1,n.shadowOffsetY=1),n.font="25px Baloo, FallbackFont",n.fillText(o.level+" "+shortener(b.level+1),920,350),n.restore()),xp_1.xp.auto_clean&&(0,xp_1.clean)(),{attachment:r.toBuffer("image/png"),description:"Simply-XP Rank Card",name:"rank.png"}}function RoundedBox(e,a,l,o,t,r,n){var i=n?.roundCorners||{top:!0,bottom:!0};e.beginPath(),e.moveTo(a+(i.top?r:0),l),e.lineTo(a+o-(i.top?r:0),l),i.top&&e.quadraticCurveTo(a+o,l,a+o,l+r),e.lineTo(a+o,l+t-(i.bottom?r:0)),i.bottom&&e.quadraticCurveTo(a+o,l+t,a+o-r,l+t),e.lineTo(a+(i.bottom?r:0),l+t),i.bottom&&e.quadraticCurveTo(a,l+t,a,l+t-r),e.lineTo(a,l+(i.top?r:0)),i.top&&e.quadraticCurveTo(a,l,a+r,l),e.closePath(),n?.fill&&(n?.clip&&e.clip(),n.fill?.color&&(e.fillStyle=n.fill.color),n.fill?.alpha&&(e.globalAlpha=n.fill.alpha),e.fillRect(a,l,o,t)),n?.stroke&&(n.stroke?.color&&(e.strokeStyle=n.stroke.color),n.stroke?.width&&(e.lineWidth=n.stroke.width),e.stroke()),n?.clip&&e.clip()}function shortener(e,a){let l="",o=0;if(!e||0===e)return"0";if(e>Number.MAX_SAFE_INTEGER)return"∞";for(;1e3<=e&&o<8;)e/=1e3,o++;switch(o){case 0:l="";break;case 1:l="K";break;case 2:l="M";break;case 3:l="B";break;case 4:l="T";break;case 5:l="Qa";break;case 6:l="Qi";break;default:l="S+"}return""+e.toFixed(0===o||a?0:2)+l}function dynamicFont(e,a,l,o,t,r){let n=r;for(;0<n&&(e.font=n+"px Baloo, FallbackFont",!(e.measureText(a).width<t));)n--;e.textAlign="center",e.fillText(a,l,o)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.RoundedBox=exports.rankCard=exports.leaderboardCard=exports.compareCard=void 0;const canvas_1=require("@napi-rs/canvas"),xp_1=require("../xp"),xplogs_1=require("./functions/xplogs"),path_1=require("path");exports.compareCard=compareCard,exports.leaderboardCard=leaderboardCard,exports.rankCard=rankCard,exports.RoundedBox=RoundedBox;
@@ -6,6 +6,7 @@
6
6
  * @property {number} limit - Limit of users to return (2-10)
7
7
  */
8
8
  export interface ChartOptions {
9
+ fallbackFont?: string;
9
10
  font?: string;
10
11
  limit?: 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
11
12
  theme?: "blue" | "dark" | "discord" | "green" | "orange" | "red" | "space" | "yellow";
package/lib/src/charts.js CHANGED
@@ -7,4 +7,4 @@
7
7
  * @link `Documentation:` https://simplyxp.js.org/docs/next/functions/charts
8
8
  * @returns {Promise<{attachment: Buffer, description: string, name: string}>} Chart attachment
9
9
  * @throws {XpFatal} If invalid parameters are provided, or if there are not enough users to create a chart
10
- */async function charts(guildId,options={}){var t,o,a,r,i,l,F,s,e;if(!guildId)throw new xplogs_1.XpFatal({function:"charts()",message:"No Guild ID Provided"});if(!options)throw new xplogs_1.XpFatal({function:"charts()",message:"No Options Provided"});options.theme&&["blue","dark","discord","green","orange","red","space","yellow"].includes(options.theme)||(xplogs_1.XpLog.warn("charts()","Invalid theme provided, defaulting to discord"),options.theme="discord"),options.type&&["bar","doughnut","pie"].includes(options.type)||(xplogs_1.XpLog.warn("charts()","Invalid type provided, defaulting to bar chart"),options.type="bar");let n;if((t=await(0,xp_1.leaderboard)(guildId,Math.min(Math.max(options?.limit||10,2),10)).catch(XPError=>{throw new xplogs_1.XpFatal({function:"charts()",message:XPError.message})})).length<2)throw new xplogs_1.XpFatal({function:"charts()",message:"Not enough users to create a chart"});switch(t.sort((a,b)=>b.position-a.position),await(0,xp_1.registerFont)(options?.font||"https://fonts.cdnfonts.com/s/14539/Baloo-Regular.woff","Baloo"),await(0,xp_1.registerFont)("https://cdn.jsdelivr.net/fontsource/fonts/mochiy-pop-one@latest/japanese-400-normal.woff2","MochiyPopOne"),options.theme){case"blue":n={background:"#1e1e3c",barColor:"#747fff",pieColors:["#747fff","#2832C2","#59788E","#00d2e7","#281E5D","#a9f5ff","#000e3f","#30edc2","#186c84","#0098ff"],textColor:"#FFFFFF"};break;case"dark":n={background:"#1e1e1e",barColor:"#747474",pieColors:["#1B1D1F","#454C53","#72787F","#999999","#9EA4AA","#CCCCCC","#C9CDD2","#DEDEDE","#E8EBED","#FFFFFF"],textColor:"#FFFFFF"};break;case"discord":n={background:"#36393f",barColor:"#5865F2",pieColors:["#5865F2","#57F287","#FEE75C","#EB459E","#ED4245","#FFFFFF","#000000","#FAA61A","#C04DF9","#00AAFF"],textColor:"#FFFFFF"};break;case"green":n={background:"#1e321e",barColor:"#74ff7f",pieColors:["#00FF00","#008000","#7FFF00","#32CD32","#228B22","#006400","#9ACD32","#00FA9A","#ADFF2F","#7CFC00"],textColor:"#FFFFFF"};break;case"orange":n={background:"#321e1e",barColor:"#ff9f74",pieColors:["#FF8C00","#FF5E0E","#FF4500","#FF6347","#E26310","#F5761A","#FD673A","#FFA500","#FF7F50","#FFD700"],textColor:"#FFFFFF"};break;case"red":n={background:"#321e1e",barColor:"#ff7474",pieColors:["#FF0000","#FF2400","#FF4500","#FF6347","#FF7F50","#FF8C00","#FFA07A","#FFA500","#FFC0CB","#FFD700"],textColor:"#FFFFFF"};break;case"space":n={background:"#001F3F",barColor:"#192E5B",pieColors:["#192E5B","#1F3F7F","#264FA3","#2C5FC7","#337FEA","#3D8FFF","#4D9FFF","#5DAFFF","#6DBFFF","#7DCFFF"],textColor:"#FFFFFF"};break;case"yellow":n={background:"#32321e",barColor:"#ffff74",pieColors:["#FFFD37","#FFEF00","#FDFF00","#DAA520","#F4C430","#E4D00A","#D2B55B","#FFFFE0","#FFFACD","#F5DEB3"],textColor:"#FFFFFF"}}const d=(0,canvas_1.createCanvas)(920,600),h=d.getContext("2d"),c=Math.max(...t.map(user=>user.level));if((0,cards_1.RoundedBox)(h,0,0,d.width,d.height,25,{clip:!0}),h.fillStyle=n.background,h.fillRect(0,0,d.width,d.height),"space"===options.theme){(guildId=h.createRadialGradient(d.width/2,d.height/2,1,d.width/2,d.height/2,Math.max(d.width,d.height))).addColorStop(0,"#000000"),guildId.addColorStop(1,"#001F3F"),h.fillStyle=guildId,h.fillRect(0,0,d.width,d.height),(guildId=h.createRadialGradient(150,150,10,150,150,100)).addColorStop(0,"#F2F2F2"),guildId.addColorStop(.8,"#D3D3D3"),guildId.addColorStop(1,"#001F3F"),h.fillStyle=guildId,h.beginPath(),h.arc(150,150,100,0,2*Math.PI),h.fill(),o=["#6B6B6B","#AA8F00","#473E83","#456579"];for(let e=0;e<o.length;e++)a=Math.random()*d.width,r=Math.random()*d.height,i=50*Math.random()+30,h.beginPath(),h.arc(a,r,i,0,2*Math.PI),h.fillStyle=o[e]||"#FFFFFF",h.fill();h.filter="blur(5px)",h.drawImage(d,0,0),h.filter="none";for(let e=0;e<100;e++)l=Math.random()*d.width,F=Math.random()*d.height,s=2*Math.random(),h.beginPath(),h.arc(l,F,s,0,2*Math.PI),h.fillStyle="#FFFFFF",h.fill()}let p=d.width-40,u=d.height-40;switch(options.type){case"bar":{e=h.measureText(c.toString()).width,p=d.width-e-100,u=d.height-140;const f=p/t.length-20,g=e+60,x=d.height-70;await Promise.all(t.map(async(user,index)=>{var e,t=(user.level===1/0?1:user.level/c)*u,index=g+index*(20+f),o=x-t,t=(h.save(),(0,cards_1.RoundedBox)(h,index,o,f,t,10,{clip:!0,fill:{color:n.barColor}}),h.restore(),index+f/2),index=(h.fillStyle=n.textColor,h.font="22px Baloo, MochiyPopOne",user.level.toString()),a=h.measureText(index).width,o=o-10,index=(h.fillText(index,t-a/2,o),user?.name||user.user),a=h.measureText(index).width,o=(h.font=Math.min(Math.floor(f/a*16),18)+"px Baloo, MochiyPopOne",a=h.measureText(index).width,30+x);"space"===options.theme&&(e=t-(user=a+20)/2,h.fillStyle="rgba(0, 0, 0, 0.5)",h.fillRect(e,o-18,user,25)),h.fillStyle=n.textColor,h.fillText(index,t-a/2,o)}))}break;case"doughnut":{const C=t.reduce((sum,user)=>sum+user.level,0),m=Math.min(p,u)/3,b=.6*m;let e=-Math.PI/2;const w=d.width/2,y=d.height/2;await Promise.all(t.map(async(user,index)=>{user=e+2*Math.PI*(user.level/C),h.fillStyle=n.pieColors[index%n.pieColors.length]||"#FFFFFF",h.beginPath(),h.moveTo(w+m*Math.cos(e),y+m*Math.sin(e)),h.arc(w,y,m,e,user),h.lineTo(w+b*Math.cos(user),y+b*Math.sin(user)),h.arc(w,y,b,user,e,!0),h.closePath(),h.fill(),e=user}))}break;case"pie":{const D=t.reduce((sum,user)=>sum+user.level,0),M=Math.min(p,u)/3;let e=-Math.PI/2;const v=d.width/2,A=d.height/2;await Promise.all(t.map(async(user,index)=>{user=e+2*Math.PI*(user.level/D),h.fillStyle=n.pieColors[index%n.pieColors.length]||"#FFFFFF",h.beginPath(),h.moveTo(v,A),h.arc(v,A,M,e,user),h.closePath(),h.fill(),e=user}))}break;default:throw new xplogs_1.XpFatal({function:"charts()",message:"Invalid chart type provided"})}if(["doughnut","pie"].includes(options.type)){const E=d.height-20-20*t.length;h.fillStyle="rgba(0,0,0,0.25)",h.fillRect(15,E-5,200,20*t.length+5),h.font="12px Baloo, MochiyPopOne",await Promise.all(t.map(async(user,index)=>{var e=n.pieColors[index%n.pieColors.length],index=E+20*index;h.fillStyle=e||"#FFFFFF",h.fillRect(20,index,15,15),h.fillStyle=n.textColor,h.fillText(user?.name||user.user,40,11.5+index)}))}return xp_1.xp.auto_clean&&(0,xp_1.clean)(),{attachment:d.toBuffer("image/png"),description:"Chart",name:"chart.png"}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.charts=void 0;const canvas_1=require("@napi-rs/canvas"),cards_1=require("./cards"),xp_1=require("../xp"),xplogs_1=require("./functions/xplogs");exports.charts=charts;
10
+ */async function charts(e,r={}){var t,a,o,F,l,i,n,s,h;if(!e)throw new xplogs_1.XpFatal({function:"charts()",message:"No Guild ID Provided"});if(!r)throw new xplogs_1.XpFatal({function:"charts()",message:"No Options Provided"});r.theme&&["blue","dark","discord","green","orange","red","space","yellow"].includes(r.theme)||(xplogs_1.XpLog.warn("charts()","Invalid theme provided, defaulting to discord"),r.theme="discord"),r.type&&["bar","doughnut","pie"].includes(r.type)||(xplogs_1.XpLog.warn("charts()","Invalid type provided, defaulting to bar chart"),r.type="bar");let c;if((t=await(0,xp_1.leaderboard)(e,Math.min(Math.max(r?.limit||10,2),10)).catch(e=>{throw new xplogs_1.XpFatal({function:"charts()",message:e.message})})).length<2)throw new xplogs_1.XpFatal({function:"charts()",message:"Not enough users to create a chart"});switch(t.sort((e,t)=>t.position-e.position),await(0,xp_1.registerFont)(r?.font||(0,path_1.join)(__dirname,"fonts","Baloo2-ExtraBold.woff2"),"Baloo"),r.fallbackFont&&await(0,xp_1.registerFont)(r.fallbackFont,"FallbackFont"),r.theme){case"blue":c={background:"#1e1e3c",barColor:"#747fff",pieColors:["#747fff","#2832C2","#59788E","#00d2e7","#281E5D","#a9f5ff","#000e3f","#30edc2","#186c84","#0098ff"],textColor:"#FFFFFF"};break;case"dark":c={background:"#1e1e1e",barColor:"#747474",pieColors:["#1B1D1F","#454C53","#72787F","#999999","#9EA4AA","#CCCCCC","#C9CDD2","#DEDEDE","#E8EBED","#FFFFFF"],textColor:"#FFFFFF"};break;case"discord":c={background:"#36393f",barColor:"#5865F2",pieColors:["#5865F2","#57F287","#FEE75C","#EB459E","#ED4245","#FFFFFF","#000000","#FAA61A","#C04DF9","#00AAFF"],textColor:"#FFFFFF"};break;case"green":c={background:"#1e321e",barColor:"#74ff7f",pieColors:["#00FF00","#008000","#7FFF00","#32CD32","#228B22","#006400","#9ACD32","#00FA9A","#ADFF2F","#7CFC00"],textColor:"#FFFFFF"};break;case"orange":c={background:"#321e1e",barColor:"#ff9f74",pieColors:["#FF8C00","#FF5E0E","#FF4500","#FF6347","#E26310","#F5761A","#FD673A","#FFA500","#FF7F50","#FFD700"],textColor:"#FFFFFF"};break;case"red":c={background:"#321e1e",barColor:"#ff7474",pieColors:["#FF0000","#FF2400","#FF4500","#FF6347","#FF7F50","#FF8C00","#FFA07A","#FFA500","#FFC0CB","#FFD700"],textColor:"#FFFFFF"};break;case"space":c={background:"#001F3F",barColor:"#192E5B",pieColors:["#192E5B","#1F3F7F","#264FA3","#2C5FC7","#337FEA","#3D8FFF","#4D9FFF","#5DAFFF","#6DBFFF","#7DCFFF"],textColor:"#FFFFFF"};break;case"yellow":c={background:"#32321e",barColor:"#ffff74",pieColors:["#FFFD37","#FFEF00","#FDFF00","#DAA520","#F4C430","#E4D00A","#D2B55B","#FFFFE0","#FFFACD","#F5DEB3"],textColor:"#FFFFFF"}}const d=(0,canvas_1.createCanvas)(920,600),p=d.getContext("2d"),f=Math.max(...t.map(e=>e.level));if((0,cards_1.RoundedBox)(p,0,0,d.width,d.height,25,{clip:!0}),p.fillStyle=c.background,p.fillRect(0,0,d.width,d.height),"space"===r.theme){(e=p.createRadialGradient(d.width/2,d.height/2,1,d.width/2,d.height/2,Math.max(d.width,d.height))).addColorStop(0,"#000000"),e.addColorStop(1,"#001F3F"),p.fillStyle=e,p.fillRect(0,0,d.width,d.height),(e=p.createRadialGradient(150,150,10,150,150,100)).addColorStop(0,"#F2F2F2"),e.addColorStop(.8,"#D3D3D3"),e.addColorStop(1,"#001F3F"),p.fillStyle=e,p.beginPath(),p.arc(150,150,100,0,2*Math.PI),p.fill(),a=["#6B6B6B","#AA8F00","#473E83","#456579"];for(let e=0;e<a.length;e++)o=Math.random()*d.width,F=Math.random()*d.height,l=50*Math.random()+30,p.beginPath(),p.arc(o,F,l,0,2*Math.PI),p.fillStyle=a[e]||"#FFFFFF",p.fill();p.filter="blur(5px)",p.drawImage(d,0,0),p.filter="none";for(let e=0;e<100;e++)i=Math.random()*d.width,n=Math.random()*d.height,s=2*Math.random(),p.beginPath(),p.arc(i,n,s,0,2*Math.PI),p.fillStyle="#FFFFFF",p.fill()}let g=d.width-40,C=d.height-40;switch(r.type){case"bar":{h=p.measureText(f.toString()).width,g=d.width-h-100,C=d.height-140;const u=g/t.length-20,b=h+60,m=d.height-70;await Promise.all(t.map(async(e,t)=>{var a,o=(e.level===1/0?1:e.level/f)*C,t=b+t*(20+u),F=m-o,o=(p.save(),(0,cards_1.RoundedBox)(p,t,F,u,o,10,{clip:!0,fill:{color:c.barColor}}),p.restore(),t+u/2),t=(p.fillStyle=c.textColor,p.font="22px Baloo, FallbackFont",e.level.toString()),l=p.measureText(t).width,F=F-10,t=(p.fillText(t,o-l/2,F),e?.name||e.user),l=p.measureText(t).width,F=(p.font=Math.min(Math.floor(u/l*16),18)+"px Baloo, FallbackFont",l=p.measureText(t).width,30+m);"space"===r.theme&&(a=o-(e=l+20)/2,p.fillStyle="rgba(0, 0, 0, 0.5)",p.fillRect(a,F-18,e,25)),p.fillStyle=c.textColor,p.fillText(t,o-l/2,F)}))}break;case"doughnut":{const x=t.reduce((e,t)=>e+t.level,0),w=Math.min(g,C)/3,D=.6*w;let a=-Math.PI/2;const v=d.width/2,y=d.height/2;await Promise.all(t.map(async(e,t)=>{e=a+2*Math.PI*(e.level/x),p.fillStyle=c.pieColors[t%c.pieColors.length]||"#FFFFFF",p.beginPath(),p.moveTo(v+w*Math.cos(a),y+w*Math.sin(a)),p.arc(v,y,w,a,e),p.lineTo(v+D*Math.cos(e),y+D*Math.sin(e)),p.arc(v,y,D,e,a,!0),p.closePath(),p.fill(),a=e}))}break;case"pie":{const k=t.reduce((e,t)=>e+t.level,0),A=Math.min(g,C)/3;let a=-Math.PI/2;const E=d.width/2,M=d.height/2;await Promise.all(t.map(async(e,t)=>{e=a+2*Math.PI*(e.level/k),p.fillStyle=c.pieColors[t%c.pieColors.length]||"#FFFFFF",p.beginPath(),p.moveTo(E,M),p.arc(E,M,A,a,e),p.closePath(),p.fill(),a=e}))}break;default:throw new xplogs_1.XpFatal({function:"charts()",message:"Invalid chart type provided"})}if(["doughnut","pie"].includes(r.type)){const _=d.height-20-20*t.length;p.fillStyle="rgba(0,0,0,0.25)",p.fillRect(15,_-5,200,20*t.length+5),p.font="12px Baloo, FallbackFont",await Promise.all(t.map(async(e,t)=>{var a=c.pieColors[t%c.pieColors.length],t=_+20*t;p.fillStyle=a||"#FFFFFF",p.fillRect(20,t,15,15),p.fillStyle=c.textColor,p.fillText(e?.name||e.user,40,11.5+t)}))}return xp_1.xp.auto_clean&&(0,xp_1.clean)(),{attachment:d.toBuffer("image/png"),description:"Chart",name:"chart.png"}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.charts=void 0;const xp_1=require("../xp"),canvas_1=require("@napi-rs/canvas"),path_1=require("path"),cards_1=require("./cards"),xplogs_1=require("./functions/xplogs");exports.charts=charts;
@@ -8,7 +8,8 @@
8
8
  * @link `Documentation:` https://simplyxp.js.org/docs/next/functions/connect
9
9
  * @returns {Promise<boolean>}
10
10
  * @throws {XpFatal} If an invalid type is provided or if the value is not provided.
11
- */async function connect(uri,options={type:void 0}){var e,{type:t,auto_create:o,auto_clean:a,notify:r,debug:n,xp_rate:s}=options;if(!s||"slow"!==s&&"normal"!==s&&"fast"!==s&&isNaN(s)||(xp_1.xp.xp_rate="slow"===s?.05:"normal"===s?.1:"fast"===s?.5:s),!uri)throw new xplogs_1.XpFatal({function:"connect()",message:"No URI Provided"});switch(!1===r&&(xp_1.xp.notify=!1),o&&(xp_1.xp.auto_create=!0),a&&(xp_1.xp.auto_clean=!0),n&&(xp_1.xp.debug=!0),t||(options.type="mongodb",xplogs_1.XpLog.warn("connect()","Database type not provided, defaulting to MongoDB")),t){case"mongodb":if(e=(await Promise.resolve().then(()=>__importStar(require("mongodb")))).MongoClient,!await checkPackageVersion("mongodb",3,6))return xplogs_1.XpLog.err("connect()","MongoDB Version 3 to 6 is required");e=await e.connect(uri).catch(error=>{throw new xplogs_1.XpFatal({function:"connect()",message:error.message})}),xp_1.xp.dbType="mongodb",xp_1.xp.database=e||void 0;break;case"sqlite":try{var[i,p]=await Promise.all([Promise.resolve().then(()=>__importStar(require("better-sqlite3"))),checkPackageVersion("better-sqlite3",7,9)]);if(!p)return xplogs_1.XpLog.err("connect()","better-sqlite3 Version 7 to 9 is required");xp_1.xp.database=new i.default(uri),xp_1.xp.dbType="sqlite",xp_1.xp.database.exec(`CREATE TABLE IF NOT EXISTS "simply-xps"
11
+ */
12
+ async function connect(e,t={type:void 0}){var a,{type:o,auto_create:n,auto_clean:r,notify:s,debug:c,xp_rate:i}=t;if(!i||"slow"!==i&&"normal"!==i&&"fast"!==i&&isNaN(i)||(xp_1.xp.xp_rate="slow"===i?.05:"normal"===i?.1:"fast"===i?.5:i),!e)throw new xplogs_1.XpFatal({function:"connect()",message:"No URI Provided"});switch(!1===s&&(xp_1.xp.notify=!1),n&&(xp_1.xp.auto_create=!0),r&&(xp_1.xp.auto_clean=!0),c&&(xp_1.xp.debug=!0),o||(t.type="mongodb",xplogs_1.XpLog.warn("connect()","Database type not provided, defaulting to MongoDB")),o){case"mongodb":if(a=(await Promise.resolve().then(()=>__importStar(require("mongodb")))).MongoClient,!await checkPackageVersion("mongodb",3,6))return xplogs_1.XpLog.err("connect()","MongoDB Version 3 to 6 is required");a=await a.connect(e).catch(e=>{throw new xplogs_1.XpFatal({function:"connect()",message:e.message})}),xp_1.xp.dbType="mongodb",xp_1.xp.database=a||void 0;break;case"sqlite":try{var[p,l]=await Promise.all([Promise.resolve().then(()=>__importStar(require("better-sqlite3"))),checkPackageVersion("better-sqlite3",7,9)]);if(!l)return xplogs_1.XpLog.err("connect()","better-sqlite3 Version 7 to 9 is required");xp_1.xp.database=new p.default(e),xp_1.xp.dbType="sqlite",xp_1.xp.database.exec(`CREATE TABLE IF NOT EXISTS "simply-xps"
12
13
  (
13
14
  user TEXT NOT NULL,
14
15
  guild TEXT NOT NULL,
@@ -24,12 +25,13 @@
24
25
  gid TEXT NOT NULL,
25
26
  lvlrole TEXT NOT NULL,
26
27
  lastUpdated TEXT NOT NULL
27
- )`)}catch(t){if("object"==typeof t&&null!==t&&void 0!==(e=t).code&&"MODULE_NOT_FOUND"!==e.code)throw new xplogs_1.XpFatal({function:"connect()",message:e.message})}break;default:throw new xplogs_1.XpFatal({function:"connect()",message:"DATABASE TYPE NOT PROVIDED OR INVALID"})}return!!xp_1.xp.database&&(xplogs_1.XpLog.info("connect()","Connected to database!"),a&&(0,xp_1.clean)({db:!0}),await xp_1.db.findAll("simply-xps").then(users=>{users.filter(user=>user?.xp_rate!==xp_1.xp.xp_rate).map(user=>{xp_1.db.updateOne({collection:"simply-xps",data:{user:user.user,guild:user.guild}},{collection:"simply-xps",data:{user:user.user,guild:user.guild,level:(0,xp_1.convertFrom)(user.xp,"xp"),xp:user.xp,xp_rate:xp_1.xp.xp_rate}})})}),xplogs_1.XpLog.debug("connect()","UPDATED ALL USERS WITH NEW XP RATE"),!0)}
28
+ )`)}catch(e){if("object"==typeof e&&null!==e&&void 0!==(a=e).code&&"MODULE_NOT_FOUND"!==a.code)throw new xplogs_1.XpFatal({function:"connect()",message:a.message})}break;default:throw new xplogs_1.XpFatal({function:"connect()",message:"DATABASE TYPE NOT PROVIDED OR INVALID"})}return!!xp_1.xp.database&&(xplogs_1.XpLog.info("connect()","Connected to database!"),r&&(0,xp_1.clean)({db:!0}),await xp_1.db.findAll("simply-xps").then(e=>{e.filter(e=>e?.xp_rate!==xp_1.xp.xp_rate).map(e=>{xp_1.db.updateOne({collection:"simply-xps",data:{user:e.user,guild:e.guild}},{collection:"simply-xps",data:{user:e.user,guild:e.guild,level:(0,xp_1.convertFrom)(e.xp,"xp"),xp:e.xp,xp_rate:xp_1.xp.xp_rate}})})}),xplogs_1.XpLog.debug("connect()","UPDATED ALL USERS WITH NEW XP RATE"),!0)}
28
29
  /**
29
30
  * Returns the package manager used
30
31
  * @private
31
32
  * @returns {Promise<"yarn" | "npm" | "pnpm">}
32
- */async function getPackageManager(){const e=(await Promise.resolve().then(()=>__importStar(require("fs")))).existsSync;var t=["yarn.lock","pnpm-lock.yaml","pnpm-lock.json","package-lock.json"].filter(lockfile=>e(lockfile));if(1===t.length){if("yarn.lock"===t[0])return xplogs_1.XpLog.debug("getPackageManager()","Using YARN"),"yarn";if("pnpm-lock.yaml"===t[0]||"pnpm-lock.json"===t[0])return xplogs_1.XpLog.debug("getPackageManager()","Using PNPM"),"pnpm"}return xplogs_1.XpLog.debug("getPackageManager()","Using NPM"),"npm"}
33
+ */
34
+ async function getPackageManager(){const t=(await Promise.resolve().then(()=>__importStar(require("fs")))).existsSync;var e=["yarn.lock","pnpm-lock.yaml","pnpm-lock.json","package-lock.json"].filter(e=>t(e));if(1===e.length){if("yarn.lock"===e[0])return xplogs_1.XpLog.debug("getPackageManager()","Using YARN"),"yarn";if("pnpm-lock.yaml"===e[0]||"pnpm-lock.json"===e[0])return xplogs_1.XpLog.debug("getPackageManager()","Using PNPM"),"pnpm"}return xplogs_1.XpLog.debug("getPackageManager()","Using NPM"),"npm"}
33
35
  /**
34
36
  * Check database package versions
35
37
  * @private
@@ -38,4 +40,4 @@
38
40
  * @param {number} max - Maximum Major Version Number (Optional)
39
41
  * @returns {Promise<boolean>}
40
42
  * @throws {XpFatal} If the package version is not supported
41
- */async function checkPackageVersion(type,min,max){try{var e=await Promise.resolve(type+"/package.json").then(s=>__importStar(require(s)));return parseInt(e.version.substring(0,1))>=min&&(!max||parseInt(e.version.substring(0,1))<=max)}catch(e){return xplogs_1.XpLog.info("checkPackageVersion()",`Installing ${type} [V${max||min}] | Please wait...`),(0,child_process_1.execSync)(await getPackageManager()+` add ${type}@${max||min}.x.x`),xplogs_1.XpLog.warn("checkPackageVersion()",`Installed ${type}. Please restart!`),process.exit(1)}}var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var e=Object.getOwnPropertyDescriptor(m,k);e&&("get"in e?m.__esModule:!e.writable&&!e.configurable)||(e={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,e)}:function(o,m,k,k2){o[k2=void 0===k2?k:k2]=m[k]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=this&&this.__importStar||function(mod){var e,t;if(mod&&mod.__esModule)return mod;if(e={},null!=mod)for(t in mod)"default"!==t&&Object.prototype.hasOwnProperty.call(mod,t)&&__createBinding(e,mod,t);return __setModuleDefault(e,mod),e};Object.defineProperty(exports,"__esModule",{value:!0}),exports.checkPackageVersion=exports.connect=void 0;const xplogs_1=require("./functions/xplogs"),child_process_1=require("child_process"),xp_1=require("../xp");exports.connect=connect,exports.checkPackageVersion=checkPackageVersion;
43
+ */async function checkPackageVersion(t,a,o){try{var e=await Promise.resolve(t+"/package.json").then(e=>__importStar(require(e)));return parseInt(e.version.substring(0,1))>=a&&(!o||parseInt(e.version.substring(0,1))<=o)}catch(e){return xplogs_1.XpLog.info("checkPackageVersion()",`Installing ${t} [V${o||a}] | Please wait...`),(0,child_process_1.execSync)(await getPackageManager()+` add ${t}@${o||a}.x.x`),xplogs_1.XpLog.warn("checkPackageVersion()",`Installed ${t}. Please restart!`),process.exit(1)}}var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,a,o){void 0===o&&(o=a);var n=Object.getOwnPropertyDescriptor(t,a);n&&("get"in n?t.__esModule:!n.writable&&!n.configurable)||(n={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,o,n)}:function(e,t,a,o){e[o=void 0===o?a:o]=t[a]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(e){var t,a;if(e&&e.__esModule)return e;if(t={},null!=e)for(a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&__createBinding(t,e,a);return __setModuleDefault(t,e),t};Object.defineProperty(exports,"__esModule",{value:!0}),exports.checkPackageVersion=exports.connect=void 0;const xplogs_1=require("./functions/xplogs"),child_process_1=require("child_process"),xp_1=require("../xp");exports.connect=connect,exports.checkPackageVersion=checkPackageVersion;
package/lib/src/create.js CHANGED
@@ -8,4 +8,5 @@
8
8
  * @link `Documentation:` https://simplyxp.js.org/docs/next/functions/create
9
9
  * @returns {Promise<UserResult>}
10
10
  * @throws {XpFatal} If invalid parameters are provided
11
- */async function create(userId,guildId,username){if(!userId)throw new xplogs_1.XpFatal({function:"create()",message:"User ID was not provided"});if(!guildId)throw new xplogs_1.XpFatal({function:"create()",message:"Guild ID was not provided"});var e;if(username)return await(e=(await Promise.resolve().then(()=>__importStar(require("./functions/database")))).db).findOne({collection:"simply-xps",data:{user:userId,guild:guildId}})||e.createOne({collection:"simply-xps",data:{name:username,user:userId,guild:guildId,level:0,xp:0,xp_rate:xp_1.xp.xp_rate}});throw new xplogs_1.XpFatal({function:"create()",message:"Username was not provided"})}var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var e=Object.getOwnPropertyDescriptor(m,k);e&&("get"in e?m.__esModule:!e.writable&&!e.configurable)||(e={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,e)}:function(o,m,k,k2){o[k2=void 0===k2?k:k2]=m[k]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=this&&this.__importStar||function(mod){var e,t;if(mod&&mod.__esModule)return mod;if(e={},null!=mod)for(t in mod)"default"!==t&&Object.prototype.hasOwnProperty.call(mod,t)&&__createBinding(e,mod,t);return __setModuleDefault(e,mod),e};Object.defineProperty(exports,"__esModule",{value:!0}),exports.create=void 0;const xplogs_1=require("./functions/xplogs"),xp_1=require("../xp");exports.create=create;
11
+ */
12
+ async function create(e,t,r){if(!e)throw new xplogs_1.XpFatal({function:"create()",message:"User ID was not provided"});if(!t)throw new xplogs_1.XpFatal({function:"create()",message:"Guild ID was not provided"});var a;if(r)return await(a=(await Promise.resolve().then(()=>__importStar(require("./functions/database")))).db).findOne({collection:"simply-xps",data:{user:e,guild:t}})||a.createOne({collection:"simply-xps",data:{name:r,user:e,guild:t,level:0,xp:0,xp_rate:xp_1.xp.xp_rate}});throw new xplogs_1.XpFatal({function:"create()",message:"Username was not provided"})}var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&("get"in i?t.__esModule:!i.writable&&!i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,a,i)}:function(e,t,r,a){e[a=void 0===a?r:a]=t[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(e){var t,r;if(e&&e.__esModule)return e;if(t={},null!=e)for(r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&__createBinding(t,e,r);return __setModuleDefault(t,e),t};Object.defineProperty(exports,"__esModule",{value:!0}),exports.create=void 0;const xplogs_1=require("./functions/xplogs"),xp_1=require("../xp");exports.create=create;
package/lib/src/fetch.js CHANGED
@@ -8,4 +8,4 @@
8
8
  * @link `Documentation:` https://simplyxp.js.org/docs/next/functions/fetch
9
9
  * @returns {Promise<{name: string | null, user: string, guild: string, level: number, position: number, xp: number}>}
10
10
  * @throws {XpFatal} If invalid parameters are provided, or if the user data is not found.
11
- */async function fetch(userId,guildId,username){var e;if(!userId)throw new xplogs_1.XpFatal({function:"create()",message:"User ID was not provided"});if(!guildId)throw new xplogs_1.XpFatal({function:"create()",message:"Guild ID was not provided"});(0,xp_1.clean)({db:!0});let t=(e=await(await Promise.resolve().then(()=>__importStar(require("./functions/database")))).db.find({collection:"simply-xps",data:{guild:guildId}})).find(u=>u.user===userId);if(!t){if(!xp_1.xp.auto_create||!username)throw new xplogs_1.XpFatal({function:"fetch()",message:"User data not found"});t=await(await Promise.resolve().then(()=>__importStar(require("./create")))).create(guildId,userId,username)}return guildId=e.sort((a,b)=>b.xp-a.xp).findIndex(u=>u.user===userId)+1,{name:t?.name,user:t.user,guild:t.guild,level:t.level,position:guildId,xp:t.xp}}var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var e=Object.getOwnPropertyDescriptor(m,k);e&&("get"in e?m.__esModule:!e.writable&&!e.configurable)||(e={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,e)}:function(o,m,k,k2){o[k2=void 0===k2?k:k2]=m[k]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=this&&this.__importStar||function(mod){var e,t;if(mod&&mod.__esModule)return mod;if(e={},null!=mod)for(t in mod)"default"!==t&&Object.prototype.hasOwnProperty.call(mod,t)&&__createBinding(e,mod,t);return __setModuleDefault(e,mod),e};Object.defineProperty(exports,"__esModule",{value:!0}),exports.fetch=void 0;const xplogs_1=require("./functions/xplogs"),xp_1=require("../xp");exports.fetch=fetch;
11
+ */async function fetch(t,e,r){var i;if(!t)throw new xplogs_1.XpFatal({function:"create()",message:"User ID was not provided"});if(!e)throw new xplogs_1.XpFatal({function:"create()",message:"Guild ID was not provided"});(0,xp_1.clean)({db:!0});let n=(i=await(await Promise.resolve().then(()=>__importStar(require("./functions/database")))).db.find({collection:"simply-xps",data:{guild:e}})).find(e=>e.user===t);if(!n){if(!xp_1.xp.auto_create||!r)throw new xplogs_1.XpFatal({function:"fetch()",message:"User data not found"});n=await(await Promise.resolve().then(()=>__importStar(require("./create")))).create(e,t,r)}return e=i.sort((e,t)=>t.xp-e.xp).findIndex(e=>e.user===t)+1,{name:n?.name,user:n.user,guild:n.guild,level:n.level,position:e,xp:n.xp}}var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,r,i){void 0===i&&(i=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&("get"in n?t.__esModule:!n.writable&&!n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,n)}:function(e,t,r,i){e[i=void 0===i?r:i]=t[r]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(e){var t,r;if(e&&e.__esModule)return e;if(t={},null!=e)for(r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&__createBinding(t,e,r);return __setModuleDefault(t,e),t};Object.defineProperty(exports,"__esModule",{value:!0}),exports.fetch=void 0;const xplogs_1=require("./functions/xplogs"),xp_1=require("../xp");exports.fetch=fetch;
@@ -5,7 +5,7 @@
5
5
  * @param {string} functionName
6
6
  * @returns {void}
7
7
  * @private
8
- */function handleError(error,functionName){throw new xplogs_1.XpFatal({function:"db."+functionName,message:error})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.db=void 0;const xplogs_1=require("./xplogs"),xp_1=require("../../xp");class db{
8
+ */function handleError(e,a){throw new xplogs_1.XpFatal({function:"db."+a,message:e})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.db=void 0;const xplogs_1=require("./xplogs"),xp_1=require("../../xp");class db{
9
9
  /**
10
10
  * Gets a collection from the database.
11
11
  * @param {collection} collection - The collection to get.
@@ -13,7 +13,7 @@
13
13
  * @returns {Collection} The collection.
14
14
  * @throws {XpFatal} Throws an error if there is no database connection, or database type is invalid.
15
15
  */
16
- static getCollection(collection){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"getCollection()",message:"No database connection"});if("mongodb"!==xp_1.xp.dbType)throw new xplogs_1.XpFatal({function:"getCollection()",message:"MongoDB has to be your database type to use this function."});return xp_1.xp.database.db().collection(collection)}
16
+ static getCollection(e){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"getCollection()",message:"No database connection"});if("mongodb"!==xp_1.xp.dbType)throw new xplogs_1.XpFatal({function:"getCollection()",message:"MongoDB has to be your database type to use this function."});return xp_1.xp.database.db().collection(e)}
17
17
  /**
18
18
  * Creates one document in the database.
19
19
  *
@@ -22,7 +22,7 @@ static getCollection(collection){if(!xp_1.xp.database)throw new xplogs_1.XpFatal
22
22
  * @link https://simplyxp.js.org/docs/next/handlers/database#createOne Documentation
23
23
  * @returns {Promise<UserResult | LevelRoleResult>} The created document.
24
24
  * @throws {XpFatal} Throws an error if there is no database connection.
25
- */static async createOne(query){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"createOne()",message:"No database connection"});switch(xp_1.xp.dbType){case"mongodb":xp_1.xp.database.db().collection(query.collection).insertOne({...query.data,lastUpdated:(new Date).toISOString()}).catch(error=>handleError(error,"createOne()"));break;case"sqlite":"simply-xps"===query.collection?xp_1.xp.database.prepare('INSERT INTO "simply-xps" (user, guild, level, name, lastUpdated, xp, xp_rate) VALUES (?, ?, ?, ?, ?, ?, ?)').run(query.data.user,query.data.guild,query.data.level,query.data?.name,(new Date).toISOString(),query.data.xp,query.data.xp_rate):xp_1.xp.database.prepare('INSERT INTO "simply-xp-levelroles" (gid, lvlrole, lastUpdated) VALUES (?, ?, ?)').run(query.data.guild,JSON.stringify(query.data.lvlrole),(new Date).toISOString())}return db.findOne(query)}
25
+ */static async createOne(e){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"createOne()",message:"No database connection"});switch(xp_1.xp.dbType){case"mongodb":xp_1.xp.database.db().collection(e.collection).insertOne({...e.data,lastUpdated:(new Date).toISOString()}).catch(e=>handleError(e,"createOne()"));break;case"sqlite":"simply-xps"===e.collection?xp_1.xp.database.prepare('INSERT INTO "simply-xps" (user, guild, level, name, lastUpdated, xp, xp_rate) VALUES (?, ?, ?, ?, ?, ?, ?)').run(e.data.user,e.data.guild,e.data.level,e.data?.name,(new Date).toISOString(),e.data.xp,e.data.xp_rate):xp_1.xp.database.prepare('INSERT INTO "simply-xp-levelroles" (gid, lvlrole, lastUpdated) VALUES (?, ?, ?)').run(e.data.guild,JSON.stringify(e.data.lvlrole),(new Date).toISOString())}return db.findOne(e)}
26
26
  /**
27
27
  * Deletes multiple documents from the database.
28
28
  * @async
@@ -30,7 +30,7 @@ static getCollection(collection){if(!xp_1.xp.database)throw new xplogs_1.XpFatal
30
30
  * @link https://simplyxp.js.org/docs/next/handlers/database#deleteMany Documentation
31
31
  * @returns {Promise<boolean>} `true` if the documents were successfully deleted, otherwise `false`.
32
32
  * @throws {XpFatal} Throws an error if there is no database connection.
33
- */static async deleteMany(query){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"deleteMany()",message:"No database connection"});let e;switch(xp_1.xp.dbType){case"mongodb":e=xp_1.xp.database.db().collection(query.collection).deleteMany(query.data).catch(error=>handleError(error,"deleteMany()"));break;case"sqlite":e=("simply-xps"===query.collection?xp_1.xp.database.prepare('DELETE FROM "simply-xps" WHERE guild = ?'):xp_1.xp.database.prepare('DELETE FROM "simply-xp-levelroles" WHERE gid = ?')).run(query.data.guild)}return!!e}
33
+ */static async deleteMany(e){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"deleteMany()",message:"No database connection"});let a;switch(xp_1.xp.dbType){case"mongodb":a=xp_1.xp.database.db().collection(e.collection).deleteMany(e.data).catch(e=>handleError(e,"deleteMany()"));break;case"sqlite":a=("simply-xps"===e.collection?xp_1.xp.database.prepare('DELETE FROM "simply-xps" WHERE guild = ?'):xp_1.xp.database.prepare('DELETE FROM "simply-xp-levelroles" WHERE gid = ?')).run(e.data.guild)}return!!a}
34
34
  /**
35
35
  * Deletes one document from the database.
36
36
  *
@@ -39,7 +39,7 @@ static getCollection(collection){if(!xp_1.xp.database)throw new xplogs_1.XpFatal
39
39
  * @link https://simplyxp.js.org/docs/next/handlers/database#deleteOne Documentation
40
40
  * @returns {Promise<boolean>} `true` if the document was successfully deleted, otherwise `false`.
41
41
  * @throws {XpFatal} Throws an error if there is no database connection.
42
- */static async deleteOne(query){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"deleteOne()",message:"No database connection"});let e;switch(xp_1.xp.dbType){case"mongodb":e=xp_1.xp.database.db().collection(query.collection).deleteOne(query.data).catch(error=>handleError(error,"deleteOne()"));break;case"sqlite":e="simply-xps"===query.collection?xp_1.xp.database.prepare('DELETE FROM "simply-xps" WHERE guild = ? AND user = ?').run(query.data.guild,query.data.user):(e=(e=await this.find(query)).filter(row=>row.lvlrole.lvl===query.data.lvlrole.lvl)[0],xp_1.xp.database.prepare('DELETE FROM "simply-xp-levelroles" WHERE gid = ? AND lvlrole = ?').run(query.data.guild,JSON.stringify(e.lvlrole)))}return!!e}
42
+ */static async deleteOne(a){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"deleteOne()",message:"No database connection"});let e;switch(xp_1.xp.dbType){case"mongodb":e=xp_1.xp.database.db().collection(a.collection).deleteOne(a.data).catch(e=>handleError(e,"deleteOne()"));break;case"sqlite":e="simply-xps"===a.collection?xp_1.xp.database.prepare('DELETE FROM "simply-xps" WHERE guild = ? AND user = ?').run(a.data.guild,a.data.user):(e=(e=await this.find(a)).filter(e=>e.lvlrole.lvl===a.data.lvlrole.lvl)[0],xp_1.xp.database.prepare('DELETE FROM "simply-xp-levelroles" WHERE gid = ? AND lvlrole = ?').run(a.data.guild,JSON.stringify(e.lvlrole)))}return!!e}
43
43
  /**
44
44
  * Finds one document in the database.
45
45
  *
@@ -48,7 +48,7 @@ static getCollection(collection){if(!xp_1.xp.database)throw new xplogs_1.XpFatal
48
48
  * @link https://simplyxp.js.org/docs/next/handlers/database#findOne Documentation
49
49
  * @returns {Promise<UserResult | LevelRoleResult>} The found document.
50
50
  * @throws {XpFatal} Throws an error if there is no database connection.
51
- */static async findOne(query){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"findOne()",message:"No database connection"});let e;switch(xp_1.xp.dbType){case"mongodb":e="simply-xps"===query.collection?await xp_1.xp.database.db().collection(query.collection).findOne(query.data).catch(error=>handleError(error,"findOne()")):await xp_1.xp.database.db().collection(query.collection).findOne({guild:query.data.guild,"lvlrole.lvl":query.data.lvlrole.lvl}).catch(error=>handleError(error,"findOne()"));break;case"sqlite":e="simply-xps"===query.collection?xp_1.xp.database.prepare('SELECT * FROM "simply-xps" WHERE guild = ? AND user = ?').get(query.data.guild,query.data.user):(e=await this.find(query)).filter(row=>row.lvlrole.lvl===query.data.lvlrole.lvl)[0]}return e}
51
+ */static async findOne(a){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"findOne()",message:"No database connection"});let e;switch(xp_1.xp.dbType){case"mongodb":e="simply-xps"===a.collection?await xp_1.xp.database.db().collection(a.collection).findOne(a.data).catch(e=>handleError(e,"findOne()")):await xp_1.xp.database.db().collection(a.collection).findOne({guild:a.data.guild,"lvlrole.lvl":a.data.lvlrole.lvl}).catch(e=>handleError(e,"findOne()"));break;case"sqlite":e="simply-xps"===a.collection?xp_1.xp.database.prepare('SELECT * FROM "simply-xps" WHERE guild = ? AND user = ?').get(a.data.guild,a.data.user):(e=await this.find(a)).filter(e=>e.lvlrole.lvl===a.data.lvlrole.lvl)[0]}return e}
52
52
  /**
53
53
  * Finds multiple documents in the database.
54
54
  *
@@ -57,14 +57,14 @@ static getCollection(collection){if(!xp_1.xp.database)throw new xplogs_1.XpFatal
57
57
  * @link https://simplyxp.js.org/docs/next/handlers/database#find Documentation
58
58
  * @returns {Promise<UserResult[] | LevelRoleResult[]>} An array of found documents.
59
59
  * @throws {XpFatal} Throws an error if there is no database connection.
60
- */static async find(query){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"find()",message:"No database connection"});let e;switch(xp_1.xp.dbType){case"mongodb":e=xp_1.xp.database.db().collection(query.collection).find(query.data).toArray().catch(error=>handleError(error,"find()"));break;case"sqlite":"simply-xps"===query.collection?e=xp_1.xp.database.prepare('SELECT * FROM "simply-xps" WHERE guild = ?').all(query.data.guild):(e=xp_1.xp.database.prepare('SELECT * FROM "simply-xp-levelroles" WHERE gid = ?').all(query.data.guild)).length&&(e=await Promise.all(e.map(async row=>(row.lvlrole=JSON.parse(row.lvlrole),row))))}return e}
60
+ */static async find(e){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"find()",message:"No database connection"});let a;switch(xp_1.xp.dbType){case"mongodb":a=xp_1.xp.database.db().collection(e.collection).find(e.data).toArray().catch(e=>handleError(e,"find()"));break;case"sqlite":"simply-xps"===e.collection?a=xp_1.xp.database.prepare('SELECT * FROM "simply-xps" WHERE guild = ?').all(e.data.guild):(a=xp_1.xp.database.prepare('SELECT * FROM "simply-xp-levelroles" WHERE gid = ?').all(e.data.guild)).length&&(a=await Promise.all(a.map(async e=>(e.lvlrole=JSON.parse(e.lvlrole),e))))}return a}
61
61
  /**
62
62
  * Finds all documents in a collection.
63
63
  * @param {"simply-xps" | "simply-xp-levelroles"} collection - The collection to search for all documents.
64
64
  * @link https://simplyxp.js.org/docs/next/handlers/database#findAll Documentation
65
65
  * @returns {Promise<UserResult[] | LevelRoleResult[]>} An array of found documents.
66
66
  * @throws {XpFatal} Throws an error if there is no database connection.
67
- */static async findAll(collection){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"findAll()",message:"No database connection"});let e;switch(xp_1.xp.dbType){case"mongodb":e=xp_1.xp.database.db().collection(collection).find().toArray().catch(error=>handleError(error,"findAll()"));break;case"sqlite":"simply-xps"===collection?e=xp_1.xp.database.prepare('SELECT * FROM "simply-xps"').all():(e=xp_1.xp.database.prepare('SELECT * FROM "simply-xp-levelroles"').all()).length&&(e=await Promise.all(e.map(async row=>(row.lvlrole=JSON.parse(row.lvlrole),row))))}return e}
67
+ */static async findAll(e){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"findAll()",message:"No database connection"});let a;switch(xp_1.xp.dbType){case"mongodb":a=xp_1.xp.database.db().collection(e).find().toArray().catch(e=>handleError(e,"findAll()"));break;case"sqlite":"simply-xps"===e?a=xp_1.xp.database.prepare('SELECT * FROM "simply-xps"').all():(a=xp_1.xp.database.prepare('SELECT * FROM "simply-xp-levelroles"').all()).length&&(a=await Promise.all(a.map(async e=>(e.lvlrole=JSON.parse(e.lvlrole),e))))}return a}
68
68
  /**
69
69
  * Updates one document in the database.
70
70
  *
@@ -75,4 +75,4 @@ static getCollection(collection){if(!xp_1.xp.database)throw new xplogs_1.XpFatal
75
75
  * @link https://simplyxp.js.org/docs/next/handlers/database#updateOne Documentation
76
76
  * @returns {Promise<UserResult | LevelRoleResult>} The updated document.
77
77
  * @throws {XpFatal} Throws an error if there is no database connection.
78
- */static async updateOne(filter,update,options){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"updateOne()",message:"No database connection"});switch(xp_1.xp.dbType){case"mongodb":await xp_1.xp.database.db().collection(update.collection).updateOne(filter.data,{$set:{...update.data,lastUpdated:(new Date).toISOString()}},options).catch(error=>handleError(error,"updateOne()"));break;case"sqlite":if("simply-xps"===filter.collection&&"simply-xps"===update.collection)xp_1.xp.database.prepare(`UPDATE "simply-xps" SET xp_rate = ?, xp = ?, lastUpdated = ?, level = ? ${update.data?.name?", name = ?":""} WHERE guild = ? AND user = ?`).run(update.data?.name?[update.data.xp_rate,update.data.xp,(new Date).toISOString(),update.data.level,update.data.name,filter.data.guild,filter.data.user]:[update.data.xp_rate,update.data.xp,(new Date).toISOString(),update.data.level,filter.data.guild,filter.data.user]);else{if("simply-xp-levelroles"!==filter.collection||"simply-xp-levelroles"!==update.collection)throw new xplogs_1.XpFatal({function:"updateOne()",message:"Collection mismatch, expected same collection on both filter and update."});xp_1.xp.database.prepare('UPDATE "simply-xp-levelroles" SET lvlrole = ? WHERE gid = ?').run(JSON.stringify(update.data.lvlrole),filter.data.guild)}}return db.findOne(update)}}exports.db=db;
78
+ */static async updateOne(e,a,t){if(!xp_1.xp.database)throw new xplogs_1.XpFatal({function:"updateOne()",message:"No database connection"});switch(xp_1.xp.dbType){case"mongodb":await xp_1.xp.database.db().collection(a.collection).updateOne(e.data,{$set:{...a.data,lastUpdated:(new Date).toISOString()}},t).catch(e=>handleError(e,"updateOne()"));break;case"sqlite":if("simply-xps"===e.collection&&"simply-xps"===a.collection)xp_1.xp.database.prepare(`UPDATE "simply-xps" SET xp_rate = ?, xp = ?, lastUpdated = ?, level = ? ${a.data?.name?", name = ?":""} WHERE guild = ? AND user = ?`).run(a.data?.name?[a.data.xp_rate,a.data.xp,(new Date).toISOString(),a.data.level,a.data.name,e.data.guild,e.data.user]:[a.data.xp_rate,a.data.xp,(new Date).toISOString(),a.data.level,e.data.guild,e.data.user]);else{if("simply-xp-levelroles"!==e.collection||"simply-xp-levelroles"!==a.collection)throw new xplogs_1.XpFatal({function:"updateOne()",message:"Collection mismatch, expected same collection on both filter and update."});xp_1.xp.database.prepare('UPDATE "simply-xp-levelroles" SET lvlrole = ? WHERE gid = ?').run(JSON.stringify(a.data.lvlrole),e.data.guild)}}return db.findOne(a)}}exports.db=db;
@@ -12,4 +12,4 @@
12
12
  * @param {number} [options.timeout] - Request Timeout in Milliseconds
13
13
  * @returns {Promise<Object|Buffer|string>} - Returns the response from the request.
14
14
  * @throws {PromiseRejectedResult} - If the request fails.
15
- */function https(url,options={}){return new Promise((resolve,reject)=>{const e=(0,https_1.request)({agent:new https_1.Agent({keepAlive:!0}),headers:options?.headers||{"Content-Type":"application/json"},hostname:new url_1.URL(url).hostname,method:options?.method||"GET",path:options?.endpoint||new url_1.URL(url).pathname},response=>{const e=[];response.on("error",reject),response.on("data",chunk=>e.push(Buffer.from(chunk))),response.on("end",()=>{options?.statusCode&&response.statusCode!==options?.statusCode&&reject({error:"Unexpected Status Code",status:response.statusCode});try{switch(options?.responseType||"json"){case"json":resolve(JSON.parse(Buffer.concat(e).toString()));break;case"stream":resolve(Buffer.concat(e));break;default:resolve(Buffer.concat(e).toString())}}catch(e){reject(e)}})}).on("error",reject);e.setTimeout(options?.timeout||5e3,()=>{e.destroy(),reject({error:"Request Timed Out",status:408})}),options?.body&&e.write(JSON.stringify(options.body)),e.end()})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.https=void 0;const https_1=require("https"),url_1=require("url");exports.https=https;
15
+ */function https(e,o={}){return new Promise((s,r)=>{const t=(0,https_1.request)({agent:new https_1.Agent({keepAlive:!0}),headers:o?.headers||{"Content-Type":"application/json"},hostname:new url_1.URL(e).hostname,method:o?.method||"GET",path:o?.endpoint||new url_1.URL(e).pathname},t=>{const e=[];t.on("error",r),t.on("data",t=>e.push(Buffer.from(t))),t.on("end",()=>{o?.statusCode&&t.statusCode!==o?.statusCode&&r({error:"Unexpected Status Code",status:t.statusCode});try{switch(o?.responseType||"json"){case"json":s(JSON.parse(Buffer.concat(e).toString()));break;case"stream":s(Buffer.concat(e));break;default:s(Buffer.concat(e).toString())}}catch(t){r(t)}})}).on("error",r);t.setTimeout(o?.timeout||5e3,()=>{t.destroy(),r({error:"Request Timed Out",status:408})}),o?.body&&t.write(JSON.stringify(o.body)),t.end()})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.https=void 0;const https_1=require("https"),url_1=require("url");exports.https=https;
@@ -24,8 +24,11 @@ interface NewClientOptions {
24
24
  auto_create: boolean;
25
25
  auto_clean: boolean;
26
26
  dbOptions: {
27
- type: "mongodb" | "sqlite";
28
- database: MongoClient | Database;
27
+ type: "mongodb";
28
+ database: MongoClient;
29
+ } | {
30
+ type: "sqlite";
31
+ database: Database;
29
32
  };
30
33
  debug: boolean;
31
34
  notify: boolean;
@@ -6,7 +6,7 @@
6
6
  * @link `Documentation:` https://simplyxp.js.org/docs/next/clean
7
7
  * @returns {void} - Nothing.
8
8
  * @throws {XpFatal} If an error occurs.
9
- */function clean(options={}){options?.db&&xp_1.xp?.database&&xp_1.db.findAll("simply-xps").then(users=>{users.forEach(async user=>{0===user.level&&0===user.xp&&await xp_1.db.deleteOne({collection:"simply-xps",data:{user:user.user,guild:user.guild}})}),xplogs_1.XpLog.debug("clean()","REMOVED ALL USERS WITHOUT XP")}),(0,canvas_1.clearAllCache)(),xplogs_1.XpLog.debug("clean()","CLEARED CANVAS CACHE")}
9
+ */function clean(e={}){e?.db&&xp_1.xp?.database&&xp_1.db.findAll("simply-xps").then(e=>{e.forEach(async e=>{0===e.level&&0===e.xp&&await xp_1.db.deleteOne({collection:"simply-xps",data:{user:e.user,guild:e.guild}})}),xplogs_1.XpLog.debug("clean()","REMOVED ALL USERS WITHOUT XP")}),(0,canvas_1.clearAllCache)(),xplogs_1.XpLog.debug("clean()","CLEARED CANVAS CACHE")}
10
10
  /**
11
11
  * Convert XP to level and vice versa.
12
12
  *
@@ -15,7 +15,7 @@
15
15
  * @link `Documentation:` https://simplyxp.js.org/docs/next/Functions/convert
16
16
  * @returns {number} - The converted value. (XP to level or level to XP)
17
17
  * @throws {XpFatal} If an invalid type is provided or if the value is not provided.
18
- */function convertFrom(value,type="level"){if(isNaN(value))throw new xplogs_1.XpFatal({function:"convertFrom()",message:"Value was not provided"});if("xp"!==type&&"level"!==type)throw new xplogs_1.XpFatal({function:"convert()",message:"Invalid type provided"});if("level"===type)return Math.pow(Math.max(0,value)/xp_1.xp.xp_rate,2);if("xp"===type)return Math.floor(xp_1.xp.xp_rate*Math.sqrt(Math.max(0,value)));throw new xplogs_1.XpFatal({function:"convertFrom()",message:"Invalid type provided"})}
18
+ */function convertFrom(e,t="level"){if(isNaN(e))throw new xplogs_1.XpFatal({function:"convertFrom()",message:"Value was not provided"});if("xp"!==t&&"level"!==t)throw new xplogs_1.XpFatal({function:"convert()",message:"Invalid type provided"});if("level"===t)return Math.pow(Math.max(0,e)/xp_1.xp.xp_rate,2);if("xp"===t)return Math.floor(xp_1.xp.xp_rate*Math.sqrt(Math.max(0,e)));throw new xplogs_1.XpFatal({function:"convertFrom()",message:"Invalid type provided"})}
19
19
  /**
20
20
  * Registers fonts from URLs or paths (For convenience).
21
21
  * @param {string} pathOrURL - The path or URL to the font.
@@ -24,15 +24,15 @@
24
24
  * @link `Documentation:` https://simplyxp.js.org/docs/next/Functions/registerFont
25
25
  * @returns {Promise<void>} - Nothing.
26
26
  * @throws {XpFatal} If an invalid path or URL is provided.
27
- */async function registerFont(pathOrURL,name,timeout=1500){xp_1.xp.registeredFonts.includes(name)||(pathOrURL.startsWith("https://")?await(0,xp_1.https)(pathOrURL,{responseType:"stream",timeout:timeout}).then(font=>{canvas_1.GlobalFonts.register(font,name),xp_1.xp.registeredFonts.push(name)}).catch(error=>{throw new xplogs_1.XpFatal({function:"registerFont()",message:`Failed to register font from URL
28
- `+JSON.stringify(error)})}):(canvas_1.GlobalFonts.registerFromPath(pathOrURL,name),xp_1.xp.registeredFonts.push(name)))}
27
+ */async function registerFont(e,t,a=1500){xp_1.xp.registeredFonts.includes(t)||(e.startsWith("https://")?await(0,xp_1.https)(e,{responseType:"stream",timeout:a}).then(e=>{canvas_1.GlobalFonts.register(e,t),xp_1.xp.registeredFonts.push(t)}).catch(e=>{throw new xplogs_1.XpFatal({function:"registerFont()",message:`Failed to register font from URL
28
+ `+JSON.stringify(e)})}):(canvas_1.GlobalFonts.registerFromPath(e,t),xp_1.xp.registeredFonts.push(t)))}
29
29
  /**
30
30
  * Register Simply-XP Plugins.
31
31
  * @param {Plugin[]} plugins - The plugins to register.
32
32
  * @link `Documentation:` https://simplyxp.js.org/docs/next/Functions/registerPlugins
33
33
  * @returns {void} - Nothing.
34
34
  * @throws {XpFatal} If an invalid plugin is provided.
35
- */function registerPlugins(plugins){if(!Array.isArray(plugins))throw new xplogs_1.XpFatal({function:"registerPlugins()",message:"Plugins must be an array"});plugins.forEach(async plugin=>{let e=!1,t=!0;if(plugin?.initialize&&plugin?.name||(t=!1,xplogs_1.XpLog.warn("registerPlugins()",plugin?.name?plugin.name.toUpperCase()+" PLUGIN NOT INITIALIZED: No initialize function provided.":"INVALID PLUGIN PROVIDED")),Array.isArray(plugin?.requiredVersions)&&!plugin.requiredVersions.includes(xp_1.xp.version)&&(plugin.requiredVersions.forEach(version=>{parseInt(version)?t=!(!parseInt(version)||1!==version.length||xp_1.xp.version.split(".")[0]!==version):version.match(/\d\.\d\.\d/)||t||(e=!0,t=!0)}),e&&xplogs_1.XpLog.warn("registerPlugins()",plugin.name.toUpperCase()+" PLUGIN FAILED VERSION CHECKS, ANYWAYS..."),t||e||xplogs_1.XpLog.warn("registerPlugins()",plugin.name.toUpperCase()+" PLUGIN NOT INITIALIZED: Requires: v"+plugin.requiredVersions.join(", v"))),t)try{await plugin.initialize(xp_1.xp).then(()=>{xplogs_1.XpLog.info("registerPlugins()",plugin.name.toUpperCase()+" PLUGIN INITIALIZED")})}catch(e){throw new xplogs_1.XpFatal({function:"registerPlugins()",message:`Failed to initialize plugin: ${plugin.name}
35
+ */function registerPlugins(e){if(!Array.isArray(e))throw new xplogs_1.XpFatal({function:"registerPlugins()",message:"Plugins must be an array"});e.forEach(async t=>{let a=!1,p=!0;if(t?.initialize&&t?.name||(p=!1,xplogs_1.XpLog.warn("registerPlugins()",t?.name?t.name.toUpperCase()+" PLUGIN NOT INITIALIZED: No initialize function provided.":"INVALID PLUGIN PROVIDED")),Array.isArray(t?.requiredVersions)&&!t.requiredVersions.includes(xp_1.xp.version)&&(t.requiredVersions.forEach(e=>{parseInt(e)?p=!(!parseInt(e)||1!==e.length||xp_1.xp.version.split(".")[0]!==e):e.match(/\d\.\d\.\d/)||p||(a=!0,p=!0)}),a&&xplogs_1.XpLog.warn("registerPlugins()",t.name.toUpperCase()+" PLUGIN FAILED VERSION CHECKS, ANYWAYS..."),p||a||xplogs_1.XpLog.warn("registerPlugins()",t.name.toUpperCase()+" PLUGIN NOT INITIALIZED: Requires: v"+t.requiredVersions.join(", v"))),p)try{await t.initialize(xp_1.xp).then(()=>{xplogs_1.XpLog.info("registerPlugins()",t.name.toUpperCase()+" PLUGIN INITIALIZED")})}catch(e){throw new xplogs_1.XpFatal({function:"registerPlugins()",message:`Failed to initialize plugin: ${t.name}
36
36
  `+e})}})}
37
37
  /**
38
38
  * Updates the options of the XP client.
@@ -40,4 +40,4 @@
40
40
  * @link `Documentation:` https://simplyxp.js.org/docs/next/Functions/updateOptions
41
41
  * @returns {void} - Nothing.
42
42
  * @throws {XpFatal} If an invalid option is provided.
43
- */function updateOptions(clientOptions){if(!clientOptions)throw new xplogs_1.XpFatal({function:"updateOptions()",message:"Options were not provided"});if("object"!=typeof clientOptions)throw new xplogs_1.XpFatal({function:"updateOptions()",message:"Options must be an object"});if(clientOptions?.auto_clean&&(xp_1.xp.auto_clean=!0),clientOptions?.auto_create&&(xp_1.xp.auto_create=!0),clientOptions?.debug&&(xp_1.xp.debug=!0),clientOptions?.notify&&(xp_1.xp.notify=clientOptions.notify),clientOptions?.xp_rate&&("number"==typeof clientOptions.xp_rate||["fast","normal","slow"].includes(clientOptions.xp_rate))&&(xp_1.xp.xp_rate="slow"===clientOptions.xp_rate?.05:"normal"===clientOptions.xp_rate?.1:"fast"===clientOptions.xp_rate?.5:clientOptions.xp_rate),clientOptions.dbOptions&&"object"==typeof clientOptions.dbOptions&&clientOptions.dbOptions.type&&clientOptions.dbOptions.database){var{type:e,database:t}=clientOptions.dbOptions;if(!(e&&"mongodb"===e||"sqlite"===e))throw new xplogs_1.XpFatal({function:"updateOptions()",message:"Invalid database type provided"});if(xp_1.xp.dbType=e,t){xp_1.xp.database=t;const n="mongodb"===xp_1.xp.dbType?{name:"MongoDB",type:"mongodb",min:3,max:6}:{name:"Better-SQLite3",type:"better-sqlite3",min:7,max:9};(0,connect_1.checkPackageVersion)(n.type,n.min,n.max).then(result=>{if(!result)throw new xplogs_1.XpFatal({function:"updateOptions()",message:`${n.name} V${n.min} up to V${n.max} is required.`});switch(xp_1.xp.dbType){case"mongodb":xp_1.xp.database.db().command({ping:1}).catch(()=>{throw xp_1.xp.database=void 0,new xplogs_1.XpFatal({function:"updateOptions()",message:"Invalid MongoDB connection"})});break;case"sqlite":try{xp_1.xp.database.prepare("SELECT 1").get()}catch(e){throw new xplogs_1.XpFatal({function:"updateOptions()",message:"Invalid SQLite connection"})}}})}}clientOptions?.auto_clean&&clean({db:!0}),xp_1.db.findAll("simply-xps").then(users=>{users.filter(user=>user?.xp_rate!==xp_1.xp.xp_rate).map(async user=>{await xp_1.db.updateOne({collection:"simply-xps",data:{user:user.user,guild:user.guild}},{collection:"simply-xps",data:{user:user.user,guild:user.guild,level:convertFrom(user.xp,"xp"),xp:user.xp,xp_rate:xp_1.xp.xp_rate}})}),xplogs_1.XpLog.debug("updateOptions()","UPDATED ALL USERS WITH NEW XP RATE")})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.updateOptions=exports.registerPlugins=exports.registerFont=exports.convertFrom=exports.clean=void 0;const connect_1=require("../connect"),canvas_1=require("@napi-rs/canvas"),xp_1=require("../../xp"),xplogs_1=require("./xplogs");exports.clean=clean,exports.convertFrom=convertFrom,exports.registerFont=registerFont,exports.registerPlugins=registerPlugins,exports.updateOptions=updateOptions;
43
+ */function updateOptions(e){if(!e)throw new xplogs_1.XpFatal({function:"updateOptions()",message:"Options were not provided"});if("object"!=typeof e)throw new xplogs_1.XpFatal({function:"updateOptions()",message:"Options must be an object"});if(e?.auto_clean&&(xp_1.xp.auto_clean=!0),e?.auto_create&&(xp_1.xp.auto_create=!0),e?.debug&&(xp_1.xp.debug=!0),e?.notify&&(xp_1.xp.notify=e.notify),e?.xp_rate&&("number"==typeof e.xp_rate||["fast","normal","slow"].includes(e.xp_rate))&&(xp_1.xp.xp_rate="slow"===e.xp_rate?.05:"normal"===e.xp_rate?.1:"fast"===e.xp_rate?.5:e.xp_rate),e.dbOptions&&"object"==typeof e.dbOptions&&e.dbOptions.type&&e.dbOptions.database){var{type:t,database:a}=e.dbOptions;if(!(t&&"mongodb"===t||"sqlite"===t))throw new xplogs_1.XpFatal({function:"updateOptions()",message:"Invalid database type provided"});if(xp_1.xp.dbType=t,a){xp_1.xp.database=a;const p="mongodb"===xp_1.xp.dbType?{name:"MongoDB",type:"mongodb",min:3,max:6}:{name:"Better-SQLite3",type:"better-sqlite3",min:7,max:9};(0,connect_1.checkPackageVersion)(p.type,p.min,p.max).then(e=>{if(!e)throw new xplogs_1.XpFatal({function:"updateOptions()",message:`${p.name} V${p.min} up to V${p.max} is required.`});switch(xp_1.xp.dbType){case"mongodb":xp_1.xp.database.db().command({ping:1}).catch(()=>{throw xp_1.xp.database=void 0,new xplogs_1.XpFatal({function:"updateOptions()",message:"Invalid MongoDB connection"})});break;case"sqlite":try{xp_1.xp.database.prepare("SELECT 1").get()}catch(e){throw new xplogs_1.XpFatal({function:"updateOptions()",message:"Invalid SQLite connection"})}}})}}e?.auto_clean&&clean({db:!0}),xp_1.db.findAll("simply-xps").then(e=>{e.filter(e=>e?.xp_rate!==xp_1.xp.xp_rate).map(async e=>{await xp_1.db.updateOne({collection:"simply-xps",data:{user:e.user,guild:e.guild}},{collection:"simply-xps",data:{user:e.user,guild:e.guild,level:convertFrom(e.xp,"xp"),xp:e.xp,xp_rate:xp_1.xp.xp_rate}})}),xplogs_1.XpLog.debug("updateOptions()","UPDATED ALL USERS WITH NEW XP RATE")})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.updateOptions=exports.registerPlugins=exports.registerFont=exports.convertFrom=exports.clean=void 0;const connect_1=require("../connect"),canvas_1=require("@napi-rs/canvas"),xp_1=require("../../xp"),xplogs_1=require("./xplogs");exports.clean=clean,exports.convertFrom=convertFrom,exports.registerFont=registerFont,exports.registerPlugins=registerPlugins,exports.updateOptions=updateOptions;
@@ -1,15 +1,15 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.XpEvents=exports.XpLog=exports.XpFatal=void 0;const xp_1=require("../../xp");class XpFatal extends Error{constructor(options){super(options.function+": "+options.message)}}exports.XpFatal=XpFatal,Object.defineProperty(XpFatal.prototype,"name",{value:"SimplyXpFatal"});class XpLog{static log(level,xpFunction,message){var e=XpEvents.eventCallback?.[level],t=level.toUpperCase(),s=xpFunction.toUpperCase();e&&"function"==typeof e?e(xpFunction,message):console.log(`[SIMPLY XP] ${{debug:"",info:"",error:"",warn:""}[level]}(${t}) ${s}: `+message)}static debug(xpFunction,message){xp_1.xp.debug&&XpLog.log("debug",xpFunction,message)}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.XpEvents=exports.XpLog=exports.XpFatal=void 0;const xp_1=require("../../xp");class XpFatal extends Error{constructor(e){super(e.function+": "+e.message)}}exports.XpFatal=XpFatal,Object.defineProperty(XpFatal.prototype,"name",{value:"SimplyXpFatal"});class XpLog{static log(e,t,o){var p=XpEvents.eventCallback?.[e],r=e.toUpperCase(),a=t.toUpperCase();p&&"function"==typeof p?p(t,o):console.log(`[SIMPLY XP] ${{debug:"",info:"",error:"",warn:""}[e]}(${r}) ${a}: `+o)}static debug(e,t){xp_1.xp.debug&&XpLog.log("debug",e,t)}
2
2
  /**
3
3
  * Emits an info log
4
4
  * @param {string} xpFunction - The command or context of the log message
5
5
  * @param {string} message - The log message
6
6
  * @returns {boolean} Returns true
7
7
  * @private
8
- */static info(xpFunction,message){return xp_1.xp.notify&&XpLog.log("info",xpFunction,message),!0}
8
+ */static info(e,t){return xp_1.xp.notify&&XpLog.log("info",e,t),!0}
9
9
  /**
10
10
  * Emits an error log
11
11
  * @param {string} xpFunction - The command or context of the log message
12
12
  * @param {string} message - The log message
13
13
  * @returns {boolean} Returns false
14
14
  * @private
15
- */static err(xpFunction,message){return XpLog.log("error",xpFunction,message),!1}static warn(xpFunction,message){XpLog.log("warn",xpFunction,message)}}exports.XpLog=XpLog;class XpEvents{static eventCallback;static on(callbacks){XpEvents.eventCallback=callbacks}}exports.XpEvents=XpEvents;
15
+ */static err(e,t){return XpLog.log("error",e,t),!1}static warn(e,t){XpLog.log("warn",e,t)}}exports.XpLog=XpLog;class XpEvents{static eventCallback;static on(e){XpEvents.eventCallback=e}}exports.XpEvents=XpEvents;
@@ -7,4 +7,4 @@
7
7
  * @link `Documentation:` https://simplyxp.js.org/docs/next/functions/leaderboard
8
8
  * @returns {Promise<User[]>} Array of all users in the leaderboard
9
9
  * @throws {XpFatal} If guild ID is not provided or limit is less than 1
10
- */async function leaderboard(guildId,limit){if(limit&&!(1<=limit))throw new xplogs_1.XpFatal({function:"leaderboard()",message:"Limit must be a number greater than 0"});const e=new Set;return guildId=guildId?(await xp_1.db.find({collection:"simply-xps",data:{guild:guildId}})).sort((a,b)=>b.xp-a.xp):(await xp_1.db.findAll("simply-xps")).sort((a,b)=>b.xp-a.xp).filter(user=>!e.has(user.user)&&(e.add(user.user),!0)),await Promise.all(guildId.map(async(user,index)=>(user.position=index+1,user))),guildId.slice(0,limit)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.leaderboard=void 0;const xplogs_1=require("./functions/xplogs"),xp_1=require("../xp");exports.leaderboard=leaderboard;
10
+ */async function leaderboard(e,r){if(r&&!(1<=r))throw new xplogs_1.XpFatal({function:"leaderboard()",message:"Limit must be a number greater than 0"});const a=new Set;return e=e?(await xp_1.db.find({collection:"simply-xps",data:{guild:e}})).sort((e,r)=>r.xp-e.xp):(await xp_1.db.findAll("simply-xps")).sort((e,r)=>r.xp-e.xp).filter(e=>!a.has(e.user)&&(a.add(e.user),!0)),await Promise.all(e.map(async(e,r)=>(e.position=r+1,e))),e.slice(0,r)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.leaderboard=void 0;const xplogs_1=require("./functions/xplogs"),xp_1=require("../xp");exports.leaderboard=leaderboard;
@@ -7,7 +7,7 @@
7
7
  * @returns {Promise<boolean>} - Returns true if migration is successful
8
8
  * @throws {XpLog.err} - If migration fails.
9
9
  */
10
- static async discord_xp(deleteOld=!1){var e=await xp_1.db.getCollection("levels").find().toArray();xplogs_1.XpLog.debug("migrate.discord_xp()",`FOUND ${e.length} DOCUMENTS`);try{for(const r of e)await xp_1.db.findOne({collection:"simply-xps",data:{guild:r.guildID,user:r.userID}})||(await xp_1.db.createOne({collection:"simply-xps",data:{guild:r.guildID,user:r.userID,xp:r.xp,level:(0,xp_1.convertFrom)(r.xp,"xp")}}),deleteOld&&await xp_1.db.getCollection("levels").deleteOne({userID:r.userID,guildID:r.guildID}));return!0}catch(e){return xplogs_1.XpLog.err("migrate.discord_xp()",e),!1}}
10
+ static async discord_xp(e=!1){var r=await xp_1.db.getCollection("levels").find().toArray();xplogs_1.XpLog.debug("migrate.discord_xp()",`FOUND ${r.length} DOCUMENTS`);try{for(const t of r)await xp_1.db.findOne({collection:"simply-xps",data:{guild:t.guildID,user:t.userID}})||(await xp_1.db.createOne({collection:"simply-xps",data:{guild:t.guildID,user:t.userID,xp:t.xp,level:(0,xp_1.convertFrom)(t.xp,"xp")}}),e&&await xp_1.db.getCollection("levels").deleteOne({userID:t.userID,guildID:t.guildID}));return!0}catch(e){return xplogs_1.XpLog.err("migrate.discord_xp()",e),!1}}
11
11
  /**
12
12
  * Effortlessly migrate from MongoDB to SQLite. (or vice versa)
13
13
  * @async
@@ -16,4 +16,4 @@ static async discord_xp(deleteOld=!1){var e=await xp_1.db.getCollection("levels"
16
16
  * @link `Documentation:` https://simplyxp.js.org/docs/next/classes/migrate#migratefromdb
17
17
  * @returns {Promise<boolean>} - Returns true if migration is successful
18
18
  * @throws {XpFatal} - If parameters are not provided correctly
19
- */static async fromDB(dbType,connection){if(!dbType)throw new xplogs_1.XpFatal({function:"migrate.database()",message:"No database type provided"});if(!connection)throw new xplogs_1.XpFatal({function:"migrate.database()",message:"No database connection provided"});if(xp_1.xp.dbType===dbType)return xplogs_1.XpLog.info("migrate.fromDB()","Same database received, that was unnecessary!");let e;switch(dbType){case"mongodb":try{if(!await(0,connect_1.checkPackageVersion)("mongodb",4,6))return xplogs_1.XpLog.err("migrate.fromDB()","MongoDB V4 up to V6 is required");e=await connection.db().collection("simply-xps").find().toArray()}catch(e){return xplogs_1.XpLog.err("migrate.fromDB()",e),!1}break;case"sqlite":try{if(!await(0,connect_1.checkPackageVersion)("better-sqlite3",7,8))return xplogs_1.XpLog.err("migrate.fromDB()","better-sqlite3 V7 up to V8 is required");e=connection.prepare("SELECT * FROM `simply-xps`").all()}catch(e){return xplogs_1.XpLog.err("migrate.fromDB()",e),!1}}return xplogs_1.XpLog.debug("migrate.fromDB()",`FOUND ${e.length} RESULTS`),await Promise.all(e.map(async user=>await xp_1.db.findOne({collection:"simply-xps",data:{guild:user.guild,user:user.user}})?xp_1.db.updateOne({collection:"simply-xps",data:{guild:user.guild,user:user.user}},{collection:"simply-xps",data:{guild:user.guild,user:user.user,name:user.name,xp:user.xp,level:user.level}}):xp_1.db.createOne({collection:"simply-xps",data:{guild:user.guild,user:user.user,xp:user.xp,level:user.level}}))),!0}}exports.migrate=migrate;
19
+ */static async fromDB(e,r){if(!e)throw new xplogs_1.XpFatal({function:"migrate.database()",message:"No database type provided"});if(!r)throw new xplogs_1.XpFatal({function:"migrate.database()",message:"No database connection provided"});if(xp_1.xp.dbType===e)return xplogs_1.XpLog.info("migrate.fromDB()","Same database received, that was unnecessary!");let t;switch(e){case"mongodb":try{if(!await(0,connect_1.checkPackageVersion)("mongodb",4,6))return xplogs_1.XpLog.err("migrate.fromDB()","MongoDB V4 up to V6 is required");t=await r.db().collection("simply-xps").find().toArray()}catch(e){return xplogs_1.XpLog.err("migrate.fromDB()",e),!1}break;case"sqlite":try{if(!await(0,connect_1.checkPackageVersion)("better-sqlite3",7,8))return xplogs_1.XpLog.err("migrate.fromDB()","better-sqlite3 V7 up to V8 is required");t=r.prepare("SELECT * FROM `simply-xps`").all()}catch(e){return xplogs_1.XpLog.err("migrate.fromDB()",e),!1}}return xplogs_1.XpLog.debug("migrate.fromDB()",`FOUND ${t.length} RESULTS`),await Promise.all(t.map(async e=>await xp_1.db.findOne({collection:"simply-xps",data:{guild:e.guild,user:e.user}})?xp_1.db.updateOne({collection:"simply-xps",data:{guild:e.guild,user:e.user}},{collection:"simply-xps",data:{guild:e.guild,user:e.user,name:e.name,xp:e.xp,level:e.level}}):xp_1.db.createOne({collection:"simply-xps",data:{guild:e.guild,user:e.user,xp:e.xp,level:e.level}}))),!0}}exports.migrate=migrate;
package/lib/src/remove.js CHANGED
@@ -9,7 +9,7 @@
9
9
  * @link `Documentation:` https://simplyxp.js.org/docs/next/functions/addlevel
10
10
  * @returns {Promise<UserResult>} - Object of user data on success
11
11
  * @throws {XpFatal} - If parameters are not provided correctly
12
- */async function removeLevel(userId,guildId,level,username){if(!userId)throw new xplogs_1.XpFatal({function:"removeLevel()",message:"User ID was not provided"});if(!guildId)throw new xplogs_1.XpFatal({function:"removeLevel()",message:"Guild ID was not provided"});if(isNaN(level))throw new xplogs_1.XpFatal({function:"removeLevel()",message:"Level was not provided"});var e=await xp_1.db.findOne({collection:"simply-xps",data:{user:userId,guild:guildId}});if(e)return xp_1.db.updateOne({collection:"simply-xps",data:{user:userId,guild:guildId}},{collection:"simply-xps",data:{name:username||e?.name||userId,user:userId,guild:guildId,level:e.level-level,xp:(0,xp_1.convertFrom)(e.level-level),xp_rate:xp_1.xp.xp_rate}});if(xp_1.xp.auto_create&&username)return xp_1.db.createOne({collection:"simply-xps",data:{guild:guildId,user:userId,name:username,level:0,xp:0,xp_rate:xp_1.xp.xp_rate}});throw new xplogs_1.XpFatal({function:"removeLevel()",message:"User does not exist"})}
12
+ */async function removeLevel(e,o,t,l){if(!e)throw new xplogs_1.XpFatal({function:"removeLevel()",message:"User ID was not provided"});if(!o)throw new xplogs_1.XpFatal({function:"removeLevel()",message:"Guild ID was not provided"});if(isNaN(t))throw new xplogs_1.XpFatal({function:"removeLevel()",message:"Level was not provided"});var a=await xp_1.db.findOne({collection:"simply-xps",data:{user:e,guild:o}});if(a)return xp_1.db.updateOne({collection:"simply-xps",data:{user:e,guild:o}},{collection:"simply-xps",data:{name:l||a?.name||e,user:e,guild:o,level:a.level-t,xp:(0,xp_1.convertFrom)(a.level-t),xp_rate:xp_1.xp.xp_rate}});if(xp_1.xp.auto_create&&l)return xp_1.db.createOne({collection:"simply-xps",data:{guild:o,user:e,name:l,level:0,xp:0,xp_rate:xp_1.xp.xp_rate}});throw new xplogs_1.XpFatal({function:"removeLevel()",message:"User does not exist"})}
13
13
  /**
14
14
  * Add XP to a user.
15
15
  * @async
@@ -20,4 +20,4 @@
20
20
  * @link `Documentation:` https://simplyxp.js.org/docs/next/functions/addxp
21
21
  * @returns {Promise<XPResult>} - Object of user data on success.
22
22
  * @throws {XpFatal} - If parameters are not provided correctly.
23
- */async function removeXP(userId,guildId,xpData,username){var e;if(!("number"==typeof xpData||"object"==typeof xp_1.xp&&xpData.min&&xpData.max))throw new xplogs_1.XpFatal({function:"addXP()",message:"XP is not a number or object, make sure you are using the correct syntax"});if("object"==typeof xpData&&(xpData=Math.floor(Math.random()*(xpData.max-xpData.min)+xpData.min)),!userId)throw new xplogs_1.XpFatal({function:"removeXP()",message:"User ID was not provided"});if(!guildId)throw new xplogs_1.XpFatal({function:"removeXP()",message:"Guild ID was not provided"});let a;if(e=await xp_1.db.findOne({collection:"simply-xps",data:{user:userId,guild:guildId}}))a=await xp_1.db.updateOne({collection:"simply-xps",data:{user:userId,guild:guildId}},{collection:"simply-xps",data:{user:userId,guild:guildId,name:username||e?.name||userId,level:(0,xp_1.convertFrom)(e.xp-xpData,"xp"),xp:e.xp-xpData,xp_rate:xp_1.xp.xp_rate}}).catch(err=>{throw new xplogs_1.XpFatal({function:"removeXP()",message:err.stack})});else{if(!xp_1.xp.auto_create||!username)throw new xplogs_1.XpFatal({function:"removeXP()",message:"User does not exist"});a=await xp_1.db.createOne({collection:"simply-xps",data:{guild:guildId,user:userId,name:username,level:0,xp:0,xp_rate:xp_1.xp.xp_rate}}).catch(err=>{throw new xplogs_1.XpFatal({function:"removeXP()",message:err.stack})})}return xpData=xplogs_1.XpEvents.eventCallback,(username=e?.level&&a?.level?a.level!==e.level?a.level-e.level:0:0<a?.level?a.level:0)<0&&xpData?.levelDown&&"function"==typeof xpData.levelDown&&xpData.levelDown(a,await xp_1.roleSetup.getRoles(userId,guildId,{includeNextRoles:!0})),0<username&&xpData?.levelUp&&"function"==typeof xpData.levelUp&&xpData.levelUp(a,await xp_1.roleSetup.getRoles(userId,guildId)),{...a,levelDifference:username}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.removeXP=exports.removeLevel=void 0;const xplogs_1=require("./functions/xplogs"),xp_1=require("../xp");exports.removeLevel=removeLevel,exports.removeXP=removeXP;
23
+ */async function removeXP(e,o,t,l){var a;if(!("number"==typeof t||"object"==typeof xp_1.xp&&t.min&&t.max))throw new xplogs_1.XpFatal({function:"addXP()",message:"XP is not a number or object, make sure you are using the correct syntax"});if("object"==typeof t&&(t=Math.floor(Math.random()*(t.max-t.min)+t.min)),!e)throw new xplogs_1.XpFatal({function:"removeXP()",message:"User ID was not provided"});if(!o)throw new xplogs_1.XpFatal({function:"removeXP()",message:"Guild ID was not provided"});let p;if(a=await xp_1.db.findOne({collection:"simply-xps",data:{user:e,guild:o}}))p=await xp_1.db.updateOne({collection:"simply-xps",data:{user:e,guild:o}},{collection:"simply-xps",data:{user:e,guild:o,name:l||a?.name||e,level:(0,xp_1.convertFrom)(a.xp-t,"xp"),xp:a.xp-t,xp_rate:xp_1.xp.xp_rate}}).catch(e=>{throw new xplogs_1.XpFatal({function:"removeXP()",message:e.stack})});else{if(!xp_1.xp.auto_create||!l)throw new xplogs_1.XpFatal({function:"removeXP()",message:"User does not exist"});p=await xp_1.db.createOne({collection:"simply-xps",data:{guild:o,user:e,name:l,level:0,xp:0,xp_rate:xp_1.xp.xp_rate}}).catch(e=>{throw new xplogs_1.XpFatal({function:"removeXP()",message:e.stack})})}return t=xplogs_1.XpEvents.eventCallback,(l=a?.level&&p?.level?p.level!==a.level?p.level-a.level:0:0<p?.level?p.level:0)<0&&t?.levelDown&&"function"==typeof t.levelDown&&t.levelDown(p,await xp_1.roleSetup.getRoles(e,o,{includeNextRoles:!0})),0<l&&t?.levelUp&&"function"==typeof t.levelUp&&t.levelUp(p,await xp_1.roleSetup.getRoles(e,o)),{...p,levelDifference:l}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.removeXP=exports.removeLevel=void 0;const xplogs_1=require("./functions/xplogs"),xp_1=require("../xp");exports.removeLevel=removeLevel,exports.removeXP=removeXP;
package/lib/src/reset.js CHANGED
@@ -9,4 +9,4 @@
9
9
  * @link `Documentation:` https://simplyxp.js.org/docs/next/functions/reset
10
10
  * @returns {Promise<boolean>}
11
11
  * @throws {XpFatal} If an invalid type is provided or if the value is not provided.
12
- */async function reset(userId,guildId,erase=!1,username){var e;if(userId&&guildId)return e={guild:guildId,user:userId,xp_rate:xp_1.xp.xp_rate},await xp_1.db.findOne({collection:"simply-xps",data:e})?(erase?await xp_1.db.deleteOne({collection:"simply-xps",data:e}).catch(error=>{throw new xplogs_1.XpFatal({function:"reset()",message:error})}):await xp_1.db.updateOne({collection:"simply-xps",data:{user:userId,guild:guildId}},{collection:"simply-xps",data:{...e,level:0,xp:0}}).catch(error=>{throw new xplogs_1.XpFatal({function:"reset()",message:error})}),!0):xp_1.xp.auto_create&&!erase&&username?(await xp_1.db.createOne({collection:"simply-xps",data:e}).catch(error=>{throw new xplogs_1.XpFatal({function:"reset()",message:error.stack})}),!0):xplogs_1.XpLog.info("reset()","User was not found, we did not know what to do without a username.");throw new xplogs_1.XpFatal({function:"reset()",message:"Invalid parameters provided"})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.reset=void 0;const xplogs_1=require("./functions/xplogs"),xp_1=require("../xp");exports.reset=reset;
12
+ */async function reset(e,t,a=!1,s){var o;if(e&&t)return o={guild:t,user:e,xp_rate:xp_1.xp.xp_rate},await xp_1.db.findOne({collection:"simply-xps",data:o})?(a?await xp_1.db.deleteOne({collection:"simply-xps",data:o}).catch(e=>{throw new xplogs_1.XpFatal({function:"reset()",message:e})}):await xp_1.db.updateOne({collection:"simply-xps",data:{user:e,guild:t}},{collection:"simply-xps",data:{...o,level:0,xp:0}}).catch(e=>{throw new xplogs_1.XpFatal({function:"reset()",message:e})}),!0):xp_1.xp.auto_create&&!a&&s?(await xp_1.db.createOne({collection:"simply-xps",data:o}).catch(e=>{throw new xplogs_1.XpFatal({function:"reset()",message:e.stack})}),!0):xplogs_1.XpLog.info("reset()","User was not found, we did not know what to do without a username.");throw new xplogs_1.XpFatal({function:"reset()",message:"Invalid parameters provided"})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.reset=void 0;const xplogs_1=require("./functions/xplogs"),xp_1=require("../xp");exports.reset=reset;
@@ -8,7 +8,7 @@
8
8
  * @returns {Promise<boolean>} - True if successful
9
9
  * @throws {XpFatal} If an invalid type is provided or value is not provided.
10
10
  */
11
- static async add(guildId,options){if(!guildId)throw new xplogs_1.XpFatal({function:"roleSetup.add()",message:"Guild ID was not provided"});if(!options)throw new xplogs_1.XpFatal({function:"roleSetup.add()",message:"Options were not provided"});if(isNaN(options?.level))throw new xplogs_1.XpFatal({function:"roleSetup.add()",message:"Level must be a number"});if(options?.role)return"string"==typeof options?.role&&(options.role=[options.role]),xp_1.db.createOne({collection:"simply-xp-levelroles",data:{guild:guildId,lvlrole:{lvl:options.level,role:options.role}}}).then(()=>!0).catch(()=>!1);throw new xplogs_1.XpFatal({function:"roleSetup.add()",message:"Role was not provided"})}
11
+ static async add(e,l){if(!e)throw new xplogs_1.XpFatal({function:"roleSetup.add()",message:"Guild ID was not provided"});if(!l)throw new xplogs_1.XpFatal({function:"roleSetup.add()",message:"Options were not provided"});if(isNaN(l?.level))throw new xplogs_1.XpFatal({function:"roleSetup.add()",message:"Level must be a number"});if(l?.role)return"string"==typeof l?.role&&(l.role=[l.role]),xp_1.db.createOne({collection:"simply-xp-levelroles",data:{guild:e,lvlrole:{lvl:l.level,role:l.role}}}).then(()=>!0).catch(()=>!1);throw new xplogs_1.XpFatal({function:"roleSetup.add()",message:"Role was not provided"})}
12
12
  /**
13
13
  * Get roles for a user's level
14
14
  * @async
@@ -18,7 +18,7 @@ static async add(guildId,options){if(!guildId)throw new xplogs_1.XpFatal({functi
18
18
  * @link `Documentation:` https://simplyxp.js.org/docs/next/classes/roleSetup#roleSetupgetRoles
19
19
  * @returns {Promise<string[]>} - Array of role IDs or empty array if none
20
20
  * @throws {XpFatal} If an invalid type is provided or value is not provided.
21
- */static async getRoles(userId,guildId,options={}){if(!userId)throw new xplogs_1.XpFatal({function:"roleSetup.getRoles()",message:"User ID was not provided"});if(!guildId)throw new xplogs_1.XpFatal({function:"roleSetup.getRoles()",message:"Guild ID was not provided"});const e=await xp_1.db.findOne({collection:"simply-xps",data:{user:userId,guild:guildId}});if(userId=await roleSetup.list(guildId),!e||!e?.level)return[];const l=[];return userId.forEach(({lvlrole:{lvl,role}})=>{role&&(lvl<e.level&&options?.includePreviousRoles||lvl>e.level&&options?.includeNextRoles||lvl===e.level)&&l.push(...Array.isArray(role)?role:[role])}),l}
21
+ */static async getRoles(e,l,o={}){if(!e)throw new xplogs_1.XpFatal({function:"roleSetup.getRoles()",message:"User ID was not provided"});if(!l)throw new xplogs_1.XpFatal({function:"roleSetup.getRoles()",message:"Guild ID was not provided"});const t=await xp_1.db.findOne({collection:"simply-xps",data:{user:e,guild:l}});if(e=await roleSetup.list(l),!t||!t?.level)return[];const s=[];return e.forEach(({lvlrole:{lvl:e,role:l}})=>{l&&(e<t.level&&o?.includePreviousRoles||e>t.level&&o?.includeNextRoles||e===t.level)&&s.push(...Array.isArray(l)?l:[l])}),s}
22
22
  /**
23
23
  * Find a role in roleSetup
24
24
  * @async
@@ -27,7 +27,7 @@ static async add(guildId,options){if(!guildId)throw new xplogs_1.XpFatal({functi
27
27
  * @link `Documentation:` https://simplyxp.js.org/docs/next/classes/roleSetup#roleSetupfind
28
28
  * @returns {Promise<LevelRoleResult>} - The level role object
29
29
  * @throws {XpFatal} If an invalid type is provided or value is not provided.
30
- */static async find(guildId,levelNumber){if(!guildId)throw new xplogs_1.XpFatal({function:"roleSetup.find()",message:"Guild ID was not provided"});if(isNaN(levelNumber))throw new xplogs_1.XpFatal({function:"roleSetup.find()",message:"Level Number was not provided"});return xp_1.db.findOne({collection:"simply-xp-levelroles",data:{guild:guildId,lvlrole:{lvl:levelNumber}}})}
30
+ */static async find(e,l){if(!e)throw new xplogs_1.XpFatal({function:"roleSetup.find()",message:"Guild ID was not provided"});if(isNaN(l))throw new xplogs_1.XpFatal({function:"roleSetup.find()",message:"Level Number was not provided"});return xp_1.db.findOne({collection:"simply-xp-levelroles",data:{guild:e,lvlrole:{lvl:l}}})}
31
31
  /**
32
32
  * List all level roles in a guild
33
33
  * @async
@@ -35,7 +35,7 @@ static async add(guildId,options){if(!guildId)throw new xplogs_1.XpFatal({functi
35
35
  * @link `Documentation:` https://simplyxp.js.org/docs/next/classes/roleSetup#roleSetuplist
36
36
  * @returns {Promise<LevelRoleResult[]>} - The level role object
37
37
  * @throws {XpFatal} If there are no roles in the guild.
38
- */static async list(guildId){if(guildId)return xp_1.db.find({collection:"simply-xp-levelroles",data:{guild:guildId,lvlrole:{lvl:null,role:null}}});throw new xplogs_1.XpFatal({function:"roleSetup.list()",message:"Guild ID was not provided"})}
38
+ */static async list(e){if(e)return xp_1.db.find({collection:"simply-xp-levelroles",data:{guild:e,lvlrole:{lvl:null,role:null}}});throw new xplogs_1.XpFatal({function:"roleSetup.list()",message:"Guild ID was not provided"})}
39
39
  /**
40
40
  * Remove a level from the role setup
41
41
  * @async
@@ -44,4 +44,4 @@ static async add(guildId,options){if(!guildId)throw new xplogs_1.XpFatal({functi
44
44
  * @link `Documentation:` https://simplyxp.js.org/docs/next/classes/roleSetup#roleSetupremove
45
45
  * @returns {Promise<boolean>} - True if successful
46
46
  * @throws {XpFatal} If an invalid type is provided or value is not provided.
47
- */static async remove(guildId,levelNumber){if(!guildId)throw new xplogs_1.XpFatal({function:"roleSetup.remove()",message:"Guild ID was not provided"});if(isNaN(levelNumber))throw new xplogs_1.XpFatal({function:"roleSetup.remove()",message:"Level Number was not provided"});return xp_1.db.deleteOne({collection:"simply-xp-levelroles",data:{guild:guildId,lvlrole:{lvl:levelNumber}}})}}exports.roleSetup=roleSetup;
47
+ */static async remove(e,l){if(!e)throw new xplogs_1.XpFatal({function:"roleSetup.remove()",message:"Guild ID was not provided"});if(isNaN(l))throw new xplogs_1.XpFatal({function:"roleSetup.remove()",message:"Level Number was not provided"});return xp_1.db.deleteOne({collection:"simply-xp-levelroles",data:{guild:e,lvlrole:{lvl:l}}})}}exports.roleSetup=roleSetup;
package/lib/src/set.js CHANGED
@@ -9,7 +9,7 @@
9
9
  * @link `Documentation:` https://simplyxp.js.org/docs/next/functions/setlevel
10
10
  * @returns {Promise<UserResult>} - Object of user data on success
11
11
  * @throws {XpFatal} - If parameters are not provided correctly
12
- */async function setLevel(userId,guildId,level,username){if(!userId)throw new xplogs_1.XpFatal({function:"setLevel()",message:"User ID was not provided"});if(!guildId)throw new xplogs_1.XpFatal({function:"setLevel()",message:"Guild ID was not provided"});if(isNaN(level))throw new xplogs_1.XpFatal({function:"setLevel()",message:"Level was not provided"});if(await xp_1.db.findOne({collection:"simply-xps",data:{user:userId,guild:guildId}}))return xp_1.db.updateOne({collection:"simply-xps",data:{user:userId,guild:guildId}},{collection:"simply-xps",data:{user:userId,guild:guildId,level:level,xp:(0,xp_1.convertFrom)(level),xp_rate:xp_1.xp.xp_rate}});if(xp_1.xp.auto_create&&username)return xp_1.db.createOne({collection:"simply-xps",data:{guild:guildId,user:userId,name:username,level:level,xp:(0,xp_1.convertFrom)(level),xp_rate:xp_1.xp.xp_rate}});throw new xplogs_1.XpFatal({function:"setLevel()",message:"User does not exist"})}
12
+ */async function setLevel(e,t,l,s){if(!e)throw new xplogs_1.XpFatal({function:"setLevel()",message:"User ID was not provided"});if(!t)throw new xplogs_1.XpFatal({function:"setLevel()",message:"Guild ID was not provided"});if(isNaN(l))throw new xplogs_1.XpFatal({function:"setLevel()",message:"Level was not provided"});if(await xp_1.db.findOne({collection:"simply-xps",data:{user:e,guild:t}}))return xp_1.db.updateOne({collection:"simply-xps",data:{user:e,guild:t}},{collection:"simply-xps",data:{user:e,guild:t,level:l,xp:(0,xp_1.convertFrom)(l),xp_rate:xp_1.xp.xp_rate}});if(xp_1.xp.auto_create&&s)return xp_1.db.createOne({collection:"simply-xps",data:{guild:t,user:e,name:s,level:l,xp:(0,xp_1.convertFrom)(l),xp_rate:xp_1.xp.xp_rate}});throw new xplogs_1.XpFatal({function:"setLevel()",message:"User does not exist"})}
13
13
  /**
14
14
  * Set user XP
15
15
  * @async
@@ -20,4 +20,4 @@
20
20
  * @link `Documentation:` https://simplyxp.js.org/docs/next/functions/setxp
21
21
  * @returns {Promise<XPResult>} - Object of user data on success
22
22
  * @throws {XpFatal} - If parameters are not provided correctly
23
- */async function setXP(userId,guildId,xpData,username){var e;if(!userId)throw new xplogs_1.XpFatal({function:"setXP()",message:"User ID was not provided"});if(!guildId)throw new xplogs_1.XpFatal({function:"setXP()",message:"Guild ID was not provided"});if(isNaN(xpData))throw new xplogs_1.XpFatal({function:"setXP()",message:"XP was not provided"});let l;if(e=await xp_1.db.findOne({collection:"simply-xps",data:{user:userId,guild:guildId}}))l=await xp_1.db.updateOne({collection:"simply-xps",data:{user:userId,guild:guildId}},{collection:"simply-xps",data:{name:username||e?.name||userId,user:userId,guild:guildId,level:(0,xp_1.convertFrom)(xpData),xp:xpData,xp_rate:xp_1.xp.xp_rate}});else{if(!xp_1.xp.auto_create||!username)throw new xplogs_1.XpFatal({function:"setXP()",message:"User does not exist"});l=await xp_1.db.createOne({collection:"simply-xps",data:{guild:guildId,user:userId,name:username,level:(0,xp_1.convertFrom)(xpData),xp:xpData,xp_rate:xp_1.xp.xp_rate}})}return username=xplogs_1.XpEvents.eventCallback,(xpData=e?.level&&l?.level?l.level!==e.level?l.level-e.level:0:0<l?.level?l.level:0)<0&&username?.levelDown&&"function"==typeof username.levelDown&&username.levelDown(l,await xp_1.roleSetup.getRoles(userId,guildId,{includeNextRoles:!0})),0<xpData&&username?.levelUp&&"function"==typeof username.levelUp&&username.levelUp(l,await xp_1.roleSetup.getRoles(userId,guildId)),{...l,levelDifference:xpData}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.setXP=exports.setLevel=void 0;const xplogs_1=require("./functions/xplogs"),xp_1=require("../xp");exports.setLevel=setLevel,exports.setXP=setXP;
23
+ */async function setXP(e,t,l,s){var p;if(!e)throw new xplogs_1.XpFatal({function:"setXP()",message:"User ID was not provided"});if(!t)throw new xplogs_1.XpFatal({function:"setXP()",message:"Guild ID was not provided"});if(isNaN(l))throw new xplogs_1.XpFatal({function:"setXP()",message:"XP was not provided"});let o;if(p=await xp_1.db.findOne({collection:"simply-xps",data:{user:e,guild:t}}))o=await xp_1.db.updateOne({collection:"simply-xps",data:{user:e,guild:t}},{collection:"simply-xps",data:{name:s||p?.name||e,user:e,guild:t,level:(0,xp_1.convertFrom)(l),xp:l,xp_rate:xp_1.xp.xp_rate}});else{if(!xp_1.xp.auto_create||!s)throw new xplogs_1.XpFatal({function:"setXP()",message:"User does not exist"});o=await xp_1.db.createOne({collection:"simply-xps",data:{guild:t,user:e,name:s,level:(0,xp_1.convertFrom)(l),xp:l,xp_rate:xp_1.xp.xp_rate}})}return s=xplogs_1.XpEvents.eventCallback,(l=p?.level&&o?.level?o.level!==p.level?o.level-p.level:0:0<o?.level?o.level:0)<0&&s?.levelDown&&"function"==typeof s.levelDown&&s.levelDown(o,await xp_1.roleSetup.getRoles(e,t,{includeNextRoles:!0})),0<l&&s?.levelUp&&"function"==typeof s.levelUp&&s.levelUp(o,await xp_1.roleSetup.getRoles(e,t)),{...o,levelDifference:l}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.setXP=exports.setLevel=void 0;const xplogs_1=require("./functions/xplogs"),xp_1=require("../xp");exports.setLevel=setLevel,exports.setXP=setXP;
package/lib/xp.js CHANGED
@@ -51,6 +51,6 @@ exports.xp = {
51
51
  debug: false,
52
52
  notify: true,
53
53
  registeredFonts: [],
54
- version: "2.0.0-beta.0",
54
+ version: "2.0.0-beta.0-fix.0",
55
55
  xp_rate: 0.1
56
56
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "simply-xp",
3
- "version": "2.0.0-beta.0",
3
+ "version": "2.0.0-beta.0-fix.0",
4
4
  "description": "The easiest way to implement xp system",
5
5
  "main": "lib/xp.js",
6
6
  "scripts": {
@@ -45,12 +45,12 @@
45
45
  "@napi-rs/canvas": "0.1.41"
46
46
  },
47
47
  "devDependencies": {
48
- "@eslint/eslintrc": "^2.1.4",
48
+ "@eslint/eslintrc": "^3.0.0",
49
49
  "@types/better-sqlite3": "^7.6.8",
50
- "@types/node": "^20.10.5",
51
- "@typescript-eslint/eslint-plugin": "^6.16.0",
52
- "@typescript-eslint/parser": "^6.16.0",
53
- "better-sqlite3": "^9.2.2",
50
+ "@types/node": "^20.11.5",
51
+ "@typescript-eslint/eslint-plugin": "^6.19.0",
52
+ "@typescript-eslint/parser": "^6.19.0",
53
+ "better-sqlite3": "^9.3.0",
54
54
  "eslint": "^8.56.0",
55
55
  "mongodb": "^6.3.0",
56
56
  "typescript": "^5.3.3",