mowojang 0.8.3 → 0.9.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
@@ -24,7 +24,7 @@ The `Client` constructor accepts an **optional** configuration object.
24
24
  ```TS
25
25
  const Mowojang = new MowojangClient({
26
26
  baseURL: "https://mowojang.matdoes.dev", // The base URL for the Mowojang API
27
- fallback: true, // Whether to fallback to mowojang.seraph.si if the default baseURL is down
27
+ fallback: true, // Whether to fallback to playerdb.co if the default baseURL is down
28
28
  timeout: 10000, // Request timeout in milliseconds
29
29
  validation: {
30
30
  enabled: true, // Enable automatic validation for inputs (UUIDs and Usernames)
@@ -33,6 +33,10 @@ const Mowojang = new MowojangClient({
33
33
  })
34
34
  ```
35
35
 
36
+ > [!NOTE]
37
+ > Other Mojang APIs work too. Just point `baseURL` at the path and the username/UUID is appended:
38
+ > `https://playerdb.co/api/player/minecraft` → `.../minecraft/Pixelic`
39
+
36
40
  > [!TIP]
37
41
  > If you plan on using this in a long-running process with heavy usage check out this guide on how to setup custom caching to prevent memory leaks.
38
42
  > Guide: [Custom-Caching](docs/custom-caching.md)
