odesli.js 1.1.1 → 1.3.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.
package/lib/index.js CHANGED
@@ -1,390 +1,1274 @@
1
- const fetch = require('node-fetch')
2
-
3
- /**
4
- * Simple in-memory cache for API responses
5
- * @private
6
- */
7
- const cache = new Map()
8
- const CACHE_TTL = 5 * 60 * 1000 // 5 minutes
9
-
10
- /**
11
- * Clear expired cache entries
12
- * @private
13
- */
14
- function clearExpiredCache () {
15
- const now = Date.now()
16
- for (const [key, value] of cache.entries()) {
17
- if (now - value.timestamp > CACHE_TTL) {
18
- cache.delete(key)
19
- }
20
- }
21
- }
22
-
23
- /**
24
- * Get cached response if available and not expired
25
- * @param {string} key - Cache key
26
- * @returns {Object|null} Cached response or null if not found/expired
27
- * @private
28
- */
29
- function getCachedResponse (key) {
30
- clearExpiredCache()
31
- const cached = cache.get(key)
32
- if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
33
- return cached.data
34
- }
35
- return null
36
- }
37
-
38
- /**
39
- * Cache a response
40
- * @param {string} key - Cache key
41
- * @param {Object} data - Response data to cache
42
- * @private
43
- */
44
- function cacheResponse (key, data) {
45
- cache.set(key, {
46
- data,
47
- timestamp: Date.now()
48
- })
49
- }
50
-
51
- /**
52
- * Odesli API Client
53
- *
54
- * A Node.js client for the Odesli API (formerly song.link/album.link) that helps you find links to music across multiple streaming platforms.
55
- *
56
- * @example
57
- * ```javascript
58
- * const Odesli = require('odesli.js');
59
- *
60
- * // Initialize without API key (10 requests/minute limit)
61
- * const odesli = new Odesli();
62
- *
63
- * // Or with API key for higher limits
64
- * const odesli = new Odesli({
65
- * apiKey: 'your-api-key-here',
66
- * version: 'v1-alpha.1'
67
- * });
68
- *
69
- * // Fetch a song by URL
70
- * const song = await odesli.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR');
71
- * console.log(`${song.title} by ${song.artist[0]}`);
72
- * ```
73
- */
74
- module.exports = class Odesli {
75
- /**
76
- * Create a new Odesli instance
77
- *
78
- * @param {Object} options - Configuration options
79
- * @param {string} [options.apiKey] - Optional API key for higher rate limits (10+ requests/minute). Without an API key, you're limited to 10 requests per minute.
80
- * @param {string} [options.version='v1-alpha.1'] - API version to use
81
- * @param {boolean} [options.cache=true] - Enable response caching (5 minute TTL)
82
- * @param {number} [options.timeout=10000] - Request timeout in milliseconds
83
- *
84
- * @example
85
- * ```javascript
86
- * // Basic usage without API key
87
- * const odesli = new Odesli();
88
- *
89
- * // With API key for higher limits
90
- * const odesli = new Odesli({
91
- * apiKey: 'your-api-key-here',
92
- * version: 'v1-alpha.1',
93
- * cache: true,
94
- * timeout: 10000
95
- * });
96
- * ```
97
- */
98
- constructor (options = {}) {
99
- const { apiKey = undefined, version = 'v1-alpha.1', cache = true, timeout = 10000 } = options || {}
100
- this.apiKey = apiKey || undefined
101
- this.version = version || 'v1-alpha.1'
102
- this.cacheEnabled = cache
103
- this.timeout = timeout
104
- }
105
-
106
- /**
107
- * Make a request to the Odesli API with caching and timeout support
108
- *
109
- * @param {string} path - API endpoint path
110
- * @returns {Promise<Object>} API response
111
- * @private
112
- */
113
- async _request (path) {
114
- const url = `https://api.song.link/${this.version}/${path}${this.apiKey !== undefined ? `&key=${this.apiKey}` : ''}`
115
-
116
- // Check cache first if enabled
117
- if (this.cacheEnabled) {
118
- const cached = getCachedResponse(url)
119
- if (cached) {
120
- return cached
121
- }
122
- }
123
-
124
- try {
125
- // Create AbortController for timeout
126
- const controller = new AbortController()
127
- const timeoutId = setTimeout(() => controller.abort(), this.timeout)
128
-
129
- const response = await fetch(url, {
130
- signal: controller.signal,
131
- headers: {
132
- 'User-Agent': 'odesli.js/1.0.3',
133
- Accept: 'application/json'
134
- }
135
- })
136
-
137
- clearTimeout(timeoutId)
138
-
139
- if (!response.ok) {
140
- throw new Error(`HTTP ${response.status}: ${response.statusText}`)
141
- }
142
-
143
- const result = await response.json()
144
-
145
- // Handle errors
146
- if (result.statusCode) {
147
- // Codes in the `4xx` range indicate an error that failed given the information provided
148
- if (result.statusCode === 429) throw new Error(`${result.statusCode}: ${result.code}, You are being rate limited, No API Key is 10 Requests / Minute.`)
149
- // Codes in the `4xx` range indicate an error that failed given the information provided
150
- if (result.statusCode.toString().startsWith(4)) throw new Error(`${result.statusCode}: ${result.code}, Codes in the 4xx range indicate an error that failed given the information provided.`)
151
- // Codes in the 5xx range indicate an error with Songlink's servers.
152
- if (result.statusCode.toString().startsWith(5)) throw new Error(`${result.statusCode}: ${result.code}, Codes in the 5xx range indicate an error with Songlink's servers.`)
153
- // Otherwise if the code is not 200 (Success), throw a generic error.
154
- if (result.statusCode !== 200) throw new Error(`${result.statusCode}: ${result.code}`)
155
- // return undefined as we didn't find anything.
156
- return undefined
157
- }
158
-
159
- // Cache successful responses
160
- if (this.cacheEnabled && result) {
161
- cacheResponse(url, result)
162
- }
163
-
164
- return result
165
- } catch (err) {
166
- if (err.name === 'AbortError') {
167
- throw new Error(`Request timeout after ${this.timeout}ms`)
168
- }
169
- if (err.message === 'Unexpected token < in JSON at position 0') {
170
- throw new Error('API returned an unexpected result.')
171
- }
172
- throw err
173
- }
174
- }
175
-
176
- /**
177
- * Clear the response cache
178
- *
179
- * @example
180
- * ```javascript
181
- * const odesli = new Odesli();
182
- * odesli.clearCache(); // Clear all cached responses
183
- * ```
184
- */
185
- clearCache () {
186
- cache.clear()
187
- }
188
-
189
- /**
190
- * Get cache statistics
191
- *
192
- * @returns {Object} Cache statistics
193
- * @example
194
- * ```javascript
195
- * const odesli = new Odesli();
196
- * const stats = odesli.getCacheStats();
197
- * console.log(`Cache size: ${stats.size}, Hit rate: ${stats.hitRate}%`);
198
- * ```
199
- */
200
- getCacheStats () {
201
- clearExpiredCache()
202
- return {
203
- size: cache.size,
204
- ttl: CACHE_TTL
205
- }
206
- }
207
-
208
- /**
209
- * Fetch song/album information by URL from any supported streaming platform
210
- *
211
- * @param {string} url - URL from any supported streaming platform (Spotify, Apple Music, YouTube, etc.)
212
- * @param {string} [country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results
213
- * @returns {Promise<Object>} Song/album information with links to all available platforms
214
- *
215
- * @example
216
- * ```javascript
217
- * // Fetch a song by Spotify URL
218
- * const song = await odesli.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR');
219
- * console.log(`${song.title} by ${song.artist[0]}`);
220
- *
221
- * // Fetch with custom country
222
- * const song = await odesli.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR', 'GB');
223
- *
224
- * // Get all available platform links
225
- * Object.keys(song.linksByPlatform).forEach(platform => {
226
- * console.log(`${platform}: ${song.linksByPlatform[platform].url}`);
227
- * });
228
- * ```
229
- *
230
- * @throws {Error} When no URL is provided
231
- * @throws {Error} When API returns an error (rate limiting, invalid URL, etc.)
232
- */
233
- async fetch (url, country = 'US') {
234
- if (!url) throw new Error('No URL was provided to odesli.fetch()')
235
- const path = `links?url=${encodeURIComponent(url)}&userCountry=${country}`
236
- const song = await this._request(path)
237
-
238
- // Handle edge cases where response is malformed
239
- if (!song || !song.entityUniqueId || !song.entitiesByUniqueId || !song.entitiesByUniqueId[song.entityUniqueId]) {
240
- return song || {}
241
- }
242
-
243
- const id = song.entitiesByUniqueId[song.entityUniqueId].id
244
- const title = song.entitiesByUniqueId[song.entityUniqueId].title
245
-
246
- // Convert Artist into Array for easier extraction of features
247
- Object.values(song.entitiesByUniqueId).forEach(function (values) {
248
- if (values.artistName && typeof values.artistName === 'string') {
249
- values.artistName = values.artistName.split(', ')
250
- }
251
- })
252
-
253
- const artist = song.entitiesByUniqueId[song.entityUniqueId].artistName
254
- const type = song.entitiesByUniqueId[song.entityUniqueId].type
255
- const thumbnail = song.entitiesByUniqueId[song.entityUniqueId].thumbnailUrl
256
-
257
- return {
258
- ...song,
259
- id,
260
- title,
261
- artist,
262
- type,
263
- thumbnail
264
- }
265
- }
266
-
267
- /**
268
- * Fetch song/album information by platform, type, and ID
269
- *
270
- * @param {string} platform - Platform name (spotify, appleMusic, youtube, etc.)
271
- * @param {string} type - Content type ('song' or 'album')
272
- * @param {string} id - Platform-specific ID (can be full format like 'SPOTIFY_SONG::123' or just '123')
273
- * @param {string} [country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results
274
- * @returns {Promise<Object>} Song/album information with links to all available platforms
275
- *
276
- * @example
277
- * ```javascript
278
- * // Get song by Spotify ID
279
- * const song = await odesli.getByParams('spotify', 'song', '4Km5HrUvYTaSUfiSGPJeQR');
280
- * console.log(song.title);
281
- *
282
- * // Get album by Apple Music ID
283
- * const album = await odesli.getByParams('appleMusic', 'album', '123456789');
284
- * console.log(album.title);
285
- *
286
- * // Using full ID format
287
- * const song = await odesli.getByParams('spotify', 'song', 'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR');
288
- * ```
289
- *
290
- * @throws {Error} When platform, type, or ID is not provided
291
- * @throws {Error} When API returns an error
292
- */
293
- async getByParams (platform, type, id, country = 'US') {
294
- if (!platform) throw new Error('No `platform` was provided to odesli.getByParams()')
295
- if (!type) throw new Error('No `type` was provided to odesli.getByParams()')
296
- if (!id) throw new Error('No `id` was provided to odesli.getByParams()')
297
-
298
- // if they happen to input the full id (PLATFORM_SONG::UNIQUEID), just get the UNIQUEID
299
- id = id.replace(/[^::]+::/g, '')
300
- const path = `links?platform=${platform}&type=${type}&id=${id}&userCountry=${country}`
301
- const song = await this._request(path)
302
-
303
- // Handle edge cases where response is malformed
304
- if (!song || !song.entityUniqueId || !song.entitiesByUniqueId || !song.entitiesByUniqueId[song.entityUniqueId]) {
305
- return song || {}
306
- }
307
-
308
- // Convert Artist into Array for easier extraction of features
309
- Object.values(song.entitiesByUniqueId).forEach(function (values) {
310
- if (values.artistName && typeof values.artistName === 'string') {
311
- values.artistName = values.artistName.split(', ')
312
- }
313
- })
314
-
315
- // Easier extraction of page's title, album, and thumbnail
316
- const title = song.entitiesByUniqueId[song.entityUniqueId].title
317
- const artist = song.entitiesByUniqueId[song.entityUniqueId].artistName
318
- const thumbnail = song.entitiesByUniqueId[song.entityUniqueId].thumbnailUrl
319
- const entityType = song.entitiesByUniqueId[song.entityUniqueId].type
320
-
321
- return {
322
- ...song,
323
- title,
324
- artist,
325
- thumbnail,
326
- type: entityType
327
- }
328
- }
329
-
330
- /**
331
- * Fetch song/album information by entity ID
332
- *
333
- * @param {string} id - Full entity ID in format 'PLATFORM_TYPE::UNIQUEID' (e.g., 'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR')
334
- * @param {string} [country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results
335
- * @returns {Promise<Object>} Song/album information with links to all available platforms
336
- *
337
- * @example
338
- * ```javascript
339
- * // Get song by entity ID
340
- * const song = await odesli.getById('SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR');
341
- * console.log(song.title);
342
- *
343
- * // Get album by entity ID
344
- * const album = await odesli.getById('APPLEMUSIC_ALBUM::123456789');
345
- * console.log(album.title);
346
- * ```
347
- *
348
- * @throws {Error} When ID is not provided
349
- * @throws {Error} When ID format is invalid (must match 'PLATFORM_TYPE::UNIQUEID')
350
- * @throws {Error} When API returns an error
351
- */
352
- async getById (id, country = 'US') {
353
- if (!id) throw new Error('No `id` was provided to odesli.getById()')
354
- if (!id.match(/\w+_\w+::\w+/g)) throw new Error('Provided Entity ID Does not match format. `<PLATFORM>_<SONG|ALBUM>::<UNIQUEID>`')
355
-
356
- // Convert string into seperate params
357
- const platform = id.replace(/_\w+::\w+/g, '').toLowerCase()
358
- const type = id.replace(/\w+_/g, '').replace(/::\w+/g, '').toLowerCase()
359
- const unique = id.replace(/\w+::/g, '')
360
-
361
- const path = `links?platform=${platform}&type=${type}&id=${unique}&userCountry=${country}`
362
- const song = await this._request(path)
363
-
364
- // Handle edge cases where response is malformed
365
- if (!song || !song.entityUniqueId || !song.entitiesByUniqueId || !song.entitiesByUniqueId[song.entityUniqueId]) {
366
- return song || {}
367
- }
368
-
369
- // Convert Artist into Array for easier extraction of features
370
- Object.values(song.entitiesByUniqueId).forEach(function (values) {
371
- if (values.artistName && typeof values.artistName === 'string') {
372
- values.artistName = values.artistName.split(', ')
373
- }
374
- })
375
-
376
- // Easier extraction of page's title, album, and thumbnail
377
- const title = song.entitiesByUniqueId[song.entityUniqueId].title
378
- const artist = song.entitiesByUniqueId[song.entityUniqueId].artistName
379
- const thumbnail = song.entitiesByUniqueId[song.entityUniqueId].thumbnailUrl
380
- const entityType = song.entitiesByUniqueId[song.entityUniqueId].type
381
-
382
- return {
383
- ...song,
384
- title,
385
- artist,
386
- thumbnail,
387
- type: entityType
388
- }
389
- }
390
- }
1
+ const fetch = require('node-fetch')
2
+ const { MetricsCollector } = require('./metrics')
3
+
4
+ // Read package version for User-Agent
5
+ const packageJson = require('../package.json')
6
+ const PACKAGE_VERSION = packageJson.version
7
+ const PACKAGE_NAME = packageJson.name
8
+
9
+ // Get Node.js version and platform for User-Agent
10
+ const NODE_VERSION = process.version
11
+ const PLATFORM = process.platform
12
+
13
+ /**
14
+ * Generate User-Agent string
15
+ * @returns {string} User-Agent string
16
+ * @private
17
+ */
18
+ function generateUserAgent () {
19
+ return `${PACKAGE_NAME}/${PACKAGE_VERSION} (Node.js ${NODE_VERSION}; ${PLATFORM})`
20
+ }
21
+
22
+ // Global cache storage
23
+ const cache = new Map()
24
+ const CACHE_TTL = 5 * 60 * 1000 // 5 minutes
25
+
26
+ function clearExpiredCache () {
27
+ const now = Date.now()
28
+ for (const [key, value] of cache.entries()) {
29
+ if (now - value.timestamp > CACHE_TTL) {
30
+ cache.delete(key)
31
+ }
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Get cached response if available and not expired
37
+ * @param {string} key - Cache key
38
+ * @param {MetricsCollector} metrics - Metrics collector instance
39
+ * @returns {Object|null} Cached response or null if not found/expired
40
+ * @private
41
+ */
42
+ function getCachedResponse (key, metrics) {
43
+ clearExpiredCache()
44
+ const cached = cache.get(key)
45
+ if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
46
+ if (metrics) metrics.recordRequest({ cacheHit: true })
47
+ return cached.data
48
+ }
49
+ if (metrics) metrics.recordRequest({ cacheHit: false })
50
+ return null
51
+ }
52
+
53
+ /**
54
+ * Cache a response
55
+ * @param {string} key - Cache key
56
+ * @param {Object} data - Response data to cache
57
+ * @private
58
+ */
59
+ function cacheResponse (key, data) {
60
+ cache.set(key, {
61
+ data,
62
+ timestamp: Date.now()
63
+ })
64
+ }
65
+
66
+ /**
67
+ * Odesli API Client
68
+ *
69
+ * A Node.js client for the Odesli API (formerly song.link/album.link) that helps you find links to music across multiple streaming platforms.
70
+ *
71
+ * @example
72
+ * ```javascript
73
+ * const Odesli = require('odesli.js');
74
+ *
75
+ * // Initialize without API key (10 requests/minute limit)
76
+ * const odesli = new Odesli();
77
+ *
78
+ * // Or with API key for higher limits
79
+ * const odesli = new Odesli({
80
+ * apiKey: 'your-api-key-here',
81
+ * version: 'v1-alpha.1'
82
+ * });
83
+ *
84
+ * // Fetch a song by URL
85
+ * const song = await odesli.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR');
86
+ * console.log(`${song.title} by ${song.artist[0]}`);
87
+ * ```
88
+ */
89
+ module.exports = class Odesli {
90
+ /**
91
+ * Create a new Odesli instance
92
+ *
93
+ * @param {Object} options - Configuration options
94
+ * @param {string} [options.apiKey] - Optional API key for higher rate limits (10+ requests/minute). Without an API key, you're limited to 10 requests per minute.
95
+ * @param {string} [options.version='v1-alpha.1'] - API version to use
96
+ * @param {boolean} [options.cache=true] - Enable response caching (5 minute TTL)
97
+ * @param {number} [options.timeout=10000] - Request timeout in milliseconds
98
+ * @param {number} [options.maxRetries=3] - Maximum number of retry attempts for failed requests
99
+ * @param {number} [options.retryDelay=1000] - Base delay between retries in milliseconds (uses exponential backoff)
100
+ * @param {Object} [options.headers={}] - Additional headers to include in requests
101
+ * @param {string} [options.baseUrl='https://api.song.link'] - Base URL for API requests
102
+ * @param {boolean} [options.validateParams=true] - Enable parameter validation
103
+ * @param {Function} [options.logger] - Optional logger function for debugging
104
+ * @param {MetricsCollector|boolean} [options.metrics] - Optional metrics collector instance or `false` to disable
105
+ *
106
+ * @example
107
+ * ```javascript
108
+ * // Basic usage without API key
109
+ * const odesli = new Odesli();
110
+ *
111
+ * // With API key for higher limits
112
+ * const odesli = new Odesli({
113
+ * apiKey: 'your-api-key-here',
114
+ * version: 'v1-alpha.1',
115
+ * cache: true,
116
+ * timeout: 10000,
117
+ * maxRetries: 3,
118
+ * retryDelay: 1000,
119
+ * headers: { 'User-Agent': 'MyApp/1.0' },
120
+ * validateParams: true
121
+ * });
122
+ *
123
+ * // Disable metrics
124
+ * const odesli = new Odesli({ metrics: false });
125
+ * ```
126
+ */
127
+ constructor (options = {}) {
128
+ const {
129
+ apiKey = undefined,
130
+ version = 'v1-alpha.1',
131
+ cache = true,
132
+ timeout = 10000,
133
+ maxRetries = 3,
134
+ retryDelay = 1000,
135
+ headers = {},
136
+ baseUrl = 'https://api.song.link',
137
+ validateParams = true,
138
+ logger = null,
139
+ metrics
140
+ } = options || {}
141
+
142
+ this.apiKey = apiKey || undefined
143
+ this.version = version || 'v1-alpha.1'
144
+ this.cacheEnabled = cache
145
+ this.timeout = timeout
146
+ this.maxRetries = maxRetries
147
+ this.retryDelay = retryDelay
148
+ this.customHeaders = headers
149
+ this.baseUrl = baseUrl
150
+ this.validateParams = validateParams
151
+ this.logger = logger
152
+
153
+ if (metrics === false) {
154
+ this.metrics = new MetricsCollector({ enabled: false })
155
+ } else {
156
+ this.metrics = metrics || new MetricsCollector()
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Validate URL format
162
+ * @param {string} url - URL to validate
163
+ * @returns {boolean} True if valid URL
164
+ * @private
165
+ */
166
+ _validateUrl (url) {
167
+ if (!this.validateParams) return true
168
+ try {
169
+ const urlObj = new URL(url)
170
+ return urlObj.href.length > 0
171
+ } catch {
172
+ return false
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Validate country code format
178
+ * @param {string} country - Country code to validate
179
+ * @returns {boolean} True if valid ISO 3166-1 Alpha-2 code
180
+ * @private
181
+ */
182
+ _validateCountry (country) {
183
+ if (!this.validateParams) return true
184
+ return /^[A-Z]{2}$/.test(country)
185
+ }
186
+
187
+ /**
188
+ * Validate platform name
189
+ * @param {string} platform - Platform to validate
190
+ * @returns {boolean} True if valid platform
191
+ * @private
192
+ */
193
+ _validatePlatform (platform) {
194
+ if (!this.validateParams) return true
195
+ const validPlatforms = [
196
+ 'spotify', 'itunes', 'appleMusic', 'youtube', 'youtubeMusic',
197
+ 'google', 'googleStore', 'pandora', 'deezer', 'tidal',
198
+ 'amazonStore', 'amazonMusic', 'soundcloud', 'napster', 'yandex', 'spinrilla'
199
+ ]
200
+ return validPlatforms.includes(platform.toLowerCase())
201
+ }
202
+
203
+ /**
204
+ * Validate entity type
205
+ * @param {string} type - Type to validate
206
+ * @returns {boolean} True if valid type
207
+ * @private
208
+ */
209
+ _validateType (type) {
210
+ if (!this.validateParams) return true
211
+ return ['song', 'album'].includes(type.toLowerCase())
212
+ }
213
+
214
+ /**
215
+ * Log message if logger is configured
216
+ * @param {string} message - Message to log
217
+ * @param {string} level - Log level (debug, info, warn, error)
218
+ * @private
219
+ */
220
+ _log (message, level = 'info') {
221
+ if (this.logger && typeof this.logger === 'function') {
222
+ this.logger(message, level)
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Make a request to the Odesli API with caching, timeout, and retry support
228
+ *
229
+ * @param {string} path - API endpoint path
230
+ * @returns {Promise<Object>} API response
231
+ * @private
232
+ */
233
+ async _request (path) {
234
+ const url = `${this.baseUrl}/${this.version}/${path}${this.apiKey !== undefined ? `&key=${this.apiKey}` : ''}`
235
+
236
+ // Check cache first if enabled
237
+ if (this.cacheEnabled) {
238
+ const cached = getCachedResponse(url, this.metrics)
239
+ if (cached) {
240
+ this._log(`Cache hit for ${path}`, 'debug')
241
+ return cached
242
+ }
243
+ }
244
+
245
+ let lastError
246
+ for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
247
+ try {
248
+ this._log(`Request attempt ${attempt}/${this.maxRetries} for ${path}`, 'debug')
249
+
250
+ // Create AbortController for timeout
251
+ const controller = new AbortController()
252
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout)
253
+
254
+ const response = await fetch(url, {
255
+ signal: controller.signal,
256
+ headers: {
257
+ 'User-Agent': generateUserAgent(),
258
+ ...this.customHeaders,
259
+ Accept: 'application/json'
260
+ }
261
+ })
262
+
263
+ clearTimeout(timeoutId)
264
+
265
+ if (!response || !response.ok) {
266
+ if (!response) {
267
+ if (lastError) throw lastError
268
+ throw new Error('API returned an unexpected result.')
269
+ }
270
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`)
271
+ }
272
+
273
+ const result = await response.json()
274
+
275
+ // Handle errors
276
+ if (result.statusCode) {
277
+ // Codes in the `4xx` range indicate an error that failed given the information provided
278
+ if (result.statusCode === 429) throw new Error(`${result.statusCode}: ${result.code}, You are being rate limited, No API Key is 10 Requests / Minute.`)
279
+ // Codes in the `4xx` range indicate an error that failed given the information provided
280
+ if (result.statusCode.toString().startsWith(4)) throw new Error(`${result.statusCode}: ${result.code}, Codes in the 4xx range indicate an error that failed given the information provided.`)
281
+ // Codes in the 5xx range indicate an error with Songlink's servers.
282
+ if (result.statusCode.toString().startsWith(5)) throw new Error(`${result.statusCode}: ${result.code}, Codes in the 5xx range indicate an error with Songlink's servers.`)
283
+ // Otherwise if the code is not 200 (Success), throw a generic error.
284
+ if (result.statusCode !== 200) throw new Error(`${result.statusCode}: ${result.code}`)
285
+ // return undefined as we didn't find anything.
286
+ return undefined
287
+ }
288
+
289
+ // Cache successful responses
290
+ if (this.cacheEnabled && result) {
291
+ cacheResponse(url, result)
292
+ }
293
+
294
+ this._log(`Request successful for ${path}`, 'debug')
295
+ return result
296
+ } catch (err) {
297
+ lastError = err
298
+
299
+ // Don't retry on certain errors
300
+ if (err.message.includes('429') || err.message.includes('4xx') || err.message.includes('5xx')) {
301
+ this._log(`Non-retryable error: ${err.message}`, 'error')
302
+ break
303
+ }
304
+
305
+ if (attempt < this.maxRetries) {
306
+ const delay = this.retryDelay * Math.pow(2, attempt - 1) // Exponential backoff
307
+ this._log(`Request failed, retrying in ${delay}ms: ${err.message}`, 'warn')
308
+ await new Promise(resolve => setTimeout(resolve, delay))
309
+ }
310
+ }
311
+ }
312
+
313
+ // If we get here, all retries failed
314
+ if (lastError.name === 'AbortError') {
315
+ throw new Error(`Request timeout after ${this.timeout}ms`)
316
+ }
317
+ if (lastError.message === 'Unexpected token < in JSON at position 0') {
318
+ throw new Error('API returned an unexpected result.')
319
+ }
320
+ // Preserve original error message for network errors
321
+ throw lastError
322
+ }
323
+
324
+ /**
325
+ * Clear the response cache
326
+ *
327
+ * @example
328
+ * ```javascript
329
+ * const odesli = new Odesli();
330
+ * odesli.clearCache(); // Clear all cached responses
331
+ * ```
332
+ */
333
+ clearCache () {
334
+ cache.clear()
335
+ this.metrics.reset() // Also reset metrics related to cache
336
+ this._log('Cache cleared', 'info')
337
+ }
338
+
339
+ /**
340
+ * Get cache statistics
341
+ *
342
+ * @returns {Object} Cache statistics
343
+ */
344
+ getCacheStats () {
345
+ const summary = this.metrics.getSummary()
346
+ return {
347
+ hitCount: summary.counters.cacheHits,
348
+ missCount: summary.counters.cacheMisses,
349
+ hitRate: summary.rates.cacheHitRate,
350
+ size: cache.size,
351
+ }
352
+ }
353
+
354
+ /**
355
+ * Get the metrics collector instance for more detailed statistics.
356
+ *
357
+ * @returns {MetricsCollector} The metrics collector instance.
358
+ */
359
+ getMetrics () {
360
+ return this.metrics
361
+ }
362
+
363
+ /**
364
+ * Fetch song/album information by URL(s) from any supported streaming platform
365
+ *
366
+ * @param {string|Array<string>} urlOrUrls - URL or array of URLs from any supported streaming platform (Spotify, Apple Music, YouTube, etc.)
367
+ * @param {Object|string} [options] - Options object or country code string (for backward compatibility)
368
+ * @param {string} [options.country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results
369
+ * @param {boolean} [options.skipCache=false] - Skip cache for this request
370
+ * @param {number} [options.timeout] - Override timeout for this request
371
+ * @param {number} [options.concurrency=5] - Maximum concurrent requests (batch only)
372
+ * @returns {Promise<Object>|Promise<Array<Object>>} Song/album information or array of results
373
+ *
374
+ * @example
375
+ * // Single fetch
376
+ * const song = await odesli.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR');
377
+ *
378
+ * // Batch fetch
379
+ * const songs = await odesli.fetch([
380
+ * 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
381
+ * 'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu'
382
+ * ]);
383
+ */
384
+ async fetch (urlOrUrls, options = {}) {
385
+ if (Array.isArray(urlOrUrls)) {
386
+ // Batch mode
387
+ const urls = urlOrUrls
388
+ if (urls.length === 0) {
389
+ return []
390
+ }
391
+
392
+ const { concurrency = 5, ...requestOptions } = options
393
+
394
+ const results = []
395
+ const chunks = []
396
+
397
+ // Split URLs into chunks for concurrency control
398
+ for (let i = 0; i < urls.length; i += concurrency) {
399
+ chunks.push(urls.slice(i, i + concurrency))
400
+ }
401
+
402
+ for (const chunk of chunks) {
403
+ const chunkPromises = chunk.map(async (url, _index) => {
404
+ try {
405
+ const result = await this.fetch(url, requestOptions)
406
+ // Add success property to successful responses
407
+ return { ...result, success: true }
408
+ } catch (error) {
409
+ // Enhanced error object with more context
410
+ const errorInfo = {
411
+ success: false,
412
+ url,
413
+ error: error.message,
414
+ platform: this.detectPlatform(url),
415
+ extractedId: this.extractId(url),
416
+ timestamp: new Date().toISOString(),
417
+ statusCode: this._extractStatusCode(error.message),
418
+ retryable: this._isRetryableError(error.message)
419
+ }
420
+
421
+ // Add additional context based on error type
422
+ if (error.message.includes('400')) {
423
+ errorInfo.errorType = 'BAD_REQUEST'
424
+ errorInfo.suggestion = 'Check if the URL is valid and accessible'
425
+ } else if (error.message.includes('401')) {
426
+ errorInfo.errorType = 'UNAUTHORIZED'
427
+ errorInfo.suggestion = 'API key may be required or invalid'
428
+ } else if (error.message.includes('429')) {
429
+ errorInfo.errorType = 'RATE_LIMITED'
430
+ errorInfo.suggestion = 'Rate limit exceeded, try again later'
431
+ } else if (error.message.includes('404')) {
432
+ errorInfo.errorType = 'NOT_FOUND'
433
+ errorInfo.suggestion = 'Content may not be available in the specified region'
434
+ } else if (error.message.includes('timeout')) {
435
+ errorInfo.errorType = 'TIMEOUT'
436
+ errorInfo.suggestion = 'Request timed out, try again'
437
+ } else {
438
+ errorInfo.errorType = 'UNKNOWN'
439
+ errorInfo.suggestion = 'An unexpected error occurred'
440
+ }
441
+
442
+ return errorInfo
443
+ }
444
+ })
445
+
446
+ const chunkResults = await Promise.all(chunkPromises)
447
+ results.push(...chunkResults)
448
+ }
449
+
450
+ return results
451
+ }
452
+ const url = urlOrUrls
453
+ if (!url) throw new Error('No URL was provided to odesli.fetch()')
454
+
455
+ // Handle backward compatibility: if second parameter is a string, treat it as country
456
+ let country = 'US'
457
+ let skipCache = false
458
+ let timeout = this.timeout
459
+
460
+ if (typeof options === 'string') {
461
+ country = options
462
+ } else {
463
+ country = options.country || 'US'
464
+ skipCache = options.skipCache || false
465
+ timeout = options.timeout || this.timeout
466
+ }
467
+
468
+ // Validate parameters
469
+ if (!this._validateUrl(url)) {
470
+ throw new Error('Invalid URL format provided to odesli.fetch()')
471
+ }
472
+
473
+ if (!this._validateCountry(country)) {
474
+ throw new Error('Invalid country code format. Must be ISO 3166-1 Alpha-2 (e.g., "US", "GB")')
475
+ }
476
+
477
+ const path = `links?url=${encodeURIComponent(url)}&userCountry=${country}`
478
+
479
+ // Temporarily override timeout and cache settings if specified
480
+ const originalTimeout = this.timeout
481
+ const originalCacheEnabled = this.cacheEnabled
482
+
483
+ if (timeout !== this.timeout) {
484
+ this.timeout = timeout
485
+ }
486
+
487
+ if (skipCache) {
488
+ this.cacheEnabled = false
489
+ }
490
+
491
+ try {
492
+ const song = await this._request(path)
493
+
494
+ // Handle edge cases where response is malformed
495
+ if (!song || !song.entityUniqueId || !song.entitiesByUniqueId || !song.entitiesByUniqueId[song.entityUniqueId]) {
496
+ return song || {}
497
+ }
498
+
499
+ const id = song.entitiesByUniqueId[song.entityUniqueId].id
500
+ const title = song.entitiesByUniqueId[song.entityUniqueId].title
501
+
502
+ // Convert Artist into Array for easier extraction of features
503
+ Object.values(song.entitiesByUniqueId).forEach(function (values) {
504
+ if (values.artistName && typeof values.artistName === 'string') {
505
+ values.artistName = values.artistName.split(', ')
506
+ }
507
+ })
508
+
509
+ const artist = song.entitiesByUniqueId[song.entityUniqueId].artistName
510
+ const type = song.entitiesByUniqueId[song.entityUniqueId].type
511
+ const thumbnail = song.entitiesByUniqueId[song.entityUniqueId].thumbnailUrl
512
+
513
+ return {
514
+ ...song,
515
+ id,
516
+ title,
517
+ artist,
518
+ type,
519
+ thumbnail
520
+ }
521
+ } finally {
522
+ // Restore original settings
523
+ this.timeout = originalTimeout
524
+ this.cacheEnabled = originalCacheEnabled
525
+ }
526
+ }
527
+
528
+ /**
529
+ * Fetch song/album information by platform, type, and ID
530
+ *
531
+ * @param {string} platform - Platform name (spotify, appleMusic, youtube, etc.)
532
+ * @param {string} type - Content type ('song' or 'album')
533
+ * @param {string} id - Platform-specific ID (can be full format like 'SPOTIFY_SONG::123' or just '123')
534
+ * @param {Object|string} [options] - Options object or country code string (for backward compatibility)
535
+ * @param {string} [options.country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results
536
+ * @param {boolean} [options.skipCache=false] - Skip cache for this request
537
+ * @param {number} [options.timeout] - Override timeout for this request
538
+ * @returns {Promise<Object>} Song/album information with links to all available platforms
539
+ *
540
+ * @example
541
+ * ```javascript
542
+ * // Get song by Spotify ID
543
+ * const song = await odesli.getByParams('spotify', 'song', '4Km5HrUvYTaSUfiSGPJeQR');
544
+ * console.log(song.title);
545
+ *
546
+ * // Get album by Apple Music ID (backward compatible)
547
+ * const album = await odesli.getByParams('appleMusic', 'album', '123456789', 'GB');
548
+ *
549
+ * // Using full ID format with options
550
+ * const song = await odesli.getByParams('spotify', 'song', 'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR', {
551
+ * country: 'GB',
552
+ * skipCache: true,
553
+ * timeout: 5000
554
+ * });
555
+ * ```
556
+ *
557
+ * @throws {Error} When platform, type, or ID is not provided
558
+ * @throws {Error} When platform name is invalid
559
+ * @throws {Error} When type is invalid
560
+ * @throws {Error} When country code format is invalid
561
+ * @throws {Error} When API returns an error
562
+ */
563
+ async getByParams (platform, type, id, options = {}) {
564
+ if (!platform) throw new Error('No `platform` was provided to odesli.getByParams()')
565
+ if (!type) throw new Error('No `type` was provided to odesli.getByParams()')
566
+ if (!id) throw new Error('No `id` was provided to odesli.getByParams()')
567
+
568
+ // Handle backward compatibility: if fourth parameter is a string, treat it as country
569
+ let country = 'US'
570
+ let skipCache = false
571
+ let timeout = this.timeout
572
+
573
+ if (typeof options === 'string') {
574
+ country = options
575
+ } else {
576
+ country = options.country || 'US'
577
+ skipCache = options.skipCache || false
578
+ timeout = options.timeout || this.timeout
579
+ }
580
+
581
+ // Validate parameters
582
+ if (!this._validatePlatform(platform)) {
583
+ throw new Error(`Invalid platform "${platform}". Must be one of: spotify, itunes, appleMusic, youtube, youtubeMusic, google, googleStore, pandora, deezer, tidal, amazonStore, amazonMusic, soundcloud, napster, yandex, spinrilla`)
584
+ }
585
+
586
+ if (!this._validateType(type)) {
587
+ throw new Error(`Invalid type "${type}". Must be "song" or "album"`)
588
+ }
589
+
590
+ if (!this._validateCountry(country)) {
591
+ throw new Error('Invalid country code format. Must be ISO 3166-1 Alpha-2 (e.g., "US", "GB")')
592
+ }
593
+
594
+ // if they happen to input the full id (PLATFORM_SONG::UNIQUEID), just get the UNIQUEID
595
+ id = id.replace(/[^::]+::/g, '')
596
+ const path = `links?platform=${platform}&type=${type}&id=${id}&userCountry=${country}`
597
+
598
+ // Temporarily override timeout and cache settings if specified
599
+ const originalTimeout = this.timeout
600
+ const originalCacheEnabled = this.cacheEnabled
601
+
602
+ if (timeout !== this.timeout) {
603
+ this.timeout = timeout
604
+ }
605
+
606
+ if (skipCache) {
607
+ this.cacheEnabled = false
608
+ }
609
+
610
+ try {
611
+ const song = await this._request(path)
612
+
613
+ // Handle edge cases where response is malformed
614
+ if (!song || !song.entityUniqueId || !song.entitiesByUniqueId || !song.entitiesByUniqueId[song.entityUniqueId]) {
615
+ return song || {}
616
+ }
617
+
618
+ // Convert Artist into Array for easier extraction of features
619
+ Object.values(song.entitiesByUniqueId).forEach(function (values) {
620
+ if (values.artistName && typeof values.artistName === 'string') {
621
+ values.artistName = values.artistName.split(', ')
622
+ }
623
+ })
624
+
625
+ // Easier extraction of page's title, album, and thumbnail
626
+ const title = song.entitiesByUniqueId[song.entityUniqueId].title
627
+ const artist = song.entitiesByUniqueId[song.entityUniqueId].artistName
628
+ const thumbnail = song.entitiesByUniqueId[song.entityUniqueId].thumbnailUrl
629
+ const entityType = song.entitiesByUniqueId[song.entityUniqueId].type
630
+
631
+ return {
632
+ ...song,
633
+ title,
634
+ artist,
635
+ thumbnail,
636
+ type: entityType
637
+ }
638
+ } finally {
639
+ // Restore original settings
640
+ this.timeout = originalTimeout
641
+ this.cacheEnabled = originalCacheEnabled
642
+ }
643
+ }
644
+
645
+ /**
646
+ * Fetch song/album information by entity ID
647
+ *
648
+ * @param {string} id - Full entity ID in format 'PLATFORM_TYPE::UNIQUEID' (e.g., 'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR')
649
+ * @param {Object|string} [options] - Options object or country code string (for backward compatibility)
650
+ * @param {string} [options.country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results
651
+ * @param {boolean} [options.skipCache=false] - Skip cache for this request
652
+ * @param {number} [options.timeout] - Override timeout for this request
653
+ * @returns {Promise<Object>} Song/album information with links to all available platforms
654
+ *
655
+ * @example
656
+ * ```javascript
657
+ * // Get song by entity ID
658
+ * const song = await odesli.getById('SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR');
659
+ * console.log(song.title);
660
+ *
661
+ * // Get album by entity ID (backward compatible)
662
+ * const album = await odesli.getById('APPLEMUSIC_ALBUM::123456789', 'GB');
663
+ *
664
+ * // Get song by entity ID with options
665
+ * const song = await odesli.getById('SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR', {
666
+ * country: 'GB',
667
+ * skipCache: true,
668
+ * timeout: 5000
669
+ * });
670
+ * ```
671
+ *
672
+ * @throws {Error} When ID is not provided
673
+ * @throws {Error} When ID format is invalid (must match 'PLATFORM_TYPE::UNIQUEID')
674
+ * @throws {Error} When country code format is invalid
675
+ * @throws {Error} When API returns an error
676
+ */
677
+ async getById (id, options = {}) {
678
+ if (!id) throw new Error('No `id` was provided to odesli.getById()')
679
+ if (!id.match(/\w+_\w+::\w+/g)) throw new Error('Provided Entity ID Does not match format. `<PLATFORM>_<SONG|ALBUM>::<UNIQUEID>`')
680
+
681
+ // Handle backward compatibility: if second parameter is a string, treat it as country
682
+ let country = 'US'
683
+ let skipCache = false
684
+ let timeout = this.timeout
685
+
686
+ if (typeof options === 'string') {
687
+ country = options
688
+ } else {
689
+ country = options.country || 'US'
690
+ skipCache = options.skipCache || false
691
+ timeout = options.timeout || this.timeout
692
+ }
693
+
694
+ // Validate country code
695
+ if (!this._validateCountry(country)) {
696
+ throw new Error('Invalid country code format. Must be ISO 3166-1 Alpha-2 (e.g., "US", "GB")')
697
+ }
698
+
699
+ // Convert string into seperate params
700
+ const platform = id.replace(/_\w+::\w+/g, '').toLowerCase()
701
+ const type = id.replace(/\w+_/g, '').replace(/::\w+/g, '').toLowerCase()
702
+ const unique = id.replace(/\w+::/g, '')
703
+
704
+ const path = `links?platform=${platform}&type=${type}&id=${unique}&userCountry=${country}`
705
+
706
+ // Temporarily override timeout and cache settings if specified
707
+ const originalTimeout = this.timeout
708
+ const originalCacheEnabled = this.cacheEnabled
709
+
710
+ if (timeout !== this.timeout) {
711
+ this.timeout = timeout
712
+ }
713
+
714
+ if (skipCache) {
715
+ this.cacheEnabled = false
716
+ }
717
+
718
+ try {
719
+ const song = await this._request(path)
720
+
721
+ // Handle edge cases where response is malformed
722
+ if (!song || !song.entityUniqueId || !song.entitiesByUniqueId || !song.entitiesByUniqueId[song.entityUniqueId]) {
723
+ return song || {}
724
+ }
725
+
726
+ // Convert Artist into Array for easier extraction of features
727
+ Object.values(song.entitiesByUniqueId).forEach(function (values) {
728
+ if (values.artistName && typeof values.artistName === 'string') {
729
+ values.artistName = values.artistName.split(', ')
730
+ }
731
+ })
732
+
733
+ // Easier extraction of page's title, album, and thumbnail
734
+ const title = song.entitiesByUniqueId[song.entityUniqueId].title
735
+ const artist = song.entitiesByUniqueId[song.entityUniqueId].artistName
736
+ const thumbnail = song.entitiesByUniqueId[song.entityUniqueId].thumbnailUrl
737
+ const entityType = song.entitiesByUniqueId[song.entityUniqueId].type
738
+
739
+ return {
740
+ ...song,
741
+ title,
742
+ artist,
743
+ thumbnail,
744
+ type: entityType
745
+ }
746
+ } finally {
747
+ // Restore original settings
748
+ this.timeout = originalTimeout
749
+ this.cacheEnabled = originalCacheEnabled
750
+ }
751
+ }
752
+
753
+ /**
754
+ * Fetch multiple URLs in batches with enhanced error handling
755
+ *
756
+ * @param {Array<string>} urls - Array of URLs to fetch
757
+ * @param {Object} options - Batch options
758
+ * @param {number} [options.concurrency=5] - Maximum concurrent requests
759
+ * @param {string} [options.country='US'] - Country code for all requests
760
+ * @param {boolean} [options.skipCache=false] - Skip cache for all requests
761
+ * @param {number} [options.timeout] - Timeout for all requests
762
+ * @returns {Promise<Array<Object>>} Array of results with enhanced error information
763
+ *
764
+ * @example
765
+ * ```javascript
766
+ * const results = await odesli.fetchBatch([
767
+ * 'https://open.spotify.com/track/123',
768
+ * 'https://music.apple.com/us/album/test/456?i=789'
769
+ * ], { concurrency: 3, country: 'GB' });
770
+ *
771
+ * results.forEach((result, index) => {
772
+ * if (result.success) {
773
+ * console.log(`Song ${index + 1}: ${result.title}`);
774
+ * } else {
775
+ * console.log(`Song ${index + 1}: Error - ${result.error}`);
776
+ * console.log(` Platform: ${result.platform}`);
777
+ * console.log(` ID: ${result.extractedId || 'Not found'}`);
778
+ * }
779
+ * });
780
+ * ```
781
+ */
782
+ async fetchBatch (urls, options = {}) {
783
+ if (!Array.isArray(urls)) {
784
+ throw new Error('URLs must be an array')
785
+ }
786
+
787
+ if (urls.length === 0) {
788
+ return []
789
+ }
790
+
791
+ const { concurrency = 5, ...requestOptions } = options
792
+
793
+ const results = []
794
+ const chunks = []
795
+
796
+ // Split URLs into chunks for concurrency control
797
+ for (let i = 0; i < urls.length; i += concurrency) {
798
+ chunks.push(urls.slice(i, i + concurrency))
799
+ }
800
+
801
+ for (const chunk of chunks) {
802
+ const chunkPromises = chunk.map(async (url, _index) => {
803
+ try {
804
+ const result = await this.fetch(url, requestOptions)
805
+ // Add success property to successful responses
806
+ return { ...result, success: true }
807
+ } catch (error) {
808
+ // Enhanced error object with more context
809
+ const errorInfo = {
810
+ success: false,
811
+ url,
812
+ error: error.message,
813
+ platform: this.detectPlatform(url),
814
+ extractedId: this.extractId(url),
815
+ timestamp: new Date().toISOString(),
816
+ statusCode: this._extractStatusCode(error.message),
817
+ retryable: this._isRetryableError(error.message)
818
+ }
819
+
820
+ // Add additional context based on error type
821
+ if (error.message.includes('400')) {
822
+ errorInfo.errorType = 'BAD_REQUEST'
823
+ errorInfo.suggestion = 'Check if the URL is valid and accessible'
824
+ } else if (error.message.includes('401')) {
825
+ errorInfo.errorType = 'UNAUTHORIZED'
826
+ errorInfo.suggestion = 'API key may be required or invalid'
827
+ } else if (error.message.includes('429')) {
828
+ errorInfo.errorType = 'RATE_LIMITED'
829
+ errorInfo.suggestion = 'Rate limit exceeded, try again later'
830
+ } else if (error.message.includes('404')) {
831
+ errorInfo.errorType = 'NOT_FOUND'
832
+ errorInfo.suggestion = 'Content may not be available in the specified region'
833
+ } else if (error.message.includes('timeout')) {
834
+ errorInfo.errorType = 'TIMEOUT'
835
+ errorInfo.suggestion = 'Request timed out, try again'
836
+ } else {
837
+ errorInfo.errorType = 'UNKNOWN'
838
+ errorInfo.suggestion = 'An unexpected error occurred'
839
+ }
840
+
841
+ return errorInfo
842
+ }
843
+ })
844
+
845
+ const chunkResults = await Promise.all(chunkPromises)
846
+ results.push(...chunkResults)
847
+ }
848
+
849
+ return results
850
+ }
851
+
852
+ /**
853
+ * Extract status code from error message
854
+ * @private
855
+ */
856
+ _extractStatusCode(errorMessage) {
857
+ const match = errorMessage.match(/(\d{3}):/)
858
+ return match ? parseInt(match[1]) : null
859
+ }
860
+
861
+ /**
862
+ * Determine if an error is retryable
863
+ * @private
864
+ */
865
+ _isRetryableError(errorMessage) {
866
+ const retryableStatusCodes = [408, 429, 500, 502, 503, 504]
867
+ const statusCode = this._extractStatusCode(errorMessage)
868
+ return statusCode ? retryableStatusCodes.includes(statusCode) : false
869
+ }
870
+
871
+ /**
872
+ * Detect platform from URL
873
+ *
874
+ * @param {string} url - URL to analyze
875
+ * @returns {string|null} Platform name or null if not recognized
876
+ *
877
+ * @example
878
+ * ```javascript
879
+ * const platform = odesli.detectPlatform('https://open.spotify.com/track/123');
880
+ * console.log(platform); // 'spotify'
881
+ * ```
882
+ */
883
+ detectPlatform (url) {
884
+ if (!url) return null
885
+
886
+ const urlLower = url.toLowerCase()
887
+
888
+ if (urlLower.includes('spotify.com')) return 'spotify'
889
+ if (urlLower.includes('music.apple.com') || urlLower.includes('itunes.apple.com')) return 'appleMusic'
890
+ if (urlLower.includes('youtube.com') || urlLower.includes('youtu.be')) return 'youtube'
891
+ if (urlLower.includes('youtube.com/music') || urlLower.includes('music.youtube.com')) return 'youtubeMusic'
892
+ if (urlLower.includes('tidal.com')) return 'tidal'
893
+ if (urlLower.includes('deezer.com')) return 'deezer'
894
+ if (urlLower.includes('amazon.com/music') || urlLower.includes('music.amazon.com')) return 'amazonMusic'
895
+ if (urlLower.includes('soundcloud.com')) return 'soundcloud'
896
+ if (urlLower.includes('pandora.com')) return 'pandora'
897
+ if (urlLower.includes('napster.com')) return 'napster'
898
+ if (urlLower.includes('yandex.ru/music') || urlLower.includes('music.yandex.ru')) return 'yandex'
899
+ if (urlLower.includes('spinrilla.com')) return 'spinrilla'
900
+
901
+ return null
902
+ }
903
+
904
+ /**
905
+ * Extract platform-specific ID from a URL
906
+ *
907
+ * @param {string} url - URL to extract ID from
908
+ * @returns {string|null} Platform-specific ID or null if not found
909
+ *
910
+ * @example
911
+ * ```javascript
912
+ * const id = odesli.extractId('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR');
913
+ * console.log(id); // '4Km5HrUvYTaSUfiSGPJeQR'
914
+ * ```
915
+ */
916
+ extractId (url) {
917
+ try {
918
+ const urlObj = new URL(url)
919
+ const pathParts = urlObj.pathname.split('/').filter(Boolean)
920
+
921
+ // Spotify
922
+ if (url.includes('open.spotify.com')) {
923
+ return pathParts[pathParts.length - 1]
924
+ }
925
+
926
+ // Apple Music - improved to handle various URL formats
927
+ if (url.includes('music.apple.com') || url.includes('itunes.apple.com')) {
928
+ // Handle album URLs with track IDs: /album/name/id?i=trackId
929
+ const trackIdMatch = url.match(/[?&]i=(\d+)/)
930
+ if (trackIdMatch) {
931
+ return trackIdMatch[1]
932
+ }
933
+
934
+ // Handle direct track URLs: /album/name/id
935
+ const idMatch = url.match(/\/id(\d+)/)
936
+ if (idMatch) {
937
+ return idMatch[1]
938
+ }
939
+
940
+ // Handle other Apple Music URL formats
941
+ const pathIdMatch = url.match(/\/(\d+)(?:\?|$)/)
942
+ if (pathIdMatch) {
943
+ return pathIdMatch[1]
944
+ }
945
+
946
+ return null
947
+ }
948
+
949
+ // YouTube
950
+ if (url.includes('youtube.com') || url.includes('youtu.be')) {
951
+ const videoMatch = url.match(/(?:v=|\/)([a-zA-Z0-9_-]{11})/)
952
+ return videoMatch ? videoMatch[1] : null
953
+ }
954
+
955
+ // Tidal
956
+ if (url.includes('tidal.com')) {
957
+ return pathParts[pathParts.length - 1]
958
+ }
959
+
960
+ // Deezer
961
+ if (url.includes('deezer.com')) {
962
+ return pathParts[pathParts.length - 1]
963
+ }
964
+
965
+ // Amazon Music
966
+ if (url.includes('amazon.com/music') || url.includes('music.amazon.com')) {
967
+ const idMatch = url.match(/\/albums\/([^/]+)/)
968
+ return idMatch ? idMatch[1] : null
969
+ }
970
+
971
+ // SoundCloud
972
+ if (url.includes('soundcloud.com')) {
973
+ return pathParts[pathParts.length - 1]
974
+ }
975
+
976
+ return null
977
+ } catch {
978
+ return null
979
+ }
980
+ }
981
+
982
+ /**
983
+ * Get supported platforms list
984
+ *
985
+ * @returns {Array<string>} Array of supported platform names
986
+ *
987
+ * @example
988
+ * ```javascript
989
+ * const platforms = odesli.getSupportedPlatforms();
990
+ * console.log(platforms); // ['spotify', 'appleMusic', 'youtube', ...]
991
+ * ```
992
+ */
993
+ getSupportedPlatforms () {
994
+ return [
995
+ 'spotify', 'itunes', 'appleMusic', 'youtube', 'youtubeMusic',
996
+ 'google', 'googleStore', 'pandora', 'deezer', 'tidal',
997
+ 'amazonStore', 'amazonMusic', 'soundcloud', 'napster', 'yandex', 'spinrilla'
998
+ ]
999
+ }
1000
+
1001
+ /**
1002
+ * Get the current User-Agent string used for requests
1003
+ *
1004
+ * @returns {string} Current User-Agent string
1005
+ * @example
1006
+ * ```javascript
1007
+ * const odesli = new Odesli();
1008
+ * console.log(odesli.getUserAgent());
1009
+ * // Output: "@mattraus/odesli.js/1.1.2 (Node.js v18.17.0; win32)"
1010
+ * ```
1011
+ */
1012
+ getUserAgent () {
1013
+ return generateUserAgent()
1014
+ }
1015
+
1016
+ /**
1017
+ * Get all valid ISO 3166-1 alpha-2 country codes and names
1018
+ * @returns {Array<{ code: string, name: string }>} Array of country code/name pairs
1019
+ */
1020
+ static getCountryOptions() {
1021
+ // List from the CountryCode enum
1022
+ return [
1023
+ { code: 'AF', name: 'Afghanistan' },
1024
+ { code: 'AX', name: 'Aland Islands' },
1025
+ { code: 'AL', name: 'Albania' },
1026
+ { code: 'DZ', name: 'Algeria' },
1027
+ { code: 'AS', name: 'American Samoa' },
1028
+ { code: 'AD', name: 'Andorra' },
1029
+ { code: 'AO', name: 'Angola' },
1030
+ { code: 'AI', name: 'Anguilla' },
1031
+ { code: 'AQ', name: 'Antarctica' },
1032
+ { code: 'AG', name: 'Antigua and Barbuda' },
1033
+ { code: 'AR', name: 'Argentina' },
1034
+ { code: 'AM', name: 'Armenia' },
1035
+ { code: 'AW', name: 'Aruba' },
1036
+ { code: 'AU', name: 'Australia' },
1037
+ { code: 'AT', name: 'Austria' },
1038
+ { code: 'AZ', name: 'Azerbaijan' },
1039
+ { code: 'BS', name: 'Bahamas' },
1040
+ { code: 'BH', name: 'Bahrain' },
1041
+ { code: 'BD', name: 'Bangladesh' },
1042
+ { code: 'BB', name: 'Barbados' },
1043
+ { code: 'BY', name: 'Belarus' },
1044
+ { code: 'BE', name: 'Belgium' },
1045
+ { code: 'BZ', name: 'Belize' },
1046
+ { code: 'BJ', name: 'Benin' },
1047
+ { code: 'BM', name: 'Bermuda' },
1048
+ { code: 'BT', name: 'Bhutan' },
1049
+ { code: 'BO', name: 'Bolivia' },
1050
+ { code: 'BQ', name: 'Bonaire, Sint Eustatius and Saba' },
1051
+ { code: 'BA', name: 'Bosnia and Herzegovina' },
1052
+ { code: 'BW', name: 'Botswana' },
1053
+ { code: 'BV', name: 'Bouvet Island' },
1054
+ { code: 'BR', name: 'Brazil' },
1055
+ { code: 'IO', name: 'British Indian Ocean Territory' },
1056
+ { code: 'BN', name: 'Brunei Darussalam' },
1057
+ { code: 'BG', name: 'Bulgaria' },
1058
+ { code: 'BF', name: 'Burkina Faso' },
1059
+ { code: 'BI', name: 'Burundi' },
1060
+ { code: 'KH', name: 'Cambodia' },
1061
+ { code: 'CM', name: 'Cameroon' },
1062
+ { code: 'CA', name: 'Canada' },
1063
+ { code: 'CV', name: 'Cape Verde' },
1064
+ { code: 'KY', name: 'Cayman Islands' },
1065
+ { code: 'CF', name: 'Central African Republic' },
1066
+ { code: 'TD', name: 'Chad' },
1067
+ { code: 'CL', name: 'Chile' },
1068
+ { code: 'CN', name: 'China' },
1069
+ { code: 'CX', name: 'Christmas Island' },
1070
+ { code: 'CC', name: 'Cocos (Keeling) Islands' },
1071
+ { code: 'CO', name: 'Colombia' },
1072
+ { code: 'KM', name: 'Comoros' },
1073
+ { code: 'CG', name: 'Congo' },
1074
+ { code: 'CD', name: 'Congo, Democratic Republic' },
1075
+ { code: 'CK', name: 'Cook Islands' },
1076
+ { code: 'CR', name: 'Costa Rica' },
1077
+ { code: 'CI', name: "Cote d'Ivoire" },
1078
+ { code: 'HR', name: 'Croatia' },
1079
+ { code: 'CU', name: 'Cuba' },
1080
+ { code: 'CW', name: 'Curaçao' },
1081
+ { code: 'CY', name: 'Cyprus' },
1082
+ { code: 'CZ', name: 'Czech Republic' },
1083
+ { code: 'DK', name: 'Denmark' },
1084
+ { code: 'DJ', name: 'Djibouti' },
1085
+ { code: 'DM', name: 'Dominica' },
1086
+ { code: 'DO', name: 'Dominican Republic' },
1087
+ { code: 'EC', name: 'Ecuador' },
1088
+ { code: 'EG', name: 'Egypt' },
1089
+ { code: 'SV', name: 'El Salvador' },
1090
+ { code: 'GQ', name: 'Equatorial Guinea' },
1091
+ { code: 'ER', name: 'Eritrea' },
1092
+ { code: 'EE', name: 'Estonia' },
1093
+ { code: 'ET', name: 'Ethiopia' },
1094
+ { code: 'FK', name: 'Falkland Islands' },
1095
+ { code: 'FO', name: 'Faroe Islands' },
1096
+ { code: 'FJ', name: 'Fiji' },
1097
+ { code: 'FI', name: 'Finland' },
1098
+ { code: 'FR', name: 'France' },
1099
+ { code: 'GF', name: 'French Guiana' },
1100
+ { code: 'PF', name: 'French Polynesia' },
1101
+ { code: 'TF', name: 'French Southern Territories' },
1102
+ { code: 'GA', name: 'Gabon' },
1103
+ { code: 'GM', name: 'Gambia' },
1104
+ { code: 'GE', name: 'Georgia' },
1105
+ { code: 'DE', name: 'Germany' },
1106
+ { code: 'GH', name: 'Ghana' },
1107
+ { code: 'GI', name: 'Gibraltar' },
1108
+ { code: 'GR', name: 'Greece' },
1109
+ { code: 'GL', name: 'Greenland' },
1110
+ { code: 'GD', name: 'Grenada' },
1111
+ { code: 'GP', name: 'Guadeloupe' },
1112
+ { code: 'GU', name: 'Guam' },
1113
+ { code: 'GT', name: 'Guatemala' },
1114
+ { code: 'GG', name: 'Guernsey' },
1115
+ { code: 'GN', name: 'Guinea' },
1116
+ { code: 'GW', name: 'Guinea-Bissau' },
1117
+ { code: 'GY', name: 'Guyana' },
1118
+ { code: 'HT', name: 'Haiti' },
1119
+ { code: 'HM', name: 'Heard Island and McDonald Islands' },
1120
+ { code: 'VA', name: 'Holy See (Vatican City State)' },
1121
+ { code: 'HN', name: 'Honduras' },
1122
+ { code: 'HK', name: 'Hong Kong' },
1123
+ { code: 'HU', name: 'Hungary' },
1124
+ { code: 'IS', name: 'Iceland' },
1125
+ { code: 'IN', name: 'India' },
1126
+ { code: 'ID', name: 'Indonesia' },
1127
+ { code: 'IR', name: 'Iran' },
1128
+ { code: 'IQ', name: 'Iraq' },
1129
+ { code: 'IE', name: 'Ireland' },
1130
+ { code: 'IM', name: 'Isle of Man' },
1131
+ { code: 'IL', name: 'Israel' },
1132
+ { code: 'IT', name: 'Italy' },
1133
+ { code: 'JM', name: 'Jamaica' },
1134
+ { code: 'JP', name: 'Japan' },
1135
+ { code: 'JE', name: 'Jersey' },
1136
+ { code: 'JO', name: 'Jordan' },
1137
+ { code: 'KZ', name: 'Kazakhstan' },
1138
+ { code: 'KE', name: 'Kenya' },
1139
+ { code: 'KI', name: 'Kiribati' },
1140
+ { code: 'KR', name: 'Korea' },
1141
+ { code: 'KP', name: 'Korea, Democratic People\'s Republic' },
1142
+ { code: 'KW', name: 'Kuwait' },
1143
+ { code: 'KG', name: 'Kyrgyzstan' },
1144
+ { code: 'LA', name: 'Lao People\'s Democratic Republic' },
1145
+ { code: 'LV', name: 'Latvia' },
1146
+ { code: 'LB', name: 'Lebanon' },
1147
+ { code: 'LS', name: 'Lesotho' },
1148
+ { code: 'LR', name: 'Liberia' },
1149
+ { code: 'LY', name: 'Libyan Arab Jamahiriya' },
1150
+ { code: 'LI', name: 'Liechtenstein' },
1151
+ { code: 'LT', name: 'Lithuania' },
1152
+ { code: 'LU', name: 'Luxembourg' },
1153
+ { code: 'MO', name: 'Macao' },
1154
+ { code: 'MK', name: 'Macedonia' },
1155
+ { code: 'MG', name: 'Madagascar' },
1156
+ { code: 'MW', name: 'Malawi' },
1157
+ { code: 'MY', name: 'Malaysia' },
1158
+ { code: 'MV', name: 'Maldives' },
1159
+ { code: 'ML', name: 'Mali' },
1160
+ { code: 'MT', name: 'Malta' },
1161
+ { code: 'MH', name: 'Marshall Islands' },
1162
+ { code: 'MQ', name: 'Martinique' },
1163
+ { code: 'MR', name: 'Mauritania' },
1164
+ { code: 'MU', name: 'Mauritius' },
1165
+ { code: 'YT', name: 'Mayotte' },
1166
+ { code: 'MX', name: 'Mexico' },
1167
+ { code: 'FM', name: 'Micronesia' },
1168
+ { code: 'MD', name: 'Moldova' },
1169
+ { code: 'MC', name: 'Monaco' },
1170
+ { code: 'MN', name: 'Mongolia' },
1171
+ { code: 'ME', name: 'Montenegro' },
1172
+ { code: 'MS', name: 'Montserrat' },
1173
+ { code: 'MA', name: 'Morocco' },
1174
+ { code: 'MZ', name: 'Mozambique' },
1175
+ { code: 'MM', name: 'Myanmar' },
1176
+ { code: 'NA', name: 'Namibia' },
1177
+ { code: 'NR', name: 'Nauru' },
1178
+ { code: 'NP', name: 'Nepal' },
1179
+ { code: 'NL', name: 'Netherlands' },
1180
+ { code: 'NC', name: 'New Caledonia' },
1181
+ { code: 'NZ', name: 'New Zealand' },
1182
+ { code: 'NI', name: 'Nicaragua' },
1183
+ { code: 'NE', name: 'Niger' },
1184
+ { code: 'NG', name: 'Nigeria' },
1185
+ { code: 'NU', name: 'Niue' },
1186
+ { code: 'NF', name: 'Norfolk Island' },
1187
+ { code: 'MP', name: 'Northern Mariana Islands' },
1188
+ { code: 'NO', name: 'Norway' },
1189
+ { code: 'OM', name: 'Oman' },
1190
+ { code: 'PK', name: 'Pakistan' },
1191
+ { code: 'PW', name: 'Palau' },
1192
+ { code: 'PS', name: 'Palestinian Territory' },
1193
+ { code: 'PA', name: 'Panama' },
1194
+ { code: 'PG', name: 'Papua New Guinea' },
1195
+ { code: 'PY', name: 'Paraguay' },
1196
+ { code: 'PE', name: 'Peru' },
1197
+ { code: 'PH', name: 'Philippines' },
1198
+ { code: 'PN', name: 'Pitcairn' },
1199
+ { code: 'PL', name: 'Poland' },
1200
+ { code: 'PT', name: 'Portugal' },
1201
+ { code: 'PR', name: 'Puerto Rico' },
1202
+ { code: 'QA', name: 'Qatar' },
1203
+ { code: 'RE', name: 'Reunion' },
1204
+ { code: 'RO', name: 'Romania' },
1205
+ { code: 'RU', name: 'Russian Federation' },
1206
+ { code: 'RW', name: 'Rwanda' },
1207
+ { code: 'BL', name: 'Saint Barthelemy' },
1208
+ { code: 'SH', name: 'Saint Helena' },
1209
+ { code: 'KN', name: 'Saint Kitts and Nevis' },
1210
+ { code: 'LC', name: 'Saint Lucia' },
1211
+ { code: 'MF', name: 'Saint Martin' },
1212
+ { code: 'PM', name: 'Saint Pierre and Miquelon' },
1213
+ { code: 'VC', name: 'Saint Vincent and Grenadines' },
1214
+ { code: 'WS', name: 'Samoa' },
1215
+ { code: 'SM', name: 'San Marino' },
1216
+ { code: 'ST', name: 'Sao Tome and Principe' },
1217
+ { code: 'SA', name: 'Saudi Arabia' },
1218
+ { code: 'SN', name: 'Senegal' },
1219
+ { code: 'RS', name: 'Serbia' },
1220
+ { code: 'SC', name: 'Seychelles' },
1221
+ { code: 'SL', name: 'Sierra Leone' },
1222
+ { code: 'SG', name: 'Singapore' },
1223
+ { code: 'SX', name: 'Sint Maarten' },
1224
+ { code: 'SK', name: 'Slovakia' },
1225
+ { code: 'SI', name: 'Slovenia' },
1226
+ { code: 'SB', name: 'Solomon Islands' },
1227
+ { code: 'SO', name: 'Somalia' },
1228
+ { code: 'ZA', name: 'South Africa' },
1229
+ { code: 'GS', name: 'South Georgia and the South Sandwich Islands' },
1230
+ { code: 'SS', name: 'South Sudan' },
1231
+ { code: 'ES', name: 'Spain' },
1232
+ { code: 'LK', name: 'Sri Lanka' },
1233
+ { code: 'SD', name: 'Sudan' },
1234
+ { code: 'SR', name: 'Suriname' },
1235
+ { code: 'SJ', name: 'Svalbard and Jan Mayen' },
1236
+ { code: 'SZ', name: 'Swaziland' },
1237
+ { code: 'SE', name: 'Sweden' },
1238
+ { code: 'CH', name: 'Switzerland' },
1239
+ { code: 'SY', name: 'Syrian Arab Republic' },
1240
+ { code: 'TW', name: 'Taiwan' },
1241
+ { code: 'TJ', name: 'Tajikistan' },
1242
+ { code: 'TZ', name: 'Tanzania' },
1243
+ { code: 'TH', name: 'Thailand' },
1244
+ { code: 'TL', name: 'Timor-Leste' },
1245
+ { code: 'TG', name: 'Togo' },
1246
+ { code: 'TK', name: 'Tokelau' },
1247
+ { code: 'TO', name: 'Tonga' },
1248
+ { code: 'TT', name: 'Trinidad and Tobago' },
1249
+ { code: 'TN', name: 'Tunisia' },
1250
+ { code: 'TR', name: 'Turkey' },
1251
+ { code: 'TM', name: 'Turkmenistan' },
1252
+ { code: 'TC', name: 'Turks and Caicos Islands' },
1253
+ { code: 'TV', name: 'Tuvalu' },
1254
+ { code: 'UG', name: 'Uganda' },
1255
+ { code: 'UA', name: 'Ukraine' },
1256
+ { code: 'AE', name: 'United Arab Emirates' },
1257
+ { code: 'GB', name: 'United Kingdom' },
1258
+ { code: 'US', name: 'United States' },
1259
+ { code: 'UM', name: 'United States Outlying Islands' },
1260
+ { code: 'UY', name: 'Uruguay' },
1261
+ { code: 'UZ', name: 'Uzbekistan' },
1262
+ { code: 'VU', name: 'Vanuatu' },
1263
+ { code: 'VE', name: 'Venezuela' },
1264
+ { code: 'VN', name: 'Vietnam' },
1265
+ { code: 'VG', name: 'Virgin Islands, British' },
1266
+ { code: 'VI', name: 'Virgin Islands, U.S.' },
1267
+ { code: 'WF', name: 'Wallis and Futuna' },
1268
+ { code: 'EH', name: 'Western Sahara' },
1269
+ { code: 'YE', name: 'Yemen' },
1270
+ { code: 'ZM', name: 'Zambia' },
1271
+ { code: 'ZW', name: 'Zimbabwe' },
1272
+ ]
1273
+ }
1274
+ }