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,291 +0,0 @@
1
- import { create } from 'flat-cache';
2
-
3
- import { API_BASE_URL, VERSION_CHECK_INTERVAL, CACHE_TTL } from '../constants.js';
4
-
5
- /**
6
- * Version-based cache system for Warframe Market API v2
7
- * Uses version hashes from /v2/versions endpoint to invalidate cache
8
- * Backs up to persistent storage using flat-cache
9
- */
10
- export default class VersionedCache {
11
- #cache;
12
- #versions;
13
- #lastVersionCheck;
14
- #persistentCache;
15
- #cacheId;
16
-
17
- constructor({ maxSize = 100, ttl = CACHE_TTL, cacheId = 'warframe-market-v2', persistent = true } = {}) {
18
- this.#cache = new Map();
19
- this.maxSize = maxSize;
20
- this.ttl = ttl;
21
- this.#versions = undefined;
22
- this.#lastVersionCheck = undefined;
23
- this.#cacheId = cacheId;
24
-
25
- // Initialize persistent cache
26
- if (persistent) {
27
- this.#persistentCache = create({ cacheId });
28
- this.#loadFromDisk();
29
- } else {
30
- this.#persistentCache = undefined;
31
- }
32
- }
33
-
34
- /**
35
- * Load cache from disk into memory
36
- * @private
37
- */
38
- #loadFromDisk() {
39
- if (!this.#persistentCache) return;
40
-
41
- try {
42
- const keys = this.#persistentCache.keys();
43
-
44
- // Load all cached items
45
- keys.forEach((key) => {
46
- const item = this.#persistentCache.getKey(key);
47
- if (item) {
48
- // Check if item is still valid (TTL not expired)
49
- if (item.timestamp && Date.now() - item.timestamp <= this.ttl) {
50
- this.#cache.set(key, item);
51
- }
52
- }
53
- });
54
-
55
- // Load versions data
56
- const versionsData = this.#persistentCache.getKey('_versions_metadata');
57
- if (versionsData) {
58
- this.#versions = versionsData.versions;
59
- this.#lastVersionCheck = versionsData.lastVersionCheck;
60
- }
61
- } catch (error) {
62
- // If loading fails, start with empty cache
63
- // eslint-disable-next-line no-console
64
- console.warn('Failed to load cache from disk:', error.message);
65
- }
66
- }
67
-
68
- /**
69
- * Save cache to disk
70
- * @private
71
- */
72
- #saveToDisk() {
73
- if (!this.#persistentCache) return;
74
-
75
- try {
76
- // Save all cache entries
77
- Array.from(this.#cache.entries()).forEach(([key, value]) => {
78
- this.#persistentCache.setKey(key, value);
79
- });
80
-
81
- // Save versions metadata
82
- if (this.#versions || this.#lastVersionCheck) {
83
- this.#persistentCache.setKey('_versions_metadata', {
84
- versions: this.#versions,
85
- lastVersionCheck: this.#lastVersionCheck,
86
- });
87
- }
88
-
89
- // Persist to disk
90
- this.#persistentCache.save(true);
91
- } catch (error) {
92
- // If saving fails, log but don't crash
93
- // eslint-disable-next-line no-console
94
- console.warn('Failed to save cache to disk:', error.message);
95
- }
96
- }
97
-
98
- /**
99
- * Get item from cache or fetch it
100
- * @param {string} key - Cache key
101
- * @param {string} collection - Collection name (items, rivens, etc.)
102
- * @param {function} fetchFn - Function to fetch data if cache miss
103
- * @returns {Promise<*>}
104
- */
105
- async get(key, collection, fetchFn) {
106
- // Check if we should refresh based on version
107
- if (collection && (await this.shouldRefresh(collection))) {
108
- return this.refresh(key, collection, fetchFn);
109
- }
110
-
111
- // Try to get from cache
112
- const cached = this.#get(key);
113
- if (cached !== undefined) {
114
- return cached;
115
- }
116
-
117
- // Cache miss - fetch and store
118
- const data = await fetchFn();
119
- this.set(key, data, collection);
120
- return data;
121
- }
122
-
123
- /**
124
- * Set item in cache
125
- * @param {string} key - Cache key
126
- * @param {*} value - Value to cache
127
- * @param {string} [collection] - Collection name for version tracking
128
- */
129
- set(key, value, collection) {
130
- // LRU eviction if cache is full
131
- if (this.#cache.size >= this.maxSize) {
132
- const firstKey = this.#cache.keys().next().value;
133
- this.#cache.delete(firstKey);
134
-
135
- // Remove from persistent cache too
136
- if (this.#persistentCache) {
137
- this.#persistentCache.removeKey(firstKey);
138
- }
139
- }
140
-
141
- this.#cache.set(key, {
142
- value,
143
- timestamp: Date.now(),
144
- collection,
145
- });
146
-
147
- // Store collection version if provided
148
- if (collection && this.#versions) {
149
- const versionKey = `_version_${collection}`;
150
- const collectionVersion = this.#versions.data?.collections?.[collection];
151
- if (collectionVersion) {
152
- this.#cache.set(versionKey, {
153
- value: collectionVersion,
154
- timestamp: Date.now(),
155
- });
156
- }
157
- }
158
-
159
- // Persist to disk
160
- this.#saveToDisk();
161
- }
162
-
163
- /**
164
- * Get item from cache (internal)
165
- * @param {string} key - Cache key
166
- * @returns {*|undefined}
167
- * @private
168
- */
169
- #get(key) {
170
- const cached = this.#cache.get(key);
171
- if (!cached) return undefined;
172
-
173
- // Check TTL
174
- if (Date.now() - cached.timestamp > this.ttl) {
175
- this.#cache.delete(key);
176
- return undefined;
177
- }
178
-
179
- return cached.value;
180
- }
181
-
182
- /**
183
- * Check if collection should be refreshed
184
- * @param {string} collection - Collection name
185
- * @returns {Promise<boolean>}
186
- */
187
- async shouldRefresh(collection) {
188
- try {
189
- const currentVersions = await this.checkVersions();
190
- const cachedVersion = this.#get(`_version_${collection}`);
191
- const serverVersion = currentVersions.data?.collections?.[collection];
192
-
193
- return serverVersion && cachedVersion !== serverVersion;
194
- } catch {
195
- // If version check fails, don't force refresh
196
- return false;
197
- }
198
- }
199
-
200
- /**
201
- * Refresh cache entry
202
- * @param {string} key - Cache key
203
- * @param {string} collection - Collection name
204
- * @param {function} fetchFn - Function to fetch fresh data
205
- * @returns {Promise<*>}
206
- */
207
- async refresh(key, collection, fetchFn) {
208
- const data = await fetchFn();
209
- this.set(key, data, collection);
210
- return data;
211
- }
212
-
213
- /**
214
- * Check versions from server
215
- * @returns {Promise<Object>}
216
- */
217
- async checkVersions() {
218
- // Check every VERSION_CHECK_INTERVAL (5 minutes)
219
- if (this.#versions && this.#lastVersionCheck && Date.now() - this.#lastVersionCheck < VERSION_CHECK_INTERVAL) {
220
- return this.#versions;
221
- }
222
-
223
- try {
224
- const response = await fetch(`${API_BASE_URL}/versions`);
225
- if (!response.ok) {
226
- throw new Error(`Version check failed: ${response.status}`);
227
- }
228
-
229
- this.#versions = await response.json();
230
- this.#lastVersionCheck = Date.now();
231
-
232
- // Persist versions to disk
233
- this.#saveToDisk();
234
-
235
- return this.#versions;
236
- } catch (error) {
237
- // If fetch fails and we have cached versions, return them
238
- if (this.#versions) {
239
- return this.#versions;
240
- }
241
- throw error;
242
- }
243
- }
244
-
245
- /**
246
- * Clear entire cache
247
- */
248
- clear() {
249
- this.#cache.clear();
250
- this.#versions = undefined;
251
- this.#lastVersionCheck = undefined;
252
-
253
- // Clear persistent cache
254
- if (this.#persistentCache) {
255
- this.#persistentCache.destroy();
256
- // Recreate the cache file (creates new empty cache)
257
- this.#persistentCache = create({ cacheId: this.#cacheId });
258
- }
259
- }
260
-
261
- /**
262
- * Delete specific key from cache
263
- * @param {string} key - Cache key
264
- */
265
- delete(key) {
266
- this.#cache.delete(key);
267
-
268
- // Remove from persistent cache
269
- if (this.#persistentCache) {
270
- this.#persistentCache.removeKey(key);
271
- this.#persistentCache.save(true);
272
- }
273
- }
274
-
275
- /**
276
- * Get cache size
277
- * @returns {number}
278
- */
279
- size() {
280
- return this.#cache.size;
281
- }
282
-
283
- /**
284
- * Check if key exists in cache (and is valid)
285
- * @param {string} key - Cache key
286
- * @returns {boolean}
287
- */
288
- has(key) {
289
- return this.#get(key) !== undefined;
290
- }
291
- }
@@ -1,246 +0,0 @@
1
- /**
2
- * HTTP client for Warframe Market API v2
3
- */
4
-
5
- import { API_BASE_URL, DEFAULT_TIMEOUT, PLATFORMS } from '../constants.js';
6
-
7
- import { normalizeLanguage } from './i18n.js';
8
-
9
- /**
10
- * Make HTTP request with timeout
11
- * @param {string} url - URL to fetch
12
- * @param {Object} options - Fetch options
13
- * @param {number} timeout - Timeout in milliseconds
14
- * @returns {Promise<Response>}
15
- */
16
- async function fetchWithTimeout(url, options = {}, timeout = DEFAULT_TIMEOUT) {
17
- const controller = new AbortController();
18
- const timeoutId = setTimeout(() => controller.abort(), timeout);
19
-
20
- try {
21
- const response = await fetch(url, {
22
- ...options,
23
- signal: controller.signal,
24
- });
25
- clearTimeout(timeoutId);
26
- return response;
27
- } catch (error) {
28
- clearTimeout(timeoutId);
29
- if (error.name === 'AbortError') {
30
- throw new Error(`Request timeout after ${timeout}ms`);
31
- }
32
- throw error;
33
- }
34
- }
35
-
36
- /**
37
- * HTTP Client for Warframe Market API v2
38
- */
39
- export default class HttpClient {
40
- #baseURL;
41
- #timeout;
42
- #locale;
43
- #logger;
44
-
45
- /**
46
- * @param {Object} options - Client options
47
- * @param {string} [options.baseURL] - Base URL for API
48
- * @param {number} [options.timeout] - Request timeout in ms
49
- * @param {string} [options.locale] - Default language
50
- * @param {Object} [options.logger] - Logger instance
51
- */
52
- constructor(options = {}) {
53
- // Ensure baseURL ends with /
54
- let baseURL = options.baseURL || API_BASE_URL;
55
- if (!baseURL.endsWith('/')) {
56
- baseURL += '/';
57
- }
58
- this.#baseURL = baseURL;
59
- this.#timeout = options.timeout || DEFAULT_TIMEOUT;
60
- this.#locale = normalizeLanguage(options.locale || 'en');
61
- this.#logger = options.logger || console;
62
- }
63
-
64
- /**
65
- * Make GET request
66
- * @param {string} path - API path
67
- * @param {Object} options - Request options
68
- * @param {string} [options.platform] - Platform header
69
- * @param {string} [options.locale] - Language header
70
- * @param {Object} [options.query] - Query parameters
71
- * @returns {Promise<Object>}
72
- */
73
- async get(path, options = {}) {
74
- const url = this.#buildUrl(path, options.query);
75
- const headers = this.#buildHeaders(options);
76
-
77
- this.#logger.debug(`[v2] GET ${url}`);
78
-
79
- try {
80
- const response = await fetchWithTimeout(url, { headers }, this.#timeout);
81
-
82
- if (!response.ok) {
83
- throw await this.#handleError(response);
84
- }
85
-
86
- const data = await response.json();
87
- return this.#unwrapResponse(data);
88
- } catch (error) {
89
- this.#logger.error(`HTTP GET ${path} failed:`, error.message);
90
- throw error;
91
- }
92
- }
93
-
94
- /**
95
- * Make POST request
96
- * @param {string} path - API path
97
- * @param {Object} body - Request body
98
- * @param {Object} options - Request options
99
- * @returns {Promise<Object>}
100
- */
101
- async post(path, body, options = {}) {
102
- const url = this.#buildUrl(path);
103
- const headers = {
104
- ...this.#buildHeaders(options),
105
- 'Content-Type': 'application/json',
106
- };
107
-
108
- try {
109
- const response = await fetchWithTimeout(
110
- url,
111
- {
112
- method: 'POST',
113
- headers,
114
- body: JSON.stringify(body),
115
- },
116
- this.#timeout
117
- );
118
-
119
- if (!response.ok) {
120
- throw await this.#handleError(response);
121
- }
122
-
123
- const data = await response.json();
124
- return this.#unwrapResponse(data);
125
- } catch (error) {
126
- this.#logger.error(`HTTP POST ${path} failed:`, error.message);
127
- throw error;
128
- }
129
- }
130
-
131
- /**
132
- * Build full URL with query parameters
133
- * @param {string} path - API path
134
- * @param {Object} [query] - Query parameters
135
- * @returns {string}
136
- * @private
137
- */
138
- #buildUrl(path, query) {
139
- // Remove leading slash from path if present
140
- const cleanPath = path.startsWith('/') ? path.substring(1) : path;
141
- const url = new URL(cleanPath, this.#baseURL);
142
-
143
- if (query) {
144
- Object.entries(query).forEach(([key, value]) => {
145
- if (value !== undefined && value !== null) {
146
- url.searchParams.append(key, value);
147
- }
148
- });
149
- }
150
-
151
- return url.toString();
152
- }
153
-
154
- /**
155
- * Build request headers
156
- * @param {Object} options - Options
157
- * @returns {Object}
158
- * @private
159
- */
160
- #buildHeaders(options = {}) {
161
- const headers = {
162
- Accept: 'application/json',
163
- };
164
-
165
- // Add language header
166
- const locale = options.locale || this.#locale;
167
- if (locale) {
168
- headers.Language = locale;
169
- }
170
-
171
- // Add platform header if provided
172
- if (options.platform) {
173
- const normalizedPlatform = PLATFORMS[options.platform.toLowerCase()] || options.platform;
174
- headers.Platform = normalizedPlatform;
175
- }
176
-
177
- // Add authorization header if provided
178
- if (options.token) {
179
- headers.Authorization = `Bearer ${options.token}`;
180
- }
181
-
182
- // Add custom headers
183
- if (options.headers) {
184
- Object.assign(headers, options.headers);
185
- }
186
-
187
- return headers;
188
- }
189
-
190
- /**
191
- * Handle HTTP error response
192
- * @param {Response} response - Response object
193
- * @returns {Promise<Error>}
194
- * @private
195
- */
196
- async #handleError(response) {
197
- let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
198
-
199
- try {
200
- const data = await response.json();
201
- if (data.error && data.error.message) {
202
- errorMessage = data.error.message;
203
- }
204
- } catch {
205
- // If JSON parsing fails, use default error message
206
- }
207
-
208
- const error = new Error(errorMessage);
209
- error.status = response.status;
210
- error.statusText = response.statusText;
211
- return error;
212
- }
213
-
214
- /**
215
- * Unwrap API response
216
- * @param {Object} data - Response data
217
- * @returns {*}
218
- * @private
219
- */
220
- #unwrapResponse(data) {
221
- // v2 API wraps responses in { apiVersion, data, error }
222
- if (data.error) {
223
- const error = new Error(data.error.message || 'API Error');
224
- error.code = data.error.code;
225
- throw error;
226
- }
227
-
228
- return data.data;
229
- }
230
-
231
- /**
232
- * Set default locale
233
- * @param {string} locale - Language code
234
- */
235
- setLocale(locale) {
236
- this.#locale = normalizeLanguage(locale);
237
- }
238
-
239
- /**
240
- * Set timeout
241
- * @param {number} timeout - Timeout in milliseconds
242
- */
243
- setTimeout(timeout) {
244
- this.#timeout = timeout;
245
- }
246
- }
@@ -1,40 +0,0 @@
1
- /**
2
- * i18n helper utilities
3
- */
4
-
5
- import { LANGUAGES } from '../constants.js';
6
-
7
- /**
8
- * Normalize language code
9
- * @param {string} lang - Language code
10
- * @returns {string} Normalized language code
11
- */
12
- export function normalizeLanguage(lang) {
13
- if (!lang) return 'en';
14
- const normalized = lang.toLowerCase().trim();
15
- return LANGUAGES[normalized] || 'en';
16
- }
17
-
18
- /**
19
- * Extract localized data from i18n object
20
- * @param {Object} i18n - i18n object
21
- * @param {string} locale - Preferred locale
22
- * @returns {Object} Localized data
23
- */
24
- export function extractLocalized(i18n, locale = 'en') {
25
- if (!i18n) return {};
26
- return i18n[locale] || i18n.en || {};
27
- }
28
-
29
- /**
30
- * Get field from i18n object with fallback
31
- * @param {Object} i18n - i18n object
32
- * @param {string} field - Field name
33
- * @param {string} locale - Preferred locale
34
- * @param {*} defaultValue - Default value if not found
35
- * @returns {*}
36
- */
37
- export function getLocalizedField(i18n, field, locale = 'en', defaultValue = null) {
38
- const localized = extractLocalized(i18n, locale);
39
- return localized[field] ?? defaultValue;
40
- }