mowojang 0.6.1 → 0.7.1

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.
Files changed (3) hide show
  1. package/dist/index.d.ts +51 -14
  2. package/dist/index.js +108 -19
  3. package/package.json +14 -6
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { CacheOptions, CacheRequestConfig, buildStorage, buildMemoryStorage } from 'axios-cache-interceptor';
1
+ import { CacheOptions, NotEmptyStorageValue, StorageValue, AxiosStorage, CacheRequestConfig, buildStorage, buildMemoryStorage } from 'axios-cache-interceptor';
2
2
  import { LoggerConfig } from '@pixelic/logger';
3
3
 
4
4
  /**
@@ -35,30 +35,59 @@ type UUID = string;
35
35
  * };
36
36
  * ```
37
37
  */
38
- type ClientOptions = {
38
+ interface ClientOptions {
39
39
  logger?: LoggerConfig;
40
40
  validation?: ValidationOptions;
41
41
  timeout?: number;
42
42
  cache?: CacheOptions;
43
43
  baseURL?: string;
44
44
  fallback?: boolean;
45
- };
45
+ }
46
46
 
47
- type AxiosOptions = {
47
+ interface AxiosOptions {
48
48
  timeout?: number;
49
49
  cache?: CacheOptions;
50
50
  fallback: boolean;
51
- };
51
+ }
52
52
 
53
- type ValidationOptions = {
53
+ interface ValidationOptions {
54
54
  enabled?: boolean;
55
55
  minimumUsernameLength?: 1 | 2;
56
+ }
57
+
58
+ /**
59
+ * Cache helpers that proxy the internal storage from `axios-cache-interceptor`.
60
+ *
61
+ * WARNING: This is an API intended for very specific usecases.
62
+ * Incorrect writes/deletes or clearing storage at the wrong time can break cache behavior or cause unexpected errors.
63
+ *
64
+ * @link https://github.com/Pixelicc/mowojang/blob/main/docs/custom-caching.md#internal-cache-access
65
+ */
66
+ type MowojangCache = readonly {
67
+ /** Clears the entire internal cache storage. */
68
+ readonly clear: () => Promise<void>;
69
+ /** Sets a raw internal cache entry for a cache key. */
70
+ readonly set: (key: string, value: NotEmptyStorageValue) => Promise<void>;
71
+ /** Returns the raw internal cache entry for a cache key. */
72
+ readonly get: (key: string) => Promise<StorageValue>;
73
+ /** Deletes a raw internal cache entry by cache key. */
74
+ readonly del: (key: string) => Promise<void>;
75
+ /** Checks whether a cached value exists for a cache key. */
76
+ readonly has: (key: string) => Promise<boolean>;
77
+ /**
78
+ * Direct reference to the internal axios-cache-interceptor storage instance.
79
+ *
80
+ * **DO NOT USE THIS IF YOU ARE NOT 100% SURE WHAT YOU ARE DOING.**
81
+ *
82
+ * @link https://axios-cache-interceptor.js.org/guide/storages
83
+ */
84
+ readonly _storage: AxiosStorage;
56
85
  };
57
86
 
58
- type MowojangRequestConfig = {
87
+ interface MowojangRequestConfig {
59
88
  validation?: ValidationOptions;
60
89
  cache?: CacheRequestConfig<any, any>["cache"];
61
- };
90
+ }
62
91
 
63
92
  type MowojangError = "INVALID_PLAYER";
64
93
 
@@ -73,18 +102,18 @@ type MowojangResponse<D, E extends MowojangError | undefined> = Promise<
73
102
  }
74
103
  >;
75
104
 
76
- type MowojangProfile = {
105
+ interface MowojangProfile {
77
106
  UUID: UUID;
78
107
  username: Username;
79
- };
108
+ }
80
109
 
81
- type MowojangSession = {
110
+ interface MowojangSession {
82
111
  UUID: UUID;
83
112
  username: Username;
84
113
  skin: MowojangSkin;
85
114
  cape: MowojangCape;
86
115
  actions: ("FORCED_NAME_CHANGE" | "USING_BANNED_SKIN")[];
87
- };
116
+ }
88
117
 
