spotify-now-playing-banner 0.1.0 → 0.1.2
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 +118 -37
- package/dist/chunk-GKEANZNP.js +234 -0
- package/dist/chunk-GKEANZNP.js.map +1 -0
- package/dist/index.d.ts +12 -39
- package/dist/index.js +40 -6
- package/dist/index.js.map +1 -1
- package/dist/server/index.d.ts +41 -0
- package/dist/server/index.js +74 -0
- package/dist/server/index.js.map +1 -0
- package/dist/spotify-B7X9bmfI.d.ts +106 -0
- package/package.json +9 -1
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# spotify-now-playing-banner
|
|
2
2
|
|
|
3
|
-
A small React component that shows what you're listening to on Spotify — track, artist, album art, live progress, and the next item in your queue
|
|
3
|
+
A small React component that shows what you're listening to on Spotify — track, artist, album art, live progress, and the next item in your queue.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Credentials are passed explicitly by you. **The package never reads environment variables.** You can pass them as component props (direct browser calls, with the security caveat below) or to the bundled server handler (recommended).
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
@@ -10,20 +10,90 @@ No Spotify credentials are shipped to the browser. Your server holds them and ex
|
|
|
10
10
|
npm install spotify-now-playing-banner
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
React 18 or newer is required as a peer dependency.
|
|
13
|
+
React 18 or newer is required as a peer dependency. `axios` is installed automatically for the Spotify client.
|
|
14
14
|
|
|
15
|
-
## Usage
|
|
15
|
+
## Usage with credentials as props
|
|
16
16
|
|
|
17
17
|
```tsx
|
|
18
18
|
import { SpotifyBanner } from 'spotify-now-playing-banner'
|
|
19
19
|
import 'spotify-now-playing-banner/styles.css'
|
|
20
20
|
|
|
21
21
|
export function NowPlaying() {
|
|
22
|
-
return
|
|
22
|
+
return (
|
|
23
|
+
<SpotifyBanner
|
|
24
|
+
credentials={{
|
|
25
|
+
clientId: 'your-client-id',
|
|
26
|
+
clientSecret: 'your-client-secret',
|
|
27
|
+
refreshToken: 'your-refresh-token'
|
|
28
|
+
}}
|
|
29
|
+
/>
|
|
30
|
+
)
|
|
23
31
|
}
|
|
24
32
|
```
|
|
25
33
|
|
|
26
|
-
|
|
34
|
+
Shorthand props are also supported:
|
|
35
|
+
|
|
36
|
+
```tsx
|
|
37
|
+
<SpotifyBanner
|
|
38
|
+
clientId="your-client-id"
|
|
39
|
+
clientSecret="your-client-secret"
|
|
40
|
+
refreshToken="your-refresh-token"
|
|
41
|
+
/>
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
When credentials are present, the component calls `api.spotify.com` directly with axios and no `endpoint` is needed.
|
|
45
|
+
|
|
46
|
+
> **Security warning:** props are part of the client bundle. Anyone can read your `clientSecret` and `refreshToken`. Use this only for personal/local tools where exposure is acceptable. For public sites, use the server handler below.
|
|
47
|
+
|
|
48
|
+
## Usage with the bundled server handler (recommended)
|
|
49
|
+
|
|
50
|
+
Your app reads its own environment (the package does not), passes the credentials to the handler, and the component needs no props:
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
// app/api/spotify/route.ts
|
|
54
|
+
import { createSpotifyHandler } from 'spotify-now-playing-banner/server'
|
|
55
|
+
|
|
56
|
+
const handler = createSpotifyHandler({
|
|
57
|
+
clientId: process.env.SPOTIFY_CLIENT_ID!,
|
|
58
|
+
clientSecret: process.env.SPOTIFY_CLIENT_SECRET!,
|
|
59
|
+
refreshToken: process.env.SPOTIFY_REFRESH_TOKEN!
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
export const GET = handler
|
|
63
|
+
export const OPTIONS = handler
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
// api/spotify.mjs — Next.js Pages Router / Vercel Node function
|
|
68
|
+
import { createSpotifyHandler } from 'spotify-now-playing-banner/server'
|
|
69
|
+
|
|
70
|
+
export default createSpotifyHandler({
|
|
71
|
+
clientId: process.env.SPOTIFY_CLIENT_ID,
|
|
72
|
+
clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
|
|
73
|
+
refreshToken: process.env.SPOTIFY_REFRESH_TOKEN
|
|
74
|
+
})
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
```tsx
|
|
78
|
+
<SpotifyBanner />
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
The handler accepts both a Web `Request` and a Node `(req, res)` pair, caches snapshots for 5 seconds, and sets permissive CORS headers so a site on another origin can poll it.
|
|
82
|
+
|
|
83
|
+
## Props
|
|
84
|
+
|
|
85
|
+
| Prop | Type | Default | Description |
|
|
86
|
+
| --- | --- | --- | --- |
|
|
87
|
+
| `credentials` | `{ clientId, clientSecret, refreshToken }` | – | Call Spotify directly from the browser. **Publicly visible.** |
|
|
88
|
+
| `clientId` | `string` | – | Shorthand for `credentials.clientId`. |
|
|
89
|
+
| `clientSecret` | `string` | – | Shorthand for `credentials.clientSecret`. |
|
|
90
|
+
| `refreshToken` | `string` | – | Shorthand for `credentials.refreshToken`. |
|
|
91
|
+
| `endpoint` | `string` | `/api/spotify` | Status URL used when no credentials are passed. Not needed with the bundled handler. May be a full cross-origin URL. |
|
|
92
|
+
| `initialStatus` | `SpotifyStatus \| null` | `null` | Status to render before the first successful poll. The component renders nothing until it has data. |
|
|
93
|
+
| `pollIntervalMs` | `number` | `3000` | Polling interval. Set to `0` to disable polling and render only `initialStatus`. |
|
|
94
|
+
| `className` | `string` | – | Extra class names on the root `<section>`. |
|
|
95
|
+
|
|
96
|
+
The component re-fetches immediately when the tab becomes visible again, ignores stale/out-of-order responses, and locally advances the progress bar between polls. It also detects seeks or playback on another device and re-anchors progress.
|
|
27
97
|
|
|
28
98
|
```tsx
|
|
29
99
|
import lastPlayed from './data/last-played.json'
|
|
@@ -33,7 +103,6 @@ import 'spotify-now-playing-banner/styles.css'
|
|
|
33
103
|
export function NowPlaying() {
|
|
34
104
|
return (
|
|
35
105
|
<SpotifyBanner
|
|
36
|
-
endpoint="https://your-api.example.com/api/spotify"
|
|
37
106
|
initialStatus={lastPlayed as SpotifyStatus}
|
|
38
107
|
pollIntervalMs={5000}
|
|
39
108
|
className="my-banner"
|
|
@@ -42,20 +111,51 @@ export function NowPlaying() {
|
|
|
42
111
|
}
|
|
43
112
|
```
|
|
44
113
|
|
|
45
|
-
|
|
114
|
+
## Spotify API (browser-safe helpers)
|
|
46
115
|
|
|
47
|
-
|
|
48
|
-
| --- | --- | --- | --- |
|
|
49
|
-
| `endpoint` | `string` | `/api/spotify` | URL that returns a `SpotifyStatus` JSON object. May be a full cross-origin URL. |
|
|
50
|
-
| `initialStatus` | `SpotifyStatus \| null` | `null` | Status to render before the first successful poll. The component renders nothing until it has data. |
|
|
51
|
-
| `pollIntervalMs` | `number` | `3000` | Polling interval. Set to `0` to disable polling and render only `initialStatus`. |
|
|
52
|
-
| `className` | `string` | – | Extra class names on the root `<section>`. |
|
|
116
|
+
Everything is exported from the main entry, and also from `spotify-now-playing-banner/server`:
|
|
53
117
|
|
|
54
|
-
|
|
118
|
+
| Export | Description |
|
|
119
|
+
| --- | --- |
|
|
120
|
+
| `createSpotifyApi(credentials, options?)` | Credential-bound client with its own token/status caches. |
|
|
121
|
+
| `getSpotifyStatus(credentials, options?)` | One-off status fetch (call `api.getStatus()` to reuse a cache). |
|
|
122
|
+
| `fetchSpotifyStatus(credentials, options?)` | One-off fetch including `ageMs`. |
|
|
123
|
+
| `createSpotifyHandler(options)` | Server endpoint factory; options include the three credentials. |
|
|
124
|
+
| `SpotifyError` | Error type with an optional HTTP `status`. |
|
|
125
|
+
|
|
126
|
+
Each `SpotifyApi` instance keeps its own caches, so different credentials never share state.
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
import { createSpotifyApi } from 'spotify-now-playing-banner'
|
|
130
|
+
|
|
131
|
+
const api = createSpotifyApi(
|
|
132
|
+
{ clientId: 'id', clientSecret: 'secret', refreshToken: 'token' },
|
|
133
|
+
{ cacheMs: 10_000 }
|
|
134
|
+
)
|
|
135
|
+
const status = await api.getStatus()
|
|
136
|
+
api.clearCache()
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Options: `cacheMs` (default 5000), `tokenUrl` and `apiBaseUrl` (overrides, useful for tests). The handler additionally accepts `cors: false` to disable CORS headers.
|
|
140
|
+
|
|
141
|
+
```tsx
|
|
142
|
+
// Server component: render a snapshot immediately.
|
|
143
|
+
import { getSpotifyStatus } from 'spotify-now-playing-banner/server'
|
|
144
|
+
import { SpotifyBanner } from 'spotify-now-playing-banner'
|
|
145
|
+
|
|
146
|
+
export default async function Page() {
|
|
147
|
+
const status = await getSpotifyStatus({
|
|
148
|
+
clientId: process.env.SPOTIFY_CLIENT_ID!,
|
|
149
|
+
clientSecret: process.env.SPOTIFY_CLIENT_SECRET!,
|
|
150
|
+
refreshToken: process.env.SPOTIFY_REFRESH_TOKEN!
|
|
151
|
+
})
|
|
152
|
+
return <SpotifyBanner initialStatus={status} />
|
|
153
|
+
}
|
|
154
|
+
```
|
|
55
155
|
|
|
56
156
|
## API contract
|
|
57
157
|
|
|
58
|
-
The
|
|
158
|
+
The status JSON (returned by the handler, `api.getStatus()`, or your own endpoint) looks like:
|
|
59
159
|
|
|
60
160
|
```json
|
|
61
161
|
{
|
|
@@ -85,26 +185,9 @@ Fields:
|
|
|
85
185
|
- `playedAt` — ISO timestamp, or `null`.
|
|
86
186
|
- `progressMs` / `durationMs` — optional; progress is hidden when absent.
|
|
87
187
|
- `next` — optional queued item; only displayed while `playing` is `true`.
|
|
88
|
-
- `ageMs` — optional age of a
|
|
89
|
-
|
|
90
|
-
Return `null` (or a non-2xx status) when nothing is available; the component keeps its last known data.
|
|
91
|
-
|
|
92
|
-
## Server setup
|
|
188
|
+
- `ageMs` — optional age of a cached snapshot in ms, used to keep progress accurate.
|
|
93
189
|
|
|
94
|
-
The
|
|
95
|
-
|
|
96
|
-
```sh
|
|
97
|
-
SPOTIFY_CLIENT_ID=...
|
|
98
|
-
SPOTIFY_CLIENT_SECRET=...
|
|
99
|
-
SPOTIFY_REFRESH_TOKEN=...
|
|
100
|
-
```
|
|
101
|
-
|
|
102
|
-
A ready-to-use implementation lives in the source repository:
|
|
103
|
-
|
|
104
|
-
- `lib/spotify.mjs` — refreshes the access token, reads `me/player/currently-playing`, the queue, and `me/player/recently-played`, and normalizes the result.
|
|
105
|
-
- `api/spotify.mjs` — a Vercel-style handler that caches responses for 5 seconds and sets `Access-Control-Allow-Origin: *` for cross-origin sites.
|
|
106
|
-
|
|
107
|
-
If your site is on a different origin than the API, enable CORS on the endpoint (the included handler already does).
|
|
190
|
+
The handler returns `null` when nothing is available; the component keeps its last known data. Errors return `{ error }` with a 500/502 status.
|
|
108
191
|
|
|
109
192
|
## Styling
|
|
110
193
|
|
|
@@ -130,5 +213,3 @@ npm pack --dry-run
|
|
|
130
213
|
```
|
|
131
214
|
|
|
132
215
|
`npm pack --dry-run` prints the exact files that would be published (`dist/`, this README, and the license). Credentials and local data files are not included.
|
|
133
|
-
|
|
134
|
-
Maintainers publish with `npm login` followed by `npm publish`; use `npm version patch|minor|major` before each release.
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
// src/spotify.ts
|
|
2
|
+
import axios from "axios";
|
|
3
|
+
var TOKEN_URL = "https://accounts.spotify.com/api/token";
|
|
4
|
+
var API_BASE_URL = "https://api.spotify.com/v1";
|
|
5
|
+
var REQUEST_TIMEOUT = 1e4;
|
|
6
|
+
var SpotifyError = class extends Error {
|
|
7
|
+
status;
|
|
8
|
+
constructor(message, status) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "SpotifyError";
|
|
11
|
+
this.status = status;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
function assertCredentials(credentials) {
|
|
15
|
+
if (!credentials?.clientId || !credentials.clientSecret || !credentials.refreshToken) {
|
|
16
|
+
throw new SpotifyError(
|
|
17
|
+
"Spotify credentials are missing. Pass clientId, clientSecret and refreshToken to createSpotifyApi() or to <SpotifyBanner credentials={...}>."
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
return credentials;
|
|
21
|
+
}
|
|
22
|
+
function base64(input) {
|
|
23
|
+
if (typeof btoa === "function") return btoa(input);
|
|
24
|
+
const globalWithBuffer = globalThis;
|
|
25
|
+
return globalWithBuffer.Buffer?.from(input, "utf8").toString("base64") ?? "";
|
|
26
|
+
}
|
|
27
|
+
function describeError(error, fallback) {
|
|
28
|
+
if (error instanceof SpotifyError) return error;
|
|
29
|
+
if (axios.isAxiosError(error)) {
|
|
30
|
+
const status = error.response?.status;
|
|
31
|
+
const detail = error.response?.data?.error?.message;
|
|
32
|
+
const message = status === 401 || status === 403 ? "Spotify rejected the credentials or refresh token" : detail ?? error.message;
|
|
33
|
+
return new SpotifyError(`${fallback}: ${message}`, status);
|
|
34
|
+
}
|
|
35
|
+
return new SpotifyError(
|
|
36
|
+
`${fallback}: ${error instanceof Error ? error.message : "unknown error"}`
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
function artistOf(track) {
|
|
40
|
+
return (track.artists ?? []).map((artist) => artist.name).filter(Boolean).join(", ");
|
|
41
|
+
}
|
|
42
|
+
function imageOf(track) {
|
|
43
|
+
const images = track.album?.images ?? track.show?.images ?? track.images ?? [];
|
|
44
|
+
const largest = [...images].sort((a, b) => (b.width ?? 0) - (a.width ?? 0))[0];
|
|
45
|
+
return largest?.url ?? "";
|
|
46
|
+
}
|
|
47
|
+
function albumOf(track) {
|
|
48
|
+
return track.album?.name ?? track.show?.name ?? "";
|
|
49
|
+
}
|
|
50
|
+
function urlOf(track) {
|
|
51
|
+
return track.external_urls?.spotify ?? "";
|
|
52
|
+
}
|
|
53
|
+
function toStatus(track, playing, playedAt, progressMs = null) {
|
|
54
|
+
return {
|
|
55
|
+
playing,
|
|
56
|
+
track: track.name,
|
|
57
|
+
artist: artistOf(track),
|
|
58
|
+
album: albumOf(track),
|
|
59
|
+
image: imageOf(track),
|
|
60
|
+
url: urlOf(track),
|
|
61
|
+
playedAt,
|
|
62
|
+
progressMs,
|
|
63
|
+
durationMs: typeof track.duration_ms === "number" ? track.duration_ms : null,
|
|
64
|
+
next: null
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function toQueueItem(track) {
|
|
68
|
+
if (!track?.name) return null;
|
|
69
|
+
return {
|
|
70
|
+
track: track.name,
|
|
71
|
+
artist: artistOf(track),
|
|
72
|
+
album: albumOf(track) || void 0,
|
|
73
|
+
image: imageOf(track),
|
|
74
|
+
url: urlOf(track)
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
var SpotifyApi = class {
|
|
78
|
+
credentials;
|
|
79
|
+
options;
|
|
80
|
+
tokenCache = null;
|
|
81
|
+
rotatedRefreshToken = null;
|
|
82
|
+
tokenInFlight = null;
|
|
83
|
+
statusCache = null;
|
|
84
|
+
statusInFlight = null;
|
|
85
|
+
constructor(credentials, options = {}) {
|
|
86
|
+
this.credentials = { ...assertCredentials(credentials) };
|
|
87
|
+
this.options = options;
|
|
88
|
+
}
|
|
89
|
+
/** Discard this instance's cached token and status. */
|
|
90
|
+
clearCache() {
|
|
91
|
+
this.tokenCache = null;
|
|
92
|
+
this.rotatedRefreshToken = null;
|
|
93
|
+
this.tokenInFlight = null;
|
|
94
|
+
this.statusCache = null;
|
|
95
|
+
this.statusInFlight = null;
|
|
96
|
+
}
|
|
97
|
+
async getAccessToken() {
|
|
98
|
+
const now = Date.now();
|
|
99
|
+
if (this.tokenCache && this.tokenCache.expiresAt > now + 6e4) {
|
|
100
|
+
return this.tokenCache.value;
|
|
101
|
+
}
|
|
102
|
+
if (this.tokenInFlight) return this.tokenInFlight;
|
|
103
|
+
this.tokenInFlight = (async () => {
|
|
104
|
+
try {
|
|
105
|
+
const body = new URLSearchParams({
|
|
106
|
+
grant_type: "refresh_token",
|
|
107
|
+
refresh_token: this.rotatedRefreshToken ?? this.credentials.refreshToken
|
|
108
|
+
});
|
|
109
|
+
const { data } = await axios.post(
|
|
110
|
+
this.options.tokenUrl ?? TOKEN_URL,
|
|
111
|
+
body.toString(),
|
|
112
|
+
{
|
|
113
|
+
headers: {
|
|
114
|
+
Authorization: `Basic ${base64(`${this.credentials.clientId}:${this.credentials.clientSecret}`)}`,
|
|
115
|
+
"Content-Type": "application/x-www-form-urlencoded"
|
|
116
|
+
},
|
|
117
|
+
timeout: REQUEST_TIMEOUT
|
|
118
|
+
}
|
|
119
|
+
);
|
|
120
|
+
if (!data.access_token) {
|
|
121
|
+
throw new SpotifyError("Spotify token response did not contain an access token");
|
|
122
|
+
}
|
|
123
|
+
this.tokenCache = {
|
|
124
|
+
value: data.access_token,
|
|
125
|
+
expiresAt: Date.now() + (data.expires_in ?? 3600) * 1e3
|
|
126
|
+
};
|
|
127
|
+
if (data.refresh_token) this.rotatedRefreshToken = data.refresh_token;
|
|
128
|
+
return this.tokenCache.value;
|
|
129
|
+
} catch (error) {
|
|
130
|
+
throw describeError(error, "Could not refresh the Spotify access token");
|
|
131
|
+
} finally {
|
|
132
|
+
this.tokenInFlight = null;
|
|
133
|
+
}
|
|
134
|
+
})();
|
|
135
|
+
return this.tokenInFlight;
|
|
136
|
+
}
|
|
137
|
+
async getCurrentlyPlaying(api) {
|
|
138
|
+
const response = await api.get("/me/player/currently-playing", {
|
|
139
|
+
params: { additional_types: "track,episode" },
|
|
140
|
+
validateStatus: (status) => status === 200 || status === 204
|
|
141
|
+
});
|
|
142
|
+
return response.status === 200 ? response.data : null;
|
|
143
|
+
}
|
|
144
|
+
async getNextTrack(api) {
|
|
145
|
+
try {
|
|
146
|
+
const { data } = await api.get("/me/player/queue");
|
|
147
|
+
return toQueueItem(data.items?.[0]);
|
|
148
|
+
} catch {
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
async getLastPlayed(api) {
|
|
153
|
+
try {
|
|
154
|
+
const { data } = await api.get("/me/player/recently-played", {
|
|
155
|
+
params: { limit: 1 }
|
|
156
|
+
});
|
|
157
|
+
const entry = data.items?.[0];
|
|
158
|
+
if (!entry?.track) return null;
|
|
159
|
+
return toStatus(entry.track, false, entry.played_at ?? null);
|
|
160
|
+
} catch {
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/** Fetch a status snapshot, reusing a fresh cached snapshot when available. */
|
|
165
|
+
async getSnapshot() {
|
|
166
|
+
const cacheMs = Math.max(0, this.options.cacheMs ?? 5e3);
|
|
167
|
+
const ageMs = this.statusCache ? Date.now() - this.statusCache.fetchedAt : 0;
|
|
168
|
+
if (this.statusCache && ageMs < cacheMs) {
|
|
169
|
+
return { status: this.statusCache.snapshot.status, ageMs };
|
|
170
|
+
}
|
|
171
|
+
if (this.statusInFlight) return this.statusInFlight;
|
|
172
|
+
this.statusInFlight = (async () => {
|
|
173
|
+
try {
|
|
174
|
+
const token = await this.getAccessToken();
|
|
175
|
+
const api = axios.create({
|
|
176
|
+
baseURL: this.options.apiBaseUrl ?? API_BASE_URL,
|
|
177
|
+
timeout: REQUEST_TIMEOUT,
|
|
178
|
+
headers: { Authorization: `Bearer ${token}` }
|
|
179
|
+
});
|
|
180
|
+
let status = null;
|
|
181
|
+
let error = null;
|
|
182
|
+
try {
|
|
183
|
+
const current = await this.getCurrentlyPlaying(api);
|
|
184
|
+
if (current?.item) {
|
|
185
|
+
status = toStatus(
|
|
186
|
+
current.item,
|
|
187
|
+
current.is_playing === true,
|
|
188
|
+
typeof current.timestamp === "number" ? new Date(current.timestamp).toISOString() : null,
|
|
189
|
+
typeof current.progress_ms === "number" ? current.progress_ms : null
|
|
190
|
+
);
|
|
191
|
+
if (status.playing) status.next = await this.getNextTrack(api);
|
|
192
|
+
} else {
|
|
193
|
+
status = await this.getLastPlayed(api);
|
|
194
|
+
}
|
|
195
|
+
} catch (caught) {
|
|
196
|
+
error = caught;
|
|
197
|
+
}
|
|
198
|
+
if (error) throw describeError(error, "Could not read Spotify playback status");
|
|
199
|
+
if (status) {
|
|
200
|
+
this.statusCache = { snapshot: { status, ageMs: 0 }, fetchedAt: Date.now() };
|
|
201
|
+
return { status, ageMs: 0 };
|
|
202
|
+
}
|
|
203
|
+
this.statusCache = null;
|
|
204
|
+
return null;
|
|
205
|
+
} finally {
|
|
206
|
+
this.statusInFlight = null;
|
|
207
|
+
}
|
|
208
|
+
})();
|
|
209
|
+
return this.statusInFlight;
|
|
210
|
+
}
|
|
211
|
+
/** Fetch just the status JSON (including `ageMs`) the banner expects. */
|
|
212
|
+
async getStatus() {
|
|
213
|
+
const snapshot = await this.getSnapshot();
|
|
214
|
+
return snapshot ? { ...snapshot.status, ageMs: snapshot.ageMs } : null;
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
function createSpotifyApi(credentials, options = {}) {
|
|
218
|
+
return new SpotifyApi(credentials, options);
|
|
219
|
+
}
|
|
220
|
+
async function fetchSpotifyStatus(credentials, options = {}) {
|
|
221
|
+
return createSpotifyApi(credentials, options).getSnapshot();
|
|
222
|
+
}
|
|
223
|
+
async function getSpotifyStatus(credentials, options = {}) {
|
|
224
|
+
return createSpotifyApi(credentials, options).getStatus();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export {
|
|
228
|
+
SpotifyError,
|
|
229
|
+
SpotifyApi,
|
|
230
|
+
createSpotifyApi,
|
|
231
|
+
fetchSpotifyStatus,
|
|
232
|
+
getSpotifyStatus
|
|
233
|
+
};
|
|
234
|
+
//# sourceMappingURL=chunk-GKEANZNP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/spotify.ts"],"sourcesContent":["import axios from 'axios'\nimport type { SpotifyCredentials, SpotifyQueueItem, SpotifyStatus } from './types'\n\nconst TOKEN_URL = 'https://accounts.spotify.com/api/token'\nconst API_BASE_URL = 'https://api.spotify.com/v1'\nconst REQUEST_TIMEOUT = 10_000\n\ntype SpotifyImage = { url: string; width?: number; height?: number }\n\ntype SpotifyTrack = {\n name: string\n duration_ms?: number\n external_urls?: { spotify?: string }\n artists?: Array<{ name: string }>\n album?: { name?: string; images?: SpotifyImage[] }\n show?: { name?: string; images?: SpotifyImage[] }\n images?: SpotifyImage[]\n}\n\ntype TokenResponse = { access_token: string; expires_in?: number; refresh_token?: string }\ntype CurrentlyPlayingResponse = {\n is_playing?: boolean\n progress_ms?: number | null\n timestamp?: number\n item?: SpotifyTrack | null\n}\ntype QueueResponse = { items?: SpotifyTrack[] }\ntype RecentlyPlayedResponse = {\n items?: Array<{ played_at?: string; track?: SpotifyTrack }>\n}\ntype ErrorResponse = { error?: { message?: string } }\n\n/** An error from Spotify or from invalid credential input. */\nexport class SpotifyError extends Error {\n readonly status?: number\n\n constructor(message: string, status?: number) {\n super(message)\n this.name = 'SpotifyError'\n this.status = status\n }\n}\n\n/** A status snapshot plus the age of the API's cached copy. */\nexport type SpotifySnapshot = {\n status: SpotifyStatus\n ageMs: number\n}\n\nexport type SpotifyApiOptions = {\n /** Cache lifetime in milliseconds. Defaults to 5000. */\n cacheMs?: number\n /** Override the token endpoint (useful for tests). */\n tokenUrl?: string\n /** Override the Web API base URL (useful for tests). */\n apiBaseUrl?: string\n}\n\nfunction assertCredentials(credentials: SpotifyCredentials | undefined): SpotifyCredentials {\n if (!credentials?.clientId || !credentials.clientSecret || !credentials.refreshToken) {\n throw new SpotifyError(\n 'Spotify credentials are missing. Pass clientId, clientSecret and refreshToken to createSpotifyApi() or to <SpotifyBanner credentials={...}>.'\n )\n }\n return credentials\n}\n\nfunction base64(input: string): string {\n if (typeof btoa === 'function') return btoa(input)\n const globalWithBuffer = globalThis as {\n Buffer?: { from(value: string, encoding: string): { toString(encoding: string): string } }\n }\n return globalWithBuffer.Buffer?.from(input, 'utf8').toString('base64') ?? ''\n}\n\nfunction describeError(error: unknown, fallback: string): SpotifyError {\n if (error instanceof SpotifyError) return error\n if (axios.isAxiosError(error)) {\n const status = error.response?.status\n const detail = (error.response?.data as ErrorResponse | undefined)?.error?.message\n const message = status === 401 || status === 403\n ? 'Spotify rejected the credentials or refresh token'\n : (detail ?? error.message)\n return new SpotifyError(`${fallback}: ${message}`, status)\n }\n return new SpotifyError(\n `${fallback}: ${error instanceof Error ? error.message : 'unknown error'}`\n )\n}\n\nfunction artistOf(track: SpotifyTrack): string {\n return (track.artists ?? []).map((artist) => artist.name).filter(Boolean).join(', ')\n}\n\nfunction imageOf(track: SpotifyTrack): string {\n const images = track.album?.images ?? track.show?.images ?? track.images ?? []\n const largest = [...images].sort((a, b) => (b.width ?? 0) - (a.width ?? 0))[0]\n return largest?.url ?? ''\n}\n\nfunction albumOf(track: SpotifyTrack): string {\n return track.album?.name ?? track.show?.name ?? ''\n}\n\nfunction urlOf(track: SpotifyTrack): string {\n return track.external_urls?.spotify ?? ''\n}\n\nfunction toStatus(\n track: SpotifyTrack,\n playing: boolean,\n playedAt: string | null,\n progressMs: number | null = null\n): SpotifyStatus {\n return {\n playing,\n track: track.name,\n artist: artistOf(track),\n album: albumOf(track),\n image: imageOf(track),\n url: urlOf(track),\n playedAt,\n progressMs,\n durationMs: typeof track.duration_ms === 'number' ? track.duration_ms : null,\n next: null\n }\n}\n\nfunction toQueueItem(track: SpotifyTrack | undefined): SpotifyQueueItem | null {\n if (!track?.name) return null\n return {\n track: track.name,\n artist: artistOf(track),\n album: albumOf(track) || undefined,\n image: imageOf(track),\n url: urlOf(track)\n }\n}\n\n/**\n * A credential-bound Spotify client. Each instance keeps its own token and\n * status caches, so different credentials never share state.\n */\nexport class SpotifyApi {\n private readonly credentials: SpotifyCredentials\n private readonly options: SpotifyApiOptions\n\n private tokenCache: { value: string; expiresAt: number } | null = null\n private rotatedRefreshToken: string | null = null\n private tokenInFlight: Promise<string> | null = null\n\n private statusCache: { snapshot: SpotifySnapshot; fetchedAt: number } | null = null\n private statusInFlight: Promise<SpotifySnapshot | null> | null = null\n\n constructor(credentials: SpotifyCredentials, options: SpotifyApiOptions = {}) {\n this.credentials = { ...assertCredentials(credentials) }\n this.options = options\n }\n\n /** Discard this instance's cached token and status. */\n clearCache(): void {\n this.tokenCache = null\n this.rotatedRefreshToken = null\n this.tokenInFlight = null\n this.statusCache = null\n this.statusInFlight = null\n }\n\n private async getAccessToken(): Promise<string> {\n const now = Date.now()\n if (this.tokenCache && this.tokenCache.expiresAt > now + 60_000) {\n return this.tokenCache.value\n }\n if (this.tokenInFlight) return this.tokenInFlight\n\n this.tokenInFlight = (async () => {\n try {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: this.rotatedRefreshToken ?? this.credentials.refreshToken\n })\n\n const { data } = await axios.post<TokenResponse>(\n this.options.tokenUrl ?? TOKEN_URL,\n body.toString(),\n {\n headers: {\n Authorization: `Basic ${base64(`${this.credentials.clientId}:${this.credentials.clientSecret}`)}`,\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n timeout: REQUEST_TIMEOUT\n }\n )\n\n if (!data.access_token) {\n throw new SpotifyError('Spotify token response did not contain an access token')\n }\n\n this.tokenCache = {\n value: data.access_token,\n expiresAt: Date.now() + (data.expires_in ?? 3600) * 1000\n }\n if (data.refresh_token) this.rotatedRefreshToken = data.refresh_token\n return this.tokenCache.value\n } catch (error) {\n throw describeError(error, 'Could not refresh the Spotify access token')\n } finally {\n this.tokenInFlight = null\n }\n })()\n\n return this.tokenInFlight\n }\n\n private async getCurrentlyPlaying(\n api: ReturnType<typeof axios.create>\n ): Promise<CurrentlyPlayingResponse | null> {\n const response = await api.get<CurrentlyPlayingResponse>('/me/player/currently-playing', {\n params: { additional_types: 'track,episode' },\n validateStatus: (status) => status === 200 || status === 204\n })\n return response.status === 200 ? response.data : null\n }\n\n private async getNextTrack(\n api: ReturnType<typeof axios.create>\n ): Promise<SpotifyQueueItem | null> {\n try {\n const { data } = await api.get<QueueResponse>('/me/player/queue')\n return toQueueItem(data.items?.[0])\n } catch {\n // The queue is optional; a banner without \"up next\" is still useful.\n return null\n }\n }\n\n private async getLastPlayed(\n api: ReturnType<typeof axios.create>\n ): Promise<SpotifyStatus | null> {\n try {\n const { data } = await api.get<RecentlyPlayedResponse>('/me/player/recently-played', {\n params: { limit: 1 }\n })\n const entry = data.items?.[0]\n if (!entry?.track) return null\n return toStatus(entry.track, false, entry.played_at ?? null)\n } catch {\n return null\n }\n }\n\n /** Fetch a status snapshot, reusing a fresh cached snapshot when available. */\n async getSnapshot(): Promise<SpotifySnapshot | null> {\n const cacheMs = Math.max(0, this.options.cacheMs ?? 5000)\n const ageMs = this.statusCache ? Date.now() - this.statusCache.fetchedAt : 0\n if (this.statusCache && ageMs < cacheMs) {\n return { status: this.statusCache.snapshot.status, ageMs }\n }\n if (this.statusInFlight) return this.statusInFlight\n\n this.statusInFlight = (async () => {\n try {\n const token = await this.getAccessToken()\n const api = axios.create({\n baseURL: this.options.apiBaseUrl ?? API_BASE_URL,\n timeout: REQUEST_TIMEOUT,\n headers: { Authorization: `Bearer ${token}` }\n })\n\n let status: SpotifyStatus | null = null\n let error: unknown = null\n try {\n const current = await this.getCurrentlyPlaying(api)\n if (current?.item) {\n status = toStatus(\n current.item,\n current.is_playing === true,\n typeof current.timestamp === 'number'\n ? new Date(current.timestamp).toISOString()\n : null,\n typeof current.progress_ms === 'number' ? current.progress_ms : null\n )\n if (status.playing) status.next = await this.getNextTrack(api)\n } else {\n status = await this.getLastPlayed(api)\n }\n } catch (caught) {\n error = caught\n }\n\n if (error) throw describeError(error, 'Could not read Spotify playback status')\n\n if (status) {\n this.statusCache = { snapshot: { status, ageMs: 0 }, fetchedAt: Date.now() }\n return { status, ageMs: 0 }\n }\n this.statusCache = null\n return null\n } finally {\n this.statusInFlight = null\n }\n })()\n\n return this.statusInFlight\n }\n\n /** Fetch just the status JSON (including `ageMs`) the banner expects. */\n async getStatus(): Promise<SpotifyStatus | null> {\n const snapshot = await this.getSnapshot()\n return snapshot ? { ...snapshot.status, ageMs: snapshot.ageMs } : null\n }\n}\n\n/** Create a credential-bound Spotify client. */\nexport function createSpotifyApi(\n credentials: SpotifyCredentials,\n options: SpotifyApiOptions = {}\n): SpotifyApi {\n return new SpotifyApi(credentials, options)\n}\n\n/** One-off snapshot fetch. Use `createSpotifyApi` to keep the cache between calls. */\nexport async function fetchSpotifyStatus(\n credentials: SpotifyCredentials,\n options: SpotifyApiOptions = {}\n): Promise<SpotifySnapshot | null> {\n return createSpotifyApi(credentials, options).getSnapshot()\n}\n\n/** One-off status fetch. Use `createSpotifyApi` to keep the cache between calls. */\nexport async function getSpotifyStatus(\n credentials: SpotifyCredentials,\n options: SpotifyApiOptions = {}\n): Promise<SpotifyStatus | null> {\n return createSpotifyApi(credentials, options).getStatus()\n}\n"],"mappings":";AAAA,OAAO,WAAW;AAGlB,IAAM,YAAY;AAClB,IAAM,eAAe;AACrB,IAAM,kBAAkB;AA4BjB,IAAM,eAAN,cAA2B,MAAM;AAAA,EAC7B;AAAA,EAET,YAAY,SAAiB,QAAiB;AAC5C,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAiBA,SAAS,kBAAkB,aAAiE;AAC1F,MAAI,CAAC,aAAa,YAAY,CAAC,YAAY,gBAAgB,CAAC,YAAY,cAAc;AACpF,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,OAAO,OAAuB;AACrC,MAAI,OAAO,SAAS,WAAY,QAAO,KAAK,KAAK;AACjD,QAAM,mBAAmB;AAGzB,SAAO,iBAAiB,QAAQ,KAAK,OAAO,MAAM,EAAE,SAAS,QAAQ,KAAK;AAC5E;AAEA,SAAS,cAAc,OAAgB,UAAgC;AACrE,MAAI,iBAAiB,aAAc,QAAO;AAC1C,MAAI,MAAM,aAAa,KAAK,GAAG;AAC7B,UAAM,SAAS,MAAM,UAAU;AAC/B,UAAM,SAAU,MAAM,UAAU,MAAoC,OAAO;AAC3E,UAAM,UAAU,WAAW,OAAO,WAAW,MACzC,sDACC,UAAU,MAAM;AACrB,WAAO,IAAI,aAAa,GAAG,QAAQ,KAAK,OAAO,IAAI,MAAM;AAAA,EAC3D;AACA,SAAO,IAAI;AAAA,IACT,GAAG,QAAQ,KAAK,iB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AAW,aAAa,OAAO;AAC5C;AAGA,eAAsB,mBACpB,aACA,UAA6B,CAAC,GACG;AACjC,SAAO,iBAAiB,aAAa,OAAO,EAAE,YAAY;AAC5D;AAGA,eAAsB,iBACpB,aACA,UAA6B,CAAC,GACC;AAC/B,SAAO,iBAAiB,aAAa,OAAO,EAAE,UAAU;AAC1D;","names":[]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,44 +1,17 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
type SpotifyQueueItem = {
|
|
5
|
-
track: string;
|
|
6
|
-
artist: string;
|
|
7
|
-
album?: string;
|
|
8
|
-
image: string;
|
|
9
|
-
url: string;
|
|
10
|
-
};
|
|
11
|
-
/** The response returned by the Spotify status endpoint this component polls. */
|
|
12
|
-
type SpotifyStatus = {
|
|
13
|
-
playing: boolean;
|
|
14
|
-
track: string;
|
|
15
|
-
artist: string;
|
|
16
|
-
album: string;
|
|
17
|
-
image: string;
|
|
18
|
-
url: string;
|
|
19
|
-
playedAt: string | null;
|
|
20
|
-
progressMs?: number | null;
|
|
21
|
-
durationMs?: number | null;
|
|
22
|
-
next?: SpotifyQueueItem | null;
|
|
23
|
-
/** Age of the server-side snapshot in milliseconds. */
|
|
24
|
-
ageMs?: number;
|
|
25
|
-
};
|
|
26
|
-
type SpotifyBannerProps = {
|
|
27
|
-
/** URL of the endpoint that returns a SpotifyStatus. Defaults to `/api/spotify`. */
|
|
28
|
-
endpoint?: string;
|
|
29
|
-
/** Data to render before the first poll succeeds. */
|
|
30
|
-
initialStatus?: SpotifyStatus | null;
|
|
31
|
-
/** Polling interval in milliseconds. Set to 0 to disable polling. Defaults to 3000. */
|
|
32
|
-
pollIntervalMs?: number;
|
|
33
|
-
/** Extra class names applied to the root element. */
|
|
34
|
-
className?: string;
|
|
35
|
-
};
|
|
2
|
+
import { S as SpotifyBannerProps } from './spotify-B7X9bmfI.js';
|
|
3
|
+
export { a as SpotifyApi, b as SpotifyApiOptions, c as SpotifyCredentials, d as SpotifyError, e as SpotifyQueueItem, f as SpotifySnapshot, g as SpotifyStatus, h as createSpotifyApi, i as fetchSpotifyStatus, j as getSpotifyStatus } from './spotify-B7X9bmfI.js';
|
|
36
4
|
|
|
37
5
|
/**
|
|
38
|
-
* Shows the current (or most recent) Spotify track
|
|
39
|
-
*
|
|
6
|
+
* Shows the current (or most recent) Spotify track. Pass `credentials` to
|
|
7
|
+
* call Spotify directly, or rely on the bundled server handler at
|
|
8
|
+
* `/api/spotify` by omitting them.
|
|
9
|
+
*
|
|
10
|
+
* WARNING: credentials passed to a client component are public. Prefer the
|
|
11
|
+
* server handler for real applications.
|
|
12
|
+
*
|
|
13
|
+
* Styling comes from `spotify-now-playing-banner/styles.css`.
|
|
40
14
|
*/
|
|
41
|
-
declare function SpotifyBanner({ endpoint, initialStatus, pollIntervalMs, className }: SpotifyBannerProps): react.JSX.Element | null;
|
|
15
|
+
declare function SpotifyBanner({ credentials, clientId, clientSecret, refreshToken, endpoint, initialStatus, pollIntervalMs, className }: SpotifyBannerProps): react.JSX.Element | null;
|
|
42
16
|
|
|
43
|
-
export { SpotifyBanner };
|
|
44
|
-
export type { SpotifyBannerProps, SpotifyQueueItem, SpotifyStatus };
|
|
17
|
+
export { SpotifyBanner, SpotifyBannerProps };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SpotifyApi,
|
|
3
|
+
SpotifyError,
|
|
4
|
+
createSpotifyApi,
|
|
5
|
+
fetchSpotifyStatus,
|
|
6
|
+
getSpotifyStatus
|
|
7
|
+
} from "./chunk-GKEANZNP.js";
|
|
8
|
+
|
|
1
9
|
// src/SpotifyBanner.tsx
|
|
2
|
-
import { useEffect, useState } from "react";
|
|
10
|
+
import { useEffect, useMemo, useState } from "react";
|
|
3
11
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
4
12
|
function trackKey(status) {
|
|
5
13
|
return `${status.track}|${status.playedAt ?? ""}`;
|
|
@@ -11,11 +19,30 @@ function formatTime(ms) {
|
|
|
11
19
|
return `${minutes}:${String(seconds).padStart(2, "0")}`;
|
|
12
20
|
}
|
|
13
21
|
function SpotifyBanner({
|
|
22
|
+
credentials,
|
|
23
|
+
clientId,
|
|
24
|
+
clientSecret,
|
|
25
|
+
refreshToken,
|
|
14
26
|
endpoint = "/api/spotify",
|
|
15
27
|
initialStatus = null,
|
|
16
28
|
pollIntervalMs = 3e3,
|
|
17
29
|
className
|
|
18
30
|
}) {
|
|
31
|
+
const resolvedCredentials = useMemo(
|
|
32
|
+
() => credentials ?? (clientId && clientSecret && refreshToken ? { clientId, clientSecret, refreshToken } : null),
|
|
33
|
+
[
|
|
34
|
+
credentials?.clientId,
|
|
35
|
+
credentials?.clientSecret,
|
|
36
|
+
credentials?.refreshToken,
|
|
37
|
+
clientId,
|
|
38
|
+
clientSecret,
|
|
39
|
+
refreshToken
|
|
40
|
+
]
|
|
41
|
+
);
|
|
42
|
+
const api = useMemo(
|
|
43
|
+
() => resolvedCredentials ? createSpotifyApi(resolvedCredentials) : null,
|
|
44
|
+
[resolvedCredentials]
|
|
45
|
+
);
|
|
19
46
|
const [status, setStatus] = useState(initialStatus);
|
|
20
47
|
const [anchor, setAnchor] = useState(null);
|
|
21
48
|
const [now, setNow] = useState(() => Date.now());
|
|
@@ -26,9 +53,11 @@ function SpotifyBanner({
|
|
|
26
53
|
const refresh = async () => {
|
|
27
54
|
const requestId = ++latestRequest;
|
|
28
55
|
try {
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
|
|
56
|
+
const live = api ? await api.getStatus() : await (async () => {
|
|
57
|
+
const response = await fetch(endpoint, { cache: "no-store" });
|
|
58
|
+
if (!response.ok) return null;
|
|
59
|
+
return await response.json();
|
|
60
|
+
})();
|
|
32
61
|
if (!mounted || requestId !== latestRequest || !live?.track) return;
|
|
33
62
|
const at = Date.now();
|
|
34
63
|
const ageMs = Number.isFinite(live.ageMs) ? Math.max(0, live.ageMs) : 0;
|
|
@@ -58,7 +87,7 @@ function SpotifyBanner({
|
|
|
58
87
|
window.clearInterval(interval);
|
|
59
88
|
document.removeEventListener("visibilitychange", onVisibilityChange);
|
|
60
89
|
};
|
|
61
|
-
}, [endpoint, pollIntervalMs]);
|
|
90
|
+
}, [api, endpoint, pollIntervalMs]);
|
|
62
91
|
useEffect(() => {
|
|
63
92
|
if (!status?.playing || !anchor) return;
|
|
64
93
|
const interval = window.setInterval(() => setNow(Date.now()), 500);
|
|
@@ -152,6 +181,11 @@ function SpotifyBanner({
|
|
|
152
181
|
) });
|
|
153
182
|
}
|
|
154
183
|
export {
|
|
155
|
-
|
|
184
|
+
SpotifyApi,
|
|
185
|
+
SpotifyBanner,
|
|
186
|
+
SpotifyError,
|
|
187
|
+
createSpotifyApi,
|
|
188
|
+
fetchSpotifyStatus,
|
|
189
|
+
getSpotifyStatus
|
|
156
190
|
};
|
|
157
191
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/SpotifyBanner.tsx"],"sourcesContent":["import { useEffect, useState } from 'react'\nimport type { SpotifyBannerProps, SpotifyStatus } from './types'\n\ntype ProgressAnchor = {\n progressMs: number\n at: number\n key: string\n}\n\nfunction trackKey(status: SpotifyStatus) {\n return `${status.track}|${status.playedAt ?? ''}`\n}\n\nfunction formatTime(ms: number) {\n const totalSeconds = Math.max(0, Math.floor(ms / 1000))\n const minutes = Math.floor(totalSeconds / 60)\n const seconds = totalSeconds % 60\n return `${minutes}:${String(seconds).padStart(2, '0')}`\n}\n\n/**\n * Shows the current (or most recent) Spotify track and polls an endpoint for\n * updates. Styling comes from `spotify-now-playing-banner/styles.css`.\n */\nexport function SpotifyBanner({\n endpoint = '/api/spotify',\n initialStatus = null,\n pollIntervalMs = 3000,\n className\n}: SpotifyBannerProps) {\n const [status, setStatus] = useState<SpotifyStatus | null>(initialStatus)\n const [anchor, setAnchor] = useState<ProgressAnchor | null>(null)\n const [now, setNow] = useState(() => Date.now())\n\n useEffect(() => {\n if (pollIntervalMs <= 0) return\n\n let mounted = true\n let latestRequest = 0\n\n const refresh = async () => {\n const requestId = ++latestRequest\n try {\n const response = await fetch(endpoint, { cache: 'no-store' })\n if (!response.ok) return\n\n const live = (await response.json()) as SpotifyStatus | null\n if (!mounted || requestId !== latestRequest || !live?.track) return\n\n const at = Date.now()\n const ageMs = Number.isFinite(live.ageMs) ? Math.max(0, live.ageMs!) : 0\n const snapshotAt = at - ageMs\n const nextAnchor: ProgressAnchor | null =\n typeof live.progressMs === 'number'\n ? { progressMs: live.progressMs, at: snapshotAt, key: trackKey(live) }\n : null\n\n setStatus(live)\n setNow(at)\n setAnchor((prev) => {\n if (!nextAnchor) return null\n if (!prev || prev.key !== nextAnchor.key) return nextAnchor\n\n // A cached snapshot already includes its age, so it should agree with\n // the locally projected position. Keep the smoother local anchor\n // unless there's a real jump (seek, resume on another device).\n const projected = prev.progressMs + Math.max(0, snapshotAt - prev.at)\n return Math.abs(nextAnchor.progressMs - projected) > 1000 ? nextAnchor : prev\n })\n } catch {\n // Keep the last known status when the endpoint is unavailable.\n }\n }\n\n void refresh()\n\n const interval = window.setInterval(() => {\n void refresh()\n }, pollIntervalMs)\n\n const onVisibilityChange = () => {\n if (document.visibilityState === 'visible') void refresh()\n }\n document.addEventListener('visibilitychange', onVisibilityChange)\n\n return () => {\n mounted = false\n window.clearInterval(interval)\n document.removeEventListener('visibilitychange', onVisibilityChange)\n }\n }, [endpoint, pollIntervalMs])\n\n // Advance progress locally between polls. Paused tracks stay put.\n useEffect(() => {\n if (!status?.playing || !anchor) return\n const interval = window.setInterval(() => setNow(Date.now()), 500)\n return () => window.clearInterval(interval)\n }, [status?.playing, anchor])\n\n const progress = (() => {\n if (!status || !anchor || anchor.key !== trackKey(status)) return null\n const duration = status.durationMs\n if (!duration || duration <= 0) return null\n\n const current = Math.min(\n duration,\n anchor.progressMs + (status.playing ? Math.max(0, now - anchor.at) : 0)\n )\n return { current, duration, percent: Math.min(100, (current / duration) * 100) }\n })()\n\n const upNext = status?.playing ? status.next : null\n if (!status) return null\n\n return (\n <section className={className ? `spb-banner ${className}` : 'spb-banner'}>\n <a\n href={status.url}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"spb-banner__link\"\n aria-label={`${status.playing ? 'Now playing' : 'Last played'} on Spotify: ${status.track} by ${status.artist}${\n progress ? `, ${formatTime(progress.current)} of ${formatTime(progress.duration)}` : ''\n }${upNext?.track ? `, up next: ${upNext.track} by ${upNext.artist}` : ''}`}\n >\n <img\n src={status.image}\n alt=\"\"\n aria-hidden=\"true\"\n className=\"spb-banner__backdrop\"\n />\n <div className=\"spb-banner__overlay\" />\n\n <div className=\"spb-banner__content\">\n <div className=\"spb-banner__meta\">\n <span className=\"spb-banner__badge\">▶ Spotify</span>\n <span className=\"spb-banner__label\">\n {status.playing ? 'Now playing' : 'Last played'}\n </span>\n {progress && (\n <span className=\"spb-banner__time\">\n {formatTime(progress.current)} / {formatTime(progress.duration)}\n </span>\n )}\n </div>\n <p className=\"spb-banner__title\">{status.track}</p>\n <p className=\"spb-banner__artist\">{status.artist}</p>\n\n {upNext?.track && (\n <div className=\"spb-banner__up-next\">\n {upNext.image && (\n <img\n src={upNext.image}\n alt=\"\"\n aria-hidden=\"true\"\n className=\"spb-banner__up-next-image\"\n />\n )}\n <span className=\"spb-banner__up-next-label\">Up next</span>\n <span className=\"spb-banner__up-next-title\">\n {upNext.track}\n {upNext.artist && <span className=\"spb-banner__up-next-artist\"> — {upNext.artist}</span>}\n </span>\n </div>\n )}\n </div>\n\n <img\n src={status.image}\n alt={status.album ? `${status.album} album art` : 'Album art'}\n className=\"spb-banner__art\"\n />\n\n {progress && (\n <div\n className=\"spb-banner__progress\"\n role=\"progressbar\"\n aria-label=\"Track progress\"\n aria-valuemin={0}\n aria-valuemax={progress.duration}\n aria-valuenow={Math.round(progress.current)}\n >\n <div className=\"spb-banner__progress-fill\" style={{ width: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AAQ,SACP,qBAAC,SAAI,WAAU,uBACZ;AAAA,mBAAO,SACN;AAAA,cAAC;AAAA;AAAA,gBACC,KAAK,OAAO;AAAA,gBACZ,KAAI;AAAA,gBACJ,eAAY;AAAA,gBACZ,WAAU;AAAA;AAAA,YACZ;AAAA,YAEF,oBAAC,UAAK,WAAU,6BAA4B,qBAAO;AAAA,YACnD,qBAAC,UAAK,WAAU,6BACb;AAAA,qBAAO;AAAA,cACP,OAAO,UAAU,qBAAC,UAAK,WAAU,8BAA6B;AAAA;AAAA,gBAAI,OAAO;AAAA,iBAAO;AAAA,eACnF;AAAA,aACF;AAAA,WAEJ;AAAA,QAEA;AAAA,UAAC;AAAA;AAAA,YACC,KAAK,OAAO;AAAA,YACZ,KAAK,OAAO,QAAQ,GAAG,OAAO,KAAK,eAAe;AAAA,YAClD,WAAU;AAAA;AAAA,QACZ;AAAA,QAEC,YACC;AAAA,UAAC;AAAA;AAAA,YACC,WAAU;AAAA,YACV,MAAK;AAAA,YACL,cAAW;AAAA,YACX,iBAAe;AAAA,YACf,iBAAe,SAAS;AAAA,YACxB,iBAAe,KAAK,MAAM,SAAS,OAAO;AAAA,YAE1C,8BAAC,SAAI,WAAU,6BAA4B,OAAO,EAAE,OAAO,GAAG,SAAS,OAAO,IAAI,GAChF,8BAAC,UAAK,WAAU,4BAA2B,GAC7C;AAAA;AAAA,QACF;AAAA;AAAA;AAAA,EAEJ,GACF;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/SpotifyBanner.tsx"],"sourcesContent":["import { useEffect, useMemo, useState } from 'react'\nimport { createSpotifyApi } from './spotify'\nimport type { SpotifyBannerProps, SpotifyCredentials, SpotifyStatus } from './types'\n\ntype ProgressAnchor = {\n progressMs: number\n at: number\n key: string\n}\n\nfunction trackKey(status: SpotifyStatus) {\n return `${status.track}|${status.playedAt ?? ''}`\n}\n\nfunction formatTime(ms: number) {\n const totalSeconds = Math.max(0, Math.floor(ms / 1000))\n const minutes = Math.floor(totalSeconds / 60)\n const seconds = totalSeconds % 60\n return `${minutes}:${String(seconds).padStart(2, '0')}`\n}\n\n/**\n * Shows the current (or most recent) Spotify track. Pass `credentials` to\n * call Spotify directly, or rely on the bundled server handler at\n * `/api/spotify` by omitting them.\n *\n * WARNING: credentials passed to a client component are public. Prefer the\n * server handler for real applications.\n *\n * Styling comes from `spotify-now-playing-banner/styles.css`.\n */\nexport function SpotifyBanner({\n credentials,\n clientId,\n clientSecret,\n refreshToken,\n endpoint = '/api/spotify',\n initialStatus = null,\n pollIntervalMs = 3000,\n className\n}: SpotifyBannerProps) {\n const resolvedCredentials = useMemo<SpotifyCredentials | null>(\n () => credentials\n ?? (clientId && clientSecret && refreshToken\n ? { clientId, clientSecret, refreshToken }\n : null),\n [\n credentials?.clientId,\n credentials?.clientSecret,\n credentials?.refreshToken,\n clientId,\n clientSecret,\n refreshToken\n ]\n )\n\n const api = useMemo(\n () => (resolvedCredentials ? createSpotifyApi(resolvedCredentials) : null),\n [resolvedCredentials]\n )\n\n const [status, setStatus] = useState<SpotifyStatus | null>(initialStatus)\n const [anchor, setAnchor] = useState<ProgressAnchor | null>(null)\n const [now, setNow] = useState(() => Date.now())\n\n useEffect(() => {\n if (pollIntervalMs <= 0) return\n\n let mounted = true\n let latestRequest = 0\n\n const refresh = async () => {\n const requestId = ++latestRequest\n try {\n const live = api\n ? await api.getStatus()\n : await (async () => {\n const response = await fetch(endpoint, { cache: 'no-store' })\n if (!response.ok) return null\n return (await response.json()) as SpotifyStatus | null\n })()\n if (!mounted || requestId !== latestRequest || !live?.track) return\n\n const at = Date.now()\n const ageMs = Number.isFinite(live.ageMs) ? Math.max(0, live.ageMs!) : 0\n const snapshotAt = at - ageMs\n const nextAnchor: ProgressAnchor | null =\n typeof live.progressMs === 'number'\n ? { progressMs: live.progressMs, at: snapshotAt, key: trackKey(live) }\n : null\n\n setStatus(live)\n setNow(at)\n setAnchor((prev) => {\n if (!nextAnchor) return null\n if (!prev || prev.key !== nextAnchor.key) return nextAnchor\n\n // A cached snapshot already includes its age, so it should agree with\n // the locally projected position. Keep the smoother local anchor\n // unless there's a real jump (seek, resume on another device).\n const projected = prev.progressMs + Math.max(0, snapshotAt - prev.at)\n return Math.abs(nextAnchor.progressMs - projected) > 1000 ? nextAnchor : prev\n })\n } catch {\n // Keep the last known status when the endpoint is unavailable.\n }\n }\n\n void refresh()\n\n const interval = window.setInterval(() => {\n void refresh()\n }, pollIntervalMs)\n\n const onVisibilityChange = () => {\n if (document.visibilityState === 'visible') void refresh()\n }\n document.addEventListener('visibilitychange', onVisibilityChange)\n\n return () => {\n mounted = false\n window.clearInterval(interval)\n document.removeEventListener('visibilitychange', onVisibilityChange)\n }\n }, [api, endpoint, pollIntervalMs])\n\n // Advance progress locally between polls. Paused tracks stay put.\n useEffect(() => {\n if (!status?.playing || !anchor) return\n const interval = window.setInterval(() => setNow(Date.now()), 500)\n return () => window.clearInterval(interval)\n }, [status?.playing, anchor])\n\n const progress = (() => {\n if (!status || !anchor || anchor.key !== trackKey(status)) return null\n const duration = status.durationMs\n if (!duration || duration <= 0) return null\n\n const current = Math.min(\n duration,\n anchor.progressMs + (status.playing ? Math.max(0, now - anchor.at) : 0)\n )\n return { current, duration, percent: Math.min(100, (current / duration) * 100) }\n })()\n\n const upNext = status?.playing ? status.next : null\n if (!status) return null\n\n return (\n <section className={className ? `spb-banner ${className}` : 'spb-banner'}>\n <a\n href={status.url}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"spb-banner__link\"\n aria-label={`${status.playing ? 'Now playing' : 'Last played'} on Spotify: ${status.track} by ${status.artist}${\n progress ? `, ${formatTime(progress.current)} of ${formatTime(progress.duration)}` : ''\n }${upNext?.track ? `, up next: ${upNext.track} by ${upNext.artist}` : ''}`}\n >\n <img\n src={status.image}\n alt=\"\"\n aria-hidden=\"true\"\n className=\"spb-banner__backdrop\"\n />\n <div className=\"spb-banner__overlay\" />\n\n <div className=\"spb-banner__content\">\n <div className=\"spb-banner__meta\">\n <span className=\"spb-banner__badge\">▶ Spotify</span>\n <span className=\"spb-banner__label\">\n {status.playing ? 'Now playing' : 'Last played'}\n </span>\n {progress && (\n <span className=\"spb-banner__time\">\n {formatTime(progress.current)} / {formatTime(progress.duration)}\n </span>\n )}\n </div>\n <p className=\"spb-banner__title\">{status.track}</p>\n <p className=\"spb-banner__artist\">{status.artist}</p>\n\n {upNext?.track && (\n <div className=\"spb-banner__up-next\">\n {upNext.image && (\n <img\n src={upNext.image}\n alt=\"\"\n aria-hidden=\"true\"\n className=\"spb-banner__up-next-image\"\n />\n )}\n <span className=\"spb-banner__up-next-label\">Up next</span>\n <span className=\"spb-banner__up-next-title\">\n {upNext.track}\n {upNext.artist && <span className=\"spb-banner__up-next-artist\"> — {upNext.artist}</span>}\n </span>\n </div>\n )}\n </div>\n\n <img\n src={status.image}\n alt={status.album ? `${status.album} album art` : 'Album art'}\n className=\"spb-banner__art\"\n />\n\n {progress && (\n <div\n className=\"spb-banner__progress\"\n role=\"progressbar\"\n aria-label=\"Track progress\"\n aria-valuemin={0}\n aria-valuemax={progress.duration}\n aria-valuenow={Math.round(progress.current)}\n >\n <div className=\"spb-banner__progress-fill\" style={{ width: `${progress.percent}%` }}>\n <span className=\"spb-banner__progress-dot\" />\n </div>\n </div>\n )}\n </a>\n </section>\n )\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,WAAW,SAAS,gBAAgB;AA+JrC,cAeM,YAfN;AArJR,SAAS,SAAS,QAAuB;AACvC,SAAO,GAAG,OAAO,KAAK,IAAI,OAAO,YAAY,EAAE;AACjD;AAEA,SAAS,WAAW,IAAY;AAC9B,QAAM,eAAe,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,GAAI,CAAC;AACtD,QAAM,UAAU,KAAK,MAAM,eAAe,EAAE;AAC5C,QAAM,UAAU,eAAe;AAC/B,SAAO,GAAG,OAAO,IAAI,OAAO,OAAO,EAAE,SAAS,GAAG,GAAG,CAAC;AACvD;AAYO,SAAS,cAAc;AAAA,EAC5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mBAAO,SACN;AAAA,cAAC;AAAA;AAAA,gBACC,KAAK,OAAO;AAAA,gBACZ,KAAI;AAAA,gBACJ,eAAY;AAAA,gBACZ,WAAU;AAAA;AAAA,YACZ;AAAA,YAEF,oBAAC,UAAK,WAAU,6BAA4B,qBAAO;AAAA,YACnD,qBAAC,UAAK,WAAU,6BACb;AAAA,qBAAO;AAAA,cACP,OAAO,UAAU,qBAAC,UAAK,WAAU,8BAA6B;AAAA;AAAA,gBAAI,OAAO;AAAA,iBAAO;AAAA,eACnF;AAAA,aACF;AAAA,WAEJ;AAAA,QAEA;AAAA,UAAC;AAAA;AAAA,YACC,KAAK,OAAO;AAAA,YACZ,KAAK,OAAO,QAAQ,GAAG,OAAO,KAAK,eAAe;AAAA,YAClD,WAAU;AAAA;AAAA,QACZ;AAAA,QAEC,YACC;AAAA,UAAC;AAAA;AAAA,YACC,WAAU;AAAA,YACV,MAAK;AAAA,YACL,cAAW;AAAA,YACX,iBAAe;AAAA,YACf,iBAAe,SAAS;AAAA,YACxB,iBAAe,KAAK,MAAM,SAAS,OAAO;AAAA,YAE1C,8BAAC,SAAI,WAAU,6BAA4B,OAAO,EAAE,OAAO,GAAG,SAAS,OAAO,IAAI,GAChF,8BAAC,UAAK,WAAU,4BAA2B,GAC7C;AAAA;AAAA,QACF;AAAA;AAAA;AAAA,EAEJ,GACF;AAEJ;","names":[]}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { c as SpotifyCredentials, b as SpotifyApiOptions } from '../spotify-B7X9bmfI.js';
|
|
2
|
+
export { a as SpotifyApi, d as SpotifyError, f as SpotifySnapshot, h as createSpotifyApi, i as fetchSpotifyStatus, j as getSpotifyStatus } from '../spotify-B7X9bmfI.js';
|
|
3
|
+
|
|
4
|
+
/** Minimal Node request shape, so `@types/node` is not required. */
|
|
5
|
+
interface NodeRequestLike {
|
|
6
|
+
method?: string;
|
|
7
|
+
url?: string;
|
|
8
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
9
|
+
}
|
|
10
|
+
/** Minimal Node response shape, so `@types/node` is not required. */
|
|
11
|
+
interface NodeResponseLike {
|
|
12
|
+
statusCode?: number;
|
|
13
|
+
setHeader(name: string, value: string | string[]): unknown;
|
|
14
|
+
end(body?: string): unknown;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Accepts either a Web `Request` (Next.js App Router, Vercel, Edge) or a Node
|
|
18
|
+
* `(req, res)` pair (Next.js Pages Router, plain Node/Vercel functions).
|
|
19
|
+
*/
|
|
20
|
+
interface SpotifyHandler {
|
|
21
|
+
(request: Request): Promise<Response>;
|
|
22
|
+
(req: NodeRequestLike, res: NodeResponseLike): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
type SpotifyHandlerOptions = SpotifyCredentials & SpotifyApiOptions & {
|
|
25
|
+
/** Add permissive CORS headers so another origin can poll. Defaults to true. */
|
|
26
|
+
cors?: boolean;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Create a read-only Spotify status endpoint from explicit credentials.
|
|
31
|
+
* The returned function works as either:
|
|
32
|
+
*
|
|
33
|
+
* - a Web handler: `export const GET = createSpotifyHandler(credentials)`
|
|
34
|
+
* - a Node handler: `export default createSpotifyHandler(credentials)`
|
|
35
|
+
*
|
|
36
|
+
* No environment variables are read by this package.
|
|
37
|
+
*/
|
|
38
|
+
declare function createSpotifyHandler(options: SpotifyHandlerOptions): SpotifyHandler;
|
|
39
|
+
|
|
40
|
+
export { SpotifyApiOptions, SpotifyCredentials, createSpotifyHandler };
|
|
41
|
+
export type { NodeRequestLike, NodeResponseLike, SpotifyHandler, SpotifyHandlerOptions };
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SpotifyApi,
|
|
3
|
+
SpotifyError,
|
|
4
|
+
createSpotifyApi,
|
|
5
|
+
fetchSpotifyStatus,
|
|
6
|
+
getSpotifyStatus
|
|
7
|
+
} from "../chunk-GKEANZNP.js";
|
|
8
|
+
|
|
9
|
+
// src/server/handler.ts
|
|
10
|
+
function responseHeaders(cors) {
|
|
11
|
+
return {
|
|
12
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
13
|
+
"Cache-Control": "no-store",
|
|
14
|
+
...cors ? {
|
|
15
|
+
"Access-Control-Allow-Origin": "*",
|
|
16
|
+
"Access-Control-Allow-Methods": "GET, OPTIONS",
|
|
17
|
+
"Access-Control-Allow-Headers": "Content-Type"
|
|
18
|
+
} : {}
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
function sendNode(res, statusCode, body, cors) {
|
|
22
|
+
res.statusCode = statusCode;
|
|
23
|
+
for (const [name, value] of Object.entries(responseHeaders(cors))) {
|
|
24
|
+
res.setHeader(name, value);
|
|
25
|
+
}
|
|
26
|
+
res.end(body === void 0 ? void 0 : JSON.stringify(body));
|
|
27
|
+
}
|
|
28
|
+
function createSpotifyHandler(options) {
|
|
29
|
+
const cors = options.cors !== false;
|
|
30
|
+
const api = createSpotifyApi(options, options);
|
|
31
|
+
return (async (requestOrReq, res) => {
|
|
32
|
+
const isNodeStyle = res != null;
|
|
33
|
+
const method = isNodeStyle ? requestOrReq.method ?? "GET" : requestOrReq.method;
|
|
34
|
+
if (method === "OPTIONS") {
|
|
35
|
+
if (isNodeStyle) return sendNode(res, 204, void 0, cors);
|
|
36
|
+
return new Response(null, { status: 204, headers: responseHeaders(cors) });
|
|
37
|
+
}
|
|
38
|
+
if (method !== "GET" && method != null) {
|
|
39
|
+
const body = { error: "Method not allowed" };
|
|
40
|
+
if (isNodeStyle) return sendNode(res, 405, body, cors);
|
|
41
|
+
return new Response(JSON.stringify(body), {
|
|
42
|
+
status: 405,
|
|
43
|
+
headers: responseHeaders(cors)
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
const snapshot = await api.getSnapshot();
|
|
48
|
+
const body = snapshot ? { ...snapshot.status, ageMs: snapshot.ageMs } : null;
|
|
49
|
+
if (isNodeStyle) return sendNode(res, 200, body, cors);
|
|
50
|
+
return new Response(JSON.stringify(body), {
|
|
51
|
+
status: 200,
|
|
52
|
+
headers: responseHeaders(cors)
|
|
53
|
+
});
|
|
54
|
+
} catch (error) {
|
|
55
|
+
const message = error instanceof SpotifyError ? error.message : "Unable to fetch Spotify status";
|
|
56
|
+
const statusCode = error instanceof SpotifyError && error.status === 401 ? 502 : 500;
|
|
57
|
+
const body = { error: message };
|
|
58
|
+
if (isNodeStyle) return sendNode(res, statusCode, body, cors);
|
|
59
|
+
return new Response(JSON.stringify(body), {
|
|
60
|
+
status: statusCode,
|
|
61
|
+
headers: responseHeaders(cors)
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
export {
|
|
67
|
+
SpotifyApi,
|
|
68
|
+
SpotifyError,
|
|
69
|
+
createSpotifyApi,
|
|
70
|
+
createSpotifyHandler,
|
|
71
|
+
fetchSpotifyStatus,
|
|
72
|
+
getSpotifyStatus
|
|
73
|
+
};
|
|
74
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/server/handler.ts"],"sourcesContent":["import { createSpotifyApi, SpotifyError } from '../spotify'\nimport type {\n NodeRequestLike,\n NodeResponseLike,\n SpotifyHandler,\n SpotifyHandlerOptions\n} from './types'\n\nfunction responseHeaders(cors: boolean): Record<string, string> {\n return {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Cache-Control': 'no-store',\n ...(cors\n ? {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type'\n }\n : {})\n }\n}\n\nfunction sendNode(\n res: NodeResponseLike,\n statusCode: number,\n body: unknown,\n cors: boolean\n): void {\n res.statusCode = statusCode\n for (const [name, value] of Object.entries(responseHeaders(cors))) {\n res.setHeader(name, value)\n }\n res.end(body === undefined ? undefined : JSON.stringify(body))\n}\n\n/**\n * Create a read-only Spotify status endpoint from explicit credentials.\n * The returned function works as either:\n *\n * - a Web handler: `export const GET = createSpotifyHandler(credentials)`\n * - a Node handler: `export default createSpotifyHandler(credentials)`\n *\n * No environment variables are read by this package.\n */\nexport function createSpotifyHandler(options: SpotifyHandlerOptions): SpotifyHandler {\n const cors = options.cors !== false\n const api = createSpotifyApi(options, options)\n\n return (async (\n requestOrReq: Request | NodeRequestLike,\n res?: NodeResponseLike\n ): Promise<Response | void> => {\n const isNodeStyle = res != null\n const method = isNodeStyle\n ? (requestOrReq as NodeRequestLike).method ?? 'GET'\n : (requestOrReq as Request).method\n\n if (method === 'OPTIONS') {\n if (isNodeStyle) return sendNode(res!, 204, undefined, cors)\n return new Response(null, { status: 204, headers: responseHeaders(cors) })\n }\n\n if (method !== 'GET' && method != null) {\n const body = { error: 'Method not allowed' }\n if (isNodeStyle) return sendNode(res!, 405, body, cors)\n return new Response(JSON.stringify(body), {\n status: 405,\n headers: responseHeaders(cors)\n })\n }\n\n try {\n const snapshot = await api.getSnapshot()\n const body = snapshot ? { ...snapshot.status, ageMs: snapshot.ageMs } : null\n if (isNodeStyle) return sendNode(res!, 200, body, cors)\n return new Response(JSON.stringify(body), {\n status: 200,\n headers: responseHeaders(cors)\n })\n } catch (error) {\n const message = error instanceof SpotifyError\n ? error.message\n : 'Unable to fetch Spotify status'\n const statusCode = error instanceof SpotifyError && error.status === 401 ? 502 : 500\n const body = { error: message }\n if (isNodeStyle) return sendNode(res!, statusCode, body, cors)\n return new Response(JSON.stringify(body), {\n status: statusCode,\n headers: responseHeaders(cors)\n })\n }\n }) as SpotifyHandler\n}\n"],"mappings":";;;;;;;;;AAQA,SAAS,gBAAgB,MAAuC;AAC9D,SAAO;AAAA,IACL,gBAAgB;AAAA,IAChB,iBAAiB;AAAA,IACjB,GAAI,OACA;AAAA,MACE,+BAA+B;AAAA,MAC/B,gCAAgC;AAAA,MAChC,gCAAgC;AAAA,IAClC,IACA,CAAC;AAAA,EACP;AACF;AAEA,SA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J,YAAM,aAAa,iBAAiB,gBAAgB,MAAM,WAAW,MAAM,MAAM;AACjF,YAAM,OAAO,EAAE,OAAO,QAAQ;AAC9B,UAAI,YAAa,QAAO,SAAS,KAAM,YAAY,MAAM,IAAI;AAC7D,aAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;AAAA,QACxC,QAAQ;AAAA,QACR,SAAS,gBAAgB,IAAI;AAAA,MAC/B,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/** Spotify OAuth app credentials. */
|
|
2
|
+
type SpotifyCredentials = {
|
|
3
|
+
clientId: string;
|
|
4
|
+
clientSecret: string;
|
|
5
|
+
refreshToken: string;
|
|
6
|
+
};
|
|
7
|
+
/** A track (or podcast episode) in the playback queue. */
|
|
8
|
+
type SpotifyQueueItem = {
|
|
9
|
+
track: string;
|
|
10
|
+
artist: string;
|
|
11
|
+
album?: string;
|
|
12
|
+
image: string;
|
|
13
|
+
url: string;
|
|
14
|
+
};
|
|
15
|
+
/** The status JSON returned by the Spotify status endpoint or API helper. */
|
|
16
|
+
type SpotifyStatus = {
|
|
17
|
+
playing: boolean;
|
|
18
|
+
track: string;
|
|
19
|
+
artist: string;
|
|
20
|
+
album: string;
|
|
21
|
+
image: string;
|
|
22
|
+
url: string;
|
|
23
|
+
playedAt: string | null;
|
|
24
|
+
progressMs?: number | null;
|
|
25
|
+
durationMs?: number | null;
|
|
26
|
+
next?: SpotifyQueueItem | null;
|
|
27
|
+
/** Age of the server-side snapshot in milliseconds. */
|
|
28
|
+
ageMs?: number;
|
|
29
|
+
};
|
|
30
|
+
type SpotifyBannerProps = {
|
|
31
|
+
/**
|
|
32
|
+
* Spotify credentials for direct, in-browser calls to the Spotify API.
|
|
33
|
+
* WARNING: anything in client props is public — anyone can read these
|
|
34
|
+
* values. Prefer the server handler for real applications.
|
|
35
|
+
*/
|
|
36
|
+
credentials?: SpotifyCredentials;
|
|
37
|
+
/** Shorthand for `credentials.clientId`. */
|
|
38
|
+
clientId?: string;
|
|
39
|
+
/** Shorthand for `credentials.clientSecret`. */
|
|
40
|
+
clientSecret?: string;
|
|
41
|
+
/** Shorthand for `credentials.refreshToken`. */
|
|
42
|
+
refreshToken?: string;
|
|
43
|
+
/**
|
|
44
|
+
* URL of the status endpoint. Defaults to `/api/spotify`. Used only when no
|
|
45
|
+
* credentials are passed. Not needed when using the bundled handler.
|
|
46
|
+
*/
|
|
47
|
+
endpoint?: string;
|
|
48
|
+
/** Data to render before the first poll succeeds. */
|
|
49
|
+
initialStatus?: SpotifyStatus | null;
|
|
50
|
+
/** Polling interval in milliseconds. Set to 0 to disable polling. Defaults to 3000. */
|
|
51
|
+
pollIntervalMs?: number;
|
|
52
|
+
/** Extra class names applied to the root element. */
|
|
53
|
+
className?: string;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/** An error from Spotify or from invalid credential input. */
|
|
57
|
+
declare class SpotifyError extends Error {
|
|
58
|
+
readonly status?: number;
|
|
59
|
+
constructor(message: string, status?: number);
|
|
60
|
+
}
|
|
61
|
+
/** A status snapshot plus the age of the API's cached copy. */
|
|
62
|
+
type SpotifySnapshot = {
|
|
63
|
+
status: SpotifyStatus;
|
|
64
|
+
ageMs: number;
|
|
65
|
+
};
|
|
66
|
+
type SpotifyApiOptions = {
|
|
67
|
+
/** Cache lifetime in milliseconds. Defaults to 5000. */
|
|
68
|
+
cacheMs?: number;
|
|
69
|
+
/** Override the token endpoint (useful for tests). */
|
|
70
|
+
tokenUrl?: string;
|
|
71
|
+
/** Override the Web API base URL (useful for tests). */
|
|
72
|
+
apiBaseUrl?: string;
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* A credential-bound Spotify client. Each instance keeps its own token and
|
|
76
|
+
* status caches, so different credentials never share state.
|
|
77
|
+
*/
|
|
78
|
+
declare class SpotifyApi {
|
|
79
|
+
private readonly credentials;
|
|
80
|
+
private readonly options;
|
|
81
|
+
private tokenCache;
|
|
82
|
+
private rotatedRefreshToken;
|
|
83
|
+
private tokenInFlight;
|
|
84
|
+
private statusCache;
|
|
85
|
+
private statusInFlight;
|
|
86
|
+
constructor(credentials: SpotifyCredentials, options?: SpotifyApiOptions);
|
|
87
|
+
/** Discard this instance's cached token and status. */
|
|
88
|
+
clearCache(): void;
|
|
89
|
+
private getAccessToken;
|
|
90
|
+
private getCurrentlyPlaying;
|
|
91
|
+
private getNextTrack;
|
|
92
|
+
private getLastPlayed;
|
|
93
|
+
/** Fetch a status snapshot, reusing a fresh cached snapshot when available. */
|
|
94
|
+
getSnapshot(): Promise<SpotifySnapshot | null>;
|
|
95
|
+
/** Fetch just the status JSON (including `ageMs`) the banner expects. */
|
|
96
|
+
getStatus(): Promise<SpotifyStatus | null>;
|
|
97
|
+
}
|
|
98
|
+
/** Create a credential-bound Spotify client. */
|
|
99
|
+
declare function createSpotifyApi(credentials: SpotifyCredentials, options?: SpotifyApiOptions): SpotifyApi;
|
|
100
|
+
/** One-off snapshot fetch. Use `createSpotifyApi` to keep the cache between calls. */
|
|
101
|
+
declare function fetchSpotifyStatus(credentials: SpotifyCredentials, options?: SpotifyApiOptions): Promise<SpotifySnapshot | null>;
|
|
102
|
+
/** One-off status fetch. Use `createSpotifyApi` to keep the cache between calls. */
|
|
103
|
+
declare function getSpotifyStatus(credentials: SpotifyCredentials, options?: SpotifyApiOptions): Promise<SpotifyStatus | null>;
|
|
104
|
+
|
|
105
|
+
export { SpotifyApi as a, SpotifyError as d, createSpotifyApi as h, fetchSpotifyStatus as i, getSpotifyStatus as j };
|
|
106
|
+
export type { SpotifyBannerProps as S, SpotifyApiOptions as b, SpotifyCredentials as c, SpotifyQueueItem as e, SpotifySnapshot as f, SpotifyStatus as g };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "spotify-now-playing-banner",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "A reusable React banner that shows a Spotify now-playing or last-played track, with live progress and up-next.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -20,6 +20,11 @@
|
|
|
20
20
|
"import": "./dist/index.js",
|
|
21
21
|
"default": "./dist/index.js"
|
|
22
22
|
},
|
|
23
|
+
"./server": {
|
|
24
|
+
"types": "./dist/server/index.d.ts",
|
|
25
|
+
"import": "./dist/server/index.js",
|
|
26
|
+
"default": "./dist/server/index.js"
|
|
27
|
+
},
|
|
23
28
|
"./styles.css": "./dist/styles.css",
|
|
24
29
|
"./package.json": "./package.json"
|
|
25
30
|
},
|
|
@@ -43,5 +48,8 @@
|
|
|
43
48
|
"@types/react": "^19.3.3",
|
|
44
49
|
"tsup": "^9.0.0",
|
|
45
50
|
"typescript": "^6.0.3"
|
|
51
|
+
},
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"axios": "^1.21.1"
|
|
46
54
|
}
|
|
47
55
|
}
|