mowojang 0.9.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -161,7 +161,7 @@ declare class Client {
161
161
  private shouldValidate;
162
162
  private getValidationMinLength;
163
163
  private getCacheKey;
164
- private mirrorProfileCacheEntries;
164
+ private mirrorPlayerCacheEntries;
165
165
  private _clearCache;
166
166
  private _setCacheKey;
167
167
  private _getCacheKey;
package/dist/index.js CHANGED
@@ -5,10 +5,11 @@ 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.9.1"];
8
+ var define_VERSION_default = ["1.0.0"];
9
9
 
10
10
  // src/utils.ts
11
11
  var undashUUID = /* @__PURE__ */ __name((UUID) => UUID.replaceAll("-", "").toLowerCase(), "undashUUID");
12
+ var formatRequestDuration = /* @__PURE__ */ __name((duration) => duration === void 0 ? "N/A ms" : `${duration}ms`, "formatRequestDuration");
12
13
  var dashUUID = /* @__PURE__ */ __name((UUID) => undashUUID(UUID).replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5"), "dashUUID");
13
14
 
14
15
  // src/validators.ts
@@ -33,116 +34,6 @@ var validateArray = /* @__PURE__ */ __name((array, validatorFunction, ...params)
33
34
  if (!Array.isArray(array)) return false;
34
35
  return array.every((item) => validatorFunction(item, ...params));
35
36
  }, "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");
68
- var axiosInstance_default = /* @__PURE__ */ __name((options, logger) => {
69
- const instance = setupCache(
70
- axios.create({
71
- timeout: options?.timeout ?? 1e4,
72
- maxRedirects: 0,
73
- validateStatus: /* @__PURE__ */ __name((status) => status === 200 || status === 404 || status === 400, "validateStatus"),
74
- headers: {
75
- "User-Agent": `axios/${axios.VERSION} mowojang/${define_VERSION_default[0]} (https://www.npmjs.com/package/mowojang)`,
76
- Accept: "application/json"
77
- }
78
- }),
79
- {
80
- methods: ["get", "post"],
81
- cacheTakeover: false,
82
- cachePredicate: {
83
- statusCheck: /* @__PURE__ */ __name((status) => status === 200 || status === 404, "statusCheck")
84
- },
85
- ...options?.cache
86
- }
87
- );
88
- instance.interceptors.request.use((req) => {
89
- req.internalId = Math.random().toString(16).slice(2, 10).padEnd(8, "0");
90
- logger.debug("Mowojang", `${req.method?.toUpperCase()} ${axios.getUri(req)}`, req.internalId);
91
- return req;
92
- });
93
- instance.interceptors.response.use(
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
- }
105
- if (res.cached) {
106
- logger.debug(
107
- "Mowojang",
108
- `${res.stale ? "GET-CACHE-STALE" : "GET-CACHE"} ${axios.getUri(res.config)}`,
109
- // @ts-expect-error
110
- res.config.internalId
111
- );
112
- }
113
- return res;
114
- },
115
- (err) => {
116
- const isConnectionError = ["ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN"].includes(err.code) || (err?.response?.status ?? 0) >= 500;
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);
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);
141
- return Promise.reject(err);
142
- }
143
- );
144
- return instance;
145
- }, "default");
146
37
 
147
38
  // node_modules/.pnpm/@jsr+pixelic__logger@0.3.0/node_modules/@jsr/pixelic__logger/src/index.js
148
39
  var ANSI = {
@@ -275,7 +166,145 @@ var Logger = class {
275
166
  }
276
167
  };
277
168
 
