@tcgdex/sdk
Version:
Communicate with the Open Source TCGdex API in Javascript/Typescript using the SDK
783 lines (764 loc) • 23.4 kB
JavaScript
"use strict";
var TCGdex = (() => {
var __getOwnPropNames = Object.getOwnPropertyNames;
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
// node_modules/@dzeio/object-util/dist/ObjectUtil.mjs
function objectLoop(obj, fn) {
mustBeObject(obj);
const keys = objectKeys(obj);
for (let index = 0; index < keys.length; index++) {
const key = keys[index];
const stop = fn(obj[key], key, index);
if (stop === false) {
return false;
}
}
return true;
}
function objectKeys(obj) {
mustBeObject(obj);
if (Array.isArray(obj)) {
return Array.from(obj.keys());
}
return Object.keys(obj);
}
function isObject(item) {
return typeof item === "object" && item !== null;
}
function mustBeObject(item) {
if (!isObject(item)) {
throw new Error("Input is not an object!");
}
return true;
}
var init_ObjectUtil = __esm({
"node_modules/@dzeio/object-util/dist/ObjectUtil.mjs"() {
"use strict";
}
});
// node_modules/@cachex/core/dist/index.mjs
var CacheAsbract;
var init_dist = __esm({
"node_modules/@cachex/core/dist/index.mjs"() {
"use strict";
init_ObjectUtil();
CacheAsbract = class {
getMultiple(keys, defaultValues) {
const res = {};
for (let idx = 0; idx < keys.length; idx++) {
const key = keys[idx];
const value = this.get(key, defaultValues == null ? void 0 : defaultValues[idx]);
if (typeof value === "undefined") {
continue;
}
res[key] = value;
}
return res;
}
setMultiple(values, ttl) {
objectLoop(values, (v, k) => {
this.set(k, v, ttl);
});
return true;
}
deleteMultiple(keys) {
for (const key of keys) {
this.delete(key);
}
return true;
}
};
}
});
// node_modules/@cachex/memory/dist/index.mjs
var MemoryCache;
var init_dist2 = __esm({
"node_modules/@cachex/memory/dist/index.mjs"() {
"use strict";
init_dist();
MemoryCache = class extends CacheAsbract {
constructor() {
super(...arguments);
this.cache = /* @__PURE__ */ new Map();
}
get(key, defaultValue) {
const item = this.cache.get(key);
if (!item) {
return defaultValue != null ? defaultValue : void 0;
}
if (item.expire && item.expire < (/* @__PURE__ */ new Date()).getTime()) {
this.delete(key);
return defaultValue != null ? defaultValue : void 0;
}
return item.data;
}
set(key, value, ttl) {
let expire;
if (ttl) {
expire = (/* @__PURE__ */ new Date()).getTime() + ttl * 1e3;
}
this.cache.set(key, {
data: value,
expire
});
return true;
}
delete(key) {
this.cache.delete(key);
return true;
}
clear() {
this.cache.clear();
return true;
}
has(key) {
return this.cache.has(key);
}
};
}
});
// node_modules/@cachex/web-storage/dist/index.mjs
var BrowserStorageCache;
var init_dist3 = __esm({
"node_modules/@cachex/web-storage/dist/index.mjs"() {
"use strict";
init_dist();
BrowserStorageCache = class extends CacheAsbract {
constructor(prefix, session = false) {
super();
this.prefix = prefix;
try {
window;
} catch {
throw new Error('The current context is not in a browser or the variable "window" is not available.');
}
if (session) {
this.storage = window.sessionStorage;
} else {
this.storage = window.localStorage;
}
if (!this.storage) {
throw new Error("window.localStorage or window.sessionStorage are unavailable.");
}
}
get(key, defaultValue) {
const raw = this.storage.getItem(this.getFinalKey(key));
if (!raw) {
return defaultValue != null ? defaultValue : void 0;
}
const item = JSON.parse(raw);
if (item.expire && item.expire < (/* @__PURE__ */ new Date()).getTime()) {
this.delete(key);
return defaultValue != null ? defaultValue : void 0;
}
return item.data;
}
set(key, value, ttl) {
let expire = void 0;
if (ttl) {
expire = (/* @__PURE__ */ new Date()).getTime() + ttl * 1e3;
}
const data = {
data: value,
expire
};
this.storage.setItem(this.getFinalKey(key), JSON.stringify(data));
return true;
}
delete(key) {
this.storage.removeItem(this.getFinalKey(key));
return true;
}
clear() {
const keys = this.keys();
return this.deleteMultiple(keys);
}
has(key) {
return !!this.storage.getItem(this.getFinalKey(key));
}
/**
* get the list of keys that are in the context of this cache component
*/
keys() {
const list = [];
for (let idx = 0; idx < this.storage.length; idx++) {
const key = this.storage.key(idx);
if (typeof key !== "string" || this.prefix && !(key == null ? void 0 : key.startsWith(`@${this.prefix}/`))) {
continue;
}
list.push(key);
}
return list;
}
/**
* retrieve the prefixed key from the original
* @param key the original key without prefix
* @returns the new key with the prefix if set
*/
getFinalKey(key) {
if (!this.prefix) {
return key;
}
return `@${this.prefix}/${key}`;
}
};
}
});
// src/models/Model.ts
var Model;
var init_Model = __esm({
"src/models/Model.ts"() {
"use strict";
init_ObjectUtil();
Model = class {
constructor(sdk) {
this.sdk = sdk;
}
/**
* build a model depending on the data given
* @param model the model to build
* @param data the data to fill it with
*/
static build(model, data) {
if (!data) {
throw new Error("data is necessary.");
}
model.fill(data);
return model;
}
fill(obj) {
objectLoop(obj, (value, key) => {
this[key] = value;
});
}
};
}
});
// src/endpoints/Endpoint.ts
var Endpoint;
var init_Endpoint = __esm({
"src/endpoints/Endpoint.ts"() {
"use strict";
init_Model();
Endpoint = class {
constructor(tcgdex, itemModel, listModel, endpoint) {
this.tcgdex = tcgdex;
this.itemModel = itemModel;
this.listModel = listModel;
this.endpoint = endpoint;
}
async get(id) {
const res = await this.tcgdex.fetch(this.endpoint, id);
if (!res) {
return null;
}
return Model.build(new this.itemModel(this.tcgdex), res);
}
async list(query) {
const res = await this.tcgdex.fetchWithQuery([this.endpoint], query == null ? void 0 : query.params);
return (res != null ? res : []).map((it) => Model.build(new this.listModel(this.tcgdex), it));
}
};
}
});
// src/endpoints/SimpleEndpoint.ts
var SimpleEndpoint;
var init_SimpleEndpoint = __esm({
"src/endpoints/SimpleEndpoint.ts"() {
"use strict";
init_Model();
SimpleEndpoint = class {
constructor(tcgdex, itemModel, endpoint) {
this.tcgdex = tcgdex;
this.itemModel = itemModel;
this.endpoint = endpoint;
}
async get(id) {
const res = await this.tcgdex.fetch(this.endpoint, id);
if (!res) {
return null;
}
return Model.build(new this.itemModel(this.tcgdex), res);
}
async list(query) {
var _a;
return (_a = await this.tcgdex.fetchWithQuery([this.endpoint], query == null ? void 0 : query.params)) != null ? _a : [];
}
};
}
});
// src/models/CardResume.ts
var CardResume;
var init_CardResume = __esm({
"src/models/CardResume.ts"() {
"use strict";
init_Model();
CardResume = class extends Model {
/**
* the the Card Image full URL
*
* @param {Quality} quality the quality you want your image to be in
* @param {Extension} extension extension you want you image to be
* @return the full card URL
*/
getImageURL(quality = "high", extension = "png") {
return `${this.image}/${quality}.${extension}`;
}
/**
* Get the full Card
*
* @return the full card if available
*/
async getCard() {
return await this.sdk.card.get(this.id);
}
};
}
});
// src/models/Card.ts
var Card;
var init_Card = __esm({
"src/models/Card.ts"() {
"use strict";
init_CardResume();
Card = class extends CardResume {
async getCard() {
return this;
}
async getSet() {
return await this.sdk.set.get(this.set.id);
}
};
}
});
// src/models/SerieResume.ts
var SerieResume;
var init_SerieResume = __esm({
"src/models/SerieResume.ts"() {
"use strict";
init_Model();
SerieResume = class extends Model {
/**
* the the Card Image full URL
*
* @param {Quality} quality the quality you want your image to be in
* @param {Extension} extension extension you want you image to be
* @return the full card URL
*/
getImageURL(extension = "png") {
return `${this.logo}.${extension}`;
}
async getSerie() {
return await this.sdk.serie.get(this.id);
}
};
}
});
// src/models/SetResume.ts
var SetResume;
var init_SetResume = __esm({
"src/models/SetResume.ts"() {
"use strict";
init_Model();
SetResume = class extends Model {
async getSet() {
return await this.sdk.set.get(this.id);
}
};
}
});
// src/models/Serie.ts
var Serie;
var init_Serie = __esm({
"src/models/Serie.ts"() {
"use strict";
init_ObjectUtil();
init_Model();
init_SerieResume();
init_SetResume();
Serie = class extends SerieResume {
fill(obj) {
objectLoop(obj, (value, key) => {
switch (key) {
case "sets":
this.sets = value.map((it) => Model.build(new SetResume(this.sdk), it));
break;
default:
this[key] = value;
break;
}
});
}
};
}
});
// src/models/Set.ts
var Set;
var init_Set = __esm({
"src/models/Set.ts"() {
"use strict";
init_ObjectUtil();
init_CardResume();
init_Model();
Set = class extends Model {
async getSerie() {
return this.sdk.serie.get(this.serie.id);
}
fill(obj) {
objectLoop(obj, (value, key) => {
switch (key) {
case "cards":
this.cards = value.map((it) => Model.build(new CardResume(this.sdk), it));
break;
default:
this[key] = value;
break;
}
});
}
};
}
});
// src/models/StringEndpoint.ts
var StringEndpoint;
var init_StringEndpoint = __esm({
"src/models/StringEndpoint.ts"() {
"use strict";
init_ObjectUtil();
init_CardResume();
init_Model();
StringEndpoint = class extends Model {
fill(obj) {
objectLoop(obj, (value, key) => {
switch (key) {
case "cards":
this.cards = value.map((it) => Model.build(new CardResume(this.sdk), it));
break;
default:
this[key] = value;
break;
}
});
}
};
}
});
// src/utils.ts
function detectContext() {
try {
const isBrowser = !!window;
return isBrowser ? "browser" : "server";
} catch {
return "server";
}
}
var ENDPOINTS;
var init_utils = __esm({
"src/utils.ts"() {
"use strict";
ENDPOINTS = [
"cards",
"categories",
"dex-ids",
"energy-types",
"hp",
"illustrators",
"rarities",
"regulation-marks",
"retreats",
"series",
"sets",
"stages",
"suffixes",
"trainer-types",
"types",
"variants",
"random"
];
}
});
// src/version.js
var version;
var init_version = __esm({
"src/version.js"() {
"use strict";
version = "2.7.1";
}
});
// src/tcgdex.ts
var _TCGdex, TCGdex;
var init_tcgdex = __esm({
"src/tcgdex.ts"() {
"use strict";
init_dist2();
init_dist3();
init_Endpoint();
init_SimpleEndpoint();
init_Card();
init_CardResume();
init_Model();
init_Serie();
init_SerieResume();
init_Set();
init_SetResume();
init_StringEndpoint();
init_utils();
init_version();
_TCGdex = class _TCGdex {
constructor(lang = "en") {
/**
* the previously hidden caching system used by TCGdex to not kill the API
*/
this.cache = detectContext() === "browser" ? new BrowserStorageCache("tcgdex-cache") : new MemoryCache();
/**
* the default cache TTL, only subsequent requests will have their ttl changed
*/
this.cacheTTL = 60 * 60;
// random card/set/serie endpoints
this.random = {
card: async () => {
const res = await this.fetch("random", "card");
return Model.build(new Card(this), res);
},
set: async () => {
const res = await this.fetch("random", "set");
return Model.build(new Set(this), res);
},
serie: async () => {
const res = await this.fetch("random", "serie");
return Model.build(new Serie(this), res);
}
};
this.card = new Endpoint(this, Card, CardResume, "cards");
this.set = new Endpoint(this, Set, SetResume, "sets");
this.serie = new Endpoint(this, Serie, SerieResume, "series");
this.type = new SimpleEndpoint(this, StringEndpoint, "types");
this.retreat = new SimpleEndpoint(this, StringEndpoint, "retreats");
this.rarity = new SimpleEndpoint(this, StringEndpoint, "rarities");
this.illustrator = new SimpleEndpoint(this, StringEndpoint, "illustrators");
this.hp = new SimpleEndpoint(this, StringEndpoint, "hp");
this.categorie = new SimpleEndpoint(this, StringEndpoint, "categories");
this.dexID = new SimpleEndpoint(this, StringEndpoint, "dex-ids");
this.energyType = new SimpleEndpoint(this, StringEndpoint, "energy-types");
this.regulationMark = new SimpleEndpoint(this, StringEndpoint, "regulation-marks");
this.stage = new SimpleEndpoint(this, StringEndpoint, "stages");
this.suffixe = new SimpleEndpoint(this, StringEndpoint, "suffixes");
this.trainerType = new SimpleEndpoint(this, StringEndpoint, "trainer-types");
this.variant = new SimpleEndpoint(this, StringEndpoint, "variants");
this.lang = "en";
this.endpointURL = "https://api.tcgdex.net/v2";
this.setLang(lang);
}
/**
* @deprecated use the constructor parameter or {@link TCGdex.setLang} when in an instance
*/
static setDefaultLang(lang) {
_TCGdex.defaultLang = lang;
}
/**
* @deprecated use {@link TCGdex.setLang} when in an instance
*/
static getDefaultLang() {
return _TCGdex.defaultLang;
}
/**
* the endpoint URL
* ex: `https://api.tcgdex.net/v2`
* @param endpoint the url
*/
setEndpoint(endpoint) {
this.endpointURL = endpoint;
}
getEndpoint() {
return this.endpointURL;
}
/**
* set the current cache methodology
* @param cache the cache to use
*/
setCache(cache) {
this.cache = cache;
}
/**
* get the current cache methodology
* @param cache the cache to use
*/
getCache() {
return this.cache;
}
/**
* the endpoint URL
* ex: `https://api.tcgdex.net/v2`
* @param endpoint the url
*/
setCacheTTL(seconds) {
this.cacheTTL = seconds;
}
/**
* get the current useed cache ttl in seconds
* @returns the cache ttl in seconds
*/
getCacheTTL() {
return this.cacheTTL;
}
getLang() {
var _a, _b;
return (_b = (_a = this.lang) != null ? _a : _TCGdex.defaultLang) != null ? _b : "en";
}
setLang(lang) {
this.lang = lang;
}
/**
* Shortcut to easily fetch a card using both it's global id and it's local ID
* @param id the card global/local ID
* @param set the card set name/ID (optionnal)
* @returns the card object
*/
async fetchCard(id, set) {
const path = set ? ["sets", set] : ["cards"];
return this.fetch(...path, id);
}
/**
* Shortcut to easily fetch cards using an optionnal set name/ID
* @param set the card set name/ID (optionnal)
* @returns a card list
*/
async fetchCards(set) {
if (set) {
const fSet = await this.fetch("sets", set);
return fSet ? fSet.cards : void 0;
}
return this.fetch("cards");
}
/**
* @deprecated use `this.fetch('sets', set)`
*/
async fetchSet(set) {
return this.fetch("sets", set);
}
/**
* @deprecated use `this.fetch('series', serie)`
*/
async fetchSerie(serie) {
return this.fetch("series", serie);
}
/**
* @deprecated use `this.fetch('series')`
*/
async fetchSeries() {
return this.fetch("series");
}
/**
* Shortcut to easily fetch sets using an optionnal serie name/ID
* @param serie the card set name/ID (optionnal)
* @returns a card list
*/
async fetchSets(serie) {
if (serie) {
const fSerie = await this.fetch("series", serie);
return fSerie ? fSerie.sets : void 0;
}
return this.fetch("sets");
}
/**
* Fetch The differents endpoints depending on the first argument
* @param endpoint_0 {'hp' | 'retreats' | 'categories' | 'illustrators' | 'rarities' | 'types'}
* Possible value 'cards' | 'categories' | 'hp' | 'illustrators' | 'rarities' | 'retreats' | 'series' | 'sets' | 'types'
* @param endpoint_1 {string} (Optionnal) some details to go from the index file to the item file (mostly the ID/name)
* @param endpoint_2 {string} (Optionnal) only for sets the card local ID to fetch the card through the set
*/
async fetch(...endpoint) {
if (endpoint.length === 0) {
throw new Error("endpoint to fetch is empty!");
}
const baseEndpoint = endpoint.shift().toLowerCase();
if (!ENDPOINTS.includes(baseEndpoint)) {
throw new Error(`unknown endpoint to fetch! (${baseEndpoint})`);
}
return this.actualFetch(this.getFullURL([baseEndpoint, ...endpoint]));
}
/**
* @param endpoint the endpoint to fetch
* @param query the query
*/
async fetchWithQuery(endpoint, query) {
if (endpoint.length === 0) {
throw new Error("endpoint to fetch is empty!");
}
const baseEndpoint = endpoint[0].toLowerCase();
if (!ENDPOINTS.includes(baseEndpoint)) {
throw new Error(`unknown endpoint to fetch! (${baseEndpoint})`);
}
return this.actualFetch(this.getFullURL(endpoint, query));
}
/**
* format the final URL
*/
getFullURL(path, searchParams) {
const url = new URL(`${this.getEndpoint()}/${this.getLang()}`);
url.pathname = `${url.pathname}/${path.join("/")}`;
for (const param of searchParams != null ? searchParams : []) {
url.searchParams.append(param.key, param.value.toString());
}
return url.toString();
}
async actualFetch(path) {
const cached = this.cache.get(path);
if (cached) {
return cached;
}
const resp = await _TCGdex.fetch(path, {
headers: {
"user-agent": `/javascript-sdk/${version}`
}
});
if (resp.status >= 500) {
try {
const json2 = JSON.stringify(await resp.json());
throw new Error(json2);
} catch {
throw new Error("TCGdex Server responded with an invalid error :(");
}
}
if (resp.status !== 200) {
return void 0;
}
const json = await resp.json();
this.cache.set(path, json, this.cacheTTL);
return json;
}
};
/**
* How the remote data is going to be fetched
*/
_TCGdex.fetch = detectContext() === "browser" ? (...params) => window.fetch(...params) : fetch;
/**
* @deprecated to change the lang use {@link TCGdex.getLang} and {@link TCGdex.setLang}
*/
_TCGdex.defaultLang = "en";
TCGdex = _TCGdex;
}
});
// src/tcgdex.browser.ts
var require_tcgdex_browser = __commonJS({
"src/tcgdex.browser.ts"(exports, module) {
init_tcgdex();
module.exports = TCGdex;
}
});
return require_tcgdex_browser();
})();
/*! Bundled license information:
@cachex/core/dist/index.mjs:
(*!
* Library based on the awesome PHP Psr 16 SimpleCache
*
* CacheX is a simple, easy to use and meant to be replaceable Cache library for most usage
*)
*/
//# sourceMappingURL=tcgdex.browser.global.js.map