odesli.js 1.3.9 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -10,19 +10,262 @@ const PACKAGE_NAME = packageJson.name
10
10
  const NODE_VERSION = process.version
11
11
  const PLATFORM = process.platform
12
12
 
13
+ const SUNSET_DOCS_URL =
14
+ 'https://linktr.ee/help/articles/15201827-sunsetting-the-songlink-odesli-public-api'
15
+
16
+ const SUPPORTED_PLATFORMS = [
17
+ 'spotify',
18
+ 'itunes',
19
+ 'appleMusic',
20
+ 'youtube',
21
+ 'youtubeMusic',
22
+ 'google',
23
+ 'googleStore',
24
+ 'pandora',
25
+ 'deezer',
26
+ 'tidal',
27
+ 'amazonStore',
28
+ 'amazonMusic',
29
+ 'soundcloud',
30
+ 'napster',
31
+ 'yandex',
32
+ 'spinrilla',
33
+ 'audiomack',
34
+ 'anghami',
35
+ 'boomplay',
36
+ 'audius'
37
+ ]
38
+
39
+ const NON_RETRYABLE_STATUS_CODES = new Set([400, 401, 403, 404, 410])
40
+ const RETRYABLE_STATUS_CODES = new Set([408, 429, 500, 502, 503, 504])
41
+
13
42
  /**
14
- * Generate User-Agent string
15
- * @returns {string} User-Agent string
43
+ * Structured error for Odesli/Songlink API failures.
44
+ *
45
+ * @extends Error
46
+ * @since 2.0.0
47
+ */
48
+ class OdesliError extends Error {
49
+ /**
50
+ * @param {string} message - Human-readable error message
51
+ * @param {Object} [options={}] - Error metadata
52
+ * @param {string} [options.code] - Machine-readable error code
53
+ * @param {number|null} [options.statusCode=null] - HTTP status code when applicable
54
+ * @param {boolean} [options.retryable=false] - Whether the request is safe to retry
55
+ * @param {string} [options.docsUrl] - Documentation URL for remediation
56
+ * @param {Error} [options.cause] - Underlying cause
57
+ */
58
+ constructor (message, options = {}) {
59
+ super(message)
60
+ this.name = 'OdesliError'
61
+ this.code = options.code || 'ODESLI_ERROR'
62
+ this.statusCode =
63
+ typeof options.statusCode === 'number' ? options.statusCode : null
64
+ this.retryable = Boolean(options.retryable)
65
+ this.docsUrl = options.docsUrl || undefined
66
+ if (options.cause) {
67
+ this.cause = options.cause
68
+ }
69
+ if (Error.captureStackTrace) {
70
+ Error.captureStackTrace(this, OdesliError)
71
+ }
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Generate User-Agent string for API requests.
77
+ *
78
+ * Creates a User-Agent string in the format:
79
+ * `{packageName}/{version} (Node.js {nodeVersion}; {platform})`
80
+ *
81
+ * @returns {string} User-Agent string (e.g., 'odesli.js/2.0.0 (Node.js v18.0.0; win32)')
16
82
  * @private
83
+ * @since 1.1.0
17
84
  */
18
85
  function generateUserAgent () {
19
86
  return `${PACKAGE_NAME}/${PACKAGE_VERSION} (Node.js ${NODE_VERSION}; ${PLATFORM})`
20
87
  }
21
88
 
89
+ /**
90
+ * Build a Songlink API request URL and a secret-free cache key.
91
+ *
92
+ * @param {string} baseUrl - API base URL
93
+ * @param {string} version - API version segment
94
+ * @param {string} path - Path and query string without leading slash
95
+ * @param {string} apiKey - Allowlisted Songlink API key
96
+ * @returns {{ requestUrl: string, cacheKey: string }}
97
+ * @private
98
+ */
99
+ function buildRequestUrls (baseUrl, version, path, apiKey) {
100
+ const normalizedBase = `${String(baseUrl || '').replace(/\/$/, '')}/`
101
+ const normalizedVersion = String(version || '').replace(/^\/|\/$/g, '')
102
+ const normalizedPath = String(path || '').replace(/^\//, '')
103
+ const requestUrl = new URL(
104
+ `${normalizedVersion}/${normalizedPath}`,
105
+ normalizedBase
106
+ )
107
+ const cacheKey = requestUrl.toString()
108
+ requestUrl.searchParams.set('key', apiKey)
109
+ return {
110
+ requestUrl: requestUrl.toString(),
111
+ cacheKey
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Parse response body text as JSON when possible.
117
+ *
118
+ * @param {string} bodyText - Raw response body
119
+ * @returns {Object|null}
120
+ * @private
121
+ */
122
+ function parseJsonBody (bodyText) {
123
+ if (!bodyText) return null
124
+ try {
125
+ return JSON.parse(bodyText)
126
+ } catch {
127
+ return null
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Create an OdesliError from an API HTTP response.
133
+ *
134
+ * @param {number} statusCode - HTTP status code
135
+ * @param {Object|null} payload - Parsed JSON payload when available
136
+ * @param {string} [statusText] - HTTP status text
137
+ * @param {Headers|Object} [headers] - Response headers
138
+ * @returns {OdesliError}
139
+ * @private
140
+ */
141
+ function createApiError (statusCode, payload, statusText, headers) {
142
+ const apiCode =
143
+ payload && typeof payload.code === 'string' ? payload.code : undefined
144
+ const effectiveStatus =
145
+ (payload && typeof payload.statusCode === 'number'
146
+ ? payload.statusCode
147
+ : statusCode) || statusCode
148
+
149
+ if (
150
+ effectiveStatus === 401 &&
151
+ apiCode === 'PUBLIC_API_ACCESS_DEPRECATED'
152
+ ) {
153
+ return new OdesliError(
154
+ 'Songlink/Odesli public API access is deprecated. An allowlisted API key is required.',
155
+ {
156
+ code: 'PUBLIC_API_ACCESS_DEPRECATED',
157
+ statusCode: 401,
158
+ retryable: false,
159
+ docsUrl: SUNSET_DOCS_URL
160
+ }
161
+ )
162
+ }
163
+
164
+ if (effectiveStatus === 401 && apiCode === 'INVALID_ACCESS_KEY') {
165
+ return new OdesliError(
166
+ 'The provided Songlink/Odesli API key was rejected (INVALID_ACCESS_KEY).',
167
+ {
168
+ code: 'INVALID_ACCESS_KEY',
169
+ statusCode: 401,
170
+ retryable: false,
171
+ docsUrl: SUNSET_DOCS_URL
172
+ }
173
+ )
174
+ }
175
+
176
+ if (effectiveStatus === 401) {
177
+ return new OdesliError(
178
+ 'Unauthorized Songlink/Odesli API request. Check that your allowlisted API key is valid.',
179
+ {
180
+ code: apiCode || 'UNAUTHORIZED',
181
+ statusCode: 401,
182
+ retryable: false,
183
+ docsUrl: SUNSET_DOCS_URL
184
+ }
185
+ )
186
+ }
187
+
188
+ if (effectiveStatus === 410) {
189
+ return new OdesliError(
190
+ 'Songlink/Odesli API endpoint returned 410 Gone. The public API was retired on July 31, 2026.',
191
+ {
192
+ code: 'API_SUNSET_GONE',
193
+ statusCode: 410,
194
+ retryable: false,
195
+ docsUrl: SUNSET_DOCS_URL
196
+ }
197
+ )
198
+ }
199
+
200
+ if (effectiveStatus === 429) {
201
+ const retryAfterHeader =
202
+ headers && typeof headers.get === 'function'
203
+ ? headers.get('retry-after')
204
+ : headers && headers['retry-after']
205
+ const retryAfterSeconds = Number(retryAfterHeader)
206
+ const error = new OdesliError(
207
+ `${effectiveStatus}: ${apiCode || 'RATE_LIMITED'}, You are being rate limited. Retry later.`,
208
+ {
209
+ code: apiCode || 'RATE_LIMITED',
210
+ statusCode: 429,
211
+ retryable: true,
212
+ docsUrl: SUNSET_DOCS_URL
213
+ }
214
+ )
215
+ if (Number.isFinite(retryAfterSeconds) && retryAfterSeconds > 0) {
216
+ error.retryAfterMs = retryAfterSeconds * 1000
217
+ }
218
+ return error
219
+ }
220
+
221
+ if (String(effectiveStatus).startsWith('4')) {
222
+ return new OdesliError(
223
+ `${effectiveStatus}: ${apiCode || statusText || 'CLIENT_ERROR'}, Codes in the 4xx range indicate an error that failed given the information provided.`,
224
+ {
225
+ code: apiCode || 'CLIENT_ERROR',
226
+ statusCode: effectiveStatus,
227
+ retryable: false,
228
+ docsUrl: SUNSET_DOCS_URL
229
+ }
230
+ )
231
+ }
232
+
233
+ if (String(effectiveStatus).startsWith('5')) {
234
+ return new OdesliError(
235
+ `${effectiveStatus}: ${apiCode || statusText || 'SERVER_ERROR'}, Codes in the 5xx range indicate an error with Songlink's servers.`,
236
+ {
237
+ code: apiCode || 'SERVER_ERROR',
238
+ statusCode: effectiveStatus,
239
+ retryable: true,
240
+ docsUrl: SUNSET_DOCS_URL
241
+ }
242
+ )
243
+ }
244
+
245
+ return new OdesliError(
246
+ `${effectiveStatus}: ${apiCode || statusText || 'ODESLI_ERROR'}`,
247
+ {
248
+ code: apiCode || 'ODESLI_ERROR',
249
+ statusCode: effectiveStatus,
250
+ retryable: RETRYABLE_STATUS_CODES.has(effectiveStatus),
251
+ docsUrl: SUNSET_DOCS_URL
252
+ }
253
+ )
254
+ }
255
+
22
256
  // Global cache storage
23
257
  const cache = new Map()
24
258
  const CACHE_TTL = 5 * 60 * 1000 // 5 minutes
25
259
 
260
+ /**
261
+ * Clear expired entries from the cache.
262
+ *
263
+ * Removes cache entries that have exceeded the TTL (Time To Live).
264
+ * Called automatically before cache lookups.
265
+ *
266
+ * @private
267
+ * @since 1.1.0
268
+ */
26
269
  function clearExpiredCache () {
27
270
  const now = Date.now()
28
271
  for (const [key, value] of cache.entries()) {
@@ -33,11 +276,16 @@ function clearExpiredCache () {
33
276
  }
34
277
 
35
278
  /**
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
279
+ * Get cached response if available and not expired.
280
+ *
281
+ * Checks the cache for a valid (non-expired) response and records
282
+ * cache hit/miss metrics if a metrics collector is provided.
283
+ *
284
+ * @param {string} key - Cache key (typically the full API URL)
285
+ * @param {MetricsCollector} [metrics] - Optional metrics collector instance
286
+ * @returns {Object|null} Cached response data or null if not found/expired
40
287
  * @private
288
+ * @since 1.1.0
41
289
  */
42
290
  function getCachedResponse (key, metrics) {
43
291
  clearExpiredCache()
@@ -51,10 +299,15 @@ function getCachedResponse (key, metrics) {
51
299
  }
52
300
 
53
301
  /**
54
- * Cache a response
55
- * @param {string} key - Cache key
302
+ * Cache a response with timestamp for TTL management.
303
+ *
304
+ * Stores response data in the cache with a timestamp. The cache entry
305
+ * will be automatically expired after CACHE_TTL milliseconds.
306
+ *
307
+ * @param {string} key - Cache key (typically the full API URL)
56
308
  * @param {Object} data - Response data to cache
57
309
  * @private
310
+ * @since 1.1.0
58
311
  */
59
312
  function cacheResponse (key, data) {
60
313
  cache.set(key, {
@@ -63,22 +316,33 @@ function cacheResponse (key, data) {
63
316
  })
64
317
  }
65
318
 
319
+ /**
320
+ * @module odesli
321
+ * @description A Node.js client for the Odesli API (formerly song.link/album.link) that helps you find links to music across multiple streaming platforms.
322
+ * @author Mattr <me@mtr.gg>
323
+ * @version 2.0.0
324
+ * @license ISC
325
+ * @see {@link https://github.com/MattrAus/odesli.js|GitHub Repository}
326
+ * @see {@link https://www.npmjs.com/package/odesli.js|NPM Package}
327
+ */
328
+
66
329
  /**
67
330
  * Odesli API Client
68
331
  *
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
- *
332
+ * @summary A Node.js client for the Songlink/Odesli API that helps you find links to music across multiple streaming platforms.
333
+ * @class
334
+ * @memberof module:odesli
335
+ * @version 2.0.0
336
+ * @tutorial getting-started
337
+ * @tutorial advanced-usage
71
338
  * @example
72
339
  * ```javascript
73
340
  * const Odesli = require('odesli.js');
74
341
  *
75
- * // Initialize without API key (10 requests/minute limit)
76
- * const odesli = new Odesli();
77
- *
78
- * // Or with API key for higher limits
342
+ * // Prefer environment configuration in production
343
+ * // process.env.ODESLI_API_KEY = 'your-allowlisted-key'
79
344
  * const odesli = new Odesli({
80
- * apiKey: 'your-api-key-here',
81
- * version: 'v1-alpha.1'
345
+ * apiKey: process.env.ODESLI_API_KEY
82
346
  * });
83
347
  *
84
348
  * // Fetch a song by URL
@@ -86,12 +350,12 @@ function cacheResponse (key, data) {
86
350
  * console.log(`${song.title} by ${song.artist[0]}`);
87
351
  * ```
88
352
  */
89
- module.exports = class Odesli {
353
+ class Odesli {
90
354
  /**
91
355
  * Create a new Odesli instance
92
356
  *
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.
357
+ * @param {Object} [options={}] - Configuration options
358
+ * @param {string} [options.apiKey] - Allowlisted Songlink/Odesli API key. Falls back to `process.env.ODESLI_API_KEY`. Required as of v2.0.0.
95
359
  * @param {string} [options.version='v1-alpha.1'] - API version to use
96
360
  * @param {boolean} [options.cache=true] - Enable response caching (5 minute TTL)
97
361
  * @param {number} [options.timeout=10000] - Request timeout in milliseconds
@@ -105,12 +369,12 @@ module.exports = class Odesli {
105
369
  *
106
370
  * @example
107
371
  * ```javascript
108
- * // Basic usage without API key
109
- * const odesli = new Odesli();
372
+ * // From environment variable
373
+ * const odesli = new Odesli(); // uses process.env.ODESLI_API_KEY
110
374
  *
111
- * // With API key for higher limits
375
+ * // Explicit API key
112
376
  * const odesli = new Odesli({
113
- * apiKey: 'your-api-key-here',
377
+ * apiKey: process.env.ODESLI_API_KEY,
114
378
  * version: 'v1-alpha.1',
115
379
  * cache: true,
116
380
  * timeout: 10000,
@@ -121,7 +385,10 @@ module.exports = class Odesli {
121
385
  * });
122
386
  *
123
387
  * // Disable metrics
124
- * const odesli = new Odesli({ metrics: false });
388
+ * const odesli = new Odesli({
389
+ * apiKey: process.env.ODESLI_API_KEY,
390
+ * metrics: false
391
+ * });
125
392
  * ```
126
393
  */
127
394
  constructor (options = {}) {
@@ -139,7 +406,22 @@ module.exports = class Odesli {
139
406
  metrics
140
407
  } = options || {}
141
408
 
142
- this.apiKey = apiKey || undefined
409
+ const resolvedKey = String(
410
+ apiKey ?? process.env.ODESLI_API_KEY ?? ''
411
+ ).trim()
412
+
413
+ if (!resolvedKey) {
414
+ throw new OdesliError(
415
+ 'Songlink/Odesli retired its unauthenticated public API on July 31, 2026. Pass { apiKey } or set ODESLI_API_KEY with an allowlisted key.',
416
+ {
417
+ code: 'MISSING_API_KEY',
418
+ retryable: false,
419
+ docsUrl: SUNSET_DOCS_URL
420
+ }
421
+ )
422
+ }
423
+
424
+ this.apiKey = resolvedKey
143
425
  this.version = version || 'v1-alpha.1'
144
426
  this.cacheEnabled = cache
145
427
  this.timeout = timeout
@@ -192,12 +474,9 @@ module.exports = class Odesli {
192
474
  */
193
475
  _validatePlatform (platform) {
194
476
  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())
477
+ return SUPPORTED_PLATFORMS.map((p) => p.toLowerCase()).includes(
478
+ String(platform || '').toLowerCase()
479
+ )
201
480
  }
202
481
 
203
482
  /**
@@ -224,18 +503,31 @@ module.exports = class Odesli {
224
503
  }
225
504
 
226
505
  /**
227
- * Make a request to the Odesli API with caching, timeout, and retry support
506
+ * Make a request to the Odesli API with caching, timeout, and retry support.
507
+ *
508
+ * This method handles:
509
+ * - Cache checking and storage (keyed without the API key)
510
+ * - Request timeouts
511
+ * - Automatic retries with exponential backoff for retryable failures
512
+ * - Structured error handling for sunset / auth / rate-limit responses
228
513
  *
229
- * @param {string} path - API endpoint path
230
- * @returns {Promise<Object>} API response
514
+ * @param {string} path - API endpoint path (e.g., 'links?url=...')
515
+ * @returns {Promise<Object>} API response object
516
+ * @throws {OdesliError} When the request fails
231
517
  * @private
518
+ * @since 1.1.0
232
519
  */
233
520
  async _request (path) {
234
- const url = `${this.baseUrl}/${this.version}/${path}${this.apiKey !== undefined ? `&key=${this.apiKey}` : ''}`
235
-
236
- // Check cache first if enabled
521
+ const { requestUrl, cacheKey } = buildRequestUrls(
522
+ this.baseUrl,
523
+ this.version,
524
+ path,
525
+ this.apiKey
526
+ )
527
+
528
+ // Check cache first if enabled (secret-free cache key)
237
529
  if (this.cacheEnabled) {
238
- const cached = getCachedResponse(url, this.metrics)
530
+ const cached = getCachedResponse(cacheKey, this.metrics)
239
531
  if (cached) {
240
532
  this._log(`Cache hit for ${path}`, 'debug')
241
533
  return cached
@@ -245,90 +537,138 @@ module.exports = class Odesli {
245
537
  let lastError
246
538
  for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
247
539
  try {
248
- this._log(`Request attempt ${attempt}/${this.maxRetries} for ${path}`, 'debug')
249
-
250
- // Create AbortController for timeout
540
+ this._log(
541
+ `Request attempt ${attempt}/${this.maxRetries} for ${path}`,
542
+ 'debug'
543
+ )
544
+
251
545
  const controller = new AbortController()
252
546
  const timeoutId = setTimeout(() => controller.abort(), this.timeout)
253
547
 
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
- })
548
+ let response
549
+ try {
550
+ response = await fetch(requestUrl, {
551
+ signal: controller.signal,
552
+ headers: {
553
+ 'User-Agent': generateUserAgent(),
554
+ ...this.customHeaders,
555
+ Accept: 'application/json'
556
+ }
557
+ })
558
+ } finally {
559
+ clearTimeout(timeoutId)
560
+ }
262
561
 
263
- clearTimeout(timeoutId)
562
+ if (!response) {
563
+ throw new OdesliError('API returned an unexpected result.', {
564
+ code: 'UNEXPECTED_RESPONSE',
565
+ retryable: true,
566
+ docsUrl: SUNSET_DOCS_URL
567
+ })
568
+ }
264
569
 
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}`)
570
+ const bodyText = await response.text()
571
+ const result = parseJsonBody(bodyText)
572
+
573
+ const payloadStatus =
574
+ result && typeof result.statusCode === 'number'
575
+ ? result.statusCode
576
+ : null
577
+ const effectiveStatus = payloadStatus || response.status
578
+
579
+ if (!response.ok || (payloadStatus && payloadStatus !== 200)) {
580
+ throw createApiError(
581
+ effectiveStatus,
582
+ result,
583
+ response.statusText,
584
+ response.headers
585
+ )
271
586
  }
272
587
 
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
588
+ if (bodyText && result === null) {
589
+ throw new OdesliError('API returned an unexpected result.', {
590
+ code: 'UNEXPECTED_RESPONSE',
591
+ statusCode: response.status,
592
+ retryable: true,
593
+ docsUrl: SUNSET_DOCS_URL
594
+ })
287
595
  }
288
596
 
289
- // Cache successful responses
290
597
  if (this.cacheEnabled && result) {
291
- cacheResponse(url, result)
598
+ cacheResponse(cacheKey, result)
292
599
  }
293
600
 
294
601
  this._log(`Request successful for ${path}`, 'debug')
295
602
  return result
296
603
  } 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
604
+ if (err && err.name === 'AbortError') {
605
+ lastError = new OdesliError(
606
+ `Request timeout after ${this.timeout}ms`,
607
+ {
608
+ code: 'TIMEOUT',
609
+ retryable: true,
610
+ docsUrl: SUNSET_DOCS_URL,
611
+ cause: err
612
+ }
613
+ )
614
+ } else if (err instanceof OdesliError) {
615
+ lastError = err
616
+ } else {
617
+ lastError = new OdesliError(err.message || 'Request failed', {
618
+ code: 'NETWORK_ERROR',
619
+ retryable: true,
620
+ docsUrl: SUNSET_DOCS_URL,
621
+ cause: err
622
+ })
303
623
  }
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))
624
+
625
+ const shouldRetry =
626
+ lastError.retryable === true &&
627
+ !NON_RETRYABLE_STATUS_CODES.has(lastError.statusCode) &&
628
+ attempt < this.maxRetries
629
+
630
+ if (!shouldRetry) {
631
+ this._log(`Non-retryable error: ${lastError.message}`, 'error')
632
+ break
309
633
  }
634
+
635
+ const delay =
636
+ typeof lastError.retryAfterMs === 'number'
637
+ ? lastError.retryAfterMs
638
+ : this.retryDelay * Math.pow(2, attempt - 1)
639
+ this._log(
640
+ `Request failed, retrying in ${delay}ms: ${lastError.message}`,
641
+ 'warn'
642
+ )
643
+ await new Promise((resolve) => setTimeout(resolve, delay))
310
644
  }
311
645
  }
312
646
 
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
647
  throw lastError
322
648
  }
323
649
 
324
650
  /**
325
- * Clear the response cache
651
+ * Clear the response cache and reset cache-related metrics.
652
+ *
653
+ * This removes all cached API responses. Useful when you need fresh data
654
+ * or want to free up memory. Cache statistics are also reset.
326
655
  *
327
656
  * @example
328
657
  * ```javascript
329
- * const odesli = new Odesli();
330
- * odesli.clearCache(); // Clear all cached responses
658
+ * const odesli = new Odesli({ apiKey: process.env.ODESLI_API_KEY });
659
+ *
660
+ * // Fetch and cache a song
661
+ * await odesli.fetch('https://open.spotify.com/track/123');
662
+ *
663
+ * // Later, clear cache to get fresh data
664
+ * odesli.clearCache();
665
+ *
666
+ * // Next fetch will make a new API request
667
+ * await odesli.fetch('https://open.spotify.com/track/123');
331
668
  * ```
669
+ *
670
+ * @see {@link Odesli#getCacheStats} To check cache statistics before clearing
671
+ * @since 1.1.0
332
672
  */
333
673
  clearCache () {
334
674
  cache.clear()
@@ -337,9 +677,26 @@ module.exports = class Odesli {
337
677
  }
338
678
 
339
679
  /**
340
- * Get cache statistics
680
+ * Get cache statistics including hit rate, size, and performance metrics.
681
+ *
682
+ * @summary Retrieve cache performance statistics including hit rate and size.
683
+ *
684
+ * @returns {Object} Cache statistics object
685
+ * @returns {number} returns.hitCount - Number of cache hits
686
+ * @returns {number} returns.missCount - Number of cache misses
687
+ * @returns {number} returns.hitRate - Cache hit rate (0-1, where 1 is 100%)
688
+ * @returns {number} returns.size - Current number of cached items
689
+ *
690
+ * @example
691
+ * ```javascript
692
+ * const stats = odesli.getCacheStats();
693
+ * console.log(`Cache hit rate: ${(stats.hitRate * 100).toFixed(1)}%`);
694
+ * console.log(`Cached items: ${stats.size}`);
695
+ * ```
341
696
  *
342
- * @returns {Object} Cache statistics
697
+ * @see {@link Odesli#clearCache} To clear the cache
698
+ * @see {@link Odesli#getMetrics} For more detailed metrics
699
+ * @since 1.1.0
343
700
  */
344
701
  getCacheStats () {
345
702
  const summary = this.metrics.getSummary()
@@ -352,34 +709,94 @@ module.exports = class Odesli {
352
709
  }
353
710
 
354
711
  /**
355
- * Get the metrics collector instance for more detailed statistics.
712
+ * Get the metrics collector instance for detailed performance and usage statistics.
713
+ *
714
+ * The metrics collector tracks:
715
+ * - Request counts (total, successful, failed)
716
+ * - Cache performance (hits, misses, hit rate)
717
+ * - Response times (average, min, max)
718
+ * - Error rates and types
719
+ * - Rate limit events
720
+ *
721
+ * @returns {MetricsCollector} The metrics collector instance with detailed statistics
722
+ *
723
+ * @example
724
+ * ```javascript
725
+ * const metrics = odesli.getMetrics();
726
+ * const summary = metrics.getSummary();
727
+ * console.log(`Total requests: ${summary.counters.totalRequests}`);
728
+ * console.log(`Average response time: ${summary.timing.averageResponseTime}ms`);
729
+ * console.log(`Error rate: ${summary.rates.errorRate * 100}%`);
730
+ * ```
356
731
  *
357
- * @returns {MetricsCollector} The metrics collector instance.
732
+ * @see {@link module:odesli/metrics.MetricsCollector} For MetricsCollector API
733
+ * @since 1.1.0
358
734
  */
359
735
  getMetrics () {
360
736
  return this.metrics
361
737
  }
362
738
 
363
739
  /**
364
- * Fetch song/album information by URL(s) from any supported streaming platform
740
+ * Fetch song/album information by URL(s) from any supported streaming platform.
741
+ *
742
+ * @summary Primary method for retrieving music links with support for single URLs and batch processing.
743
+ *
744
+ * This is the primary method for retrieving music links. It supports both single URLs
745
+ * and batch processing of multiple URLs with automatic error handling.
365
746
  *
747
+ * @async
366
748
  * @param {string|Array<string>} urlOrUrls - URL or array of URLs from any supported streaming platform (Spotify, Apple Music, YouTube, etc.)
367
749
  * @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
750
+ * @param {string} [options.country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results. Use {@link Odesli.getCountryOptions} to get valid codes.
751
+ * @param {boolean} [options.skipCache=false] - Skip cache for this request (useful for getting fresh data)
752
+ * @param {number} [options.timeout] - Override timeout for this request in milliseconds
753
+ * @param {number} [options.concurrency=5] - Maximum concurrent requests when processing arrays (batch only)
754
+ * @returns {Promise<Object>|Promise<Array<Object>>} Song/album information or array of results. Each result includes:
755
+ * - `title` - Song/album title
756
+ * - `artist` - Array of artist names
757
+ * - `type` - Content type ('song' or 'album')
758
+ * - `thumbnail` - Thumbnail image URL
759
+ * - `pageUrl` - Song.link page URL
760
+ * - `linksByPlatform` - Object with platform-specific links
761
+ * - `entitiesByUniqueId` - Detailed entity information
373
762
  *
374
763
  * @example
764
+ * ```javascript
375
765
  * // Single fetch
376
766
  * const song = await odesli.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR');
767
+ * console.log(`${song.title} by ${song.artist.join(', ')}`);
377
768
  *
378
- * // Batch fetch
769
+ * // Batch fetch with options
379
770
  * const songs = await odesli.fetch([
380
771
  * 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
381
772
  * 'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu'
382
- * ]);
773
+ * ], {
774
+ * country: 'GB',
775
+ * concurrency: 3,
776
+ * skipCache: true
777
+ * });
778
+ *
779
+ * // Handle batch results with errors
780
+ * songs.forEach((result, index) => {
781
+ * if (result.error) {
782
+ * console.error(`Song ${index + 1} failed: ${result.error}`);
783
+ * } else {
784
+ * console.log(`Song ${index + 1}: ${result.title}`);
785
+ * }
786
+ * });
787
+ * ```
788
+ *
789
+ * @throws {Error} When URL format is invalid
790
+ * @throws {Error} When country code format is invalid (must be ISO 3166-1 Alpha-2)
791
+ * @throws {Error} When API returns an error (4xx/5xx status codes)
792
+ * @throws {Error} When request times out
793
+ * @throws {Error} When rate limit is exceeded (429 status)
794
+ *
795
+ * @see {@link Odesli#getByParams} For fetching by platform, type, and ID
796
+ * @see {@link Odesli#getById} For fetching by entity ID
797
+ * @see {@link Odesli#detectPlatform} To detect platform from URL
798
+ * @see {@link Odesli.getCountryOptions} To get valid country codes
799
+ * @since 1.1.0
383
800
  */
384
801
  async fetch (urlOrUrls, options = {}) {
385
802
  if (Array.isArray(urlOrUrls)) {
@@ -406,7 +823,17 @@ module.exports = class Odesli {
406
823
  // Add success property to successful responses
407
824
  return { ...result, success: true }
408
825
  } catch (error) {
409
- // Enhanced error object with more context
826
+ const statusCode =
827
+ typeof error.statusCode === 'number'
828
+ ? error.statusCode
829
+ : this._extractStatusCode(error.message)
830
+ const errorCode =
831
+ typeof error.code === 'string' ? error.code : undefined
832
+ const retryable =
833
+ typeof error.retryable === 'boolean'
834
+ ? error.retryable
835
+ : this._isRetryableError(error.message)
836
+
410
837
  const errorInfo = {
411
838
  success: false,
412
839
  url,
@@ -414,31 +841,50 @@ module.exports = class Odesli {
414
841
  platform: this.detectPlatform(url),
415
842
  extractedId: this.extractId(url),
416
843
  timestamp: new Date().toISOString(),
417
- statusCode: this._extractStatusCode(error.message),
418
- retryable: this._isRetryableError(error.message)
844
+ statusCode,
845
+ retryable,
846
+ code: errorCode
419
847
  }
420
-
421
- // Add additional context based on error type
422
- if (error.message.includes('400')) {
848
+
849
+ if (errorCode === 'PUBLIC_API_ACCESS_DEPRECATED') {
850
+ errorInfo.errorType = 'PUBLIC_API_ACCESS_DEPRECATED'
851
+ errorInfo.suggestion =
852
+ 'Provide an allowlisted API key. See the Songlink/Odesli sunset docs.'
853
+ } else if (errorCode === 'INVALID_ACCESS_KEY') {
854
+ errorInfo.errorType = 'INVALID_ACCESS_KEY'
855
+ errorInfo.suggestion =
856
+ 'The provided API key was rejected. Request allowlisted access from Songlink/Odesli.'
857
+ } else if (errorCode === 'API_SUNSET_GONE' || statusCode === 410) {
858
+ errorInfo.errorType = 'API_SUNSET_GONE'
859
+ errorInfo.suggestion =
860
+ 'This API endpoint is gone. Use an allowlisted key or link to https://song.link/ directly.'
861
+ } else if (statusCode === 400) {
423
862
  errorInfo.errorType = 'BAD_REQUEST'
424
863
  errorInfo.suggestion = 'Check if the URL is valid and accessible'
425
- } else if (error.message.includes('401')) {
864
+ } else if (statusCode === 401) {
426
865
  errorInfo.errorType = 'UNAUTHORIZED'
427
- errorInfo.suggestion = 'API key may be required or invalid'
428
- } else if (error.message.includes('429')) {
866
+ errorInfo.suggestion =
867
+ 'API key is missing, invalid, or not allowlisted'
868
+ } else if (statusCode === 429) {
429
869
  errorInfo.errorType = 'RATE_LIMITED'
430
870
  errorInfo.suggestion = 'Rate limit exceeded, try again later'
431
- } else if (error.message.includes('404')) {
871
+ } else if (statusCode === 404) {
432
872
  errorInfo.errorType = 'NOT_FOUND'
433
- errorInfo.suggestion = 'Content may not be available in the specified region'
434
- } else if (error.message.includes('timeout')) {
873
+ errorInfo.suggestion =
874
+ 'Content may not be available in the specified region'
875
+ } else if (
876
+ errorCode === 'TIMEOUT' ||
877
+ String(error.message || '')
878
+ .toLowerCase()
879
+ .includes('timeout')
880
+ ) {
435
881
  errorInfo.errorType = 'TIMEOUT'
436
882
  errorInfo.suggestion = 'Request timed out, try again'
437
883
  } else {
438
884
  errorInfo.errorType = 'UNKNOWN'
439
885
  errorInfo.suggestion = 'An unexpected error occurred'
440
886
  }
441
-
887
+
442
888
  return errorInfo
443
889
  }
444
890
  })
@@ -526,39 +972,72 @@ module.exports = class Odesli {
526
972
  }
527
973
 
528
974
  /**
529
- * Fetch song/album information by platform, type, and ID
975
+ * Fetch song/album information by platform, type, and ID.
976
+ *
977
+ * @summary Fetch music information using platform, type, and ID without requiring a full URL.
978
+ *
979
+ * This method allows you to fetch music information when you already know the
980
+ * platform, content type, and ID, without needing the full URL. Useful for
981
+ * applications that store platform-specific IDs.
530
982
  *
531
- * @param {string} platform - Platform name (spotify, appleMusic, youtube, etc.)
983
+ * @async
984
+ * @param {string} platform - Platform name (spotify, appleMusic, youtube, youtubeMusic, etc.). Use {@link Odesli#getSupportedPlatforms} to get valid platforms.
532
985
  * @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')
986
+ * @param {string} id - Platform-specific ID. Can be just the ID (e.g., '4Km5HrUvYTaSUfiSGPJeQR') or full format (e.g., 'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR')
534
987
  * @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
988
+ * @param {string} [options.country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results. Use {@link Odesli.getCountryOptions} to get valid codes.
536
989
  * @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
990
+ * @param {number} [options.timeout] - Override timeout for this request in milliseconds
991
+ * @returns {Promise<Object>} Song/album information with links to all available platforms. Same structure as {@link Odesli#fetch}
539
992
  *
540
993
  * @example
541
994
  * ```javascript
542
- * // Get song by Spotify ID
995
+ * // Get song by Spotify ID (simple format)
543
996
  * const song = await odesli.getByParams('spotify', 'song', '4Km5HrUvYTaSUfiSGPJeQR');
544
- * console.log(song.title);
997
+ * console.log(`${song.title} by ${song.artist.join(', ')}`);
545
998
  *
546
- * // Get album by Apple Music ID (backward compatible)
999
+ * // Get album by Apple Music ID with country (backward compatible string format)
547
1000
  * const album = await odesli.getByParams('appleMusic', 'album', '123456789', 'GB');
548
1001
  *
549
- * // Using full ID format with options
1002
+ * // Using full ID format with options object
550
1003
  * const song = await odesli.getByParams('spotify', 'song', 'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR', {
551
1004
  * country: 'GB',
552
1005
  * skipCache: true,
553
1006
  * timeout: 5000
554
1007
  * });
1008
+ *
1009
+ * // Extract ID from URL and use with getByParams
1010
+ * const url = 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR';
1011
+ * const platform = odesli.detectPlatform(url);
1012
+ * const id = odesli.extractId(url);
1013
+ * if (platform && id) {
1014
+ * const song = await odesli.getByParams(platform, 'song', id);
1015
+ * }
1016
+ *
1017
+ * // Country-specific fetching
1018
+ * const song = await odesli.getByParams('spotify', 'song', '123', {
1019
+ * country: 'GB' // United Kingdom
1020
+ * });
1021
+ *
1022
+ * // Get country options for UI dropdowns
1023
+ * const countries = Odesli.getCountryOptions();
1024
+ * const uk = countries.find(c => c.code === 'GB');
1025
+ * console.log(uk); // { code: 'GB', name: 'United Kingdom' }
555
1026
  * ```
556
1027
  *
557
1028
  * @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
1029
+ * @throws {Error} When platform name is invalid (not in supported platforms list)
1030
+ * @throws {Error} When type is invalid (must be 'song' or 'album')
1031
+ * @throws {Error} When country code format is invalid (must be ISO 3166-1 Alpha-2)
1032
+ * @throws {Error} When API returns an error (4xx/5xx status codes)
1033
+ * @throws {Error} When request times out
1034
+ *
1035
+ * @see {@link Odesli#fetch} For fetching by URL instead
1036
+ * @see {@link Odesli#getById} For fetching by entity ID
1037
+ * @see {@link Odesli#detectPlatform} To detect platform from URL
1038
+ * @see {@link Odesli#extractId} To extract ID from URL
1039
+ * @see {@link Odesli#getSupportedPlatforms} To get valid platform names
1040
+ * @since 1.1.0
562
1041
  */
563
1042
  async getByParams (platform, type, id, options = {}) {
564
1043
  if (!platform) throw new Error('No `platform` was provided to odesli.getByParams()')
@@ -580,7 +1059,9 @@ module.exports = class Odesli {
580
1059
 
581
1060
  // Validate parameters
582
1061
  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`)
1062
+ throw new Error(
1063
+ `Invalid platform "${platform}". Must be one of: ${SUPPORTED_PLATFORMS.join(', ')}`
1064
+ )
584
1065
  }
585
1066
 
586
1067
  if (!this._validateType(type)) {
@@ -757,179 +1238,379 @@ module.exports = class Odesli {
757
1238
  }
758
1239
 
759
1240
  /**
760
- * Extract status code from error message
1241
+ * Extract status code from error message.
1242
+ *
1243
+ * Parses HTTP status codes from error messages in the format "XXX: ..."
1244
+ *
1245
+ * @param {string} errorMessage - Error message that may contain a status code
1246
+ * @returns {number|null} Extracted status code or null if not found
761
1247
  * @private
1248
+ * @since 1.1.0
762
1249
  */
763
- _extractStatusCode(errorMessage) {
764
- const match = errorMessage.match(/(\\d{3}):/)
765
- return match ? parseInt(match[1]) : null
1250
+ _extractStatusCode (errorMessage) {
1251
+ const match = String(errorMessage || '').match(/\b(\d{3})\b/)
1252
+ return match ? parseInt(match[1], 10) : null
766
1253
  }
767
1254
 
768
1255
  /**
769
- * Determine if an error is retryable
1256
+ * Determine if an error is retryable based on status code.
1257
+ *
1258
+ * Retryable status codes: 408 (Request Timeout), 429 (Too Many Requests),
1259
+ * 500 (Internal Server Error), 502 (Bad Gateway), 503 (Service Unavailable),
1260
+ * 504 (Gateway Timeout).
1261
+ *
1262
+ * @param {string} errorMessage - Error message to check
1263
+ * @returns {boolean} True if the error is retryable
770
1264
  * @private
1265
+ * @since 1.1.0
771
1266
  */
772
- _isRetryableError(errorMessage) {
773
- const retryableStatusCodes = [408, 429, 500, 502, 503, 504]
1267
+ _isRetryableError (errorMessage) {
774
1268
  const statusCode = this._extractStatusCode(errorMessage)
775
- return statusCode ? retryableStatusCodes.includes(statusCode) : false
1269
+ return statusCode ? RETRYABLE_STATUS_CODES.has(statusCode) : false
776
1270
  }
777
1271
 
778
1272
  /**
779
- * Detect platform from URL
1273
+ * Detect platform from a streaming service URL.
1274
+ *
1275
+ * Supported platforms: Spotify, Apple Music, YouTube, YouTube Music, Tidal,
1276
+ * Deezer, SoundCloud, Pandora, Napster, Yandex Music, Spinrilla, Amazon Music.
780
1277
  *
781
- * @param {string} url - URL to analyze
782
- * @returns {string|null} Platform name or null if not recognized
1278
+ * @param {string} url - URL to analyze (must be a valid URL from a supported platform)
1279
+ * @returns {string|null} Platform name (e.g., 'spotify', 'appleMusic', 'youtube') or null if not recognized
783
1280
  *
784
1281
  * @example
785
1282
  * ```javascript
786
- * const platform = odesli.detectPlatform('https://open.spotify.com/track/123');
787
- * console.log(platform); // 'spotify'
1283
+ * // Detect platform from various URLs
1284
+ * odesli.detectPlatform('https://open.spotify.com/track/123'); // 'spotify'
1285
+ * odesli.detectPlatform('https://music.apple.com/us/album/123'); // 'appleMusic'
1286
+ * odesli.detectPlatform('https://www.youtube.com/watch?v=abc'); // 'youtube'
1287
+ * odesli.detectPlatform('https://invalid-url.com'); // null
1288
+ *
1289
+ * // Use with fetch
1290
+ * const url = 'https://open.spotify.com/track/123';
1291
+ * const platform = odesli.detectPlatform(url);
1292
+ * if (platform) {
1293
+ * console.log(`Detected platform: ${platform}`);
1294
+ * const song = await odesli.fetch(url);
1295
+ * }
788
1296
  * ```
1297
+ *
1298
+ * @see {@link Odesli#extractId} To extract the ID from a URL
1299
+ * @see {@link Odesli#getSupportedPlatforms} To get list of all supported platforms
1300
+ * @since 1.1.0
789
1301
  */
790
- detectPlatform (url) {
1302
+ /**
1303
+ * Detect platform from a streaming service URL without requiring an API key.
1304
+ *
1305
+ * @param {string} url - URL to analyze
1306
+ * @returns {string|null} Platform name or null if not recognized
1307
+ * @since 2.0.0
1308
+ */
1309
+ static detectPlatform (url) {
791
1310
  if (!url) return null
792
-
1311
+
793
1312
  try {
794
1313
  const urlObj = new URL(url)
795
1314
  const hostname = urlObj.hostname.toLowerCase()
796
1315
  const pathname = urlObj.pathname.toLowerCase()
797
1316
 
798
- if (['music.youtube.com'].includes(hostname) || (['youtube.com', 'www.youtube.com'].includes(hostname) && pathname.startsWith('/music'))) return 'youtubeMusic'
799
- if (['youtube.com', 'www.youtube.com', 'youtu.be'].includes(hostname)) return 'youtube'
800
- if (['music.amazon.com'].includes(hostname) || (['amazon.com', 'www.amazon.com'].includes(hostname) && pathname.startsWith('/music'))) return 'amazonMusic'
801
- if (['music.yandex.ru'].includes(hostname) || (['yandex.ru'].includes(hostname) && pathname.startsWith('/music'))) return 'yandex'
802
- if (['open.spotify.com', 'spotify.com'].includes(hostname)) return 'spotify'
803
- if (['music.apple.com', 'itunes.apple.com'].includes(hostname)) return 'appleMusic'
1317
+ if (
1318
+ ['music.youtube.com'].includes(hostname) ||
1319
+ (['youtube.com', 'www.youtube.com'].includes(hostname) &&
1320
+ pathname.startsWith('/music'))
1321
+ ) {
1322
+ return 'youtubeMusic'
1323
+ }
1324
+ if (['youtube.com', 'www.youtube.com', 'youtu.be'].includes(hostname)) {
1325
+ return 'youtube'
1326
+ }
1327
+ if (
1328
+ ['music.amazon.com'].includes(hostname) ||
1329
+ (['amazon.com', 'www.amazon.com'].includes(hostname) &&
1330
+ pathname.startsWith('/music'))
1331
+ ) {
1332
+ return 'amazonMusic'
1333
+ }
1334
+ if (
1335
+ ['music.yandex.ru'].includes(hostname) ||
1336
+ (['yandex.ru'].includes(hostname) && pathname.startsWith('/music'))
1337
+ ) {
1338
+ return 'yandex'
1339
+ }
1340
+ if (['open.spotify.com', 'spotify.com'].includes(hostname)) {
1341
+ return 'spotify'
1342
+ }
1343
+ if (['music.apple.com', 'itunes.apple.com'].includes(hostname)) {
1344
+ return 'appleMusic'
1345
+ }
804
1346
  if (['tidal.com', 'listen.tidal.com'].includes(hostname)) return 'tidal'
805
1347
  if (['deezer.com', 'www.deezer.com'].includes(hostname)) return 'deezer'
806
- if (['soundcloud.com', 'www.soundcloud.com'].includes(hostname)) return 'soundcloud'
1348
+ if (['soundcloud.com', 'www.soundcloud.com'].includes(hostname)) {
1349
+ return 'soundcloud'
1350
+ }
807
1351
  if (['pandora.com', 'www.pandora.com'].includes(hostname)) return 'pandora'
808
1352
  if (['napster.com', 'us.napster.com'].includes(hostname)) return 'napster'
809
- if (['spinrilla.com', 'www.spinrilla.com'].includes(hostname)) return 'spinrilla'
1353
+ if (['spinrilla.com', 'www.spinrilla.com'].includes(hostname)) {
1354
+ return 'spinrilla'
1355
+ }
1356
+ if (['audiomack.com', 'www.audiomack.com'].includes(hostname)) {
1357
+ return 'audiomack'
1358
+ }
1359
+ if (['play.anghami.com', 'anghami.com', 'www.anghami.com'].includes(hostname)) {
1360
+ return 'anghami'
1361
+ }
1362
+ if (['boomplay.com', 'www.boomplay.com'].includes(hostname)) {
1363
+ return 'boomplay'
1364
+ }
1365
+ if (['audius.co', 'www.audius.co'].includes(hostname)) return 'audius'
810
1366
  } catch {
811
1367
  // Malformed URL, just ignore.
812
1368
  }
813
-
1369
+
814
1370
  return null
815
1371
  }
816
1372
 
1373
+ detectPlatform (url) {
1374
+ return Odesli.detectPlatform(url)
1375
+ }
1376
+
817
1377
  /**
818
- * Extract platform-specific ID from a URL
1378
+ * Extract platform-specific ID from a streaming service URL.
1379
+ *
1380
+ * This method parses URLs from various platforms and extracts the unique
1381
+ * identifier used by that platform. Useful for building entity IDs or
1382
+ * working with platform-specific APIs.
819
1383
  *
820
- * @param {string} url - URL to extract ID from
821
- * @returns {string|null} Platform-specific ID or null if not found
1384
+ * @param {string} url - URL to extract ID from (must be a valid URL from a supported platform)
1385
+ * @returns {string|null} Platform-specific ID (e.g., track ID, album ID) or null if not found/invalid
822
1386
  *
823
1387
  * @example
824
1388
  * ```javascript
825
- * const id = odesli.extractId('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR');
826
- * console.log(id); // '4Km5HrUvYTaSUfiSGPJeQR'
1389
+ * // Extract IDs from various platforms
1390
+ * odesli.extractId('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR');
1391
+ * // Returns: '4Km5HrUvYTaSUfiSGPJeQR'
1392
+ *
1393
+ * odesli.extractId('https://music.apple.com/us/album/test/123456789?i=987654321');
1394
+ * // Returns: '987654321' (song ID) or '123456789' (album ID)
1395
+ *
1396
+ * odesli.extractId('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
1397
+ * // Returns: 'dQw4w9WgXcQ'
1398
+ *
1399
+ * // Use with getByParams
1400
+ * const url = 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR';
1401
+ * const platform = odesli.detectPlatform(url);
1402
+ * const id = odesli.extractId(url);
1403
+ * if (platform && id) {
1404
+ * const song = await odesli.getByParams(platform, 'song', id);
1405
+ * }
827
1406
  * ```
1407
+ *
1408
+ * @see {@link Odesli#detectPlatform} To detect the platform from a URL
1409
+ * @see {@link Odesli#getByParams} To fetch using platform, type, and ID
1410
+ * @since 1.1.0
828
1411
  */
829
- extractId (url) {
1412
+ /**
1413
+ * Extract platform-specific ID from a streaming service URL without an API key.
1414
+ *
1415
+ * @param {string} url - URL to extract ID from
1416
+ * @returns {string|null} Platform-specific ID or null if not found/invalid
1417
+ * @since 2.0.0
1418
+ */
1419
+ static extractId (url) {
830
1420
  try {
831
1421
  const urlObj = new URL(url)
832
1422
  const pathParts = urlObj.pathname.split('/').filter(Boolean)
833
1423
  const hostname = urlObj.hostname.toLowerCase()
834
-
1424
+
835
1425
  // Spotify
836
1426
  if (hostname === 'open.spotify.com') {
837
1427
  return pathParts[pathParts.length - 1]
838
1428
  }
839
-
1429
+
840
1430
  // Apple Music - improved to handle various URL formats
841
1431
  if (['music.apple.com', 'itunes.apple.com'].includes(hostname)) {
842
- // Handle album URLs with track IDs: /album/name/id?i=trackId
843
1432
  const trackIdMatch = url.match(/[?&]i=(\d+)/)
844
1433
  if (trackIdMatch) {
845
1434
  return trackIdMatch[1]
846
1435
  }
847
-
848
- // Handle direct track URLs: /album/name/id
1436
+
849
1437
  const idMatch = url.match(/\/id(\d+)/)
850
1438
  if (idMatch) {
851
1439
  return idMatch[1]
852
1440
  }
853
-
854
- // Handle other Apple Music URL formats
855
- const lastPart = pathParts[pathParts.length - 1];
1441
+
1442
+ const lastPart = pathParts[pathParts.length - 1]
856
1443
  if (/^\d+$/.test(lastPart)) {
857
- return lastPart;
1444
+ return lastPart
858
1445
  }
859
-
1446
+
860
1447
  return null
861
1448
  }
862
-
1449
+
863
1450
  // YouTube
864
- if (['youtube.com', 'www.youtube.com', 'music.youtube.com', 'youtu.be'].includes(hostname)) {
1451
+ if (
1452
+ [
1453
+ 'youtube.com',
1454
+ 'www.youtube.com',
1455
+ 'music.youtube.com',
1456
+ 'youtu.be'
1457
+ ].includes(hostname)
1458
+ ) {
865
1459
  const videoMatch = url.match(/(?:v=|\/)([a-zA-Z0-9_-]{11})/)
866
1460
  return videoMatch ? videoMatch[1] : null
867
1461
  }
868
-
1462
+
869
1463
  // Tidal
870
1464
  if (['tidal.com', 'listen.tidal.com'].includes(hostname)) {
871
1465
  return pathParts[pathParts.length - 1]
872
1466
  }
873
-
1467
+
874
1468
  // Deezer
875
1469
  if (['deezer.com', 'www.deezer.com'].includes(hostname)) {
876
1470
  return pathParts[pathParts.length - 1]
877
1471
  }
878
-
1472
+
879
1473
  // Amazon Music
880
- if (['music.amazon.com'].includes(hostname) || (['amazon.com', 'www.amazon.com'].includes(hostname) && urlObj.pathname.toLowerCase().startsWith('/music'))) {
1474
+ if (
1475
+ ['music.amazon.com'].includes(hostname) ||
1476
+ (['amazon.com', 'www.amazon.com'].includes(hostname) &&
1477
+ urlObj.pathname.toLowerCase().startsWith('/music'))
1478
+ ) {
881
1479
  const idMatch = url.match(/\/albums\/([^/]+)/)
882
1480
  return idMatch ? idMatch[1] : null
883
1481
  }
884
-
1482
+
885
1483
  // SoundCloud
886
1484
  if (['soundcloud.com', 'www.soundcloud.com'].includes(hostname)) {
887
1485
  return pathParts[pathParts.length - 1]
888
1486
  }
889
-
1487
+
890
1488
  return null
891
1489
  } catch {
892
1490
  return null
893
1491
  }
894
1492
  }
895
1493
 
1494
+ extractId (url) {
1495
+ return Odesli.extractId(url)
1496
+ }
1497
+
896
1498
  /**
897
- * Get supported platforms list
1499
+ * Get list of all supported streaming platforms without an API key.
898
1500
  *
899
1501
  * @returns {Array<string>} Array of supported platform names
900
- *
901
- * @example
902
- * ```javascript
903
- * const platforms = odesli.getSupportedPlatforms();
904
- * console.log(platforms); // ['spotify', 'appleMusic', 'youtube', ...]
905
- * ```
1502
+ * @since 2.0.0
906
1503
  */
1504
+ static getSupportedPlatforms () {
1505
+ return [...SUPPORTED_PLATFORMS]
1506
+ }
1507
+
907
1508
  getSupportedPlatforms () {
908
- return [
909
- 'spotify', 'itunes', 'appleMusic', 'youtube', 'youtubeMusic',
910
- 'google', 'googleStore', 'pandora', 'deezer', 'tidal',
911
- 'amazonStore', 'amazonMusic', 'soundcloud', 'napster', 'yandex', 'spinrilla'
912
- ]
1509
+ return Odesli.getSupportedPlatforms()
1510
+ }
1511
+
1512
+ /**
1513
+ * Build a Songlink landing-page URL for a track/album URL without calling the API.
1514
+ *
1515
+ * Useful when you do not have an allowlisted API key and only need a shareable
1516
+ * `https://song.link/...` page.
1517
+ *
1518
+ * @param {string} url - Streaming platform URL
1519
+ * @returns {string} Songlink page URL
1520
+ * @throws {OdesliError} When the URL is missing or invalid
1521
+ * @since 2.0.0
1522
+ */
1523
+ static getPageUrl (url) {
1524
+ if (!url || typeof url !== 'string') {
1525
+ throw new OdesliError('A valid URL is required to build a Songlink page URL.', {
1526
+ code: 'INVALID_URL',
1527
+ retryable: false,
1528
+ docsUrl: SUNSET_DOCS_URL
1529
+ })
1530
+ }
1531
+
1532
+ try {
1533
+ // Validate URL format
1534
+ // eslint-disable-next-line no-new
1535
+ new URL(url)
1536
+ } catch (err) {
1537
+ throw new OdesliError('A valid URL is required to build a Songlink page URL.', {
1538
+ code: 'INVALID_URL',
1539
+ retryable: false,
1540
+ docsUrl: SUNSET_DOCS_URL,
1541
+ cause: err
1542
+ })
1543
+ }
1544
+
1545
+ return `https://song.link/${url}`
1546
+ }
1547
+
1548
+ getPageUrl (url) {
1549
+ return Odesli.getPageUrl(url)
913
1550
  }
914
1551
 
915
1552
  /**
916
- * Get the current User-Agent string used for requests
1553
+ * Get the current User-Agent string used for API requests.
1554
+ *
1555
+ * The User-Agent includes package name, version, Node.js version, and platform.
1556
+ * This is automatically generated and used in all API requests.
1557
+ *
1558
+ * @returns {string} Current User-Agent string (e.g., 'odesli.js/2.0.0 (Node.js v18.0.0; win32)')
917
1559
  *
918
- * @returns {string} Current User-Agent string
919
1560
  * @example
920
1561
  * ```javascript
921
- * const odesli = new Odesli();
922
- * console.log(odesli.getUserAgent());
923
- * // Output: "@mattraus/odesli.js/1.1.2 (Node.js v18.17.0; win32)"
1562
+ * const ua = odesli.getUserAgent();
1563
+ * console.log(ua);
1564
+ * // Output: 'odesli.js/2.0.0 (Node.js v18.0.0; win32)'
1565
+ *
1566
+ * // Use for debugging or logging
1567
+ * console.log(`Making request with User-Agent: ${odesli.getUserAgent()}`);
924
1568
  * ```
1569
+ *
1570
+ * @since 1.1.0
925
1571
  */
926
1572
  getUserAgent () {
927
1573
  return generateUserAgent()
928
1574
  }
929
1575
 
930
1576
  /**
931
- * Get all valid ISO 3166-1 alpha-2 country codes and names
932
- * @returns {Array<{ code: string, name: string }>} Array of country code/name pairs
1577
+ * Get all available country codes with their full names for use in UI dropdowns or validation.
1578
+ *
1579
+ * @summary Retrieve all valid ISO 3166-1 Alpha-2 country codes with full names for UI components.
1580
+ *
1581
+ * Returns an array of objects containing ISO 3166-1 Alpha-2 country codes and their
1582
+ * corresponding full country names. Useful for building country selection UI components
1583
+ * or validating country codes.
1584
+ *
1585
+ * @static
1586
+ * @readonly
1587
+ * @returns {Array<{ code: string, name: string }>} Array of country code/name pairs, sorted alphabetically by name
1588
+ * @returns {string} returns[].code - ISO 3166-1 Alpha-2 country code (e.g., 'US', 'GB', 'CA')
1589
+ * @returns {string} returns[].name - Full country name (e.g., 'United States', 'United Kingdom', 'Canada')
1590
+ *
1591
+ * @example
1592
+ * ```javascript
1593
+ * // Get all country options
1594
+ * const countries = Odesli.getCountryOptions();
1595
+ * console.log(`Total countries: ${countries.length}`); // 249
1596
+ *
1597
+ * // Use in a dropdown
1598
+ * countries.forEach(country => {
1599
+ * console.log(`${country.code}: ${country.name}`);
1600
+ * });
1601
+ *
1602
+ * // Find a specific country
1603
+ * const uk = countries.find(c => c.code === 'GB');
1604
+ * console.log(uk); // { code: 'GB', name: 'United Kingdom' }
1605
+ *
1606
+ * // Get top 10 countries
1607
+ * const topCountries = countries.slice(0, 10);
1608
+ * ```
1609
+ *
1610
+ * @see {@link Odesli#fetch} For using country codes in fetch operations
1611
+ * @see {@link Odesli#getByParams} For using country codes in getByParams
1612
+ * @see {@link Odesli#getById} For using country codes in getById
1613
+ * @since 1.2.0
933
1614
  */
934
1615
  static getCountryOptions() {
935
1616
  // List from the CountryCode enum
@@ -1186,3 +1867,14 @@ module.exports = class Odesli {
1186
1867
  ]
1187
1868
  }
1188
1869
  }
1870
+
1871
+ Odesli.Odesli = Odesli
1872
+ Odesli.default = Odesli
1873
+ Odesli.OdesliError = OdesliError
1874
+ Odesli.SUNSET_DOCS_URL = SUNSET_DOCS_URL
1875
+
1876
+ module.exports = Odesli
1877
+ module.exports.Odesli = Odesli
1878
+ module.exports.default = Odesli
1879
+ module.exports.OdesliError = OdesliError
1880
+ module.exports.SUNSET_DOCS_URL = SUNSET_DOCS_URL