odesli.js 1.1.2 → 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,16 +1,28 @@
1
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
2
12
 
3
13
  /**
4
- * Simple in-memory cache for API responses
14
+ * Generate User-Agent string
15
+ * @returns {string} User-Agent string
5
16
  * @private
6
17
  */
18
+ function generateUserAgent () {
19
+ return `${PACKAGE_NAME}/${PACKAGE_VERSION} (Node.js ${NODE_VERSION}; ${PLATFORM})`
20
+ }
21
+
22
+ // Global cache storage
7
23
  const cache = new Map()
8
24
  const CACHE_TTL = 5 * 60 * 1000 // 5 minutes
9
25
 
10
- /**
11
- * Clear expired cache entries
12
- * @private
13
- */
14
26
  function clearExpiredCache () {
15
27
  const now = Date.now()
16
28
  for (const [key, value] of cache.entries()) {
@@ -23,15 +35,18 @@ function clearExpiredCache () {
23
35
  /**
24
36
  * Get cached response if available and not expired
25
37
  * @param {string} key - Cache key
38
+ * @param {MetricsCollector} metrics - Metrics collector instance
26
39
  * @returns {Object|null} Cached response or null if not found/expired
27
40
  * @private
28
41
  */
29
- function getCachedResponse (key) {
42
+ function getCachedResponse (key, metrics) {
30
43
  clearExpiredCache()
31
44
  const cached = cache.get(key)
32
45
  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
46
+ if (metrics) metrics.recordRequest({ cacheHit: true })
33
47
  return cached.data
34
48
  }
49
+ if (metrics) metrics.recordRequest({ cacheHit: false })
35
50
  return null
36
51
  }
37
52
 
@@ -80,6 +95,13 @@ module.exports = class Odesli {
80
95
  * @param {string} [options.version='v1-alpha.1'] - API version to use
81
96
  * @param {boolean} [options.cache=true] - Enable response caching (5 minute TTL)
82
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
83
105
  *
84
106
  * @example
85
107
  * ```javascript
@@ -91,86 +113,212 @@ module.exports = class Odesli {
91
113
  * apiKey: 'your-api-key-here',
92
114
  * version: 'v1-alpha.1',
93
115
  * cache: true,
94
- * timeout: 10000
116
+ * timeout: 10000,
117
+ * maxRetries: 3,
118
+ * retryDelay: 1000,
119
+ * headers: { 'User-Agent': 'MyApp/1.0' },
120
+ * validateParams: true
95
121
  * });
122
+ *
123
+ * // Disable metrics
124
+ * const odesli = new Odesli({ metrics: false });
96
125
  * ```
97
126
  */
98
127
  constructor (options = {}) {
99
- const { apiKey = undefined, version = 'v1-alpha.1', cache = true, timeout = 10000 } = 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
+
100
142
  this.apiKey = apiKey || undefined
101
143
  this.version = version || 'v1-alpha.1'
102
144
  this.cacheEnabled = cache
103
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
+ }
104
224
  }
105
225
 
106
226
  /**
107
- * Make a request to the Odesli API with caching and timeout support
227
+ * Make a request to the Odesli API with caching, timeout, and retry support
108
228
  *
109
229
  * @param {string} path - API endpoint path
110
230
  * @returns {Promise<Object>} API response
111
231
  * @private
112
232
  */
113
233
  async _request (path) {
114
- const url = `https://api.song.link/${this.version}/${path}${this.apiKey !== undefined ? `&key=${this.apiKey}` : ''}`
234
+ const url = `${this.baseUrl}/${this.version}/${path}${this.apiKey !== undefined ? `&key=${this.apiKey}` : ''}`
115
235
 
116
236
  // Check cache first if enabled
117
237
  if (this.cacheEnabled) {
118
- const cached = getCachedResponse(url)
238
+ const cached = getCachedResponse(url, this.metrics)
119
239
  if (cached) {
240
+ this._log(`Cache hit for ${path}`, 'debug')
120
241
  return cached
121
242
  }
122
243
  }
123
244
 
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'
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}`)
134
271
  }
135
- })
136
272
 
137
- clearTimeout(timeoutId)
273
+ const result = await response.json()
138
274
 
139
- if (!response.ok) {
140
- throw new Error(`HTTP ${response.status}: ${response.statusText}`)
141
- }
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
+ }
142
288
 
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
- }
289
+ // Cache successful responses
290
+ if (this.cacheEnabled && result) {
291
+ cacheResponse(url, result)
292
+ }
158
293
 
159
- // Cache successful responses
160
- if (this.cacheEnabled && result) {
161
- cacheResponse(url, result)
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
+ }
162
310
  }
311
+ }
163
312
 
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
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.')
173
319
  }
320
+ // Preserve original error message for network errors
321
+ throw lastError
174
322
  }
175
323
 
176
324
  /**
@@ -184,83 +332,196 @@ module.exports = class Odesli {
184
332
  */
185
333
  clearCache () {
186
334
  cache.clear()
335
+ this.metrics.reset() // Also reset metrics related to cache
336
+ this._log('Cache cleared', 'info')
187
337
  }
188
338
 
189
339
  /**
190
340
  * Get cache statistics
191
341
  *
192
342
  * @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
343
  */
200
344
  getCacheStats () {
201
- clearExpiredCache()
345
+ const summary = this.metrics.getSummary()
202
346
  return {
347
+ hitCount: summary.counters.cacheHits,
348
+ missCount: summary.counters.cacheMisses,
349
+ hitRate: summary.rates.cacheHitRate,
203
350
  size: cache.size,
204
- ttl: CACHE_TTL
205
351
  }
206
352
  }
207
353
 
208
354
  /**
209
- * Fetch song/album information by URL from any supported streaming platform
355
+ * Get the metrics collector instance for more detailed statistics.
210
356
  *
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
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
214
373
  *
215
374
  * @example
216
- * ```javascript
217
- * // Fetch a song by Spotify URL
375
+ * // Single fetch
218
376
  * 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
377
  *
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.)
378
+ * // Batch fetch
379
+ * const songs = await odesli.fetch([
380
+ * 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
381
+ * 'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu'
382
+ * ]);
232
383
  */
233
- async fetch (url, country = 'US') {
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
234
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
+
235
477
  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 || {}
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
241
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
+ }
242
498
 
243
- const id = song.entitiesByUniqueId[song.entityUniqueId].id
244
- const title = song.entitiesByUniqueId[song.entityUniqueId].title
499
+ const id = song.entitiesByUniqueId[song.entityUniqueId].id
500
+ const title = song.entitiesByUniqueId[song.entityUniqueId].title
245
501
 
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
- })
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
+ })
252
508
 
