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