169
+ // src/axiosInstance.ts
170
+ var PRIMARY_HOST = "mowojang.matdoes.dev";
171
+ var FALLBACK_HOST = "playerdb.co";
172
+ var PLAYERDB_LOOKUP = "https://playerdb.co/api/player/minecraft";
173
+ var isDebugEnabled = /* @__PURE__ */ __name((logger) => LogLevels.DEBUG >= LogLevels[logger.minLevel], "isDebugEnabled");
174
+ var rewriteToPlayerDB = /* @__PURE__ */ __name((fullURL, method) => {
175
+ if ((method ?? "get").toLowerCase() !== "get") return null;
176
+ const url = new URL(fullURL);
177
+ if (url.host !== PRIMARY_HOST) return null;
178
+ const path = url.pathname.replace(/\/+$/, "") || "/";
179
+ if (path.startsWith("/session/minecraft/profile/")) {
180
+ const id = path.slice("/session/minecraft/profile/".length);
181
+ if (!id || id.includes("/")) return null;
182
+ return `${PLAYERDB_LOOKUP}/${id}`;
183
+ }
184
+ if (path.startsWith("/users/profiles/minecraft/")) {
185
+ const id = path.slice("/users/profiles/minecraft/".length);
186
+ if (!id || id.includes("/")) return null;
187
+ return `${PLAYERDB_LOOKUP}/${id}`;
188
+ }
189
+ if (path === "/" || path.includes("/")) return null;
190
+ return `${PLAYERDB_LOOKUP}/${path.slice(1)}`;
191
+ }, "rewriteToPlayerDB");
192
+ var isPlayerDBBody = /* @__PURE__ */ __name((data) => data != null && typeof data === "object" && typeof data.success === "boolean", "isPlayerDBBody");
193
+ var toMowojangShape = /* @__PURE__ */ __name((body) => {
194
+ const player = body.data?.player;
195
+ if (!body.success || !player) return null;
196
+ return {
197
+ id: player.raw_id ?? undashUUID(String(player.id ?? "")),
198
+ name: player.username,
199
+ properties: player.properties ?? [],
200
+ profileActions: []
201
+ };
202
+ }, "toMowojangShape");
203
+ var axiosInstance_default = /* @__PURE__ */ __name((options, logger) => {
204
+ const instance = setupCache(
205
+ axios.create({
206
+ timeout: options?.timeout ?? 1e4,
207
+ maxRedirects: 0,
208
+ validateStatus: /* @__PURE__ */ __name((status) => status === 200 || status === 404 || status === 400, "validateStatus"),
209
+ headers: {
210
+ "User-Agent": `axios/${axios.VERSION} mowojang/${define_VERSION_default[0]} (https://www.npmjs.com/package/mowojang)`,
211
+ Accept: "application/json"
212
+ }
213
+ }),
214
+ {
215
+ methods: ["get", "post"],
216
+ cacheTakeover: false,
217
+ cachePredicate: {
218
+ statusCheck: /* @__PURE__ */ __name((status) => status === 200 || status === 404, "statusCheck")
219
+ },
220
+ ...options?.cache
221
+ }
222
+ );
223
+ instance.interceptors.request.use((req) => {
224
+ req.internalId = Math.random().toString(16).slice(2, 10).padEnd(8, "0");
225
+ return req;
226
+ });
227
+ instance.interceptors.response.use(
228
+ (res) => {
229
+ if (isPlayerDBBody(res.data)) {
230
+ const shaped = toMowojangShape(res.data);
231
+ if (!shaped) {
232
+ res.status = 404;
233
+ res.data = "";
234
+ } else {
235
+ res.status = 200;
236
+ res.data = shaped;
237
+ }
238
+ }
239
+ if (res.cached && isDebugEnabled(logger)) {
240
+ logger.debug(
241
+ "Mowojang",
242
+ `${res.stale ? "GET-CACHE-STALE" : "GET-CACHE"} ${axios.getUri(res.config)} (${formatRequestDuration(res.duration)})`,
243
+ // @ts-expect-error
244
+ res.config.internalId
245
+ );
246
+ }
247
+ if (isDebugEnabled(logger)) {
248
+ logger.debug(
249
+ "Mowojang",
250
+ `${res.config.method?.toUpperCase()} ${axios.getUri(res.config)} (${formatRequestDuration(res.duration)})`,
251
+ // @ts-expect-error
252
+ res.config.internalId
253
+ );
254
+ }
255
+ return res;
256
+ },
257
+ (err) => {
258
+ if (isDebugEnabled(logger) && err.config) {
259
+ logger.debug(
260
+ "Mowojang",
261
+ `${err.config.method?.toUpperCase()} ${axios.getUri(err.config)} (${formatRequestDuration(err.response?.duration)})`,
262
+ err.config.internalId
263
+ );
264
+ }
265
+ const isConnectionError = ["ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN"].includes(err.code) || (err?.response?.status ?? 0) >= 500;
266
+ if (!isConnectionError) return Promise.reject(err);
267
+ const fullURL = axios.getUri(err.config);
268
+ const host = new URL(fullURL).host;
269
+ const isPrimaryHost = host === PRIMARY_HOST;
270
+ const isFallbackHost = host === FALLBACK_HOST;
271
+ const playerDBURL = rewriteToPlayerDB(fullURL, err.config.method);
272
+ const shouldRetryWithFallback = isPrimaryHost && !err.config._retry && playerDBURL !== null;
273
+ if (shouldRetryWithFallback) {
274
+ err.config._retry = true;
275
+ err.config.url = playerDBURL;
276
+ if (err.config.baseURL) delete err.config.baseURL;
277
+ }
278
+ logger.critical("Mowojang", `Failed to establish connection to ${host}`, err.config.internalId);
279
+ const shouldFallback = shouldRetryWithFallback && options.fallback;
280
+ if (shouldFallback) {
281
+ logger.info(
282
+ "Mowojang",
283
+ `Retrying request with fallback of playerdb.co (${formatRequestDuration(err.response?.duration)})`,
284
+ err.config.internalId
285
+ );
286
+ }
287
+ if (isPrimaryHost) {
288
+ logger.info(
289
+ "Mowojang",
290
+ `Check Status of Mowojang on: https://mowojang-status.pixelic.dev (${formatRequestDuration(err.response?.duration)})`
291
+ );
292
+ }
293
+ if (isFallbackHost) {
294
+ logger.info(
295
+ "Mowojang",
296
+ `Check Status of PlayerDB on: https://playerdb.co (${formatRequestDuration(err.response?.duration)})`
297
+ );
298
+ }
299
+ if (shouldFallback) return instance(err.config);
300
+ return Promise.reject(err);
301
+ }
302
+ );
303
+ return instance;
304
+ }, "default");
305
+
278
306
  // src/client.ts