89
118
  type MowojangSkin = null | {
90
119
  url: string;
@@ -104,6 +133,9 @@ declare class Client {
104
133
  private axios;
105
134
  private validation;
106
135
  private baseURL;
136
+ readonly cache: MowojangCache;
137
+ readonly version: string;
138
+ static readonly version: string;
107
139
  /**
108
140
  * Creates a new Mowojang Client Instance
109
141
  *
@@ -125,8 +157,13 @@ declare class Client {
125
157
  constructor(clientOptions?: ClientOptions);
126
158
  private shouldValidate;
127
159
  private getValidationMinLength;
128
- private getProfileCacheID;
160
+ private getCacheKey;
129
161
  private mirrorProfileCacheEntries;
162
+ private _clearCache;
163
+ private _setCacheKey;
164
+ private _getCacheKey;
165
+ private _delCacheKey;
166
+ private _hasCacheKey;
130
167
  /**
131
168
  * Returns an Array of Player Profiles consisting of their Usernames and UUIDs
132
169
  *
@@ -259,4 +296,4 @@ declare const cache: {
259
296
  buildMemoryStorage: typeof buildMemoryStorage;
260
297
  };
261
298
 
262
- export { type AxiosOptions, Client, type ClientOptions, type MowojangCape, type MowojangError, type MowojangProfile, type MowojangRequestConfig, type MowojangResponse, type MowojangSession, type MowojangSkin, type Player, type UUID, type Username, type ValidationOptions, cache, utils, validate };
299
+ export { type AxiosOptions, Client, type ClientOptions, type MowojangCache, type MowojangCape, type MowojangError, type MowojangProfile, type MowojangRequestConfig, type MowojangResponse, type MowojangSession, type MowojangSkin, type Player, type UUID, type Username, type ValidationOptions, cache, utils, validate };
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ var __defProp = Object.defineProperty;
2
2
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
3
 
4
4
  // <define:VERSION>
5
- var define_VERSION_default = ["0.6.1"];
5
+ var define_VERSION_default = ["0.7.1"];
6
6
 
7
7
  // src/utils.ts
8
8
  var undashUUID = /* @__PURE__ */ __name((UUID) => UUID.replace(/-/g, "").toLowerCase(), "undashUUID");
@@ -97,7 +97,7 @@ var axiosInstance_default = /* @__PURE__ */ __name((options, logger) => {
97
97
  return instance;
98
98
  }, "default");
99
99
 
100
- // node_modules/.pnpm/@jsr+pixelic__logger@0.2.0/node_modules/@jsr/pixelic__logger/src/index.js
100
+ // node_modules/.pnpm/@jsr+pixelic__logger@0.3.0/node_modules/@jsr/pixelic__logger/src/index.js
101
101
  var ANSI = {
102
102
  reset: "\x1B[0m",
103
103
  gray: "\x1B[90m",
@@ -123,11 +123,13 @@ var Logger = class {
123
123
  __name(this, "Logger");
124
124
  }
125
125
  minLevel = "INFO";
126
+ services;
126
127
  /**
127
128
  * @constructor Creates a Logger Instance
128
129
  */
129
130
  constructor(config) {
130
131
  if (config?.minLevel) this.minLevel = config.minLevel;
132
+ this.services = config?.services ?? [];
131
133
  }
132
134
  /**
133
135
  * @private Checks whether the given Log Level satisfies the set `minLevel` of the constructor
@@ -235,6 +237,9 @@ var Client = class {
235
237
  axios;
236
238
  validation;
237
239
  baseURL;
240
+ cache;
241
+ version = define_VERSION_default[0];
242
+ static version = define_VERSION_default[0];
238
243
  /**
239
244
  * Creates a new Mowojang Client Instance
240
245
  *
@@ -258,16 +263,25 @@ var Client = class {
258
263
  this.validation = clientOptions?.validation ?? {};
259
264
  this.baseURL = (clientOptions?.baseURL ?? "https://mowojang.matdoes.dev").toLowerCase();
260
265
  this.axios = axiosInstance_default({ fallback: true, ...clientOptions }, this.logger);
266
+ this.cache = {
267
+ clear: /* @__PURE__ */ __name(async () => await this._clearCache(), "clear"),
268
+ set: /* @__PURE__ */ __name(async (key, value) => await this._setCacheKey(key, value), "set"),
269
+ get: /* @__PURE__ */ __name(async (key) => await this._getCacheKey(key), "get"),
270
+ del: /* @__PURE__ */ __name(async (key) => await this._delCacheKey(key), "del"),
271
+ has: /* @__PURE__ */ __name(async (key) => await this._hasCacheKey(key), "has"),
272
+ _storage: this.axios.storage
273
+ };
261
274
  }
262
275
  shouldValidate(config) {
263
- return Boolean(this.validation?.enabled || config?.validation?.enabled);
276
+ return Boolean(this.validation?.enabled ?? config?.validation?.enabled);
264
277
  }
265
278
  getValidationMinLength(config) {
266
279
  return this.validation?.minimumUsernameLength ?? config?.validation?.minimumUsernameLength;
267
280
  }
268
- getProfileCacheID(player) {
269
- const normalizedPlayer = validateUUID(player) ? `uuid:${undashUUID(player).toLowerCase()}` : `username:${player.toLowerCase()}`;
270
- return `profile:${normalizedPlayer}`;
281
+ getCacheKey(prefix, value, hash = false) {
282
+ if (hash) return `${prefix}:${value}`;
283
+ const normalized = validateUUID(value) ? `uuid:${undashUUID(value).toLowerCase()}` : `username:${value.toLowerCase()}`;
284
+ return `${prefix}:${normalized}`;
271
285
  }
272
286
  async mirrorProfileCacheEntries(ID, username, UUID, internalId) {
273
287
  try {
@@ -282,8 +296,8 @@ var Client = class {
282
296
  }
283
297
  const value = await storage.get(ID);
284
298
  if (!value) return;
285
- const usernameID = this.getProfileCacheID(username);
286
- const uuidID = this.getProfileCacheID(UUID);
299
+ const usernameID = this.getCacheKey("profile", username);
300
+ const uuidID = this.getCacheKey("profile", UUID);
287
301
  if (ID !== usernameID) {
288
302
  await storage.set(usernameID, value);
289
303
  this.logger.debug("Mowojang", `PROFILE-CACHE-MIRROR-SET ${ID} -> ${usernameID}`, internalId);
@@ -296,6 +310,54 @@ var Client = class {
296
310
  this.logger.error("Mowojang", error instanceof Error ? error.message : "Unknown Error", internalId);
297
311
  }
298
312
  }
313
+ async _clearCache() {
314
+ try {
315
+ if (this.axios.storage.clear) {
316
+ return await this.axios.storage.clear();
317
+ }
318
+ } catch (error) {
319
+ this.logger.error("Mowojang", error instanceof Error ? error.message : "Unknown Error");
320
+ }
321
+ }
322
+ async _setCacheKey(key, value) {
323
+ try {
324
+ if (this.axios.storage.set) {
325
+ return await this.axios.storage.set(key, value);
326
+ }
327
+ } catch (error) {
328
+ this.logger.error("Mowojang", error instanceof Error ? error.message : "Unknown Error");
329
+ }
330
+ }
331
+ async _getCacheKey(key) {
332
+ try {
333
+ if (this.axios.storage.get) {
334
+ return await this.axios.storage.get(key);
335
+ }
336
+ } catch (error) {
337
+ this.logger.error("Mowojang", error instanceof Error ? error.message : "Unknown Error");
338
+ }
339
+ return { state: "empty" };
340
+ }
341
+ async _delCacheKey(key) {
342
+ try {
343
+ if (this.axios.storage.remove) {
344
+ return await this.axios.storage.remove(key);
345
+ }
346
+ } catch (error) {
347
+ this.logger.error("Mowojang", error instanceof Error ? error.message : "Unknown Error");
348
+ }
349
+ }
350
+ async _hasCacheKey(key) {
351
+ try {
352
+ if (this.axios.storage.get) {
353
+ const value = await this.axios.storage.get(key);
354
+ return value.state === "cached" && "data" in value;
355
+ }
356
+ } catch (error) {
357
+ this.logger.error("Mowojang", error instanceof Error ? error.message : "Unknown Error");
358
+ }
359
+ return false;
360
+ }
299
361
  /**
300
362
  * Returns an Array of Player Profiles consisting of their Usernames and UUIDs
301
363
  *
@@ -357,7 +419,7 @@ var Client = class {
357
419
  if (this.shouldValidate(config) && !validatePlayer(player, this.getValidationMinLength(config)))
358
420
  return { data: null, error: "INVALID_INPUT" };
359
421
  const fetchResponse = await this.axios.get(`${this.baseURL}/${player}`, {
360
- id: this.getProfileCacheID(player),
422
+ id: this.getCacheKey("profile", player),
361
423
  cache: config?.cache ?? { ttl: 60 * 60 * 1e3 }
362
424
  });
363
425
  if (config?.cache !== false && (typeof config?.cache !== "object" || config.cache.enabled !== false)) {
@@ -456,6 +518,7 @@ var Client = class {
456
518
  const UUID = validateUUID(player) ? undashUUID(player) : await this.getUUID(player);
457
519
  if (!UUID) return { data: null, error: "INVALID_PLAYER" };
458
520
  return await this.axios.get(`${this.baseURL}/session/minecraft/profile/${UUID}`, {
521
+ id: this.getCacheKey("session", player),
459
522
  cache: config?.cache ?? { ttl: 15 * 60 * 1e3 }
460
523
  }).then((fetchResponse) => {
461
524
  let textures = fetchResponse.data.properties.find((property) => property.name === "textures").value;
@@ -524,11 +587,24 @@ var Client = class {
524
587
  async getSkinBuffer(player, config) {
525
588
  const session = await this.getSession(player, config);
526
589
  if (session.error || !session.data.skin) return null;
527
- const fetchResponse = await this.axios.get(session.data.skin.url, {
528
- responseType: "arraybuffer",
529
- cache: config?.cache ?? { ttl: 24 * 60 * 60 * 1e3 }
530
- });
531
- return Buffer.from(fetchResponse.data);
590
+ try {
591
+ const fetchResponse = await this.axios.get(session.data.skin.url, {
592
+ id: this.getCacheKey("skin", player),
593
+ responseType: "arraybuffer",
594
+ cache: config?.cache ?? { ttl: 24 * 60 * 60 * 1e3 }
595
+ });
596
+ return Buffer.from(fetchResponse.data);
597
+ } catch (err) {
598
+ if (isAxiosError(err)) {
599
+ this.logger.error(
600
+ "Mowojang",
601
+ `An Error occured whilst trying to fetch Skin Texture for ${player}`,
602
+ err.request.internalId
603
+ );
604
+ this.logger.info("Mowojang", `Check Status of Mojang Textures API on: https://mowojang-status.pixelic.dev`);
605
+ }
606
+ return null;
607
+ }
532
608
  }
533
609
  /**
534
610
  * A simple Wrapper to retrieve only the Cape Data from a Player's Session
@@ -558,11 +634,24 @@ var Client = class {
558
634
  async getCapeBuffer(player, config) {
559
635
  const session = await this.getSession(player, config);
560
636
  if (session.error || !session.data.cape) return null;
561
- const fetchResponse = await this.axios.get(session.data.cape.url, {
562
- responseType: "arraybuffer",
563
- cache: config?.cache ?? { ttl: 30 * 24 * 60 * 60 * 1e3 }
564
- });
565
- return Buffer.from(fetchResponse.data);
637
+ try {
638
+ const fetchResponse = await this.axios.get(session.data.cape.url, {
639
+ id: this.getCacheKey("cape", session.data.cape.hash, true),
640
+ responseType: "arraybuffer",
641
+ cache: config?.cache ?? { ttl: 30 * 24 * 60 * 60 * 1e3 }
642
+ });
643
+ return Buffer.from(fetchResponse.data);
644
+ } catch (err) {
645
+ if (isAxiosError(err)) {
646
+ this.logger.error(
647
+ "Mowojang",
648
+ `An Error occured whilst trying to fetch Cape Texture for ${player}`,
649
+ err.request.internalId
650
+ );
651
+ this.logger.info("Mowojang", `Check Status of Mojang Textures API on: https://mowojang-status.pixelic.dev`);
652
+ }
653
+ return null;
654
+ }
566
655
  }
567
656
  };
568
657
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mowojang",
3
- "version": "0.6.1",
3
+ "version": "0.7.1",
4
4
  "description": "A simple TypeScript compatible wrapper for the Mowojang-API.",
5
5
  "exports": {
6
6
  ".": {
@@ -32,15 +32,23 @@
32
32
  "axios-cache-interceptor": "^1.12.0"
33
33
  },
34
34
  "devDependencies": {
35
- "@pixelic/logger": "npm:@jsr/pixelic__logger@~0.2.0",
35
+ "@eslint/js": "^10.0.1",
36
+ "@pixelic/logger": "npm:@jsr/pixelic__logger@^0.3.0",
36
37
  "@types/node": "^26.1.2",
38
+ "@typescript-eslint/eslint-plugin": "^8.66.0",
39
+ "@typescript-eslint/parser": "^8.66.0",
40
+ "eslint": "^10.8.0",
41
+ "eslint-config-prettier": "^10.1.8",
42
+ "eslint-plugin-prettier": "^5.5.6",
43
+ "prettier": "^3.9.6",
37
44
  "tsup": "^8.5.1",
38
- "typescript": "^6.0.3"
45
+ "typescript": "^6.0.3",
46
+ "typescript-eslint": "^8.66.0"
39
47
  },
40
48
  "scripts": {
41
- "build": "tsup",
49
+ "build": "pnpm tsup",
42
50
  "test": "node test test/index.js",
43
- "prettier:check": "pnpm dlx prettier . --check",
44
- "prettier:write": "pnpm dlx prettier . --write"
51
+ "lint:check": "pnpm eslint .",
52
+ "lint:fix": "pnpm eslint . --fix"
45
53
  }
46
54
  }