@mwyeow/moonify.js 1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mwyeow
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,107 @@
1
+ # Moonify.JS
2
+
3
+ <p align="center">
4
+ <a href="https://discord.gg/Bjgx9gaaHG">
5
+ <img src="https://img.shields.io/discord/1338630753512325242?color=5865F2&logo=discord&logoColor=white" alt="Discord" />
6
+ </a>
7
+ <a href="https://www.npmjs.com/package/moonify.js">
8
+ <img src="https://img.shields.io/npm/v/moonify.js?color=CB3837&logo=npm" alt="npm version" />
9
+ </a>
10
+ <a href="https://www.npmjs.com/package/moonify.js">
11
+ <img src="https://img.shields.io/npm/dt/moonify.js?color=blue" alt="npm downloads" />
12
+ </a>
13
+ <a href="https://github.com/mwyeow/moonify.js/graphs/contributors">
14
+ <img src="https://img.shields.io/github/contributors/mwyeow/moonify.js?color=teal" alt="Contributors" />
15
+ </a>
16
+ <a href="https://github.com/mwyeow/moonify.js/commits/main">
17
+ <img src="https://img.shields.io/github/last-commit/mwyeow/moonify.js" alt="Last Commit" />
18
+ </a>
19
+ <img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License" />
20
+ </p>
21
+
22
+ A lightweight TypeScript client to fetch currently playing scrobbles from Last.fm and automatically enrich them with Spotify track links, artist URLs, and repeat tracking.
23
+
24
+ ---
25
+
26
+ ## Features
27
+
28
+ - Fetches live playback status via Last.fm API.
29
+ - Automatically searches Spotify for track and artist links.
30
+ - Gracefully falls back to Last.fm URLs if Spotify credentials are unset or the track is not found.
31
+ - Detects whether the current track is on repeat across the user's latest scrobbles.
32
+ - Zero external runtime dependencies (uses native web APIs: `fetch`, `AbortController`, `btoa`).
33
+ - Works across Node.js (18+), Bun, and Deno.
34
+
35
+ ---
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ # using bun
41
+ bun add moonify.js
42
+
43
+ # using npm
44
+ npm install moonify.js
45
+
46
+ # using pnpm
47
+ pnpm add moonify.js
48
+
49
+ ```
50
+
51
+ ---
52
+
53
+ ## Quick Start
54
+
55
+ ```typescript
56
+ import { Moonify } from "moonify.js";
57
+
58
+ const moonify = new Moonify({
59
+ lastfmApiKey: process.env.LASTFM_API_KEY!,
60
+ spotifyClientId: process.env.SPOTIFY_CLIENT_ID, // optional
61
+ spotifyClientSecret: process.env.SPOTIFY_CLIENT_SECRET, // optional
62
+ requestTimeoutMs: 8000, // optional (default: 8000)
63
+ });
64
+
65
+ async function run() {
66
+ const result = await moonify.getCurrentlyPlaying("some_username");
67
+
68
+ if (!result) {
69
+ console.log("No track is playing right now.");
70
+ return;
71
+ }
72
+
73
+ console.log(`${result.trackName} by ${result.artistName}`);
74
+ console.log(`Listen here: ${result.trackUrl}`);
75
+
76
+ if (result.isOnRepeat) {
77
+ console.log(`Repeated ${result.repeatCount} times recently.`);
78
+ }
79
+ }
80
+
81
+ run();
82
+ ```
83
+
84
+ ---
85
+
86
+ ## Response Object
87
+
88
+ `getCurrentlyPlaying(username)` resolves to `null` if nothing is playing or user scrobbles are empty. When active, it returns:
89
+
90
+ | Field | Type | Description |
91
+ | ------------------ | --------- | -------------------------------------------------------- |
92
+ | `trackName` | `string` | Track name |
93
+ | `artistName` | `string` | Artist name |
94
+ | `trackUrl` | `string` | Spotify track URL (falls back to Last.fm URL) |
95
+ | `artistUrl` | `string` | Spotify artist URL (falls back to Last.fm URL) |
96
+ | `lastFmTrackUrl` | `string` | Guaranteed Last.fm track URL |
97
+ | `lastFmArtistUrl` | `string` | Guaranteed Last.fm artist URL |
98
+ | `spotifyTrackUrl` | `string` | Direct Spotify track URL (null if unfound/unconfigured) |
99
+ | `spotifyArtistUrl` | `string` | Direct Spotify artist URL (null if unfound/unconfigured) |
100
+ | `isOnRepeat` | `boolean` | `true` if repeated 2+ times in recent 10 tracks |
101
+ | `repeatCount` | `number` | Total repeat count in recent tracks |
102
+
103
+ ## Contributing
104
+
105
+ Contributions are always welcome!
106
+ If you've found a bug, have an idea, or want to improve MoonifyJS, feel free to open an issue or pull request.
107
+ Thanks for helping out! <3
package/dist/index.cjs ADDED
@@ -0,0 +1,239 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ LastFmService: () => LastFmService,
24
+ Moonify: () => Moonify,
25
+ MoonifyApiError: () => MoonifyApiError,
26
+ MoonifyAuthError: () => MoonifyAuthError,
27
+ MoonifyError: () => MoonifyError,
28
+ SpotifyService: () => SpotifyService
29
+ });
30
+ module.exports = __toCommonJS(index_exports);
31
+
32
+ // src/errors/index.ts
33
+ var MoonifyError = class extends Error {
34
+ constructor(message) {
35
+ super(message);
36
+ this.name = "MoonifyError";
37
+ Object.setPrototypeOf(this, new.target.prototype);
38
+ }
39
+ };
40
+ var MoonifyApiError = class extends MoonifyError {
41
+ status;
42
+ service;
43
+ constructor(service, status, message) {
44
+ super(`${service} api error (${status}): ${message}`);
45
+ this.name = "MoonifyApiError";
46
+ this.service = service;
47
+ this.status = status;
48
+ }
49
+ };
50
+ var MoonifyAuthError = class extends MoonifyError {
51
+ constructor(service, message) {
52
+ super(`could not authenticate with ${service}: ${message}`);
53
+ this.name = "MoonifyAuthError";
54
+ }
55
+ };
56
+
57
+ // src/http/fetcher.ts
58
+ async function requestJson(service, url, options = {}) {
59
+ const { headers, body, method = "GET", timeoutMs = 8e3 } = options;
60
+ const controller = new AbortController();
61
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
62
+ try {
63
+ const res = await fetch(url, {
64
+ method,
65
+ headers,
66
+ body,
67
+ signal: controller.signal
68
+ });
69
+ if (!res.ok) {
70
+ const errorText = await res.text().catch(() => "Unknown response body");
71
+ throw new MoonifyApiError(service, res.status, errorText);
72
+ }
73
+ return await res.json();
74
+ } finally {
75
+ clearTimeout(timer);
76
+ }
77
+ }
78
+
79
+ // src/services/lastfm.service.ts
80
+ var LastFmService = class {
81
+ apiKey;
82
+ timeoutMs;
83
+ constructor(apiKey, timeoutMs = 8e3) {
84
+ this.apiKey = apiKey;
85
+ this.timeoutMs = timeoutMs;
86
+ }
87
+ async getRecentTracks(username, limit = 10) {
88
+ const url = `https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=${encodeURIComponent(
89
+ username
90
+ )}&api_key=${this.apiKey}&format=json&limit=${limit}`;
91
+ const data = await requestJson("lastfm", url, {
92
+ timeoutMs: this.timeoutMs
93
+ });
94
+ const raw = data.recenttracks?.track;
95
+ if (!raw) return [];
96
+ return Array.isArray(raw) ? raw : [raw];
97
+ }
98
+ };
99
+
100
+ // src/services/spotify.service.ts
101
+ var SpotifyService = class {
102
+ clientId;
103
+ clientSecret;
104
+ timeoutMs;
105
+ token = null;
106
+ tokenExpiresAt = 0;
107
+ constructor(clientId, clientSecret, timeoutMs = 8e3) {
108
+ this.clientId = clientId;
109
+ this.clientSecret = clientSecret;
110
+ this.timeoutMs = timeoutMs;
111
+ }
112
+ get isConfigured() {
113
+ return Boolean(this.clientId && this.clientSecret);
114
+ }
115
+ async getAccessToken() {
116
+ if (!this.isConfigured) return null;
117
+ if (this.token && Date.now() < this.tokenExpiresAt) {
118
+ return this.token;
119
+ }
120
+ try {
121
+ const credentials = btoa(`${this.clientId}:${this.clientSecret}`);
122
+ const data = await requestJson(
123
+ "spotify",
124
+ "https://accounts.spotify.com/api/token",
125
+ {
126
+ method: "POST",
127
+ headers: {
128
+ Authorization: `Basic ${credentials}`,
129
+ "Content-Type": "application/x-www-form-urlencoded"
130
+ },
131
+ body: "grant_type=client_credentials",
132
+ timeoutMs: this.timeoutMs
133
+ }
134
+ );
135
+ this.token = data.access_token;
136
+ this.tokenExpiresAt = Date.now() + (data.expires_in - 60) * 1e3;
137
+ return this.token;
138
+ } catch (error) {
139
+ throw new MoonifyAuthError("spotify", error.message);
140
+ }
141
+ }
142
+ async resolveTrack(track, artist) {
143
+ if (!this.isConfigured) {
144
+ return { trackUrl: null, artistUrl: null };
145
+ }
146
+ try {
147
+ const token = await this.getAccessToken();
148
+ if (!token) return { trackUrl: null, artistUrl: null };
149
+ const query = encodeURIComponent(`track:${track} artist:${artist}`);
150
+ const data = await requestJson(
151
+ "spotify",
152
+ `https://api.spotify.com/v1/search?q=${query}&type=track&limit=1`,
153
+ {
154
+ headers: { Authorization: `Bearer ${token}` },
155
+ timeoutMs: this.timeoutMs
156
+ }
157
+ );
158
+ const item = data.tracks?.items?.[0];
159
+ if (!item) return { trackUrl: null, artistUrl: null };
160
+ return {
161
+ trackUrl: item.external_urls?.spotify || null,
162
+ artistUrl: item.artists?.[0]?.external_urls?.spotify || null
163
+ };
164
+ } catch {
165
+ return { trackUrl: null, artistUrl: null };
166
+ }
167
+ }
168
+ };
169
+
170
+ // src/utils/normalise.ts
171
+ function normalizeString(input) {
172
+ return input.trim().toLowerCase();
173
+ }
174
+
175
+ // src/client.ts
176
+ var Moonify = class {
177
+ lastfm;
178
+ spotify;
179
+ constructor(config) {
180
+ if (!config.lastfmApiKey) {
181
+ throw new Error("lastfm api key is required.");
182
+ }
183
+ this.lastfm = new LastFmService(
184
+ config.lastfmApiKey,
185
+ config.requestTimeoutMs
186
+ );
187
+ this.spotify = new SpotifyService(
188
+ config.spotifyClientId,
189
+ config.spotifyClientSecret,
190
+ config.requestTimeoutMs
191
+ );
192
+ }
193
+ async getCurrentlyPlaying(username) {
194
+ const tracks = await this.lastfm.getRecentTracks(username, 10);
195
+ if (tracks.length === 0) return null;
196
+ const currentTrack = tracks[0];
197
+ const isNowPlaying = currentTrack["@attr"]?.nowplaying === "true";
198
+ if (!isNowPlaying) return null;
199
+ const trackName = currentTrack.name;
200
+ const artistName = currentTrack.artist["#text"] || currentTrack.artist.name || "Unknown Artist";
201
+ const lastFmTrackUrl = currentTrack.url;
202
+ const lastFmArtistUrl = `https://www.last.fm/music/${encodeURIComponent(artistName)}`;
203
+ const spotifyMatch = await this.spotify.resolveTrack(trackName, artistName);
204
+ const normTrack = normalizeString(trackName);
205
+ const normArtist = normalizeString(artistName);
206
+ let repeatCount = 0;
207
+ for (let i = 1; i < tracks.length; i++) {
208
+ const item = tracks[i];
209
+ const tName = normalizeString(item.name || "");
210
+ const tArtist = normalizeString(
211
+ item.artist["#text"] || item.artist.name || ""
212
+ );
213
+ if (tName === normTrack && tArtist === normArtist) {
214
+ repeatCount++;
215
+ }
216
+ }
217
+ return {
218
+ trackName,
219
+ artistName,
220
+ trackUrl: spotifyMatch.trackUrl || lastFmTrackUrl,
221
+ artistUrl: spotifyMatch.artistUrl || lastFmArtistUrl,
222
+ lastFmTrackUrl,
223
+ lastFmArtistUrl,
224
+ spotifyTrackUrl: spotifyMatch.trackUrl,
225
+ spotifyArtistUrl: spotifyMatch.artistUrl,
226
+ isOnRepeat: repeatCount >= 2,
227
+ repeatCount
228
+ };
229
+ }
230
+ };
231
+ // Annotate the CommonJS export names for ESM import in node:
232
+ 0 && (module.exports = {
233
+ LastFmService,
234
+ Moonify,
235
+ MoonifyApiError,
236
+ MoonifyAuthError,
237
+ MoonifyError,
238
+ SpotifyService
239
+ });
@@ -0,0 +1,83 @@
1
+ interface MoonifyConfig {
2
+ lastfmApiKey: string;
3
+ spotifyClientId?: string;
4
+ spotifyClientSecret?: string;
5
+ requestTimeoutMs?: number;
6
+ }
7
+
8
+ interface ResolvedCurrentlyPlaying {
9
+ trackName: string;
10
+ artistName: string;
11
+ trackUrl: string;
12
+ artistUrl: string;
13
+ lastFmTrackUrl: string;
14
+ lastFmArtistUrl: string;
15
+ spotifyTrackUrl: string | null;
16
+ spotifyArtistUrl: string | null;
17
+ isOnRepeat: boolean;
18
+ repeatCount: number;
19
+ }
20
+
21
+ declare class Moonify {
22
+ private lastfm;
23
+ private spotify;
24
+ constructor(config: MoonifyConfig);
25
+ getCurrentlyPlaying(username: string): Promise<ResolvedCurrentlyPlaying | null>;
26
+ }
27
+
28
+ interface LastFmTrackArtist {
29
+ "#text"?: string;
30
+ name?: string;
31
+ mbid?: string;
32
+ }
33
+ interface LastFmRawTrack {
34
+ name: string;
35
+ artist: LastFmTrackArtist;
36
+ url: string;
37
+ streamable?: string;
38
+ mbid?: string;
39
+ album?: {
40
+ "#text"?: string;
41
+ };
42
+ "@attr"?: {
43
+ nowplaying?: string;
44
+ };
45
+ }
46
+
47
+ declare class LastFmService {
48
+ private apiKey;
49
+ private timeoutMs;
50
+ constructor(apiKey: string, timeoutMs?: number);
51
+ getRecentTracks(username: string, limit?: number): Promise<LastFmRawTrack[]>;
52
+ }
53
+
54
+ interface SpotifyTrackMatch {
55
+ trackUrl: string | null;
56
+ artistUrl: string | null;
57
+ }
58
+
59
+ declare class SpotifyService {
60
+ private clientId?;
61
+ private clientSecret?;
62
+ private timeoutMs;
63
+ private token;
64
+ private tokenExpiresAt;
65
+ constructor(clientId?: string, clientSecret?: string, timeoutMs?: number);
66
+ get isConfigured(): boolean;
67
+ private getAccessToken;
68
+ resolveTrack(track: string, artist: string): Promise<SpotifyTrackMatch>;
69
+ }
70
+
71
+ declare class MoonifyError extends Error {
72
+ constructor(message: string);
73
+ }
74
+ declare class MoonifyApiError extends MoonifyError {
75
+ status: number;
76
+ service: "lastfm" | "spotify";
77
+ constructor(service: "lastfm" | "spotify", status: number, message: string);
78
+ }
79
+ declare class MoonifyAuthError extends MoonifyError {
80
+ constructor(service: "lastfm" | "spotify", message: string);
81
+ }
82
+
83
+ export { type LastFmRawTrack, LastFmService, Moonify, MoonifyApiError, MoonifyAuthError, type MoonifyConfig, MoonifyError, type ResolvedCurrentlyPlaying, SpotifyService, type SpotifyTrackMatch };
@@ -0,0 +1,83 @@
1
+ interface MoonifyConfig {
2
+ lastfmApiKey: string;
3
+ spotifyClientId?: string;
4
+ spotifyClientSecret?: string;
5
+ requestTimeoutMs?: number;
6
+ }
7
+
8
+ interface ResolvedCurrentlyPlaying {
9
+ trackName: string;
10
+ artistName: string;
11
+ trackUrl: string;
12
+ artistUrl: string;
13
+ lastFmTrackUrl: string;
14
+ lastFmArtistUrl: string;
15
+ spotifyTrackUrl: string | null;
16
+ spotifyArtistUrl: string | null;
17
+ isOnRepeat: boolean;
18
+ repeatCount: number;
19
+ }
20
+
21
+ declare class Moonify {
22
+ private lastfm;
23
+ private spotify;
24
+ constructor(config: MoonifyConfig);
25
+ getCurrentlyPlaying(username: string): Promise<ResolvedCurrentlyPlaying | null>;
26
+ }
27
+
28
+ interface LastFmTrackArtist {
29
+ "#text"?: string;
30
+ name?: string;
31
+ mbid?: string;
32
+ }
33
+ interface LastFmRawTrack {
34
+ name: string;
35
+ artist: LastFmTrackArtist;
36
+ url: string;
37
+ streamable?: string;
38
+ mbid?: string;
39
+ album?: {
40
+ "#text"?: string;
41
+ };
42
+ "@attr"?: {
43
+ nowplaying?: string;
44
+ };
45
+ }
46
+
47
+ declare class LastFmService {
48
+ private apiKey;
49
+ private timeoutMs;
50
+ constructor(apiKey: string, timeoutMs?: number);
51
+ getRecentTracks(username: string, limit?: number): Promise<LastFmRawTrack[]>;
52
+ }
53
+
54
+ interface SpotifyTrackMatch {
55
+ trackUrl: string | null;
56
+ artistUrl: string | null;
57
+ }
58
+
59
+ declare class SpotifyService {
60
+ private clientId?;
61
+ private clientSecret?;
62
+ private timeoutMs;
63
+ private token;
64
+ private tokenExpiresAt;
65
+ constructor(clientId?: string, clientSecret?: string, timeoutMs?: number);
66
+ get isConfigured(): boolean;
67
+ private getAccessToken;
68
+ resolveTrack(track: string, artist: string): Promise<SpotifyTrackMatch>;
69
+ }
70
+
71
+ declare class MoonifyError extends Error {
72
+ constructor(message: string);
73
+ }
74
+ declare class MoonifyApiError extends MoonifyError {
75
+ status: number;
76
+ service: "lastfm" | "spotify";
77
+ constructor(service: "lastfm" | "spotify", status: number, message: string);
78
+ }
79
+ declare class MoonifyAuthError extends MoonifyError {
80
+ constructor(service: "lastfm" | "spotify", message: string);
81
+ }
82
+
83
+ export { type LastFmRawTrack, LastFmService, Moonify, MoonifyApiError, MoonifyAuthError, type MoonifyConfig, MoonifyError, type ResolvedCurrentlyPlaying, SpotifyService, type SpotifyTrackMatch };
package/dist/index.js ADDED
@@ -0,0 +1,207 @@
1
+ // src/errors/index.ts
2
+ var MoonifyError = class extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "MoonifyError";
6
+ Object.setPrototypeOf(this, new.target.prototype);
7
+ }
8
+ };
9
+ var MoonifyApiError = class extends MoonifyError {
10
+ status;
11
+ service;
12
+ constructor(service, status, message) {
13
+ super(`${service} api error (${status}): ${message}`);
14
+ this.name = "MoonifyApiError";
15
+ this.service = service;
16
+ this.status = status;
17
+ }
18
+ };
19
+ var MoonifyAuthError = class extends MoonifyError {
20
+ constructor(service, message) {
21
+ super(`could not authenticate with ${service}: ${message}`);
22
+ this.name = "MoonifyAuthError";
23
+ }
24
+ };
25
+
26
+ // src/http/fetcher.ts
27
+ async function requestJson(service, url, options = {}) {
28
+ const { headers, body, method = "GET", timeoutMs = 8e3 } = options;
29
+ const controller = new AbortController();
30
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
31
+ try {
32
+ const res = await fetch(url, {
33
+ method,
34
+ headers,
35
+ body,
36
+ signal: controller.signal
37
+ });
38
+ if (!res.ok) {
39
+ const errorText = await res.text().catch(() => "Unknown response body");
40
+ throw new MoonifyApiError(service, res.status, errorText);
41
+ }
42
+ return await res.json();
43
+ } finally {
44
+ clearTimeout(timer);
45
+ }
46
+ }
47
+
48
+ // src/services/lastfm.service.ts
49
+ var LastFmService = class {
50
+ apiKey;
51
+ timeoutMs;
52
+ constructor(apiKey, timeoutMs = 8e3) {
53
+ this.apiKey = apiKey;
54
+ this.timeoutMs = timeoutMs;
55
+ }
56
+ async getRecentTracks(username, limit = 10) {
57
+ const url = `https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=${encodeURIComponent(
58
+ username
59
+ )}&api_key=${this.apiKey}&format=json&limit=${limit}`;
60
+ const data = await requestJson("lastfm", url, {
61
+ timeoutMs: this.timeoutMs
62
+ });
63
+ const raw = data.recenttracks?.track;
64
+ if (!raw) return [];
65
+ return Array.isArray(raw) ? raw : [raw];
66
+ }
67
+ };
68
+
69
+ // src/services/spotify.service.ts
70
+ var SpotifyService = class {
71
+ clientId;
72
+ clientSecret;
73
+ timeoutMs;
74
+ token = null;
75
+ tokenExpiresAt = 0;
76
+ constructor(clientId, clientSecret, timeoutMs = 8e3) {
77
+ this.clientId = clientId;
78
+ this.clientSecret = clientSecret;
79
+ this.timeoutMs = timeoutMs;
80
+ }
81
+ get isConfigured() {
82
+ return Boolean(this.clientId && this.clientSecret);
83
+ }
84
+ async getAccessToken() {
85
+ if (!this.isConfigured) return null;
86
+ if (this.token && Date.now() < this.tokenExpiresAt) {
87
+ return this.token;
88
+ }
89
+ try {
90
+ const credentials = btoa(`${this.clientId}:${this.clientSecret}`);
91
+ const data = await requestJson(
92
+ "spotify",
93
+ "https://accounts.spotify.com/api/token",
94
+ {
95
+ method: "POST",
96
+ headers: {
97
+ Authorization: `Basic ${credentials}`,
98
+ "Content-Type": "application/x-www-form-urlencoded"
99
+ },
100
+ body: "grant_type=client_credentials",
101
+ timeoutMs: this.timeoutMs
102
+ }
103
+ );
104
+ this.token = data.access_token;
105
+ this.tokenExpiresAt = Date.now() + (data.expires_in - 60) * 1e3;
106
+ return this.token;
107
+ } catch (error) {
108
+ throw new MoonifyAuthError("spotify", error.message);
109
+ }
110
+ }
111
+ async resolveTrack(track, artist) {
112
+ if (!this.isConfigured) {
113
+ return { trackUrl: null, artistUrl: null };
114
+ }
115
+ try {
116
+ const token = await this.getAccessToken();
117
+ if (!token) return { trackUrl: null, artistUrl: null };
118
+ const query = encodeURIComponent(`track:${track} artist:${artist}`);
119
+ const data = await requestJson(
120
+ "spotify",
121
+ `https://api.spotify.com/v1/search?q=${query}&type=track&limit=1`,
122
+ {
123
+ headers: { Authorization: `Bearer ${token}` },
124
+ timeoutMs: this.timeoutMs
125
+ }
126
+ );
127
+ const item = data.tracks?.items?.[0];
128
+ if (!item) return { trackUrl: null, artistUrl: null };
129
+ return {
130
+ trackUrl: item.external_urls?.spotify || null,
131
+ artistUrl: item.artists?.[0]?.external_urls?.spotify || null
132
+ };
133
+ } catch {
134
+ return { trackUrl: null, artistUrl: null };
135
+ }
136
+ }
137
+ };
138
+
139
+ // src/utils/normalise.ts
140
+ function normalizeString(input) {
141
+ return input.trim().toLowerCase();
142
+ }
143
+
144
+ // src/client.ts
145
+ var Moonify = class {
146
+ lastfm;
147
+ spotify;
148
+ constructor(config) {
149
+ if (!config.lastfmApiKey) {
150
+ throw new Error("lastfm api key is required.");
151
+ }
152
+ this.lastfm = new LastFmService(
153
+ config.lastfmApiKey,
154
+ config.requestTimeoutMs
155
+ );
156
+ this.spotify = new SpotifyService(
157
+ config.spotifyClientId,
158
+ config.spotifyClientSecret,
159
+ config.requestTimeoutMs
160
+ );
161
+ }
162
+ async getCurrentlyPlaying(username) {
163
+ const tracks = await this.lastfm.getRecentTracks(username, 10);
164
+ if (tracks.length === 0) return null;
165
+ const currentTrack = tracks[0];
166
+ const isNowPlaying = currentTrack["@attr"]?.nowplaying === "true";
167
+ if (!isNowPlaying) return null;
168
+ const trackName = currentTrack.name;
169
+ const artistName = currentTrack.artist["#text"] || currentTrack.artist.name || "Unknown Artist";
170
+ const lastFmTrackUrl = currentTrack.url;
171
+ const lastFmArtistUrl = `https://www.last.fm/music/${encodeURIComponent(artistName)}`;
172
+ const spotifyMatch = await this.spotify.resolveTrack(trackName, artistName);
173
+ const normTrack = normalizeString(trackName);
174
+ const normArtist = normalizeString(artistName);
175
+ let repeatCount = 0;
176
+ for (let i = 1; i < tracks.length; i++) {
177
+ const item = tracks[i];
178
+ const tName = normalizeString(item.name || "");
179
+ const tArtist = normalizeString(
180
+ item.artist["#text"] || item.artist.name || ""
181
+ );
182
+ if (tName === normTrack && tArtist === normArtist) {
183
+ repeatCount++;
184
+ }
185
+ }
186
+ return {
187
+ trackName,
188
+ artistName,
189
+ trackUrl: spotifyMatch.trackUrl || lastFmTrackUrl,
190
+ artistUrl: spotifyMatch.artistUrl || lastFmArtistUrl,
191
+ lastFmTrackUrl,
192
+ lastFmArtistUrl,
193
+ spotifyTrackUrl: spotifyMatch.trackUrl,
194
+ spotifyArtistUrl: spotifyMatch.artistUrl,
195
+ isOnRepeat: repeatCount >= 2,
196
+ repeatCount
197
+ };
198
+ }
199
+ };
200
+ export {
201
+ LastFmService,
202
+ Moonify,
203
+ MoonifyApiError,
204
+ MoonifyAuthError,
205
+ MoonifyError,
206
+ SpotifyService
207
+ };
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@mwyeow/moonify.js",
3
+ "version": "1.0.0",
4
+ "description": "Resolve Last.fm currently playing track and enrich with Spotify metadata",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/mwyeow/moonify.js.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/mwyeow/moonify.js/issues"
15
+ },
16
+ "homepage": "https://github.com/mwyeow/moonify.js#readme",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "require": "./dist/index.cjs"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "scripts": {
28
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
29
+ "dev": "tsup src/index.ts --format esm,cjs --dts --watch",
30
+ "test": "bun test",
31
+ "test:live": "bun run test/live.ts",
32
+ "prepublishOnly": "bun run build"
33
+ },
34
+ "license": "MIT",
35
+ "devDependencies": {
36
+ "@types/bun": "^1.2.0",
37
+ "@types/node": "^22.0.0",
38
+ "tsup": "^8.3.0",
39
+ "typescript": "^5.7.0"
40
+ }
41
+ }