253
- const artist = song.entitiesByUniqueId[song.entityUniqueId].artistName
254
- const type = song.entitiesByUniqueId[song.entityUniqueId].type
255
- const thumbnail = song.entitiesByUniqueId[song.entityUniqueId].thumbnailUrl
509
+ const artist = song.entitiesByUniqueId[song.entityUniqueId].artistName
510
+ const type = song.entitiesByUniqueId[song.entityUniqueId].type
511
+ const thumbnail = song.entitiesByUniqueId[song.entityUniqueId].thumbnailUrl
256
512
 
257
- return {
258
- ...song,
259
- id,
260
- title,
261
- artist,
262
- type,
263
- thumbnail
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
264
525
  }
265
526
  }
266
527
 
@@ -270,7 +531,10 @@ module.exports = class Odesli {
270
531
  * @param {string} platform - Platform name (spotify, appleMusic, youtube, etc.)
271
532
  * @param {string} type - Content type ('song' or 'album')
272
533
  * @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
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
274
538
  * @returns {Promise<Object>} Song/album information with links to all available platforms
275
539
  *
276
540
  * @example
@@ -279,51 +543,102 @@ module.exports = class Odesli {
279
543
  * const song = await odesli.getByParams('spotify', 'song', '4Km5HrUvYTaSUfiSGPJeQR');
280
544
  * console.log(song.title);
281
545
  *
282
- * // Get album by Apple Music ID
283
- * const album = await odesli.getByParams('appleMusic', 'album', '123456789');
284
- * console.log(album.title);
546
+ * // Get album by Apple Music ID (backward compatible)
547
+ * const album = await odesli.getByParams('appleMusic', 'album', '123456789', 'GB');
285
548
  *
286
- * // Using full ID format
287
- * const song = await odesli.getByParams('spotify', 'song', 'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR');
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
+ * });
288
555
  * ```
289
556
  *
290
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
291
561
  * @throws {Error} When API returns an error
292
562
  */
293
- async getByParams (platform, type, id, country = 'US') {
563
+ async getByParams (platform, type, id, options = {}) {
294
564
  if (!platform) throw new Error('No `platform` was provided to odesli.getByParams()')
295
565
  if (!type) throw new Error('No `type` was provided to odesli.getByParams()')
296
566
  if (!id) throw new Error('No `id` was provided to odesli.getByParams()')
297
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
+
298
594
  // if they happen to input the full id (PLATFORM_SONG::UNIQUEID), just get the UNIQUEID
299
595
  id = id.replace(/[^::]+::/g, '')
300
596
  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 || {}
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
306
604
  }
605
+
606
+ if (skipCache) {
607
+ this.cacheEnabled = false
608
+ }
609
+
610
+ try {
611
+ const song = await this._request(path)
307
612
 
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(', ')
613
+ // Handle edge cases where response is malformed
614
+ if (!song || !song.entityUniqueId || !song.entitiesByUniqueId || !song.entitiesByUniqueId[song.entityUniqueId]) {
615
+ return song || {}
312
616
  }
313
- })
314
617
 
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
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
+ })
320
624
 
321
- return {
322
- ...song,
323
- title,
324
- artist,
325
- thumbnail,
326
- type: entityType
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
327
642
  }
328
643
  }
329
644
 
@@ -331,7 +646,10 @@ module.exports = class Odesli {
331
646
  * Fetch song/album information by entity ID
332
647
  *
333
648
  * @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
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
335
653
  * @returns {Promise<Object>} Song/album information with links to all available platforms
336
654
  *
337
655
  * @example
@@ -340,51 +658,617 @@ module.exports = class Odesli {
340
658
  * const song = await odesli.getById('SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR');
341
659
  * console.log(song.title);
342
660
  *
343
- * // Get album by entity ID
344
- * const album = await odesli.getById('APPLEMUSIC_ALBUM::123456789');
345
- * console.log(album.title);
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
+ * });
346
670
  * ```