package/dist/index.d.ts CHANGED
@@ -155,6 +155,9 @@ declare class Client {
155
155
  * ```
156
156
  */
157
157
  constructor(clientOptions?: ClientOptions);
158
+ private isPathBasedURL;
159
+ private getProfileURL;
160
+ private getSessionURL;
158
161
  private shouldValidate;
159
162
  private getValidationMinLength;
160
163
  private getCacheKey;
@@ -296,4 +299,5 @@ declare const cache: {
296
299
  buildMemoryStorage: typeof buildMemoryStorage;
297
300
  };
298
301
 
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 };
302
+ export { Client, cache, utils, validate };
303
+ export type { AxiosOptions, ClientOptions, MowojangCache, MowojangCape, MowojangError, MowojangProfile, MowojangRequestConfig, MowojangResponse, MowojangSession, MowojangSkin, Player, UUID, Username, ValidationOptions };
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ var __defProp = Object.defineProperty;
5
5
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
6
 
7
7
  // <define:VERSION>
8
- var define_VERSION_default = ["0.8.3"];
8
+ var define_VERSION_default = ["0.9.0"];
9
9
 
10
10
  // src/utils.ts
11
11
  var undashUUID = /* @__PURE__ */ __name((UUID) => UUID.replaceAll("-", "").toLowerCase(), "undashUUID");
@@ -33,12 +33,44 @@ var validateArray = /* @__PURE__ */ __name((array, validatorFunction, ...params)
33
33
  if (!Array.isArray(array)) return false;
34
34
  return array.every((item) => validatorFunction(item, ...params));
35
35
  }, "validateArray");
36
+ var PRIMARY_HOST = "mowojang.matdoes.dev";
37
+ var FALLBACK_HOST = "playerdb.co";
38
+ var PLAYERDB_LOOKUP = "https://playerdb.co/api/player/minecraft";
39
+ var rewriteToPlayerDB = /* @__PURE__ */ __name((fullURL, method) => {
40
+ if ((method ?? "get").toLowerCase() !== "get") return null;
41
+ const url = new URL(fullURL);
42
+ if (url.host !== PRIMARY_HOST) return null;
43
+ const path = url.pathname.replace(/\/+$/, "") || "/";
44
+ if (path.startsWith("/session/minecraft/profile/")) {
45
+ const id = path.slice("/session/minecraft/profile/".length);
46
+ if (!id || id.includes("/")) return null;
47
+ return `${PLAYERDB_LOOKUP}/${id}`;
48
+ }
49
+ if (path.startsWith("/users/profiles/minecraft/")) {
50
+ const id = path.slice("/users/profiles/minecraft/".length);
51
+ if (!id || id.includes("/")) return null;
52
+ return `${PLAYERDB_LOOKUP}/${id}`;
53
+ }
54
+ if (path === "/" || path.includes("/")) return null;
55
+ return `${PLAYERDB_LOOKUP}/${path.slice(1)}`;
56
+ }, "rewriteToPlayerDB");
57
+ var isPlayerDBBody = /* @__PURE__ */ __name((data) => data != null && typeof data === "object" && typeof data.success === "boolean", "isPlayerDBBody");
58
+ var toMowojangShape = /* @__PURE__ */ __name((body) => {
59
+ const player = body.data?.player;
60
+ if (!body.success || !player) return null;
61
+ return {
62
+ id: player.raw_id ?? undashUUID(String(player.id ?? "")),
63
+ name: player.username,
64
+ properties: player.properties ?? [],
65
+ profileActions: []
66
+ };
67
+ }, "toMowojangShape");
36
68
  var axiosInstance_default = /* @__PURE__ */ __name((options, logger) => {
37
69
  const instance = setupCache(
38
70
  axios.create({
39
71
  timeout: options?.timeout ?? 1e4,
40
72
  maxRedirects: 0,
41
- validateStatus: /* @__PURE__ */ __name((status) => status === 200 || status === 404, "validateStatus"),
73
+ validateStatus: /* @__PURE__ */ __name((status) => status === 200 || status === 404 || status === 400, "validateStatus"),
42
74
  headers: {
43
75
  "User-Agent": `axios/${axios.VERSION} mowojang/${define_VERSION_default[0]} (https://www.npmjs.com/package/mowojang)`,
44
76
  Accept: "application/json"
@@ -60,6 +92,16 @@ var axiosInstance_default = /* @__PURE__ */ __name((options, logger) => {
60
92
  });
61
93
  instance.interceptors.response.use(
62
94
  (res) => {
95
+ if (isPlayerDBBody(res.data)) {
96
+ const shaped = toMowojangShape(res.data);
97
+ if (!shaped) {
98
+ res.status = 404;
99
+ res.data = "";
100
+ } else {
101
+ res.status = 200;
102
+ res.data = shaped;
103
+ }
104
+ }
63
105
  if (res.cached) {
64
106
  logger.debug(
65
107
  "Mowojang",
@@ -72,26 +114,30 @@ var axiosInstance_default = /* @__PURE__ */ __name((options, logger) => {
72
114
  },
73
115
  (err) => {
74
116
  const isConnectionError = ["ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN"].includes(err.code) || (err?.response?.status ?? 0) >= 500;
75
- if (isConnectionError) {
76
- const fullURL = axios.getUri(err.config);
77
- const host = new URL(fullURL).host;
78
- if (host === "mowojang.matdoes.dev" && !err.config._retry) {
79
- err.config._retry = true;
80
- err.config.url = fullURL.replace("mowojang.matdoes.dev", "mowojang.seraph.si");
81
- if (err.config.baseURL) delete err.config.baseURL;
82
- logger.critical("Mowojang", `Failed to establish connection to mowojang.matdoes.dev`, err.config.internalId);
83
- if (options.fallback) {
84
- logger.info("Mowojang", `Retrying request with fallback of mowojang.seraph.si`, err.config.internalId);
85
- }
86
- logger.info("Mowojang", `Check Status of Mowojang on: https://mowojang-status.pixelic.dev`);
87
- if (options.fallback) return instance(err.config);
88
- } else if (host === "mowojang.seraph.si") {
89
- logger.critical("Mowojang", `Failed to establish connection to mowojang.seraph.si`, err.config.internalId);
90
- logger.info("Mowojang", `Check Status of Seraph on: https://mowojang-status.pixelic.dev`);
91
- } else {
92
- logger.critical("Mowojang", `Failed to establish connection to ${host}`, err.config.internalId);
93
- }
117
+ if (!isConnectionError) return Promise.reject(err);
118
+ const fullURL = axios.getUri(err.config);
119
+ const host = new URL(fullURL).host;
120
+ const isPrimaryHost = host === PRIMARY_HOST;
121
+ const isFallbackHost = host === FALLBACK_HOST;
122
+ const playerDBURL = rewriteToPlayerDB(fullURL, err.config.method);
123
+ const shouldRetryWithFallback = isPrimaryHost && !err.config._retry && playerDBURL !== null;
124
+ if (shouldRetryWithFallback) {
125
+ err.config._retry = true;
126
+ err.config.url = playerDBURL;
127
+ if (err.config.baseURL) delete err.config.baseURL;
128
+ }
129
+ logger.critical("Mowojang", `Failed to establish connection to ${host}`, err.config.internalId);
130
+ const shouldFallback = shouldRetryWithFallback && options.fallback;
131
+ if (shouldFallback) {
132
+ logger.info("Mowojang", `Retrying request with fallback of playerdb.co`, err.config.internalId);
94
133
  }
134
+ if (isPrimaryHost) {
135
+ logger.info("Mowojang", `Check Status of Mowojang on: https://mowojang-status.pixelic.dev`);
136
+ }
137
+ if (isFallbackHost) {
138
+ logger.info("Mowojang", `Check Status of PlayerDB on: https://playerdb.co`);
139
+ }
140
+ if (shouldFallback) return instance(err.config);
95
141
  return Promise.reject(err);
96
142
  }
97
143
  );
@@ -262,7 +308,7 @@ var Client = class {
262
308
  constructor(clientOptions) {
263
309
  this.logger = new Logger(clientOptions?.logger);
264
310
  this.validation = clientOptions?.validation ?? {};
265
- this.baseURL = (clientOptions?.baseURL ?? "https://mowojang.matdoes.dev").toLowerCase();
311
+ this.baseURL = (clientOptions?.baseURL ?? "https://mowojang.matdoes.dev").toLowerCase().replace(/\/+$/, "");
266
312
  this.axios = axiosInstance_default({ fallback: true, ...clientOptions }, this.logger);
267
313
  this.cache = {
268
314
  clear: /* @__PURE__ */ __name(async () => await this._clearCache(), "clear"),
@@ -273,6 +319,21 @@ var Client = class {
273
319
  _storage: this.axios.storage
274
320
  };
275
321
  }
322
+ isPathBasedURL() {
323
+ try {
324
+ const path = new URL(this.baseURL).pathname.replace(/\/+$/, "");
325
+ return path.length > 0;
326
+ } catch {
327
+ return false;
328
+ }
329
+ }
330
+ getProfileURL(player) {
331
+ return `${this.baseURL}/${player}`;
332
+ }
333
+ getSessionURL(UUID) {
334
+ if (this.isPathBasedURL()) return this.getProfileURL(UUID);
335
+ return `${this.baseURL}/session/minecraft/profile/${UUID}`;
336
+ }
276
337
  shouldValidate(config) {
277
338
  return Boolean(this.validation?.enabled ?? config?.validation?.enabled);
278
339
  }
@@ -380,7 +441,7 @@ var Client = class {
380
441
  if (validateUUID(player)) return undashUUID(player);
381
442
  return player.toLowerCase();
382
443
  }).sort();
383
- const usePost = config?.usePost ?? false;
444
+ const usePost = (config?.usePost ?? false) && !this.isPathBasedURL();
384
445
  if (usePost) {
385
446
  const fetchResponse = await this.axios.post(this.baseURL, players, {
386
447
  cache: config?.cache ?? { ttl: 60 * 60 * 1e3 }
@@ -420,7 +481,7 @@ var Client = class {
420
481
  try {
421
482
  if (this.shouldValidate(config) && !validatePlayer(player, this.getValidationMinLength(config)))
422
483
  return { data: null, error: "INVALID_INPUT" };
423
- const fetchResponse = await this.axios.get(`${this.baseURL}/${player}`, {
484
+ const fetchResponse = await this.axios.get(this.getProfileURL(player), {
424
485
  id: this.getCacheKey("profile", player),
425
486
  cache: config?.cache ?? { ttl: 60 * 60 * 1e3 }
426
487
  });
@@ -522,10 +583,11 @@ var Client = class {
522
583
  return { data: null, error: "INVALID_INPUT" };
523
584
  const UUID = validateUUID(player) ? undashUUID(player) : await this.getUUID(player);
524
585
  if (!UUID) return { data: null, error: "INVALID_PLAYER" };
525
- return await this.axios.get(`${this.baseURL}/session/minecraft/profile/${UUID}`, {
586
+ return await this.axios.get(this.getSessionURL(UUID), {
526
587
  id: this.getCacheKey("session", player),
527
588
  cache: config?.cache ?? { ttl: 15 * 60 * 1e3 }
528
589
  }).then((fetchResponse) => {
590
+ if (fetchResponse.status === 404) return { data: null, error: "INVALID_PLAYER" };
529
591
  let textures = fetchResponse.data.properties.find((property) => property.name === "textures").value;
530
592
  let skin = null;
531
593
  let cape = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mowojang",
3
- "version": "0.8.3",
3
+ "version": "0.9.0",
4
4
  "description": "A simple TypeScript compatible wrapper for the Mowojang-API.",
5
5
  "exports": {
6
6
  ".": {
@@ -28,22 +28,23 @@
28
28
  "node": ">=22.0.0"
29
29
  },
30
30
  "dependencies": {
31
- "axios": "^1.16.1",
32
- "axios-cache-interceptor": "^1.12.0"
31
+ "axios": "^1.20.0",
32
+ "axios-cache-interceptor": "^1.13.0"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@eslint/js": "^10.0.1",
36
36
  "@pixelic/logger": "npm:@jsr/pixelic__logger@^0.3.0",
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",
37
+ "@types/node": "^26.6.5",
38
+ "@typescript-eslint/eslint-plugin": "^8.72.0",
39
+ "@typescript-eslint/parser": "^8.72.0",
40
+ "eslint": "^10.13.0",
41
41
  "eslint-config-prettier": "^10.1.8",
42
- "eslint-plugin-prettier": "^5.5.6",
43
- "prettier": "^3.9.6",
44
- "tsup": "^8.5.1",
42
+ "eslint-plugin-prettier": "^5.5.7",
43
+ "jiti": "^2.7.0",
44
+ "prettier": "^3.9.10",
45
+ "tsup": "^9.0.0",
45
46
  "typescript": "^6.0.3",
46
- "typescript-eslint": "^8.66.0"
47
+ "typescript-eslint": "^8.72.0"
47
48
  },
48
49
  "scripts": {
49
50
  "build": "pnpm tsup",