odesli.js 1.3.9 → 2.0.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/README.md +97 -85
- package/lib/index.d.ts +114 -17
- package/lib/index.js +941 -201
- package/lib/index.mjs +6 -3
- package/lib/metrics.js +1 -1
- package/lib/rate-limiter.js +12 -8
- package/package.json +24 -5
- package/.eslintrc.js +0 -33
- package/.gitattributes +0 -1
- package/.github/dependabot.yml +0 -56
- package/.github/workflows/ci.yml +0 -94
- package/.github/workflows/dependabot-auto-merge.yml +0 -137
- package/.github/workflows/publish-github-packages.yml +0 -46
- package/.github/workflows/publish-npm.yml +0 -133
- package/.prettierignore +0 -31
- package/.prettierrc +0 -11
- package/API_IMPROVEMENTS.md +0 -318
- package/CHANGELOG.md +0 -256
- package/CODE_OF_CONDUCT.md +0 -125
- package/CONTRIBUTING.md +0 -104
- package/RELEASE_NOTES_1.1.0.md +0 -84
- package/SECURITY.md +0 -112
- package/examples/README.md +0 -442
- package/examples/advanced-features-example.js +0 -205
- package/examples/advanced-usage.js +0 -247
- package/examples/basic-usage.js +0 -100
- package/examples/cache-test.js +0 -119
- package/examples/rate-limiter-strategies.js +0 -83
- package/examples/test-apple-music-extraction.js +0 -60
- package/examples/user-agent-example.js +0 -46
- package/jest.config.js +0 -14
- package/jsdoc.json +0 -24
- package/scripts/version-bump.js +0 -41
- package/tests/advanced-features.test.js +0 -423
- package/tests/odesli.test.js +0 -742
- package/tests/setup.js +0 -22
- package/tsconfig.json +0 -21
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
|
-
*
|
|
15
|
-
*
|
|
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,28 +276,47 @@ function clearExpiredCache () {
|
|
|
33
276
|
}
|
|
34
277
|
|
|
35
278
|
/**
|
|
36
|
-
* Get cached response if available and not expired
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
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()
|
|
44
292
|
const cached = cache.get(key)
|
|
45
293
|
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
|
|
46
|
-
if (metrics
|
|
294
|
+
if (metrics && typeof metrics.recordRequest === 'function') {
|
|
295
|
+
const now = Date.now()
|
|
296
|
+
metrics.recordRequest({
|
|
297
|
+
url: key,
|
|
298
|
+
startTime: now,
|
|
299
|
+
endTime: now,
|
|
300
|
+
success: true,
|
|
301
|
+
statusCode: 200,
|
|
302
|
+
cacheHit: true
|
|
303
|
+
})
|
|
304
|
+
}
|
|
47
305
|
return cached.data
|
|
48
306
|
}
|
|
49
|
-
if (metrics) metrics.recordRequest({ cacheHit: false })
|
|
50
307
|
return null
|
|
51
308
|
}
|
|
52
309
|
|
|
53
310
|
/**
|
|
54
|
-
* Cache a response
|
|
55
|
-
*
|
|
311
|
+
* Cache a response with timestamp for TTL management.
|
|
312
|
+
*
|
|
313
|
+
* Stores response data in the cache with a timestamp. The cache entry
|
|
314
|
+
* will be automatically expired after CACHE_TTL milliseconds.
|
|
315
|
+
*
|
|
316
|
+
* @param {string} key - Cache key (typically the full API URL)
|
|
56
317
|
* @param {Object} data - Response data to cache
|
|
57
318
|
* @private
|
|
319
|
+
* @since 1.1.0
|
|
58
320
|
*/
|
|
59
321
|
function cacheResponse (key, data) {
|
|
60
322
|
cache.set(key, {
|
|
@@ -63,22 +325,33 @@ function cacheResponse (key, data) {
|
|
|
63
325
|
})
|
|
64
326
|
}
|
|
65
327
|
|
|
328
|
+
/**
|
|
329
|
+
* @module odesli
|
|
330
|
+
* @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.
|
|
331
|
+
* @author Mattr <me@mtr.gg>
|
|
332
|
+
* @version 2.0.0
|
|
333
|
+
* @license ISC
|
|
334
|
+
* @see {@link https://github.com/MattrAus/odesli.js|GitHub Repository}
|
|
335
|
+
* @see {@link https://www.npmjs.com/package/odesli.js|NPM Package}
|
|
336
|
+
*/
|
|
337
|
+
|
|
66
338
|
/**
|
|
67
339
|
* Odesli API Client
|
|
68
340
|
*
|
|
69
|
-
* A Node.js client for the Odesli API
|
|
70
|
-
*
|
|
341
|
+
* @summary A Node.js client for the Songlink/Odesli API that helps you find links to music across multiple streaming platforms.
|
|
342
|
+
* @class
|
|
343
|
+
* @memberof module:odesli
|
|
344
|
+
* @version 2.0.0
|
|
345
|
+
* @tutorial getting-started
|
|
346
|
+
* @tutorial advanced-usage
|
|
71
347
|
* @example
|
|
72
348
|
* ```javascript
|
|
73
349
|
* const Odesli = require('odesli.js');
|
|
74
350
|
*
|
|
75
|
-
* //
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
* // Or with API key for higher limits
|
|
351
|
+
* // Prefer environment configuration in production
|
|
352
|
+
* // process.env.ODESLI_API_KEY = 'your-allowlisted-key'
|
|
79
353
|
* const odesli = new Odesli({
|
|
80
|
-
* apiKey:
|
|
81
|
-
* version: 'v1-alpha.1'
|
|
354
|
+
* apiKey: process.env.ODESLI_API_KEY
|
|
82
355
|
* });
|
|
83
356
|
*
|
|
84
357
|
* // Fetch a song by URL
|
|
@@ -86,12 +359,12 @@ function cacheResponse (key, data) {
|
|
|
86
359
|
* console.log(`${song.title} by ${song.artist[0]}`);
|
|
87
360
|
* ```
|
|
88
361
|
*/
|
|
89
|
-
|
|
362
|
+
class Odesli {
|
|
90
363
|
/**
|
|
91
364
|
* Create a new Odesli instance
|
|
92
365
|
*
|
|
93
|
-
* @param {Object} options - Configuration options
|
|
94
|
-
* @param {string} [options.apiKey] -
|
|
366
|
+
* @param {Object} [options={}] - Configuration options
|
|
367
|
+
* @param {string} [options.apiKey] - Allowlisted Songlink/Odesli API key. Falls back to `process.env.ODESLI_API_KEY`. Required as of v2.0.0.
|
|
95
368
|
* @param {string} [options.version='v1-alpha.1'] - API version to use
|
|
96
369
|
* @param {boolean} [options.cache=true] - Enable response caching (5 minute TTL)
|
|
97
370
|
* @param {number} [options.timeout=10000] - Request timeout in milliseconds
|
|
@@ -105,12 +378,12 @@ module.exports = class Odesli {
|
|
|
105
378
|
*
|
|
106
379
|
* @example
|
|
107
380
|
* ```javascript
|
|
108
|
-
* //
|
|
109
|
-
* const odesli = new Odesli();
|
|
381
|
+
* // From environment variable
|
|
382
|
+
* const odesli = new Odesli(); // uses process.env.ODESLI_API_KEY
|
|
110
383
|
*
|
|
111
|
-
* //
|
|
384
|
+
* // Explicit API key
|
|
112
385
|
* const odesli = new Odesli({
|
|
113
|
-
* apiKey:
|
|
386
|
+
* apiKey: process.env.ODESLI_API_KEY,
|
|
114
387
|
* version: 'v1-alpha.1',
|
|
115
388
|
* cache: true,
|
|
116
389
|
* timeout: 10000,
|
|
@@ -121,7 +394,10 @@ module.exports = class Odesli {
|
|
|
121
394
|
* });
|
|
122
395
|
*
|
|
123
396
|
* // Disable metrics
|
|
124
|
-
* const odesli = new Odesli({
|
|
397
|
+
* const odesli = new Odesli({
|
|
398
|
+
* apiKey: process.env.ODESLI_API_KEY,
|
|
399
|
+
* metrics: false
|
|
400
|
+
* });
|
|
125
401
|
* ```
|
|
126
402
|
*/
|
|
127
403
|
constructor (options = {}) {
|
|
@@ -139,7 +415,22 @@ module.exports = class Odesli {
|
|
|
139
415
|
metrics
|
|
140
416
|
} = options || {}
|
|
141
417
|
|
|
142
|
-
|
|
418
|
+
const resolvedKey = String(
|
|
419
|
+
apiKey ?? process.env.ODESLI_API_KEY ?? ''
|
|
420
|
+
).trim()
|
|
421
|
+
|
|
422
|
+
if (!resolvedKey) {
|
|
423
|
+
throw new OdesliError(
|
|
424
|
+
'Songlink/Odesli retired its unauthenticated public API on July 31, 2026. Pass { apiKey } or set ODESLI_API_KEY with an allowlisted key.',
|
|
425
|
+
{
|
|
426
|
+
code: 'MISSING_API_KEY',
|
|
427
|
+
retryable: false,
|
|
428
|
+
docsUrl: SUNSET_DOCS_URL
|
|
429
|
+
}
|
|
430
|
+
)
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
this.apiKey = resolvedKey
|
|
143
434
|
this.version = version || 'v1-alpha.1'
|
|
144
435
|
this.cacheEnabled = cache
|
|
145
436
|
this.timeout = timeout
|
|
@@ -152,8 +443,10 @@ module.exports = class Odesli {
|
|
|
152
443
|
|
|
153
444
|
if (metrics === false) {
|
|
154
445
|
this.metrics = new MetricsCollector({ enabled: false })
|
|
446
|
+
} else if (metrics && typeof metrics === 'object') {
|
|
447
|
+
this.metrics = metrics
|
|
155
448
|
} else {
|
|
156
|
-
this.metrics =
|
|
449
|
+
this.metrics = new MetricsCollector()
|
|
157
450
|
}
|
|
158
451
|
}
|
|
159
452
|
|
|
@@ -192,12 +485,9 @@ module.exports = class Odesli {
|
|
|
192
485
|
*/
|
|
193
486
|
_validatePlatform (platform) {
|
|
194
487
|
if (!this.validateParams) return true
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
'amazonStore', 'amazonMusic', 'soundcloud', 'napster', 'yandex', 'spinrilla'
|
|
199
|
-
]
|
|
200
|
-
return validPlatforms.includes(platform.toLowerCase())
|
|
488
|
+
return SUPPORTED_PLATFORMS.map((p) => p.toLowerCase()).includes(
|
|
489
|
+
String(platform || '').toLowerCase()
|
|
490
|
+
)
|
|
201
491
|
}
|
|
202
492
|
|
|
203
493
|
/**
|
|
@@ -224,111 +514,209 @@ module.exports = class Odesli {
|
|
|
224
514
|
}
|
|
225
515
|
|
|
226
516
|
/**
|
|
227
|
-
* Make a request to the Odesli API with caching, timeout, and retry support
|
|
517
|
+
* Make a request to the Odesli API with caching, timeout, and retry support.
|
|
228
518
|
*
|
|
229
|
-
*
|
|
230
|
-
*
|
|
519
|
+
* This method handles:
|
|
520
|
+
* - Cache checking and storage (keyed without the API key)
|
|
521
|
+
* - Request timeouts
|
|
522
|
+
* - Automatic retries with exponential backoff for retryable failures
|
|
523
|
+
* - Structured error handling for sunset / auth / rate-limit responses
|
|
524
|
+
*
|
|
525
|
+
* @param {string} path - API endpoint path (e.g., 'links?url=...')
|
|
526
|
+
* @returns {Promise<Object>} API response object
|
|
527
|
+
* @throws {OdesliError} When the request fails
|
|
231
528
|
* @private
|
|
529
|
+
* @since 1.1.0
|
|
232
530
|
*/
|
|
233
531
|
async _request (path) {
|
|
234
|
-
const
|
|
235
|
-
|
|
236
|
-
|
|
532
|
+
const { requestUrl, cacheKey } = buildRequestUrls(
|
|
533
|
+
this.baseUrl,
|
|
534
|
+
this.version,
|
|
535
|
+
path,
|
|
536
|
+
this.apiKey
|
|
537
|
+
)
|
|
538
|
+
|
|
539
|
+
// Check cache first if enabled (secret-free cache key)
|
|
237
540
|
if (this.cacheEnabled) {
|
|
238
|
-
const cached = getCachedResponse(
|
|
541
|
+
const cached = getCachedResponse(cacheKey, this.metrics)
|
|
239
542
|
if (cached) {
|
|
240
543
|
this._log(`Cache hit for ${path}`, 'debug')
|
|
241
544
|
return cached
|
|
242
545
|
}
|
|
243
546
|
}
|
|
244
547
|
|
|
548
|
+
const requestStartTime = Date.now()
|
|
245
549
|
let lastError
|
|
246
550
|
for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
|
|
247
551
|
try {
|
|
248
|
-
this._log(
|
|
249
|
-
|
|
250
|
-
|
|
552
|
+
this._log(
|
|
553
|
+
`Request attempt ${attempt}/${this.maxRetries} for ${path}`,
|
|
554
|
+
'debug'
|
|
555
|
+
)
|
|
556
|
+
|
|
251
557
|
const controller = new AbortController()
|
|
252
558
|
const timeoutId = setTimeout(() => controller.abort(), this.timeout)
|
|
253
559
|
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
560
|
+
let response
|
|
561
|
+
try {
|
|
562
|
+
response = await fetch(requestUrl, {
|
|
563
|
+
signal: controller.signal,
|
|
564
|
+
headers: {
|
|
565
|
+
'User-Agent': generateUserAgent(),
|
|
566
|
+
...this.customHeaders,
|
|
567
|
+
Accept: 'application/json'
|
|
568
|
+
}
|
|
569
|
+
})
|
|
570
|
+
} finally {
|
|
571
|
+
clearTimeout(timeoutId)
|
|
572
|
+
}
|
|
262
573
|
|
|
263
|
-
|
|
574
|
+
if (!response) {
|
|
575
|
+
throw new OdesliError('API returned an unexpected result.', {
|
|
576
|
+
code: 'UNEXPECTED_RESPONSE',
|
|
577
|
+
retryable: true,
|
|
578
|
+
docsUrl: SUNSET_DOCS_URL
|
|
579
|
+
})
|
|
580
|
+
}
|
|
264
581
|
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
582
|
+
const bodyText = await response.text()
|
|
583
|
+
const result = parseJsonBody(bodyText)
|
|
584
|
+
|
|
585
|
+
const payloadStatus =
|
|
586
|
+
result && typeof result.statusCode === 'number'
|
|
587
|
+
? result.statusCode
|
|
588
|
+
: null
|
|
589
|
+
const effectiveStatus = payloadStatus || response.status
|
|
590
|
+
|
|
591
|
+
if (!response.ok || (payloadStatus && payloadStatus !== 200)) {
|
|
592
|
+
throw createApiError(
|
|
593
|
+
effectiveStatus,
|
|
594
|
+
result,
|
|
595
|
+
response.statusText,
|
|
596
|
+
response.headers
|
|
597
|
+
)
|
|
271
598
|
}
|
|
272
599
|
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
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
|
|
600
|
+
if (bodyText && result === null) {
|
|
601
|
+
throw new OdesliError('API returned an unexpected result.', {
|
|
602
|
+
code: 'UNEXPECTED_RESPONSE',
|
|
603
|
+
statusCode: response.status,
|
|
604
|
+
retryable: true,
|
|
605
|
+
docsUrl: SUNSET_DOCS_URL
|
|
606
|
+
})
|
|
287
607
|
}
|
|
288
608
|
|
|
289
|
-
// Cache successful responses
|
|
290
609
|
if (this.cacheEnabled && result) {
|
|
291
|
-
cacheResponse(
|
|
610
|
+
cacheResponse(cacheKey, result)
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
if (this.metrics && typeof this.metrics.recordRequest === 'function') {
|
|
614
|
+
this.metrics.recordRequest({
|
|
615
|
+
url: cacheKey,
|
|
616
|
+
startTime: requestStartTime,
|
|
617
|
+
endTime: Date.now(),
|
|
618
|
+
success: true,
|
|
619
|
+
statusCode: response.status,
|
|
620
|
+
cacheHit: false
|
|
621
|
+
})
|
|
292
622
|
}
|
|
293
623
|
|
|
294
624
|
this._log(`Request successful for ${path}`, 'debug')
|
|
295
625
|
return result
|
|
296
626
|
} catch (err) {
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
627
|
+
if (err && err.name === 'AbortError') {
|
|
628
|
+
lastError = new OdesliError(
|
|
629
|
+
`Request timeout after ${this.timeout}ms`,
|
|
630
|
+
{
|
|
631
|
+
code: 'TIMEOUT',
|
|
632
|
+
retryable: true,
|
|
633
|
+
docsUrl: SUNSET_DOCS_URL,
|
|
634
|
+
cause: err
|
|
635
|
+
}
|
|
636
|
+
)
|
|
637
|
+
} else if (err instanceof OdesliError) {
|
|
638
|
+
lastError = err
|
|
639
|
+
} else {
|
|
640
|
+
lastError = new OdesliError(err.message || 'Request failed', {
|
|
641
|
+
code: 'NETWORK_ERROR',
|
|
642
|
+
retryable: true,
|
|
643
|
+
docsUrl: SUNSET_DOCS_URL,
|
|
644
|
+
cause: err
|
|
645
|
+
})
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
const shouldRetry =
|
|
649
|
+
lastError.retryable === true &&
|
|
650
|
+
!NON_RETRYABLE_STATUS_CODES.has(lastError.statusCode) &&
|
|
651
|
+
attempt < this.maxRetries
|
|
652
|
+
|
|
653
|
+
if (!shouldRetry) {
|
|
654
|
+
this._log(`Non-retryable error: ${lastError.message}`, 'error')
|
|
302
655
|
break
|
|
303
656
|
}
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
657
|
+
|
|
658
|
+
const delay =
|
|
659
|
+
typeof lastError.retryAfterMs === 'number'
|
|
660
|
+
? lastError.retryAfterMs
|
|
661
|
+
: this.retryDelay * Math.pow(2, attempt - 1)
|
|
662
|
+
if (
|
|
663
|
+
lastError.statusCode === 429 &&
|
|
664
|
+
this.metrics &&
|
|
665
|
+
typeof this.metrics.recordRateLimit === 'function'
|
|
666
|
+
) {
|
|
667
|
+
this.metrics.recordRateLimit(delay)
|
|
309
668
|
}
|
|
669
|
+
this._log(
|
|
670
|
+
`Request failed, retrying in ${delay}ms: ${lastError.message}`,
|
|
671
|
+
'warn'
|
|
672
|
+
)
|
|
673
|
+
await new Promise((resolve) => setTimeout(resolve, delay))
|
|
310
674
|
}
|
|
311
675
|
}
|
|
312
676
|
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
677
|
+
if (this.metrics && typeof this.metrics.recordRequest === 'function') {
|
|
678
|
+
this.metrics.recordRequest({
|
|
679
|
+
url: cacheKey,
|
|
680
|
+
startTime: requestStartTime,
|
|
681
|
+
endTime: Date.now(),
|
|
682
|
+
success: false,
|
|
683
|
+
statusCode: lastError.statusCode,
|
|
684
|
+
error: lastError,
|
|
685
|
+
cacheHit: false
|
|
686
|
+
})
|
|
316
687
|
}
|
|
317
|
-
if (
|
|
318
|
-
|
|
688
|
+
if (this.metrics && typeof this.metrics.recordError === 'function') {
|
|
689
|
+
this.metrics.recordError(lastError, {
|
|
690
|
+
url: cacheKey,
|
|
691
|
+
statusCode: lastError.statusCode
|
|
692
|
+
})
|
|
319
693
|
}
|
|
320
|
-
|
|
694
|
+
|
|
321
695
|
throw lastError
|
|
322
696
|
}
|
|
323
697
|
|
|
324
698
|
/**
|
|
325
|
-
* Clear the response cache
|
|
699
|
+
* Clear the response cache and reset cache-related metrics.
|
|
700
|
+
*
|
|
701
|
+
* This removes all cached API responses. Useful when you need fresh data
|
|
702
|
+
* or want to free up memory. Cache statistics are also reset.
|
|
326
703
|
*
|
|
327
704
|
* @example
|
|
328
705
|
* ```javascript
|
|
329
|
-
* const odesli = new Odesli();
|
|
330
|
-
*
|
|
706
|
+
* const odesli = new Odesli({ apiKey: process.env.ODESLI_API_KEY });
|
|
707
|
+
*
|
|
708
|
+
* // Fetch and cache a song
|
|
709
|
+
* await odesli.fetch('https://open.spotify.com/track/123');
|
|
710
|
+
*
|
|
711
|
+
* // Later, clear cache to get fresh data
|
|
712
|
+
* odesli.clearCache();
|
|
713
|
+
*
|
|
714
|
+
* // Next fetch will make a new API request
|
|
715
|
+
* await odesli.fetch('https://open.spotify.com/track/123');
|
|
331
716
|
* ```
|
|
717
|
+
*
|
|
718
|
+
* @see {@link Odesli#getCacheStats} To check cache statistics before clearing
|
|
719
|
+
* @since 1.1.0
|
|
332
720
|
*/
|
|
333
721
|
clearCache () {
|
|
334
722
|
cache.clear()
|
|
@@ -337,9 +725,26 @@ module.exports = class Odesli {
|
|
|
337
725
|
}
|
|
338
726
|
|
|
339
727
|
/**
|
|
340
|
-
* Get cache statistics
|
|
728
|
+
* Get cache statistics including hit rate, size, and performance metrics.
|
|
729
|
+
*
|
|
730
|
+
* @summary Retrieve cache performance statistics including hit rate and size.
|
|
341
731
|
*
|
|
342
|
-
* @returns {Object} Cache statistics
|
|
732
|
+
* @returns {Object} Cache statistics object
|
|
733
|
+
* @returns {number} returns.hitCount - Number of cache hits
|
|
734
|
+
* @returns {number} returns.missCount - Number of cache misses
|
|
735
|
+
* @returns {number} returns.hitRate - Cache hit rate (0-1, where 1 is 100%)
|
|
736
|
+
* @returns {number} returns.size - Current number of cached items
|
|
737
|
+
*
|
|
738
|
+
* @example
|
|
739
|
+
* ```javascript
|
|
740
|
+
* const stats = odesli.getCacheStats();
|
|
741
|
+
* console.log(`Cache hit rate: ${(stats.hitRate * 100).toFixed(1)}%`);
|
|
742
|
+
* console.log(`Cached items: ${stats.size}`);
|
|
743
|
+
* ```
|
|
744
|
+
*
|
|
745
|
+
* @see {@link Odesli#clearCache} To clear the cache
|
|
746
|
+
* @see {@link Odesli#getMetrics} For more detailed metrics
|
|
747
|
+
* @since 1.1.0
|
|
343
748
|
*/
|
|
344
749
|
getCacheStats () {
|
|
345
750
|
const summary = this.metrics.getSummary()
|
|
@@ -352,34 +757,94 @@ module.exports = class Odesli {
|
|
|
352
757
|
}
|
|
353
758
|
|
|
354
759
|
/**
|
|
355
|
-
* Get the metrics collector instance for
|
|
760
|
+
* Get the metrics collector instance for detailed performance and usage statistics.
|
|
761
|
+
*
|
|
762
|
+
* The metrics collector tracks:
|
|
763
|
+
* - Request counts (total, successful, failed)
|
|
764
|
+
* - Cache performance (hits, misses, hit rate)
|
|
765
|
+
* - Response times (average, min, max)
|
|
766
|
+
* - Error rates and types
|
|
767
|
+
* - Rate limit events
|
|
768
|
+
*
|
|
769
|
+
* @returns {MetricsCollector} The metrics collector instance with detailed statistics
|
|
770
|
+
*
|
|
771
|
+
* @example
|
|
772
|
+
* ```javascript
|
|
773
|
+
* const metrics = odesli.getMetrics();
|
|
774
|
+
* const summary = metrics.getSummary();
|
|
775
|
+
* console.log(`Total requests: ${summary.counters.totalRequests}`);
|
|
776
|
+
* console.log(`Average response time: ${summary.timing.averageResponseTime}ms`);
|
|
777
|
+
* console.log(`Error rate: ${summary.rates.errorRate * 100}%`);
|
|
778
|
+
* ```
|
|
356
779
|
*
|
|
357
|
-
* @
|
|
780
|
+
* @see {@link module:odesli/metrics.MetricsCollector} For MetricsCollector API
|
|
781
|
+
* @since 1.1.0
|
|
358
782
|
*/
|
|
359
783
|
getMetrics () {
|
|
360
784
|
return this.metrics
|
|
361
785
|
}
|
|
362
786
|
|
|
363
787
|
/**
|
|
364
|
-
* Fetch song/album information by URL(s) from any supported streaming platform
|
|
788
|
+
* Fetch song/album information by URL(s) from any supported streaming platform.
|
|
789
|
+
*
|
|
790
|
+
* @summary Primary method for retrieving music links with support for single URLs and batch processing.
|
|
791
|
+
*
|
|
792
|
+
* This is the primary method for retrieving music links. It supports both single URLs
|
|
793
|
+
* and batch processing of multiple URLs with automatic error handling.
|
|
365
794
|
*
|
|
795
|
+
* @async
|
|
366
796
|
* @param {string|Array<string>} urlOrUrls - URL or array of URLs from any supported streaming platform (Spotify, Apple Music, YouTube, etc.)
|
|
367
797
|
* @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
|
|
798
|
+
* @param {string} [options.country='US'] - ISO 3166-1 Alpha-2 country code for region-specific results. Use {@link Odesli.getCountryOptions} to get valid codes.
|
|
799
|
+
* @param {boolean} [options.skipCache=false] - Skip cache for this request (useful for getting fresh data)
|
|
800
|
+
* @param {number} [options.timeout] - Override timeout for this request in milliseconds
|
|
801
|
+
* @param {number} [options.concurrency=5] - Maximum concurrent requests when processing arrays (batch only)
|
|
802
|
+
* @returns {Promise<Object>|Promise<Array<Object>>} Song/album information or array of results. Each result includes:
|
|
803
|
+
* - `title` - Song/album title
|
|
804
|
+
* - `artist` - Array of artist names
|
|
805
|
+
* - `type` - Content type ('song' or 'album')
|
|
806
|
+
* - `thumbnail` - Thumbnail image URL
|
|
807
|
+
* - `pageUrl` - Song.link page URL
|
|
808
|
+
* - `linksByPlatform` - Object with platform-specific links
|
|
809
|
+
* - `entitiesByUniqueId` - Detailed entity information
|
|
373
810
|
*
|
|
374
811
|
* @example
|
|
812
|
+
* ```javascript
|
|
375
813
|
* // Single fetch
|
|
376
814
|
* const song = await odesli.fetch('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR');
|
|
815
|
+
* console.log(`${song.title} by ${song.artist.join(', ')}`);
|
|
377
816
|
*
|
|
378
|
-
* // Batch fetch
|
|
817
|
+
* // Batch fetch with options
|
|
379
818
|
* const songs = await odesli.fetch([
|
|
380
819
|
* 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
|
|
381
820
|
* 'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu'
|
|
382
|
-
* ]
|
|
821
|
+
* ], {
|
|
822
|
+
* country: 'GB',
|
|
823
|
+
* concurrency: 3,
|
|
824
|
+
* skipCache: true
|
|
825
|
+
* });
|
|
826
|
+
*
|
|
827
|
+
* // Handle batch results with errors
|
|
828
|
+
* songs.forEach((result, index) => {
|
|
829
|
+
* if (result.error) {
|
|
830
|
+
* console.error(`Song ${index + 1} failed: ${result.error}`);
|
|
831
|
+
* } else {
|
|
832
|
+
* console.log(`Song ${index + 1}: ${result.title}`);
|
|
833
|
+
* }
|
|
834
|
+
* });
|
|
835
|
+
* ```
|
|
836
|
+
*
|
|
837
|
+
* @throws {Error} When URL format is invalid
|
|
838
|
+
* @throws {Error} When country code format is invalid (must be ISO 3166-1 Alpha-2)
|
|
839
|
+
* @throws {Error} When API returns an error (4xx/5xx status codes)
|
|
840
|
+
* @throws {Error} When request times out
|
|
841
|
+
* @throws {Error} When rate limit is exceeded (429 status)
|
|
842
|
+
*
|
|
843
|
+
* @see {@link Odesli#getByParams} For fetching by platform, type, and ID
|
|
844
|
+
* @see {@link Odesli#getById} For fetching by entity ID
|
|
845
|
+
* @see {@link Odesli#detectPlatform} To detect platform from URL
|
|
846
|
+
* @see {@link Odesli.getCountryOptions} To get valid country codes
|
|
847
|
+
* @since 1.1.0
|
|
383
848
|
*/
|
|
384
849
|
async fetch (urlOrUrls, options = {}) {
|
|
385
850
|
if (Array.isArray(urlOrUrls)) {
|
|
@@ -406,7 +871,17 @@ module.exports = class Odesli {
|
|
|
406
871
|
// Add success property to successful responses
|
|
407
872
|
return { ...result, success: true }
|
|
408
873
|
} catch (error) {
|
|
409
|
-
|
|
874
|
+
const statusCode =
|
|
875
|
+
typeof error.statusCode === 'number'
|
|
876
|
+
? error.statusCode
|
|
877
|
+
: this._extractStatusCode(error.message)
|
|
878
|
+
const errorCode =
|
|
879
|
+
typeof error.code === 'string' ? error.code : undefined
|
|
880
|
+
const retryable =
|
|
881
|
+
typeof error.retryable === 'boolean'
|
|
882
|
+
? error.retryable
|
|
883
|
+
: this._isRetryableError(error.message)
|
|
884
|
+
|
|
410
885
|
const errorInfo = {
|
|
411
886
|
success: false,
|
|
412
887
|
url,
|
|
@@ -414,31 +889,50 @@ module.exports = class Odesli {
|
|
|
414
889
|
platform: this.detectPlatform(url),
|
|
415
890
|
extractedId: this.extractId(url),
|
|
416
891
|
timestamp: new Date().toISOString(),
|
|
417
|
-
statusCode
|
|
418
|
-
retryable
|
|
892
|
+
statusCode,
|
|
893
|
+
retryable,
|
|
894
|
+
code: errorCode
|
|
419
895
|
}
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
896
|
+
|
|
897
|
+
if (errorCode === 'PUBLIC_API_ACCESS_DEPRECATED') {
|
|
898
|
+
errorInfo.errorType = 'PUBLIC_API_ACCESS_DEPRECATED'
|
|
899
|
+
errorInfo.suggestion =
|
|
900
|
+
'Provide an allowlisted API key. See the Songlink/Odesli sunset docs.'
|
|
901
|
+
} else if (errorCode === 'INVALID_ACCESS_KEY') {
|
|
902
|
+
errorInfo.errorType = 'INVALID_ACCESS_KEY'
|
|
903
|
+
errorInfo.suggestion =
|
|
904
|
+
'The provided API key was rejected. Request allowlisted access from Songlink/Odesli.'
|
|
905
|
+
} else if (errorCode === 'API_SUNSET_GONE' || statusCode === 410) {
|
|
906
|
+
errorInfo.errorType = 'API_SUNSET_GONE'
|
|
907
|
+
errorInfo.suggestion =
|
|
908
|
+
'This API endpoint is gone. Use an allowlisted key or link to https://song.link/ directly.'
|
|
909
|
+
} else if (statusCode === 400) {
|
|
423
910
|
errorInfo.errorType = 'BAD_REQUEST'
|
|
424
911
|
errorInfo.suggestion = 'Check if the URL is valid and accessible'
|
|
425
|
-
} else if (
|
|
912
|
+
} else if (statusCode === 401) {
|
|
426
913
|
errorInfo.errorType = 'UNAUTHORIZED'
|
|
427
|
-
errorInfo.suggestion =
|
|
428
|
-
|
|
914
|
+
errorInfo.suggestion =
|
|
915
|
+
'API key is missing, invalid, or not allowlisted'
|
|
916
|
+
} else if (statusCode === 429) {
|
|
429
917
|
errorInfo.errorType = 'RATE_LIMITED'
|
|
430
918
|
errorInfo.suggestion = 'Rate limit exceeded, try again later'
|
|
431
|
-
} else if (
|
|
919
|
+
} else if (statusCode === 404) {
|
|
432
920
|
errorInfo.errorType = 'NOT_FOUND'
|
|
433
|
-
errorInfo.suggestion =
|
|
434
|
-
|
|
921
|
+
errorInfo.suggestion =
|
|
922
|
+
'Content may not be available in the specified region'
|
|
923
|
+
} else if (
|
|
924
|
+
errorCode === 'TIMEOUT' ||
|
|
925
|
+
String(error.message || '')
|
|
926
|
+
.toLowerCase()
|
|
927
|
+
.includes('timeout')
|
|
928
|
+
) {
|
|
435
929
|
errorInfo.errorType = 'TIMEOUT'
|
|
436
930
|
errorInfo.suggestion = 'Request timed out, try again'
|
|
437
931
|
} else {
|
|
438
932
|
errorInfo.errorType = 'UNKNOWN'
|
|
439
933
|
errorInfo.suggestion = 'An unexpected error occurred'
|
|
440
934
|
}
|
|
441
|
-
|
|
935
|
+
|
|
442
936
|
return errorInfo
|
|
443
937
|
}
|
|
444
938
|
})
|
|
@@ -526,39 +1020,72 @@ module.exports = class Odesli {
|
|
|
526
1020
|
}
|
|
527
1021
|
|
|
528
1022
|
/**
|
|
529
|
-
* Fetch song/album information by platform, type, and ID
|
|
1023
|
+
* Fetch song/album information by platform, type, and ID.
|
|
1024
|
+
*
|
|
1025
|
+
* @summary Fetch music information using platform, type, and ID without requiring a full URL.
|
|
1026
|
+
*
|
|
1027
|
+
* This method allows you to fetch music information when you already know the
|
|
1028
|
+
* platform, content type, and ID, without needing the full URL. Useful for
|
|
1029
|
+
* applications that store platform-specific IDs.
|
|
530
1030
|
*
|
|
531
|
-
* @
|
|
1031
|
+
* @async
|
|
1032
|
+
* @param {string} platform - Platform name (spotify, appleMusic, youtube, youtubeMusic, etc.). Use {@link Odesli#getSupportedPlatforms} to get valid platforms.
|
|
532
1033
|
* @param {string} type - Content type ('song' or 'album')
|
|
533
|
-
* @param {string} id - Platform-specific ID
|
|
1034
|
+
* @param {string} id - Platform-specific ID. Can be just the ID (e.g., '4Km5HrUvYTaSUfiSGPJeQR') or full format (e.g., 'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR')
|
|
534
1035
|
* @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
|
|
1036
|
+
* @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
1037
|
* @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
|
|
1038
|
+
* @param {number} [options.timeout] - Override timeout for this request in milliseconds
|
|
1039
|
+
* @returns {Promise<Object>} Song/album information with links to all available platforms. Same structure as {@link Odesli#fetch}
|
|
539
1040
|
*
|
|
540
1041
|
* @example
|
|
541
1042
|
* ```javascript
|
|
542
|
-
* // Get song by Spotify ID
|
|
1043
|
+
* // Get song by Spotify ID (simple format)
|
|
543
1044
|
* const song = await odesli.getByParams('spotify', 'song', '4Km5HrUvYTaSUfiSGPJeQR');
|
|
544
|
-
* console.log(song.title);
|
|
1045
|
+
* console.log(`${song.title} by ${song.artist.join(', ')}`);
|
|
545
1046
|
*
|
|
546
|
-
* // Get album by Apple Music ID (backward compatible)
|
|
1047
|
+
* // Get album by Apple Music ID with country (backward compatible string format)
|
|
547
1048
|
* const album = await odesli.getByParams('appleMusic', 'album', '123456789', 'GB');
|
|
548
1049
|
*
|
|
549
|
-
* // Using full ID format with options
|
|
1050
|
+
* // Using full ID format with options object
|
|
550
1051
|
* const song = await odesli.getByParams('spotify', 'song', 'SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR', {
|
|
551
1052
|
* country: 'GB',
|
|
552
1053
|
* skipCache: true,
|
|
553
1054
|
* timeout: 5000
|
|
554
1055
|
* });
|
|
1056
|
+
*
|
|
1057
|
+
* // Extract ID from URL and use with getByParams
|
|
1058
|
+
* const url = 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR';
|
|
1059
|
+
* const platform = odesli.detectPlatform(url);
|
|
1060
|
+
* const id = odesli.extractId(url);
|
|
1061
|
+
* if (platform && id) {
|
|
1062
|
+
* const song = await odesli.getByParams(platform, 'song', id);
|
|
1063
|
+
* }
|
|
1064
|
+
*
|
|
1065
|
+
* // Country-specific fetching
|
|
1066
|
+
* const song = await odesli.getByParams('spotify', 'song', '123', {
|
|
1067
|
+
* country: 'GB' // United Kingdom
|
|
1068
|
+
* });
|
|
1069
|
+
*
|
|
1070
|
+
* // Get country options for UI dropdowns
|
|
1071
|
+
* const countries = Odesli.getCountryOptions();
|
|
1072
|
+
* const uk = countries.find(c => c.code === 'GB');
|
|
1073
|
+
* console.log(uk); // { code: 'GB', name: 'United Kingdom' }
|
|
555
1074
|
* ```
|
|
556
1075
|
*
|
|
557
1076
|
* @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
|
|
1077
|
+
* @throws {Error} When platform name is invalid (not in supported platforms list)
|
|
1078
|
+
* @throws {Error} When type is invalid (must be 'song' or 'album')
|
|
1079
|
+
* @throws {Error} When country code format is invalid (must be ISO 3166-1 Alpha-2)
|
|
1080
|
+
* @throws {Error} When API returns an error (4xx/5xx status codes)
|
|
1081
|
+
* @throws {Error} When request times out
|
|
1082
|
+
*
|
|
1083
|
+
* @see {@link Odesli#fetch} For fetching by URL instead
|
|
1084
|
+
* @see {@link Odesli#getById} For fetching by entity ID
|
|
1085
|
+
* @see {@link Odesli#detectPlatform} To detect platform from URL
|
|
1086
|
+
* @see {@link Odesli#extractId} To extract ID from URL
|
|
1087
|
+
* @see {@link Odesli#getSupportedPlatforms} To get valid platform names
|
|
1088
|
+
* @since 1.1.0
|
|
562
1089
|
*/
|
|
563
1090
|
async getByParams (platform, type, id, options = {}) {
|
|
564
1091
|
if (!platform) throw new Error('No `platform` was provided to odesli.getByParams()')
|
|
@@ -580,7 +1107,9 @@ module.exports = class Odesli {
|
|
|
580
1107
|
|
|
581
1108
|
// Validate parameters
|
|
582
1109
|
if (!this._validatePlatform(platform)) {
|
|
583
|
-
throw new Error(
|
|
1110
|
+
throw new Error(
|
|
1111
|
+
`Invalid platform "${platform}". Must be one of: ${SUPPORTED_PLATFORMS.join(', ')}`
|
|
1112
|
+
)
|
|
584
1113
|
}
|
|
585
1114
|
|
|
586
1115
|
if (!this._validateType(type)) {
|
|
@@ -757,179 +1286,379 @@ module.exports = class Odesli {
|
|
|
757
1286
|
}
|
|
758
1287
|
|
|
759
1288
|
/**
|
|
760
|
-
* Extract status code from error message
|
|
1289
|
+
* Extract status code from error message.
|
|
1290
|
+
*
|
|
1291
|
+
* Parses HTTP status codes from error messages in the format "XXX: ..."
|
|
1292
|
+
*
|
|
1293
|
+
* @param {string} errorMessage - Error message that may contain a status code
|
|
1294
|
+
* @returns {number|null} Extracted status code or null if not found
|
|
761
1295
|
* @private
|
|
1296
|
+
* @since 1.1.0
|
|
762
1297
|
*/
|
|
763
|
-
_extractStatusCode(errorMessage) {
|
|
764
|
-
const match = errorMessage.match(
|
|
765
|
-
return match ? parseInt(match[1]) : null
|
|
1298
|
+
_extractStatusCode (errorMessage) {
|
|
1299
|
+
const match = String(errorMessage || '').match(/\b(\d{3})\b/)
|
|
1300
|
+
return match ? parseInt(match[1], 10) : null
|
|
766
1301
|
}
|
|
767
1302
|
|
|
768
1303
|
/**
|
|
769
|
-
* Determine if an error is retryable
|
|
1304
|
+
* Determine if an error is retryable based on status code.
|
|
1305
|
+
*
|
|
1306
|
+
* Retryable status codes: 408 (Request Timeout), 429 (Too Many Requests),
|
|
1307
|
+
* 500 (Internal Server Error), 502 (Bad Gateway), 503 (Service Unavailable),
|
|
1308
|
+
* 504 (Gateway Timeout).
|
|
1309
|
+
*
|
|
1310
|
+
* @param {string} errorMessage - Error message to check
|
|
1311
|
+
* @returns {boolean} True if the error is retryable
|
|
770
1312
|
* @private
|
|
1313
|
+
* @since 1.1.0
|
|
771
1314
|
*/
|
|
772
|
-
_isRetryableError(errorMessage) {
|
|
773
|
-
const retryableStatusCodes = [408, 429, 500, 502, 503, 504]
|
|
1315
|
+
_isRetryableError (errorMessage) {
|
|
774
1316
|
const statusCode = this._extractStatusCode(errorMessage)
|
|
775
|
-
return statusCode ?
|
|
1317
|
+
return statusCode ? RETRYABLE_STATUS_CODES.has(statusCode) : false
|
|
776
1318
|
}
|
|
777
1319
|
|
|
778
1320
|
/**
|
|
779
|
-
* Detect platform from URL
|
|
1321
|
+
* Detect platform from a streaming service URL.
|
|
1322
|
+
*
|
|
1323
|
+
* Supported platforms: Spotify, Apple Music, YouTube, YouTube Music, Tidal,
|
|
1324
|
+
* Deezer, SoundCloud, Pandora, Napster, Yandex Music, Spinrilla, Amazon Music.
|
|
780
1325
|
*
|
|
781
|
-
* @param {string} url - URL to analyze
|
|
782
|
-
* @returns {string|null} Platform name or null if not recognized
|
|
1326
|
+
* @param {string} url - URL to analyze (must be a valid URL from a supported platform)
|
|
1327
|
+
* @returns {string|null} Platform name (e.g., 'spotify', 'appleMusic', 'youtube') or null if not recognized
|
|
783
1328
|
*
|
|
784
1329
|
* @example
|
|
785
1330
|
* ```javascript
|
|
786
|
-
*
|
|
787
|
-
*
|
|
1331
|
+
* // Detect platform from various URLs
|
|
1332
|
+
* odesli.detectPlatform('https://open.spotify.com/track/123'); // 'spotify'
|
|
1333
|
+
* odesli.detectPlatform('https://music.apple.com/us/album/123'); // 'appleMusic'
|
|
1334
|
+
* odesli.detectPlatform('https://www.youtube.com/watch?v=abc'); // 'youtube'
|
|
1335
|
+
* odesli.detectPlatform('https://invalid-url.com'); // null
|
|
1336
|
+
*
|
|
1337
|
+
* // Use with fetch
|
|
1338
|
+
* const url = 'https://open.spotify.com/track/123';
|
|
1339
|
+
* const platform = odesli.detectPlatform(url);
|
|
1340
|
+
* if (platform) {
|
|
1341
|
+
* console.log(`Detected platform: ${platform}`);
|
|
1342
|
+
* const song = await odesli.fetch(url);
|
|
1343
|
+
* }
|
|
788
1344
|
* ```
|
|
1345
|
+
*
|
|
1346
|
+
* @see {@link Odesli#extractId} To extract the ID from a URL
|
|
1347
|
+
* @see {@link Odesli#getSupportedPlatforms} To get list of all supported platforms
|
|
1348
|
+
* @since 1.1.0
|
|
789
1349
|
*/
|
|
790
|
-
|
|
1350
|
+
/**
|
|
1351
|
+
* Detect platform from a streaming service URL without requiring an API key.
|
|
1352
|
+
*
|
|
1353
|
+
* @param {string} url - URL to analyze
|
|
1354
|
+
* @returns {string|null} Platform name or null if not recognized
|
|
1355
|
+
* @since 2.0.0
|
|
1356
|
+
*/
|
|
1357
|
+
static detectPlatform (url) {
|
|
791
1358
|
if (!url) return null
|
|
792
|
-
|
|
1359
|
+
|
|
793
1360
|
try {
|
|
794
1361
|
const urlObj = new URL(url)
|
|
795
1362
|
const hostname = urlObj.hostname.toLowerCase()
|
|
796
1363
|
const pathname = urlObj.pathname.toLowerCase()
|
|
797
1364
|
|
|
798
|
-
if (
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
1365
|
+
if (
|
|
1366
|
+
['music.youtube.com'].includes(hostname) ||
|
|
1367
|
+
(['youtube.com', 'www.youtube.com'].includes(hostname) &&
|
|
1368
|
+
pathname.startsWith('/music'))
|
|
1369
|
+
) {
|
|
1370
|
+
return 'youtubeMusic'
|
|
1371
|
+
}
|
|
1372
|
+
if (['youtube.com', 'www.youtube.com', 'youtu.be'].includes(hostname)) {
|
|
1373
|
+
return 'youtube'
|
|
1374
|
+
}
|
|
1375
|
+
if (
|
|
1376
|
+
['music.amazon.com'].includes(hostname) ||
|
|
1377
|
+
(['amazon.com', 'www.amazon.com'].includes(hostname) &&
|
|
1378
|
+
pathname.startsWith('/music'))
|
|
1379
|
+
) {
|
|
1380
|
+
return 'amazonMusic'
|
|
1381
|
+
}
|
|
1382
|
+
if (
|
|
1383
|
+
['music.yandex.ru'].includes(hostname) ||
|
|
1384
|
+
(['yandex.ru'].includes(hostname) && pathname.startsWith('/music'))
|
|
1385
|
+
) {
|
|
1386
|
+
return 'yandex'
|
|
1387
|
+
}
|
|
1388
|
+
if (['open.spotify.com', 'spotify.com'].includes(hostname)) {
|
|
1389
|
+
return 'spotify'
|
|
1390
|
+
}
|
|
1391
|
+
if (['music.apple.com', 'itunes.apple.com'].includes(hostname)) {
|
|
1392
|
+
return 'appleMusic'
|
|
1393
|
+
}
|
|
804
1394
|
if (['tidal.com', 'listen.tidal.com'].includes(hostname)) return 'tidal'
|
|
805
1395
|
if (['deezer.com', 'www.deezer.com'].includes(hostname)) return 'deezer'
|
|
806
|
-
if (['soundcloud.com', 'www.soundcloud.com'].includes(hostname))
|
|
1396
|
+
if (['soundcloud.com', 'www.soundcloud.com'].includes(hostname)) {
|
|
1397
|
+
return 'soundcloud'
|
|
1398
|
+
}
|
|
807
1399
|
if (['pandora.com', 'www.pandora.com'].includes(hostname)) return 'pandora'
|
|
808
1400
|
if (['napster.com', 'us.napster.com'].includes(hostname)) return 'napster'
|
|
809
|
-
if (['spinrilla.com', 'www.spinrilla.com'].includes(hostname))
|
|
1401
|
+
if (['spinrilla.com', 'www.spinrilla.com'].includes(hostname)) {
|
|
1402
|
+
return 'spinrilla'
|
|
1403
|
+
}
|
|
1404
|
+
if (['audiomack.com', 'www.audiomack.com'].includes(hostname)) {
|
|
1405
|
+
return 'audiomack'
|
|
1406
|
+
}
|
|
1407
|
+
if (['play.anghami.com', 'anghami.com', 'www.anghami.com'].includes(hostname)) {
|
|
1408
|
+
return 'anghami'
|
|
1409
|
+
}
|
|
1410
|
+
if (['boomplay.com', 'www.boomplay.com'].includes(hostname)) {
|
|
1411
|
+
return 'boomplay'
|
|
1412
|
+
}
|
|
1413
|
+
if (['audius.co', 'www.audius.co'].includes(hostname)) return 'audius'
|
|
810
1414
|
} catch {
|
|
811
1415
|
// Malformed URL, just ignore.
|
|
812
1416
|
}
|
|
813
|
-
|
|
1417
|
+
|
|
814
1418
|
return null
|
|
815
1419
|
}
|
|
816
1420
|
|
|
1421
|
+
detectPlatform (url) {
|
|
1422
|
+
return Odesli.detectPlatform(url)
|
|
1423
|
+
}
|
|
1424
|
+
|
|
817
1425
|
/**
|
|
818
|
-
* Extract platform-specific ID from a URL
|
|
1426
|
+
* Extract platform-specific ID from a streaming service URL.
|
|
1427
|
+
*
|
|
1428
|
+
* This method parses URLs from various platforms and extracts the unique
|
|
1429
|
+
* identifier used by that platform. Useful for building entity IDs or
|
|
1430
|
+
* working with platform-specific APIs.
|
|
819
1431
|
*
|
|
820
|
-
* @param {string} url - URL to extract ID from
|
|
821
|
-
* @returns {string|null} Platform-specific ID or null if not found
|
|
1432
|
+
* @param {string} url - URL to extract ID from (must be a valid URL from a supported platform)
|
|
1433
|
+
* @returns {string|null} Platform-specific ID (e.g., track ID, album ID) or null if not found/invalid
|
|
822
1434
|
*
|
|
823
1435
|
* @example
|
|
824
1436
|
* ```javascript
|
|
825
|
-
*
|
|
826
|
-
*
|
|
1437
|
+
* // Extract IDs from various platforms
|
|
1438
|
+
* odesli.extractId('https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR');
|
|
1439
|
+
* // Returns: '4Km5HrUvYTaSUfiSGPJeQR'
|
|
1440
|
+
*
|
|
1441
|
+
* odesli.extractId('https://music.apple.com/us/album/test/123456789?i=987654321');
|
|
1442
|
+
* // Returns: '987654321' (song ID) or '123456789' (album ID)
|
|
1443
|
+
*
|
|
1444
|
+
* odesli.extractId('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
|
|
1445
|
+
* // Returns: 'dQw4w9WgXcQ'
|
|
1446
|
+
*
|
|
1447
|
+
* // Use with getByParams
|
|
1448
|
+
* const url = 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR';
|
|
1449
|
+
* const platform = odesli.detectPlatform(url);
|
|
1450
|
+
* const id = odesli.extractId(url);
|
|
1451
|
+
* if (platform && id) {
|
|
1452
|
+
* const song = await odesli.getByParams(platform, 'song', id);
|
|
1453
|
+
* }
|
|
827
1454
|
* ```
|
|
1455
|
+
*
|
|
1456
|
+
* @see {@link Odesli#detectPlatform} To detect the platform from a URL
|
|
1457
|
+
* @see {@link Odesli#getByParams} To fetch using platform, type, and ID
|
|
1458
|
+
* @since 1.1.0
|
|
828
1459
|
*/
|
|
829
|
-
|
|
1460
|
+
/**
|
|
1461
|
+
* Extract platform-specific ID from a streaming service URL without an API key.
|
|
1462
|
+
*
|
|
1463
|
+
* @param {string} url - URL to extract ID from
|
|
1464
|
+
* @returns {string|null} Platform-specific ID or null if not found/invalid
|
|
1465
|
+
* @since 2.0.0
|
|
1466
|
+
*/
|
|
1467
|
+
static extractId (url) {
|
|
830
1468
|
try {
|
|
831
1469
|
const urlObj = new URL(url)
|
|
832
1470
|
const pathParts = urlObj.pathname.split('/').filter(Boolean)
|
|
833
1471
|
const hostname = urlObj.hostname.toLowerCase()
|
|
834
|
-
|
|
1472
|
+
|
|
835
1473
|
// Spotify
|
|
836
1474
|
if (hostname === 'open.spotify.com') {
|
|
837
1475
|
return pathParts[pathParts.length - 1]
|
|
838
1476
|
}
|
|
839
|
-
|
|
1477
|
+
|
|
840
1478
|
// Apple Music - improved to handle various URL formats
|
|
841
1479
|
if (['music.apple.com', 'itunes.apple.com'].includes(hostname)) {
|
|
842
|
-
// Handle album URLs with track IDs: /album/name/id?i=trackId
|
|
843
1480
|
const trackIdMatch = url.match(/[?&]i=(\d+)/)
|
|
844
1481
|
if (trackIdMatch) {
|
|
845
1482
|
return trackIdMatch[1]
|
|
846
1483
|
}
|
|
847
|
-
|
|
848
|
-
// Handle direct track URLs: /album/name/id
|
|
1484
|
+
|
|
849
1485
|
const idMatch = url.match(/\/id(\d+)/)
|
|
850
1486
|
if (idMatch) {
|
|
851
1487
|
return idMatch[1]
|
|
852
1488
|
}
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
const lastPart = pathParts[pathParts.length - 1];
|
|
1489
|
+
|
|
1490
|
+
const lastPart = pathParts[pathParts.length - 1]
|
|
856
1491
|
if (/^\d+$/.test(lastPart)) {
|
|
857
|
-
return lastPart
|
|
1492
|
+
return lastPart
|
|
858
1493
|
}
|
|
859
|
-
|
|
1494
|
+
|
|
860
1495
|
return null
|
|
861
1496
|
}
|
|
862
|
-
|
|
1497
|
+
|
|
863
1498
|
// YouTube
|
|
864
|
-
if (
|
|
1499
|
+
if (
|
|
1500
|
+
[
|
|
1501
|
+
'youtube.com',
|
|
1502
|
+
'www.youtube.com',
|
|
1503
|
+
'music.youtube.com',
|
|
1504
|
+
'youtu.be'
|
|
1505
|
+
].includes(hostname)
|
|
1506
|
+
) {
|
|
865
1507
|
const videoMatch = url.match(/(?:v=|\/)([a-zA-Z0-9_-]{11})/)
|
|
866
1508
|
return videoMatch ? videoMatch[1] : null
|
|
867
1509
|
}
|
|
868
|
-
|
|
1510
|
+
|
|
869
1511
|
// Tidal
|
|
870
1512
|
if (['tidal.com', 'listen.tidal.com'].includes(hostname)) {
|
|
871
1513
|
return pathParts[pathParts.length - 1]
|
|
872
1514
|
}
|
|
873
|
-
|
|
1515
|
+
|
|
874
1516
|
// Deezer
|
|
875
1517
|
if (['deezer.com', 'www.deezer.com'].includes(hostname)) {
|
|
876
1518
|
return pathParts[pathParts.length - 1]
|
|
877
1519
|
}
|
|
878
|
-
|
|
1520
|
+
|
|
879
1521
|
// Amazon Music
|
|
880
|
-
if (
|
|
1522
|
+
if (
|
|
1523
|
+
['music.amazon.com'].includes(hostname) ||
|
|
1524
|
+
(['amazon.com', 'www.amazon.com'].includes(hostname) &&
|
|
1525
|
+
urlObj.pathname.toLowerCase().startsWith('/music'))
|
|
1526
|
+
) {
|
|
881
1527
|
const idMatch = url.match(/\/albums\/([^/]+)/)
|
|
882
1528
|
return idMatch ? idMatch[1] : null
|
|
883
1529
|
}
|
|
884
|
-
|
|
1530
|
+
|
|
885
1531
|
// SoundCloud
|
|
886
1532
|
if (['soundcloud.com', 'www.soundcloud.com'].includes(hostname)) {
|
|
887
1533
|
return pathParts[pathParts.length - 1]
|
|
888
1534
|
}
|
|
889
|
-
|
|
1535
|
+
|
|
890
1536
|
return null
|
|
891
1537
|
} catch {
|
|
892
1538
|
return null
|
|
893
1539
|
}
|
|
894
1540
|
}
|
|
895
1541
|
|
|
1542
|
+
extractId (url) {
|
|
1543
|
+
return Odesli.extractId(url)
|
|
1544
|
+
}
|
|
1545
|
+
|
|
896
1546
|
/**
|
|
897
|
-
* Get supported platforms
|
|
1547
|
+
* Get list of all supported streaming platforms without an API key.
|
|
898
1548
|
*
|
|
899
1549
|
* @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
|
-
* ```
|
|
1550
|
+
* @since 2.0.0
|
|
906
1551
|
*/
|
|
1552
|
+
static getSupportedPlatforms () {
|
|
1553
|
+
return [...SUPPORTED_PLATFORMS]
|
|
1554
|
+
}
|
|
1555
|
+
|
|
907
1556
|
getSupportedPlatforms () {
|
|
908
|
-
return
|
|
909
|
-
'spotify', 'itunes', 'appleMusic', 'youtube', 'youtubeMusic',
|
|
910
|
-
'google', 'googleStore', 'pandora', 'deezer', 'tidal',
|
|
911
|
-
'amazonStore', 'amazonMusic', 'soundcloud', 'napster', 'yandex', 'spinrilla'
|
|
912
|
-
]
|
|
1557
|
+
return Odesli.getSupportedPlatforms()
|
|
913
1558
|
}
|
|
914
1559
|
|
|
915
1560
|
/**
|
|
916
|
-
*
|
|
1561
|
+
* Build a Songlink landing-page URL for a track/album URL without calling the API.
|
|
1562
|
+
*
|
|
1563
|
+
* Useful when you do not have an allowlisted API key and only need a shareable
|
|
1564
|
+
* `https://song.link/...` page.
|
|
1565
|
+
*
|
|
1566
|
+
* @param {string} url - Streaming platform URL
|
|
1567
|
+
* @returns {string} Songlink page URL
|
|
1568
|
+
* @throws {OdesliError} When the URL is missing or invalid
|
|
1569
|
+
* @since 2.0.0
|
|
1570
|
+
*/
|
|
1571
|
+
static getPageUrl (url) {
|
|
1572
|
+
if (!url || typeof url !== 'string') {
|
|
1573
|
+
throw new OdesliError('A valid URL is required to build a Songlink page URL.', {
|
|
1574
|
+
code: 'INVALID_URL',
|
|
1575
|
+
retryable: false,
|
|
1576
|
+
docsUrl: SUNSET_DOCS_URL
|
|
1577
|
+
})
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
try {
|
|
1581
|
+
// Validate URL format
|
|
1582
|
+
// eslint-disable-next-line no-new
|
|
1583
|
+
new URL(url)
|
|
1584
|
+
} catch (err) {
|
|
1585
|
+
throw new OdesliError('A valid URL is required to build a Songlink page URL.', {
|
|
1586
|
+
code: 'INVALID_URL',
|
|
1587
|
+
retryable: false,
|
|
1588
|
+
docsUrl: SUNSET_DOCS_URL,
|
|
1589
|
+
cause: err
|
|
1590
|
+
})
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
return `https://song.link/${url}`
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
getPageUrl (url) {
|
|
1597
|
+
return Odesli.getPageUrl(url)
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
/**
|
|
1601
|
+
* Get the current User-Agent string used for API requests.
|
|
1602
|
+
*
|
|
1603
|
+
* The User-Agent includes package name, version, Node.js version, and platform.
|
|
1604
|
+
* This is automatically generated and used in all API requests.
|
|
1605
|
+
*
|
|
1606
|
+
* @returns {string} Current User-Agent string (e.g., 'odesli.js/2.0.0 (Node.js v18.0.0; win32)')
|
|
917
1607
|
*
|
|
918
|
-
* @returns {string} Current User-Agent string
|
|
919
1608
|
* @example
|
|
920
1609
|
* ```javascript
|
|
921
|
-
* const
|
|
922
|
-
* console.log(
|
|
923
|
-
* // Output:
|
|
1610
|
+
* const ua = odesli.getUserAgent();
|
|
1611
|
+
* console.log(ua);
|
|
1612
|
+
* // Output: 'odesli.js/2.0.0 (Node.js v18.0.0; win32)'
|
|
1613
|
+
*
|
|
1614
|
+
* // Use for debugging or logging
|
|
1615
|
+
* console.log(`Making request with User-Agent: ${odesli.getUserAgent()}`);
|
|
924
1616
|
* ```
|
|
1617
|
+
*
|
|
1618
|
+
* @since 1.1.0
|
|
925
1619
|
*/
|
|
926
1620
|
getUserAgent () {
|
|
927
1621
|
return generateUserAgent()
|
|
928
1622
|
}
|
|
929
1623
|
|
|
930
1624
|
/**
|
|
931
|
-
* Get all
|
|
932
|
-
*
|
|
1625
|
+
* Get all available country codes with their full names for use in UI dropdowns or validation.
|
|
1626
|
+
*
|
|
1627
|
+
* @summary Retrieve all valid ISO 3166-1 Alpha-2 country codes with full names for UI components.
|
|
1628
|
+
*
|
|
1629
|
+
* Returns an array of objects containing ISO 3166-1 Alpha-2 country codes and their
|
|
1630
|
+
* corresponding full country names. Useful for building country selection UI components
|
|
1631
|
+
* or validating country codes.
|
|
1632
|
+
*
|
|
1633
|
+
* @static
|
|
1634
|
+
* @readonly
|
|
1635
|
+
* @returns {Array<{ code: string, name: string }>} Array of country code/name pairs, sorted alphabetically by name
|
|
1636
|
+
* @returns {string} returns[].code - ISO 3166-1 Alpha-2 country code (e.g., 'US', 'GB', 'CA')
|
|
1637
|
+
* @returns {string} returns[].name - Full country name (e.g., 'United States', 'United Kingdom', 'Canada')
|
|
1638
|
+
*
|
|
1639
|
+
* @example
|
|
1640
|
+
* ```javascript
|
|
1641
|
+
* // Get all country options
|
|
1642
|
+
* const countries = Odesli.getCountryOptions();
|
|
1643
|
+
* console.log(`Total countries: ${countries.length}`); // 249
|
|
1644
|
+
*
|
|
1645
|
+
* // Use in a dropdown
|
|
1646
|
+
* countries.forEach(country => {
|
|
1647
|
+
* console.log(`${country.code}: ${country.name}`);
|
|
1648
|
+
* });
|
|
1649
|
+
*
|
|
1650
|
+
* // Find a specific country
|
|
1651
|
+
* const uk = countries.find(c => c.code === 'GB');
|
|
1652
|
+
* console.log(uk); // { code: 'GB', name: 'United Kingdom' }
|
|
1653
|
+
*
|
|
1654
|
+
* // Get top 10 countries
|
|
1655
|
+
* const topCountries = countries.slice(0, 10);
|
|
1656
|
+
* ```
|
|
1657
|
+
*
|
|
1658
|
+
* @see {@link Odesli#fetch} For using country codes in fetch operations
|
|
1659
|
+
* @see {@link Odesli#getByParams} For using country codes in getByParams
|
|
1660
|
+
* @see {@link Odesli#getById} For using country codes in getById
|
|
1661
|
+
* @since 1.2.0
|
|
933
1662
|
*/
|
|
934
1663
|
static getCountryOptions() {
|
|
935
1664
|
// List from the CountryCode enum
|
|
@@ -1186,3 +1915,14 @@ module.exports = class Odesli {
|
|
|
1186
1915
|
]
|
|
1187
1916
|
}
|
|
1188
1917
|
}
|
|
1918
|
+
|
|
1919
|
+
Odesli.Odesli = Odesli
|
|
1920
|
+
Odesli.default = Odesli
|
|
1921
|
+
Odesli.OdesliError = OdesliError
|
|
1922
|
+
Odesli.SUNSET_DOCS_URL = SUNSET_DOCS_URL
|
|
1923
|
+
|
|
1924
|
+
module.exports = Odesli
|
|
1925
|
+
module.exports.Odesli = Odesli
|
|
1926
|
+
module.exports.default = Odesli
|
|
1927
|
+
module.exports.OdesliError = OdesliError
|
|
1928
|
+
module.exports.SUNSET_DOCS_URL = SUNSET_DOCS_URL
|