347
671
  *
348
672
  * @throws {Error} When ID is not provided
349
673
  * @throws {Error} When ID format is invalid (must match 'PLATFORM_TYPE::UNIQUEID')
674
+ * @throws {Error} When country code format is invalid
350
675
  * @throws {Error} When API returns an error
351
676
  */
352
- async getById (id, country = 'US') {
677
+ async getById (id, options = {}) {
353
678
  if (!id) throw new Error('No `id` was provided to odesli.getById()')
354
679
  if (!id.match(/\w+_\w+::\w+/g)) throw new Error('Provided Entity ID Does not match format. `<PLATFORM>_<SONG|ALBUM>::<UNIQUEID>`')
355
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
+
356
699
  // Convert string into seperate params
357
700
  const platform = id.replace(/_\w+::\w+/g, '').toLowerCase()
358
701
  const type = id.replace(/\w+_/g, '').replace(/::\w+/g, '').toLowerCase()
359
702
  const unique = id.replace(/\w+::/g, '')
360
703
 
361
704
  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 || {}
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
367
716
  }
717
+
718
+ try {
719
+ const song = await this._request(path)
368
720
 
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(', ')
721
+ // Handle edge cases where response is malformed
722
+ if (!song || !song.entityUniqueId || !song.entitiesByUniqueId || !song.entitiesByUniqueId[song.entityUniqueId]) {
723
+ return song || {}
373
724
  }
374
- })
375
725
 
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
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
+ })
381
732
 
382
- return {
383
- ...song,
384
- title,
385
- artist,
386
- thumbnail,
387
- type: entityType
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))
388
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
+ ]
389
1273
  }
390
1274
  }