warframe-nexus-query 2.1.1 → 2.2.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.
@@ -0,0 +1,439 @@
1
+ /**
2
+ * Warframe Market API v2 Client
3
+ * Main entry point for interacting with the Warframe Market API v2
4
+ */
5
+
6
+ import HttpClient from './utils/http.js';
7
+ import VersionedCache from './utils/cache.js';
8
+ import Item from './models/Item.js';
9
+ import Order from './models/Order.js';
10
+ import Summary from './models/Summary.js';
11
+ import { calculateStatistics, getBestOrders, formatPriceRange, formatStatistics } from './utils/statistics.js';
12
+ import { normalizeLanguage } from './utils/i18n.js';
13
+ import { PLATFORMS, SHORT_CACHE_TTL, API_BASE_URL } from './constants.js';
14
+
15
+ export default class MarketFetcherV2 {
16
+ // Private fields
17
+ #http;
18
+ #cache;
19
+ #ordersCache;
20
+ #ordersCacheMaxSize;
21
+
22
+ /**
23
+ * @param {Object} options - Fetcher options
24
+ * @param {string} [options.locale='en'] - Default language
25
+ * @param {number} [options.timeout=5000] - Request timeout in ms
26
+ * @param {Object} [options.logger] - Logger instance
27
+ * @param {number} [options.cacheSize=100] - Cache size
28
+ * @param {number} [options.cacheTTL] - Cache TTL in ms
29
+ */
30
+ constructor(options = {}) {
31
+ this.locale = normalizeLanguage(options.locale || 'en');
32
+ this.logger = options.logger || console;
33
+
34
+ this.#ordersCacheMaxSize = options.ordersCacheSize || 50;
35
+
36
+ this.#http = new HttpClient({
37
+ baseURL: options.baseURL || API_BASE_URL,
38
+ locale: this.locale,
39
+ timeout: options.timeout,
40
+ logger: this.logger,
41
+ });
42
+
43
+ this.#cache = new VersionedCache({
44
+ maxSize: options.cacheSize || 100,
45
+ ttl: options.cacheTTL,
46
+ });
47
+
48
+ // Short-lived cache for orders (1 minute)
49
+ this.#ordersCache = new Map();
50
+ }
51
+
52
+ // ==========================================================================
53
+ // ITEMS
54
+ // ==========================================================================
55
+
56
+ /**
57
+ * Get list of all tradable items
58
+ * @returns {Promise<Item[]>}
59
+ */
60
+ async getItems() {
61
+ const cachedItems = await this.#cache.get('items', 'items', async () => {
62
+ const data = await this.#http.get('/items', { locale: this.locale });
63
+ // Store raw data, not Item instances, to support persistence
64
+ return data;
65
+ });
66
+
67
+ // If cached items are already Item instances, return them
68
+ if (cachedItems.length > 0 && cachedItems[0] instanceof Item) {
69
+ return cachedItems;
70
+ }
71
+
72
+ // Otherwise, reconstruct Item instances from raw data
73
+ return cachedItems.map((item) => new Item(item, this.locale));
74
+ }
75
+
76
+ /**
77
+ * Get item by slug
78
+ * @param {string} slug - Item slug
79
+ * @returns {Promise<Item>}
80
+ */
81
+ async getItemBySlug(slug) {
82
+ const cacheKey = `item_${slug}`;
83
+ const cachedItem = await this.#cache.get(cacheKey, 'items', async () => {
84
+ const data = await this.#http.get(`/item/${slug}`, { locale: this.locale });
85
+ // Store raw data, not Item instance, to support persistence
86
+ return data;
87
+ });
88
+
89
+ // If cached item is already an Item instance, return it
90
+ if (cachedItem instanceof Item) {
91
+ return cachedItem;
92
+ }
93
+
94
+ // Otherwise, reconstruct Item instance from raw data
95
+ return new Item(cachedItem, this.locale);
96
+ }
97
+
98
+ /**
99
+ * Get all items in a set
100
+ * @param {string} slug - Item slug
101
+ * @returns {Promise<{id: string, items: Item[]}>}
102
+ */
103
+ async getItemSet(slug) {
104
+ const cacheKey = `item_set_${slug}`;
105
+ return this.#cache.get(cacheKey, 'items', async () => {
106
+ const data = await this.#http.get(`/item/${slug}/set`, { locale: this.locale });
107
+ return {
108
+ id: data.id,
109
+ items: data.items.map((item) => new Item(item, this.locale)),
110
+ };
111
+ });
112
+ }
113
+
114
+ // ==========================================================================
115
+ // ORDERS
116
+ // ==========================================================================
117
+
118
+ /**
119
+ * Get top orders for an item (RECOMMENDED for price checks)
120
+ * @param {string} slug - Item slug
121
+ * @param {Object} options - Options
122
+ * @param {string} options.platform - Platform (pc, ps4, xbox, switch)
123
+ * @param {number} [options.rank] - Filter by rank
124
+ * @param {number} [options.rankLt] - Filter by rank less than
125
+ * @param {number} [options.charges] - Filter by charges
126
+ * @param {number} [options.chargesLt] - Filter by charges less than
127
+ * @param {number} [options.amberStars] - Filter by amber stars
128
+ * @param {number} [options.amberStarsLt] - Filter by amber stars less than
129
+ * @param {number} [options.cyanStars] - Filter by cyan stars
130
+ * @param {number} [options.cyanStarsLt] - Filter by cyan stars less than
131
+ * @param {string} [options.subtype] - Filter by subtype
132
+ * @returns {Promise<{buy: Order[], sell: Order[]}>}
133
+ */
134
+ async getTopOrders(slug, options = {}) {
135
+ const { platform, ...filters } = options;
136
+
137
+ if (!platform) {
138
+ throw new Error('Platform is required');
139
+ }
140
+
141
+ const cacheKey = `top_orders_${slug}_${platform}_${this.#stableStringify(filters)}`;
142
+
143
+ // Check short-lived cache
144
+ const cached = this.#getOrdersFromCache(cacheKey);
145
+ if (cached) return cached;
146
+
147
+ const data = await this.#http.get(`/orders/item/${slug}/top`, {
148
+ platform,
149
+ query: filters,
150
+ });
151
+
152
+ const result = {
153
+ buy: data.buy.map((order) => new Order(order)),
154
+ sell: data.sell.map((order) => new Order(order)),
155
+ };
156
+
157
+ this.#setOrdersCache(cacheKey, result);
158
+ return result;
159
+ }
160
+
161
+ /**
162
+ * Get all orders for an item
163
+ * @param {string} slug - Item slug
164
+ * @param {string} platform - Platform (pc, ps4, xbox, switch)
165
+ * @returns {Promise<Order[]>}
166
+ */
167
+ async getAllOrders(slug, platform) {
168
+ if (!platform) {
169
+ throw new Error('Platform is required');
170
+ }
171
+
172
+ const cacheKey = `all_orders_${slug}_${platform}`;
173
+
174
+ // Check short-lived cache
175
+ const cached = this.#getOrdersFromCache(cacheKey);
176
+ if (cached) return cached;
177
+
178
+ const data = await this.#http.get(`/orders/item/${slug}`, { platform });
179
+ const result = data.map((order) => new Order(order));
180
+
181
+ this.#setOrdersCache(cacheKey, result);
182
+ return result;
183
+ }
184
+
185
+ /**
186
+ * Get recent orders (last 4 hours)
187
+ * @param {string} platform - Platform (pc, ps4, xbox, switch)
188
+ * @returns {Promise<Order[]>}
189
+ */
190
+ async getRecentOrders(platform) {
191
+ if (!platform) {
192
+ throw new Error('Platform is required');
193
+ }
194
+
195
+ const cacheKey = `recent_orders_${platform}`;
196
+
197
+ // Check short-lived cache
198
+ const cached = this.#getOrdersFromCache(cacheKey);
199
+ if (cached) return cached;
200
+
201
+ const data = await this.#http.get('/orders/recent', { platform });
202
+ const result = data.map((order) => new Order(order));
203
+
204
+ this.#setOrdersCache(cacheKey, result);
205
+ return result;
206
+ }
207
+
208
+ // ==========================================================================
209
+ // STATISTICS (Client-side calculation)
210
+ // ==========================================================================
211
+
212
+ /**
213
+ * Calculate statistics from orders
214
+ * @param {Order[]} orders - Orders array
215
+ * @param {Object} options - Calculation options
216
+ * @returns {Object} Statistics
217
+ */
218
+ calculateStatistics(orders, options = {}) {
219
+ return calculateStatistics(orders, options);
220
+ }
221
+
222
+ /**
223
+ * Get best orders (sorted)
224
+ * @param {Order[]} orders - Orders array
225
+ * @param {Object} options - Options
226
+ * @returns {{buy: Order[], sell: Order[]}}
227
+ */
228
+ getBestOrders(orders, options = {}) {
229
+ return getBestOrders(orders, options);
230
+ }
231
+
232
+ /**
233
+ * Format price range string
234
+ * @param {Object} stats - Statistics object
235
+ * @returns {string}
236
+ */
237
+ formatPriceRange(stats) {
238
+ return formatPriceRange(stats);
239
+ }
240
+
241
+ /**
242
+ * Format statistics for display
243
+ * @param {Object} stats - Statistics object
244
+ * @param {string} type - Order type
245
+ * @returns {string}
246
+ */
247
+ formatStatistics(stats, type) {
248
+ return formatStatistics(stats, type);
249
+ }
250
+
251
+ // ==========================================================================
252
+ // SEARCH / QUERY (v1 compatibility)
253
+ // ==========================================================================
254
+
255
+ /**
256
+ * Query market for item (v1 compatibility method)
257
+ * @param {string} query - Search query
258
+ * @param {Object} options - Query options
259
+ * @param {string} options.platform - Platform
260
+ * @param {function} [options.successfulQuery] - Callback on success
261
+ * @returns {Promise<Summary[]>}
262
+ */
263
+ async queryMarket(query, options = {}) {
264
+ const { platform, successfulQuery } = options;
265
+
266
+ if (!platform) {
267
+ throw new Error('Platform is required');
268
+ }
269
+
270
+ // Search for item
271
+ const items = await this.getItems();
272
+ const normalizedQuery = query.toLowerCase().trim();
273
+
274
+ // Fuzzy search
275
+ const matches = items.filter((item) => {
276
+ const name = item.name.toLowerCase();
277
+ const slug = item.slug.toLowerCase();
278
+ return name.includes(normalizedQuery) || slug.includes(normalizedQuery);
279
+ });
280
+
281
+ if (matches.length === 0) {
282
+ throw new Error(`No items found for query: ${query}`);
283
+ }
284
+
285
+ // Use first match - but only use slug for now
286
+ const matchedSlug = matches[0].slug;
287
+
288
+ // Fetch full item data with all properties (tradingTax, ducats, etc.)
289
+ const item = await this.getItemBySlug(matchedSlug);
290
+
291
+ // Get top orders for the item
292
+ const topOrders = await this.getTopOrders(item.slug, { platform });
293
+
294
+ // Calculate statistics
295
+ const sellStats = this.calculateStatistics(topOrders.sell, {
296
+ type: 'sell',
297
+ onlineOnly: true,
298
+ });
299
+ const buyStats = this.calculateStatistics(topOrders.buy, {
300
+ type: 'buy',
301
+ onlineOnly: true,
302
+ });
303
+
304
+ // Call success callback if provided
305
+ if (successfulQuery && typeof successfulQuery === 'function') {
306
+ successfulQuery();
307
+ }
308
+
309
+ // Create Summary object for v1 compatibility
310
+ const summary = new Summary(item, topOrders, {
311
+ sell: sellStats,
312
+ buy: buyStats,
313
+ });
314
+
315
+ // Return array of summaries (v1 compatibility)
316
+ return [summary];
317
+ }
318
+
319
+ /**
320
+ * Price check query (v1 compatibility method)
321
+ * @param {string} query - Search query
322
+ * @param {string} platform - Platform
323
+ * @returns {Promise<Object>}
324
+ */
325
+ async priceCheckQuery(query, platform) {
326
+ return this.queryMarket(query, { platform });
327
+ }
328
+
329
+ // ==========================================================================
330
+ // CACHE MANAGEMENT
331
+ // ==========================================================================
332
+
333
+ /**
334
+ * Get from short-lived orders cache
335
+ * @param {string} key - Cache key
336
+ * @returns {*|null}
337
+ * @private
338
+ */
339
+ #getOrdersFromCache(key) {
340
+ const cached = this.#ordersCache.get(key);
341
+ if (!cached) return null;
342
+
343
+ // Check TTL (1 minute for orders)
344
+ if (Date.now() - cached.timestamp > SHORT_CACHE_TTL) {
345
+ this.#ordersCache.delete(key);
346
+ return null;
347
+ }
348
+
349
+ return cached.value;
350
+ }
351
+
352
+ /**
353
+ * Set short-lived orders cache
354
+ * @param {string} key - Cache key
355
+ * @param {*} value - Value to cache
356
+ * @private
357
+ */
358
+ #setOrdersCache(key, value) {
359
+ // Evict oldest entries if at capacity
360
+ if (this.#ordersCache.size >= this.#ordersCacheMaxSize) {
361
+ const oldestKey = this.#ordersCache.keys().next().value;
362
+ this.#ordersCache.delete(oldestKey);
363
+ }
364
+ this.#ordersCache.set(key, {
365
+ value,
366
+ timestamp: Date.now(),
367
+ });
368
+ }
369
+
370
+ /**
371
+ * Clear all caches
372
+ */
373
+ clearCache() {
374
+ this.#cache.clear();
375
+ this.#ordersCache.clear();
376
+ }
377
+
378
+ /**
379
+ * Check API versions
380
+ * @returns {Promise<Object>}
381
+ */
382
+ async checkVersions() {
383
+ return this.#cache.checkVersions();
384
+ }
385
+
386
+ /**
387
+ * Stable stringify for cache keys (sorts object keys recursively)
388
+ * @param {*} value - Value to stringify
389
+ * @returns {string} Deterministic JSON string
390
+ * @private
391
+ */
392
+ #stableStringify(value) {
393
+ if (value === null || value === undefined) {
394
+ return JSON.stringify(value);
395
+ }
396
+
397
+ if (typeof value !== 'object') {
398
+ return JSON.stringify(value);
399
+ }
400
+
401
+ if (Array.isArray(value)) {
402
+ return `[${value.map((item) => this.#stableStringify(item)).join(',')}]`;
403
+ }
404
+
405
+ // Sort object keys and recursively stringify
406
+ const sortedKeys = Object.keys(value).sort();
407
+ const pairs = sortedKeys.map((key) => `${JSON.stringify(key)}:${this.#stableStringify(value[key])}`);
408
+ return `{${pairs.join(',')}}`;
409
+ }
410
+
411
+ // ==========================================================================
412
+ // UTILITY
413
+ // ==========================================================================
414
+
415
+ /**
416
+ * Normalize platform
417
+ * @param {string} platform - Platform alias
418
+ * @returns {string} Normalized platform
419
+ */
420
+ normalizePlatform(platform) {
421
+ return PLATFORMS[platform?.toLowerCase()] || platform;
422
+ }
423
+
424
+ /**
425
+ * Set locale
426
+ * @param {string} locale - Language code
427
+ */
428
+ setLocale(locale) {
429
+ this.locale = normalizeLanguage(locale);
430
+ this.#http.setLocale(locale);
431
+ }
432
+
433
+ /**
434
+ * Stop and cleanup (clears all caches)
435
+ */
436
+ stop() {
437
+ this.clearCache();
438
+ }
439
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Constants for Warframe Market API v2
3
+ */
4
+
5
+ export const API_BASE_URL = process.env.MARKET_V2_URL_OVERRIDE || 'https://api.warframe.market/v2';
6
+ export const ASSETS_BASE_URL = process.env.MARKET_ASSETS_URL_OVERRIDE || 'https://warframe.market/static/assets/';
7
+
8
+ export const DEFAULT_TIMEOUT = parseInt(process.env.MARKET_TIMEOUT, 10) || 5000;
9
+ export const VERSION_CHECK_INTERVAL = 5 * 60 * 1000; // 5 minutes
10
+ export const CACHE_TTL = 60 * 60 * 1000; // 1 hour fallback TTL
11
+ export const SHORT_CACHE_TTL = 60 * 1000; // 1 minute for orders
12
+
13
+ export const PLATFORMS = {
14
+ pc: 'pc',
15
+ ps4: 'ps4',
16
+ playstation: 'ps4',
17
+ xb1: 'xbox',
18
+ xbone: 'xbox',
19
+ xbox: 'xbox',
20
+ switch: 'switch',
21
+ swi: 'switch',
22
+ ns: 'switch',
23
+ mobile: 'mobile',
24
+ };
25
+
26
+ export const LANGUAGES = {
27
+ en: 'en',
28
+ es: 'es',
29
+ fr: 'fr',
30
+ de: 'de',
31
+ it: 'it',
32
+ pl: 'pl',
33
+ pt: 'pt',
34
+ ru: 'ru',
35
+ ko: 'ko',
36
+ 'zh-hans': 'zh-hans',
37
+ 'zh-hant': 'zh-hant',
38
+ uk: 'uk',
39
+ };
40
+
41
+ export const USER_STATUS = {
42
+ INVISIBLE: 'invisible',
43
+ OFFLINE: 'offline',
44
+ ONLINE: 'online',
45
+ INGAME: 'ingame',
46
+ };
47
+
48
+ export const ACTIVITY_TYPE = {
49
+ UNKNOWN: 'UNKNOWN',
50
+ IDLE: 'IDLE',
51
+ ON_MISSION: 'ON_MISSION',
52
+ IN_DOJO: 'IN_DOJO',
53
+ IN_ORBITER: 'IN_ORBITER',
54
+ IN_RELAY: 'IN_RELAY',
55
+ };
56
+
57
+ export const ORDER_TYPE = {
58
+ BUY: 'buy',
59
+ SELL: 'sell',
60
+ };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Warframe Market API v2 - Main exports
3
+ */
4
+
5
+ export { default as MarketFetcherV2 } from './MarketFetcherV2.js';
6
+ export { default as Item } from './models/Item.js';
7
+ export { default as Order, OrderUser } from './models/Order.js';
8
+ export { default as SummaryV2 } from './models/Summary.js';
9
+ export { default as VersionedCache } from './utils/cache.js';
10
+ export { default as HttpClient } from './utils/http.js';
11
+ export { calculateStatistics, getBestOrders, formatPriceRange, formatStatistics } from './utils/statistics.js';
12
+ export * from './constants.js';
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Item model for Warframe Market API v2
3
+ * Represents a tradable item with full metadata and i18n support
4
+ */
5
+ export default class Item {
6
+ /**
7
+ * @param {Object} data - Raw item data from API
8
+ * @param {string} locale - Language code for i18n
9
+ */
10
+ constructor(data, locale = 'en') {
11
+ this.id = data.id;
12
+ this.slug = data.slug;
13
+ this.gameRef = data.gameRef;
14
+ this.tags = data.tags || [];
15
+
16
+ // Set relationships
17
+ this.setRoot = data.setRoot;
18
+ this.setParts = data.setParts || [];
19
+ this.quantityInSet = data.quantityInSet;
20
+
21
+ // Trading properties
22
+ this.rarity = data.rarity;
23
+ this.bulkTradable = data.bulkTradable || false;
24
+ this.subtypes = data.subtypes || [];
25
+ this.tradable = data.tradable;
26
+ this.vaulted = data.vaulted;
27
+
28
+ // Progression
29
+ this.maxRank = data.maxRank;
30
+ this.maxCharges = data.maxCharges;
31
+ this.maxAmberStars = data.maxAmberStars;
32
+ this.maxCyanStars = data.maxCyanStars;
33
+
34
+ // Economy
35
+ this.ducats = data.ducats;
36
+ this.vosfor = data.vosfor;
37
+ this.tradingTax = data.tradingTax;
38
+ this.baseEndo = data.baseEndo;
39
+ this.endoMultiplier = data.endoMultiplier;
40
+ this.reqMasteryRank = data.reqMasteryRank;
41
+
42
+ // i18n data
43
+ this.i18n = data.i18n || {};
44
+ this.locale = locale;
45
+
46
+ // Extract localized fields for convenience
47
+ const localizedData = this.i18n[locale] ?? this.i18n.en ?? {};
48
+ this.name = localizedData.name || this.slug;
49
+ this.description = localizedData.description;
50
+ this.wikiLink = localizedData.wikiLink;
51
+ this.icon = localizedData.icon;
52
+ this.thumb = localizedData.thumb;
53
+ this.subIcon = localizedData.subIcon;
54
+
55
+ // Type marker
56
+ this.type = 'market-v2';
57
+ }
58
+
59
+ /**
60
+ * Get localized field
61
+ * @param {string} field - Field name
62
+ * @param {string} [lang] - Language code (defaults to instance locale)
63
+ * @returns {*} Localized value
64
+ */
65
+ getLocalized(field, lang) {
66
+ const locale = lang || this.locale;
67
+ return this.i18n[locale]?.[field] || this.i18n.en?.[field];
68
+ }
69
+
70
+ /**
71
+ * Get full icon URL
72
+ * @param {string} [baseUrl='https://warframe.market/static/assets/'] - Base URL for assets
73
+ * @returns {string}
74
+ */
75
+ getIconUrl(baseUrl = 'https://warframe.market/static/assets/') {
76
+ return this.icon ? `${baseUrl}${this.icon}` : null;
77
+ }
78
+
79
+ /**
80
+ * Get full thumbnail URL
81
+ * @param {string} [baseUrl='https://warframe.market/static/assets/'] - Base URL for assets
82
+ * @returns {string}
83
+ */
84
+ getThumbUrl(baseUrl = 'https://warframe.market/static/assets/') {
85
+ return this.thumb ? `${baseUrl}${this.thumb}` : null;
86
+ }
87
+
88
+ /**
89
+ * Check if item is part of a set
90
+ * @returns {boolean}
91
+ */
92
+ isPartOfSet() {
93
+ return this.setParts && this.setParts.length > 0;
94
+ }
95
+
96
+ /**
97
+ * Check if item is vaulted
98
+ * @returns {boolean}
99
+ */
100
+ isVaulted() {
101
+ return this.vaulted === true;
102
+ }
103
+
104
+ /**
105
+ * Convert to JSON
106
+ * @returns {Object}
107
+ */
108
+ toJSON() {
109
+ return {
110
+ id: this.id,
111
+ slug: this.slug,
112
+ name: this.name,
113
+ thumb: this.thumb,
114
+ icon: this.icon,
115
+ tradingTax: this.tradingTax,
116
+ ducats: this.ducats,
117
+ vosfor: this.vosfor,
118
+ masteryLevel: this.reqMasteryRank,
119
+ tradable: this.tradable,
120
+ vaulted: this.vaulted,
121
+ wikiUrl: this.wikiLink,
122
+ description: this.description,
123
+ tags: this.tags,
124
+ type: this.type,
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Convert to string representation
130
+ * @returns {string}
131
+ */
132
+ toString() {
133
+ return `${this.name} [${this.slug}]`;
134
+ }
135
+ }