307
+ var isDebugEnabled2 = /* @__PURE__ */ __name((logger) => LogLevels.DEBUG >= LogLevels[logger.minLevel], "isDebugEnabled");
279
308
  var Client = class {
280
309
  static {
281
310
  __name(this, "Client");
@@ -345,28 +374,41 @@ var Client = class {
345
374
  const normalized = validateUUID(value) ? `uuid:${undashUUID(value).toLowerCase()}` : `username:${value.toLowerCase()}`;
346
375
  return `${prefix}:${normalized}`;
347
376
  }
348
- async mirrorProfileCacheEntries(ID, username, UUID, internalId) {
377
+ async mirrorPlayerCacheEntries(prefix, ID, username, UUID, internalId, duration) {
349
378
  try {
350
379
  const storage = this.axios.storage;
351
380
  if (!storage.get || !storage.set) {
352
381
  this.logger.warning(
353
382
  "Mowojang",
354
- `No Storage Methods available or set up for Profile Mirror to work with`,
383
+ `No Storage Methods available or set up for ${prefix} Mirror to work with`,
355
384
  internalId
356
385
  );
357
386
  return;
358
387
  }
359
388
  const value = await storage.get(ID);
360
389
  if (!value) return;
361
- const usernameID = this.getCacheKey("profile", username);
362
- const uuidID = this.getCacheKey("profile", UUID);
390
+ const usernameID = this.getCacheKey(prefix, username);
391
+ const uuidID = this.getCacheKey(prefix, UUID);
392
+ const label = prefix.toUpperCase();
363
393
  if (ID !== usernameID) {
364
394
  await storage.set(usernameID, value);
365
- this.logger.debug("Mowojang", `PROFILE-CACHE-MIRROR-SET ${ID} -> ${usernameID}`, internalId);
395
+ if (isDebugEnabled2(this.logger)) {
396
+ this.logger.debug(
397
+ "Mowojang",
398
+ `${label}-CACHE-MIRROR-SET ${ID} -> ${usernameID} (${formatRequestDuration(duration)})`,
399
+ internalId
400
+ );
401
+ }
366
402
  }
367
403
  if (ID !== uuidID) {
368
404
  await storage.set(uuidID, value);
369
- this.logger.debug("Mowojang", `PROFILE-CACHE-MIRROR-SET ${ID} -> ${uuidID}`, internalId);
405
+ if (isDebugEnabled2(this.logger)) {
406
+ this.logger.debug(
407
+ "Mowojang",
408
+ `${label}-CACHE-MIRROR-SET ${ID} -> ${uuidID} (${formatRequestDuration(duration)})`,
409
+ internalId
410
+ );
411
+ }
370
412
  }
371
413
  } catch (error) {
372
414
  this.logger.error("Mowojang", error instanceof Error ? error.message : "Unknown Error", internalId);
@@ -490,11 +532,13 @@ var Client = class {
490
532
  }
491
533
  if (config?.cache !== false && (typeof config?.cache !== "object" || config.cache.enabled !== false)) {
492
534
  const internalId = fetchResponse.config?.internalId;
493
- await this.mirrorProfileCacheEntries(
535
+ await this.mirrorPlayerCacheEntries(
536
+ "profile",
494
537
  fetchResponse.id,
495
538
  fetchResponse.data.name,
496
539
  fetchResponse.data.id,
497
- internalId
540
+ internalId,
541
+ fetchResponse.duration
498
542
  );
499
543
  }
500
544
  return {
@@ -584,9 +628,9 @@ var Client = class {
584
628
  const UUID = validateUUID(player) ? undashUUID(player) : await this.getUUID(player);
585
629
  if (!UUID) return { data: null, error: "INVALID_PLAYER" };
586
630
  return await this.axios.get(this.getSessionURL(UUID), {
587
- id: this.getCacheKey("session", player),
631
+ id: this.getCacheKey("session", UUID),
588
632
  cache: config?.cache ?? { ttl: 15 * 60 * 1e3 }
589
- }).then((fetchResponse) => {
633
+ }).then(async (fetchResponse) => {
590
634
  if (fetchResponse.status === 404) return { data: null, error: "INVALID_PLAYER" };
591
635
  let textures = fetchResponse.data.properties.find((property) => property.name === "textures").value;
592
636
  let skin = null;
@@ -609,6 +653,17 @@ var Client = class {
609
653
  };
610
654
  }
611
655
  }
656
+ if (config?.cache !== false && (typeof config?.cache !== "object" || config.cache.enabled !== false)) {
657
+ const internalId = fetchResponse.config?.internalId;
658
+ await this.mirrorPlayerCacheEntries(
659
+ "session",
660
+ fetchResponse.id,
661
+ fetchResponse.data.name,
662
+ fetchResponse.data.id,
663
+ internalId,
664
+ fetchResponse.duration
665
+ );
666
+ }
612
667
  return {
613
668
  data: {
614
669
  UUID: fetchResponse.data.id,
@@ -669,7 +724,10 @@ var Client = class {
669
724
  // @ts-expect-error
670
725
  err.config.internalId
671
726
  );
672
- this.logger.info("Mowojang", `Check Status of Mojang Textures API on: https://mowojang-status.pixelic.dev`);
727
+ this.logger.info(
728
+ "Mowojang",
729
+ `Check Status of Mojang Textures API on: https://mowojang-status.pixelic.dev (${formatRequestDuration(err.response?.duration)})`
730
+ );
673
731
  }
674
732
  return null;
675
733
  }
@@ -717,7 +775,10 @@ var Client = class {
717
775
  // @ts-expect-error
718
776
  err.config.internalId
719
777
  );
720
- this.logger.info("Mowojang", `Check Status of Mojang Textures API on: https://mowojang-status.pixelic.dev`);
778
+ this.logger.info(
779
+ "Mowojang",
780
+ `Check Status of Mojang Textures API on: https://mowojang-status.pixelic.dev (${formatRequestDuration(err.response?.duration)})`
781
+ );
721
782
  }
722
783
  return null;
723
784
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mowojang",
3
- "version": "0.9.1",
3
+ "version": "1.0.0",
4
4
  "description": "A simple TypeScript compatible wrapper for the Mowojang-API.",
5
5
  "exports": {
6
6
  ".": {
@@ -34,17 +34,17 @@
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.6.6",
38
- "@typescript-eslint/eslint-plugin": "^8.72.2",
39
- "@typescript-eslint/parser": "^8.72.2",
40
- "eslint": "^10.14.0",
41
- "eslint-config-prettier": "^10.1.8",
37
+ "@types/node": "^26.6.11",
38
+ "@typescript-eslint/eslint-plugin": "^8.74.0",
39
+ "@typescript-eslint/parser": "^8.74.0",
40
+ "eslint": "^10.16.0",
41
+ "eslint-config-prettier": "^10.1.9",
42
42
  "eslint-plugin-prettier": "^5.5.7",
43
43
  "jiti": "^2.7.0",
44
44
  "prettier": "^3.10.1",
45
45
  "tsup": "^9.0.0",
46
46
  "typescript": "^6.0.3",
47
- "typescript-eslint": "^8.72.2"
47
+ "typescript-eslint": "^8.74.0"
48
48
  },
49
49
  "scripts": {
50
50
  "build": "pnpm tsup",