odesli.js 1.3.4 → 1.3.6

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 CHANGED
@@ -1,8 +1,8 @@
1
1
  # odesli.js
2
2
 
3
- [![npm version](https://badge.fury.io/js/odesli.js.svg)](https://badge.fury.io/js/odesli.js)
4
- [![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC)
5
- [![Node.js CI](https://github.com/MattrAus/odesli.js/workflows/CI/badge.svg)](https://github.com/MattrAus/odesli.js/actions/workflows/ci.yml)
3
+ [![npm version](https://img.shields.io/npm/v/odesli.js.svg)](https://www.npmjs.com/package/odesli.js)
4
+ [![npm license](https://img.shields.io/npm/l/odesli.js)](https://github.com/MattrAus/odesli.js/blob/master/LICENSE)
5
+ [![CI](https://github.com/MattrAus/odesli.js/actions/workflows/ci.yml/badge.svg)](https://github.com/MattrAus/odesli.js/actions/workflows/ci.yml)
6
6
  [![Test Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen.svg)](https://github.com/MattrAus/odesli.js)
7
7
  [![Bundle Size](https://img.shields.io/bundlephobia/min/odesli.js)](https://bundlephobia.com/result?p=odesli.js)
8
8
  [![Downloads](https://img.shields.io/npm/dm/odesli.js.svg)](https://www.npmjs.com/package/odesli.js)
@@ -23,8 +23,6 @@ A Node.js client for the [Odesli API](https://odesli.co/) (formerly song.link/al
23
23
  - [Usage](#usage)
24
24
  - [Basic Usage](#basic-usage)
25
25
  - [Advanced Usage](#advanced-usage)
26
- - [ESM (import)](#esm-import)
27
- - [CommonJS (require)](#commonjs-require)
28
26
  - [Response Format](#response-format)
29
27
  - [Supported Platforms](#supported-platforms)
30
28
  - [TypeScript Support](#typescript-support)
@@ -36,6 +34,8 @@ A Node.js client for the [Odesli API](https://odesli.co/) (formerly song.link/al
36
34
  - [Support](#support)
37
35
  - [Extensions: Advanced Features](#extensions-advanced-features)
38
36
  - [1. Rate Limiter](#1-rate-limiter)
37
+ - [Example: With vs Without RateLimiter](#example-with-vs-without-ratelimiter)
38
+ - [Example: Using RateLimiter with Multiple Fetches](#example-using-ratelimiter-with-multiple-fetches)
39
39
  - [2. Metrics Collector](#2-metrics-collector)
40
40
  - [3. Plugin System](#3-plugin-system)
41
41
 
@@ -64,24 +64,66 @@ npm install odesli.js
64
64
  npm install @mattraus/odesli.js
65
65
  ```
66
66
 
67
- **Note**: If you encounter authentication issues, you may need to set up a GitHub token. See [GitHub Packages documentation](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-npm-registry) for details.
68
-
69
67
  ## Quick Start
70
68
 
71
- ```javascript
69
+ **CommonJS (require):**
70
+
71
+ ```js
72
72
  const Odesli = require('odesli.js');
73
73
 
74
74
  // Initialize without API key (10 requests/minute limit)
75
75
  const odesli = new Odesli();
76
76
 
77
77
  // Or with API key for higher limits
78
- const odesli = new Odesli({
79
- apiKey: 'your-api-key-here',
80
- version: 'v1-alpha.1', // optional, defaults to v1-alpha.1
81
- });
78
+ // const odesli = new Odesli({
79
+ // apiKey: 'your-api-key-here',
80
+ // version: 'v1-alpha.1', // optional, defaults to v1-alpha.1
81
+ // });
82
+
83
+ // You can also disable the metrics collector if you don't need it
84
+ // const odesliLight = new Odesli({ metrics: false });
85
+
86
+ // Fetch a song by URL (this is the actual working example)
87
+ (async () => {
88
+ try {
89
+ const song = await odesli.fetch(
90
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
91
+ );
92
+ console.log(`šŸŽµ ${song.title} by ${song.artist.join(', ')}`);
93
+ console.log(`šŸ”— Song.link: ${song.pageUrl}`);
94
+ } catch (error) {
95
+ console.error('āŒ Error:', error.message);
96
+ }
97
+ })();
98
+ ```
99
+
100
+ **ESM (import):**
101
+
102
+ ```js
103
+ import Odesli from 'odesli.js';
104
+
105
+ // Initialize without API key (10 requests/minute limit)
106
+ const odesli = new Odesli();
107
+
108
+ // Or with API key for higher limits
109
+ // const odesli = new Odesli({
110
+ // apiKey: 'your-api-key-here',
111
+ // version: 'v1-alpha.1', // optional, defaults to v1-alpha.1
112
+ // });
82
113
 
83
114
  // You can also disable the metrics collector if you don't need it
84
- const odesliLight = new Odesli({ metrics: false });
115
+ // const odesliLight = new Odesli({ metrics: false });
116
+
117
+ // Fetch a song by URL (this is the actual working example)
118
+ try {
119
+ const song = await odesli.fetch(
120
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
121
+ );
122
+ console.log(`šŸŽµ ${song.title} by ${song.artist.join(', ')}`);
123
+ console.log(`šŸ”— Song.link: ${song.pageUrl}`);
124
+ } catch (error) {
125
+ console.error('āŒ Error:', error.message);
126
+ }
85
127
  ```
86
128
 
87
129
  ## API Key
@@ -94,16 +136,48 @@ To get an API key, email `developers@song.link`.
94
136
 
95
137
  ### Basic Usage
96
138
 
97
- ```javascript
139
+ **CommonJS (require):**
140
+
141
+ ```js
98
142
  const Odesli = require('odesli.js');
99
143
 
100
144
  // Initialize without API key (10 requests/minute limit)
101
145
  const odesli = new Odesli();
102
146
 
103
147
  // Or with API key for higher limits
104
- const odesli = new Odesli({
105
- apiKey: 'your-api-key-here',
106
- });
148
+ // const odesli = new Odesli({
149
+ // apiKey: 'your-api-key-here',
150
+ // });
151
+
152
+ (async () => {
153
+ // Fetch a song by URL
154
+ const song = await odesli.fetch(
155
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
156
+ );
157
+ console.log(`${song.title} by ${song.artist.join(', ')}`);
158
+
159
+ // Fetch multiple songs at once
160
+ const urls = [
161
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
162
+ 'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
163
+ ];
164
+ const songs = await odesli.fetch(urls);
165
+ songs.forEach(song => console.log(song.title));
166
+ })();
167
+ ```
168
+
169
+ **ESM (import):**
170
+
171
+ ```js
172
+ import Odesli from 'odesli.js';
173
+
174
+ // Initialize without API key (10 requests/minute limit)
175
+ const odesli = new Odesli();
176
+
177
+ // Or with API key for higher limits
178
+ // const odesli = new Odesli({
179
+ // apiKey: 'your-api-key-here',
180
+ // });
107
181
 
108
182
  // Fetch a song by URL
109
183
  const song = await odesli.fetch(
@@ -122,7 +196,11 @@ songs.forEach(song => console.log(song.title));
122
196
 
123
197
  ### Advanced Usage
124
198
 
125
- ```javascript
199
+ **CommonJS (require):**
200
+
201
+ ```js
202
+ const Odesli = require('odesli.js');
203
+
126
204
  // Initialize with custom options
127
205
  const odesli = new Odesli({
128
206
  apiKey: 'your-api-key-here',
@@ -136,18 +214,71 @@ const odesli = new Odesli({
136
214
  logger: (message, level) => console.log(`[${level}] ${message}`),
137
215
  });
138
216
 
139
- // Fetch with options
140
- const song = await odesli.fetch('https://open.spotify.com/track/123', {
141
- country: 'GB',
142
- skipCache: false,
143
- timeout: 5000,
217
+ (async () => {
218
+ // Fetch with options
219
+ const song = await odesli.fetch('https://open.spotify.com/track/123', {
220
+ country: 'GB',
221
+ skipCache: false,
222
+ timeout: 5000,
223
+ });
224
+
225
+ // Batch fetch with concurrency control
226
+ const urls = [
227
+ 'https://open.spotify.com/track/123',
228
+ 'https://music.apple.com/us/album/test/456?i=789',
229
+ 'https://www.youtube.com/watch?v=abc123',
230
+ ];
231
+
232
+ const songs = await odesli.fetch(urls, {
233
+ country: 'US',
234
+ concurrency: 3,
235
+ skipCache: true,
236
+ });
237
+
238
+ // Handle errors in batch results
239
+ songs.forEach((song, index) => {
240
+ if (song.error) {
241
+ console.log(`Song ${index + 1}: Error - ${song.error}`);
242
+ } else {
243
+ console.log(`Song ${index + 1}: ${song.title}`);
244
+ }
245
+ });
246
+ })();
247
+ ```
248
+
249
+ **ESM (import):**
250
+
251
+ ```js
252
+ import Odesli from 'odesli.js';
253
+
254
+ // Initialize with custom options
255
+ const odesli = new Odesli({
256
+ apiKey: 'your-api-key-here',
257
+ version: 'v1-alpha.1',
258
+ cache: true,
259
+ timeout: 10000,
260
+ maxRetries: 3,
261
+ retryDelay: 1000,
262
+ headers: { 'User-Agent': 'MyApp/1.0' },
263
+ validateParams: true,
264
+ logger: (message, level) => console.log(`[${level}] ${message}`),
144
265
  });
145
266
 
267
+ // Fetch with options
268
+ const song = await odesli.fetch(
269
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
270
+ {
271
+ country: 'GB',
272
+ skipCache: false,
273
+ timeout: 5000,
274
+ }
275
+ );
276
+
146
277
  // Batch fetch with concurrency control
147
278
  const urls = [
148
- 'https://open.spotify.com/track/123',
149
- 'https://music.apple.com/us/album/test/456?i=789',
150
- 'https://www.youtube.com/watch?v=abc123',
279
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
280
+ 'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
281
+ 'https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp',
151
282
  ];
152
283
 
153
284
  const songs = await odesli.fetch(urls, {
@@ -166,29 +297,11 @@ songs.forEach((song, index) => {
166
297
  });
167
298
  ```
168
299
 
169
- ### ESM (import)
170
-
171
- ```js
172
- import { Odesli } from '@mattraus/odesli.js';
173
- import { RateLimiter } from '@mattraus/odesli.js/rate-limiter';
174
- import { MetricsCollector } from '@mattraus/odesli.js/metrics';
175
- import { PluginSystem } from '@mattraus/odesli.js/plugin-system';
176
- ```
177
-
178
- ### CommonJS (require)
179
-
180
- ```js
181
- const { Odesli } = require('@mattraus/odesli.js');
182
- const { RateLimiter } = require('@mattraus/odesli.js/rate-limiter');
183
- const { MetricsCollector } = require('@mattraus/odesli.js/metrics');
184
- const { PluginSystem } = require('@mattraus/odesli.js/plugin-system');
185
- ```
186
-
187
300
  ## Response Format
188
301
 
189
302
  All methods return a response object with the following structure:
190
303
 
191
- ```javascript
304
+ ```js
192
305
  {
193
306
  entityUniqueId: "SPOTIFY_SONG::4Km5HrUvYTaSUfiSGPJeQR",
194
307
  title: "Bad and Boujee",
@@ -245,20 +358,60 @@ All methods return a response object with the following structure:
245
358
 
246
359
  This package includes full TypeScript definitions with strict country code validation:
247
360
 
361
+ **CommonJS (require):**
362
+
248
363
  ```typescript
249
- import Odesli, { CountryCode } from 'odesli.js';
364
+ const Odesli = require('odesli.js');
250
365
 
251
366
  const odesli = new Odesli({ apiKey: 'your-key' });
252
367
 
253
- // TypeScript enforces valid country codes
254
- const song = await odesli.fetch('https://open.spotify.com/track/...', {
255
- country: 'US', // āœ… Valid - TypeScript autocomplete shows all valid codes
256
- // country: 'INVALID' // āŒ TypeScript error - not a valid CountryCode
257
- });
368
+ (async () => {
369
+ // Get all valid country codes and names for UI dropdowns
370
+ const countryOptions = Odesli.getCountryOptions();
371
+ console.log('Top 3 countries:', countryOptions.slice(0, 3));
372
+ // Output: [
373
+ // { code: 'US', name: 'United States' },
374
+ // { code: 'GB', name: 'United Kingdom' },
375
+ // { code: 'CA', name: 'Canada' }
376
+ // ]
377
+
378
+ // TypeScript enforces valid country codes
379
+ const song = await odesli.fetch(
380
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
381
+ {
382
+ country: 'US', // āœ… Valid - TypeScript autocomplete shows all valid codes
383
+ // country: 'INVALID' // āŒ TypeScript error - not a valid CountryCode
384
+ }
385
+ );
386
+ console.log(`Fetched: ${song.title}`);
387
+ })();
388
+ ```
389
+
390
+ **ESM (import):**
391
+
392
+ ```typescript
393
+ import Odesli, { CountryCode } from 'odesli.js';
394
+
395
+ const odesli = new Odesli({ apiKey: 'your-key' });
258
396
 
259
397
  // Get all valid country codes and names for UI dropdowns
260
398
  const countryOptions = Odesli.getCountryOptions();
261
- // Returns: [{ code: 'US', name: 'United States' }, { code: 'GB', name: 'United Kingdom' }, ...]
399
+ console.log('Top 3 countries:', countryOptions.slice(0, 3));
400
+ // Output: [
401
+ // { code: 'US', name: 'United States' },
402
+ // { code: 'GB', name: 'United Kingdom' },
403
+ // { code: 'CA', name: 'Canada' }
404
+ // ]
405
+
406
+ // TypeScript enforces valid country codes
407
+ const song = await odesli.fetch(
408
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
409
+ {
410
+ country: 'US', // āœ… Valid - TypeScript autocomplete shows all valid codes
411
+ // country: 'INVALID' // āŒ TypeScript error - not a valid CountryCode
412
+ }
413
+ );
414
+ console.log(`Fetched: ${song.title}`);
262
415
  ```
263
416
 
264
417
  ## Examples
@@ -273,23 +426,87 @@ Check out the [examples directory](./examples) for comprehensive usage examples:
273
426
 
274
427
  **Country-specific fetching:**
275
428
 
276
- ```javascript
429
+ **CommonJS (require):**
430
+
431
+ ```js
432
+ const Odesli = require('odesli.js');
433
+
434
+ const odesli = new Odesli();
435
+
436
+ // Get country options for UI dropdowns
437
+ const countries = Odesli.getCountryOptions();
438
+ console.log(`Available countries: ${countries.length}`);
439
+
440
+ (async () => {
441
+ // Fetch with specific country
442
+ const song = await odesli.fetch(
443
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
444
+ {
445
+ country: 'GB', // United Kingdom
446
+ }
447
+ );
448
+ console.log(`Fetched: ${song.title}`);
449
+ })();
450
+ ```
451
+
452
+ **ESM (import):**
453
+
454
+ ```js
455
+ import Odesli from 'odesli.js';
456
+
457
+ const odesli = new Odesli();
458
+
277
459
  // Get country options for UI dropdowns
278
460
  const countries = Odesli.getCountryOptions();
279
461
  console.log(`Available countries: ${countries.length}`);
280
462
 
281
463
  // Fetch with specific country
282
- const song = await odesli.fetch('https://spotify.com/track/123', {
283
- country: 'GB', // United Kingdom
284
- });
464
+ const song = await odesli.fetch(
465
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
466
+ {
467
+ country: 'GB', // United Kingdom
468
+ }
469
+ );
470
+ console.log(`Fetched: ${song.title}`);
285
471
  ```
286
472
 
287
473
  **Batch fetching with error handling:**
288
474
 
289
- ```javascript
475
+ **CommonJS (require):**
476
+
477
+ ```js
478
+ const Odesli = require('odesli.js');
479
+
480
+ const odesli = new Odesli();
481
+
482
+ const urls = [
483
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
484
+ 'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
485
+ ];
486
+
487
+ (async () => {
488
+ const results = await odesli.fetch(urls, { country: 'US' });
489
+
490
+ results.forEach((result, index) => {
491
+ if (result.error) {
492
+ console.log(`Song ${index + 1}: Error - ${result.error}`);
493
+ } else {
494
+ console.log(`Song ${index + 1}: ${result.title}`);
495
+ }
496
+ });
497
+ })();
498
+ ```
499
+
500
+ **ESM (import):**
501
+
502
+ ```js
503
+ import Odesli from 'odesli.js';
504
+
505
+ const odesli = new Odesli();
506
+
290
507
  const urls = [
291
- 'https://open.spotify.com/track/123',
292
- 'https://music.apple.com/us/album/test/456?i=789',
508
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
509
+ 'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
293
510
  ];
294
511
 
295
512
  const results = await odesli.fetch(urls, { country: 'US' });
@@ -305,9 +522,37 @@ results.forEach((result, index) => {
305
522
 
306
523
  **Platform detection and ID extraction:**
307
524
 
308
- ```javascript
309
- const platform = odesli.detectPlatform('https://open.spotify.com/track/123');
310
- const id = odesli.extractId('https://open.spotify.com/track/123');
525
+ **CommonJS (require):**
526
+
527
+ ```js
528
+ const Odesli = require('odesli.js');
529
+
530
+ const odesli = new Odesli();
531
+
532
+ // These methods are synchronous, so no async handling needed
533
+ const platform = odesli.detectPlatform(
534
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
535
+ );
536
+ const id = odesli.extractId(
537
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
538
+ );
539
+ console.log(`Platform: ${platform}, ID: ${id}`);
540
+ ```
541
+
542
+ **ESM (import):**
543
+
544
+ ```js
545
+ import Odesli from 'odesli.js';
546
+
547
+ const odesli = new Odesli();
548
+
549
+ // These methods are synchronous, so no async handling needed
550
+ const platform = odesli.detectPlatform(
551
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
552
+ );
553
+ const id = odesli.extractId(
554
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR'
555
+ );
311
556
  console.log(`Platform: ${platform}, ID: ${id}`);
312
557
  ```
313
558
 
@@ -341,18 +586,155 @@ Odesli.js provides several advanced extensions to help you build robust, scalabl
341
586
 
342
587
  **What:** Controls the number of API requests per time window using strategies like token bucket, leaky bucket, or sliding window.
343
588
 
344
- **Why use it?**
589
+ **Default Rate Limiting Behavior:**
590
+
591
+ The main Odesli client does **not** include built-in rate limiting. Rate limits are enforced by the Odesli API server:
345
592
 
346
- - Prevents hitting Odesli/Songlink API rate limits
347
- - Smooths out traffic spikes
348
- - Ensures fair usage in multi-user or batch scenarios
593
+ - **Without API key**: 10 requests per minute (enforced by API)
594
+ - **With API key**: Higher limits (enforced by API)
349
595
 
350
- **Example:**
596
+ When you exceed the API rate limit, you'll receive a 429 error: `"You are being rate limited, No API Key is 10 Requests / Minute"`
597
+
598
+ **Why use the RateLimiter extension?**
599
+
600
+ - **Prevent API errors**: Proactively limit requests before hitting API rate limits
601
+ - **Smooth traffic**: Spread requests evenly across time windows
602
+ - **Handle bursts**: Manage sudden spikes in request volume
603
+ - **Better UX**: Avoid 429 errors by staying under limits
604
+ - **Predictable behavior**: Ensure consistent request patterns
605
+
606
+ **Available Strategies:**
607
+
608
+ - **šŸŽÆ Token Bucket**: Handles bursts well, efficient memory usage
609
+ - **šŸ”„ Sliding Window**: Most accurate, precise timing (recommended)
610
+ - **šŸ’§ Leaky Bucket**: Smooths traffic, predictable output rate
611
+
612
+ **Strategy Options:**
351
613
 
352
614
  ```js
353
- const RateLimiter = require('./lib/rate-limiter');
354
- const limiter = new RateLimiter({ maxRequests: 10, windowMs: 60000 });
355
- await limiter.waitForSlot(); // Wait for a slot before making a request
615
+ // Token Bucket Strategy
616
+ const tokenBucketLimiter = new RateLimiter({
617
+ maxRequests: 10,
618
+ windowMs: 60000, // 1 minute
619
+ strategy: 'token-bucket',
620
+ // Optional: burst capacity (defaults to maxRequests)
621
+ burstCapacity: 15,
622
+ });
623
+
624
+ // Sliding Window Strategy (recommended)
625
+ const slidingWindowLimiter = new RateLimiter({
626
+ maxRequests: 5,
627
+ windowMs: 10000, // 10 seconds
628
+ strategy: 'sliding-window',
629
+ // No additional options needed
630
+ });
631
+
632
+ // Leaky Bucket Strategy
633
+ const leakyBucketLimiter = new RateLimiter({
634
+ maxRequests: 3,
635
+ windowMs: 5000, // 5 seconds
636
+ strategy: 'leaky-bucket',
637
+ // Optional: queue size limit (defaults to maxRequests * 2)
638
+ queueSize: 10,
639
+ });
640
+ ```
641
+
642
+ **Strategy Comparison:**
643
+
644
+ | Strategy | Pros | Cons | Best For | Configuration |
645
+ | ------------------ | -------------------------------- | ------------------- | --------------------------------- | ---------------------- |
646
+ | **Token Bucket** | Handles bursts, efficient memory | Less precise timing | Allowing some burst traffic | `burstCapacity` option |
647
+ | **Sliding Window** | Most accurate, no overages | More memory usage | Exact rate limiting (recommended) | No additional options |
648
+ | **Leaky Bucket** | Smooths traffic, predictable | Can delay requests | Smoothing traffic spikes | `queueSize` option |
649
+
650
+ **When to Use Each Strategy:**
651
+
652
+ - **šŸŽÆ Token Bucket**: Use when you want to allow some burst traffic while maintaining overall limits. Good for user-facing applications where occasional bursts are acceptable.
653
+
654
+ - **šŸ”„ Sliding Window**: Use when you need precise rate limiting with no overages. Best for API integrations where you must stay strictly within limits.
655
+
656
+ - **šŸ’§ Leaky Bucket**: Use when you want to smooth out traffic spikes and maintain a steady, predictable output rate. Good for background processing or batch operations.
657
+
658
+ #### Example: With vs Without RateLimiter
659
+
660
+ ```js
661
+ const Odesli = require('odesli.js');
662
+
663
+ // Without RateLimiter - relies on API rate limiting
664
+ const odesli = new Odesli();
665
+
666
+ // This works fine for < 10 requests/minute
667
+ // But will throw 429 errors if you exceed the limit
668
+ const urls = [
669
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
670
+ 'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
671
+ ];
672
+ const songs = await odesli.fetch(urls); // May hit API rate limit
673
+
674
+ // With RateLimiter - proactive client-side limiting
675
+ const { RateLimiter } = require('odesli.js/rate-limiter');
676
+ const limiter = new RateLimiter({
677
+ maxRequests: 8, // Stay safely under the 10/minute limit
678
+ windowMs: 60000,
679
+ strategy: 'sliding-window',
680
+ });
681
+
682
+ // This prevents hitting API rate limits
683
+ async function safeFetch(url) {
684
+ await limiter.waitForSlot();
685
+ return await odesli.fetch(url);
686
+ }
687
+ ```
688
+
689
+ #### Example: Using RateLimiter with Multiple Fetches
690
+
691
+ **CommonJS (require):**
692
+
693
+ ```js
694
+ const Odesli = require('odesli.js');
695
+ const { RateLimiter } = require('odesli.js/rate-limiter');
696
+
697
+ const odesli = new Odesli();
698
+ const limiter = new RateLimiter({
699
+ maxRequests: 2,
700
+ windowMs: 3000, // 2 requests per 3 seconds
701
+ strategy: 'sliding-window', // More reliable strategy
702
+ });
703
+
704
+ const urls = [
705
+ 'https://open.spotify.com/track/4Km5HrUvYTaSUfiSGPJeQR',
706
+ 'https://open.spotify.com/track/0V3wPSX9ygBnCm8psDIegu',
707
+ 'https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp',
708
+ ];
709
+
710
+ // Function to fetch with rate limiting
711
+ async function fetchWithRateLimit(url, index) {
712
+ console.log(`ā³ Request ${index + 1}: Waiting for slot...`);
713
+ await limiter.waitForSlot();
714
+ console.log(`āœ… Request ${index + 1}: Got slot, fetching...`);
715
+
716
+ const song = await odesli.fetch(url);
717
+ console.log(`šŸŽµ Request ${index + 1}: ${song.title}`);
718
+ return song;
719
+ }
720
+
721
+ // Submit all requests at once - they'll be processed automatically
722
+ (async () => {
723
+ console.log('šŸš€ Auto-Queue Rate Limiter Demo');
724
+ console.log(
725
+ `šŸ“Š Limit: ${limiter.maxRequests} requests per ${limiter.windowMs / 1000}s`
726
+ );
727
+ console.log(`šŸ”— Submitting ${urls.length} requests...\n`);
728
+
729
+ // Submit all requests - they'll be processed as slots become available
730
+ const promises = urls.map((url, index) => fetchWithRateLimit(url, index));
731
+
732
+ // Wait for all to complete
733
+ const results = await Promise.all(promises);
734
+
735
+ console.log('\nšŸŽ‰ All requests completed!');
736
+ console.log(`šŸ“Š Total songs fetched: ${results.length}`);
737
+ })();
356
738
  ```
357
739
 
358
740
  ### 2. Metrics Collector
@@ -365,13 +747,16 @@ await limiter.waitForSlot(); // Wait for a slot before making a request
365
747
  - Debug slowdowns or error spikes
366
748
  - Gather analytics for reporting or dashboards
367
749
 
368
- **Example:**
750
+ **CommonJS (require):**
751
+
752
+ ```js
753
+ const { MetricsCollector } = require('odesli.js/metrics');
754
+ ```
755
+
756
+ **ESM (import):**
369
757
 
370
758
  ```js
371
- const MetricsCollector = require('./lib/metrics');
372
- const metrics = new MetricsCollector({ enabled: true });
373
- metrics.recordRequest({ url, startTime: Date.now(), success: true });
374
- console.log(metrics.getSummary());
759
+ import { MetricsCollector } from 'odesli.js/metrics';
375
760
  ```
376
761
 
377
762
  ### 3. Plugin System
@@ -384,18 +769,16 @@ console.log(metrics.getSummary());
384
769
  - Transform responses or inject custom logic
385
770
  - Cleanly separate concerns and enable community plugins
386
771
 
387
- **Example:**
772
+ **CommonJS (require):**
388
773
 
389
774
  ```js
390
- const PluginSystem = require('./lib/plugin-system');
391
- const plugins = new PluginSystem();
392
- plugins.registerPlugin('logger', {
393
- hooks: {
394
- 'pre-request': ctx => console.log('Requesting:', ctx.url),
395
- 'post-response': ctx => console.log('Response:', ctx.url),
396
- },
397
- });
398
- await plugins.executeHook('pre-request', { url: '...' });
775
+ const { PluginSystem } = require('odesli.js/plugin-system');
776
+ ```
777
+
778
+ **ESM (import):**
779
+
780
+ ```js
781
+ import { PluginSystem } from 'odesli.js/plugin-system';
399
782
  ```
400
783
 
401
784
  See the `examples/advanced-features-example.js` for a full demonstration of these extensions in action.