@totalaudiopromo/spotcheck 0.0.0-stage → 0.1.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.
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Spotify helpers, using the client-credentials grant. Public playlist data
3
+ * only: no user sign-in and no access to anyone's private library.
4
+ */
5
+ export type SpotifyCredentials = {
6
+ spotifyClientId: string;
7
+ spotifyClientSecret: string;
8
+ };
9
+ export declare class SpotifyConfigError extends Error {
10
+ constructor();
11
+ }
12
+ export declare function getClientCredentialsToken(credentials: Partial<SpotifyCredentials>): Promise<{
13
+ access_token: string;
14
+ token_type: string;
15
+ expires_in: number;
16
+ }>;
17
+ /** Error from a non-OK Spotify response, carrying the upstream status. */
18
+ export declare class SpotifyApiError extends Error {
19
+ status: number;
20
+ constructor(status: number, detail: string);
21
+ }
22
+ export type PlaylistFull = {
23
+ id: string;
24
+ name: string | null;
25
+ description: string | null;
26
+ public: boolean | null;
27
+ followers: {
28
+ total: number;
29
+ };
30
+ tracks: {
31
+ total: number;
32
+ };
33
+ /** Popularity of the playable tracks on the first page of items (up to 100). */
34
+ trackPopularity: number[];
35
+ /** The same playable tracks with their first artist and when they were added. */
36
+ trackItems: TrackItem[];
37
+ images: Array<{
38
+ url: string;
39
+ }>;
40
+ owner: {
41
+ id?: string;
42
+ display_name: string | null;
43
+ external_urls?: {
44
+ spotify?: string;
45
+ };
46
+ };
47
+ external_urls?: {
48
+ spotify?: string;
49
+ };
50
+ };
51
+ export type TrackItem = {
52
+ popularity: number;
53
+ artistId: string | null;
54
+ addedAt: string | null;
55
+ };
56
+ /**
57
+ * Follower counts for a set of artist ids, 50 per request (Spotify's limit).
58
+ * Missing or failed batches are simply absent from the map: callers treat this
59
+ * as best-effort enrichment, never as a reason to fail a check.
60
+ */
61
+ export declare function fetchArtistFollowers(ids: string[], token: string): Promise<Map<string, number>>;
62
+ /**
63
+ * Fetch the public playlist fields the scorer needs. Throws
64
+ * SpotifyApiError (carrying the upstream status, e.g. 404 for a private/
65
+ * deleted playlist) so a caller can map it to a clear message.
66
+ */
67
+ export declare function fetchPlaylist(playlistId: string, token: string): Promise<PlaylistFull>;
68
+ /**
69
+ * Cheap pre-filter, not the final answer: true when a playlist id sits in
70
+ * Spotify's own reserved namespace for playlists it generates itself
71
+ * (editorial ones like Today's Top Hits and New Music Friday, and
72
+ * personalised ones like Discover Weekly). Real third-party playlists never
73
+ * land in this namespace (verified: 1PmwMQY86pJuAm7veFt3u2, a 59k-follower
74
+ * independent playlist, is outside it), so a false positive here isn't a
75
+ * live risk. But a match still only means "worth confirming", not "is
76
+ * Spotify's". Confirm with lookupPlaylistOwnerFromPublicPage before telling
77
+ * anyone why their check failed.
78
+ */
79
+ export declare function isSpotifyGeneratedPlaylistId(playlistId: string): boolean;
80
+ export type PlaylistOwnerLookup = {
81
+ kind: 'owned_by_spotify';
82
+ } | {
83
+ kind: 'owned_by_other';
84
+ ownerId: string;
85
+ } | {
86
+ kind: 'not_found';
87
+ } | {
88
+ kind: 'unknown';
89
+ };
90
+ /**
91
+ * Confirms who owns a playlist using Spotify's own public web page, with no
92
+ * API token needed. It's the one check left when the authenticated API 404s
93
+ * without a body: `fetchPlaylist` throws on a Today's Top Hits id with
94
+ * `{"error":{"status":404,"message":"Resource not found"}}` and nothing
95
+ * else, the same shape a genuinely deleted playlist returns, so there is no
96
+ * owner field to read off that failure. The public page at
97
+ * open.spotify.com/playlist/<id> carries a `music:creator` meta tag naming
98
+ * the real owning account directly, unauthenticated.
99
+ *
100
+ * Verified live on 11 Sep 2026: Today's Top Hits and New Music Friday both
101
+ * report `music:creator` as `open.spotify.com/user/spotify`; the real
102
+ * independent playlist above reports its actual username; a genuinely
103
+ * nonexistent id 404s the page itself, same as the API.
104
+ *
105
+ * Best-effort: Spotify doesn't document or support this page's markup, so a
106
+ * layout change or a fetch failure returns `unknown` rather than a guess.
107
+ * Callers must treat `unknown` and `owned_by_other` as "can't tell", never
108
+ * as evidence either way.
109
+ */
110
+ export declare function lookupPlaylistOwnerFromPublicPage(playlistId: string): Promise<PlaylistOwnerLookup>;
111
+ /** Wording for a 404 on a playlist that is private or deleted. */
112
+ export declare const PLAYLIST_NOT_FOUND_MESSAGE = "Playlist not found. It may be private or deleted.";
113
+ /** Shared wording for a 404 confirmed as Spotify's own generated playlist. */
114
+ export declare const SPOTIFY_GENERATED_PLAYLIST_MESSAGE: string;
115
+ /** Shared wording for a 404 we can neither confirm nor rule out as Spotify's own. */
116
+ export declare const PLAYLIST_UNVERIFIABLE_MESSAGE: string;
117
+ /** Extract a playlist id from a Spotify URL, URI or bare id. Null when invalid. */
118
+ export declare function extractPlaylistId(input: string): string | null;
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Spotify helpers, using the client-credentials grant. Public playlist data
3
+ * only: no user sign-in and no access to anyone's private library.
4
+ */
5
+ export class SpotifyConfigError extends Error {
6
+ constructor() {
7
+ super('Spotify credentials missing. Set SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET from a Spotify developer app.');
8
+ this.name = 'SpotifyConfigError';
9
+ }
10
+ }
11
+ export async function getClientCredentialsToken(credentials) {
12
+ const { spotifyClientId: clientId, spotifyClientSecret: clientSecret } = credentials;
13
+ if (!clientId || !clientSecret)
14
+ throw new SpotifyConfigError();
15
+ const response = await fetch('https://accounts.spotify.com/api/token', {
16
+ method: 'POST',
17
+ headers: {
18
+ 'Content-Type': 'application/x-www-form-urlencoded',
19
+ Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`,
20
+ },
21
+ body: 'grant_type=client_credentials',
22
+ });
23
+ if (!response.ok)
24
+ throw new SpotifyApiError(response.status, await response.text());
25
+ return response.json();
26
+ }
27
+ /** Error from a non-OK Spotify response, carrying the upstream status. */
28
+ export class SpotifyApiError extends Error {
29
+ status;
30
+ constructor(status, detail) {
31
+ super(`Spotify request failed (${status}): ${detail}`);
32
+ this.name = 'SpotifyApiError';
33
+ this.status = status;
34
+ }
35
+ }
36
+ /** Local files, episodes and removed tracks carry no meaningful popularity. */
37
+ function trackItems(items) {
38
+ if (!Array.isArray(items))
39
+ return [];
40
+ return items.flatMap(item => {
41
+ const popularity = item?.track?.popularity;
42
+ const playable = item?.is_local !== true && item?.track?.type === 'track';
43
+ if (!playable || typeof popularity !== 'number')
44
+ return [];
45
+ const artistId = item?.track?.artists?.[0]?.id;
46
+ return [{
47
+ popularity,
48
+ artistId: typeof artistId === 'string' ? artistId : null,
49
+ addedAt: typeof item?.added_at === 'string' ? item.added_at : null,
50
+ }];
51
+ });
52
+ }
53
+ const ARTISTS_PER_REQUEST = 50;
54
+ /**
55
+ * Follower counts for a set of artist ids, 50 per request (Spotify's limit).
56
+ * Missing or failed batches are simply absent from the map: callers treat this
57
+ * as best-effort enrichment, never as a reason to fail a check.
58
+ */
59
+ export async function fetchArtistFollowers(ids, token) {
60
+ const unique = [...new Set(ids)];
61
+ const followers = new Map();
62
+ for (let i = 0; i < unique.length; i += ARTISTS_PER_REQUEST) {
63
+ const batch = unique.slice(i, i + ARTISTS_PER_REQUEST);
64
+ const response = await fetch(`https://api.spotify.com/v1/artists?ids=${batch.join(',')}`, {
65
+ headers: { Authorization: `Bearer ${token}` },
66
+ });
67
+ if (!response.ok)
68
+ continue;
69
+ const data = (await response.json());
70
+ for (const artist of data.artists ?? []) {
71
+ if (artist?.id && typeof artist.followers?.total === 'number')
72
+ followers.set(artist.id, artist.followers.total);
73
+ }
74
+ }
75
+ return followers;
76
+ }
77
+ /**
78
+ * Fetch the public playlist fields the scorer needs. Throws
79
+ * SpotifyApiError (carrying the upstream status, e.g. 404 for a private/
80
+ * deleted playlist) so a caller can map it to a clear message.
81
+ */
82
+ export async function fetchPlaylist(playlistId, token) {
83
+ const fields = 'id,name,description,public,followers(total),tracks(total,items(added_at,is_local,track(type,popularity,artists(id)))),images,owner(id,display_name,external_urls),external_urls';
84
+ const response = await fetch(`https://api.spotify.com/v1/playlists/${playlistId}?fields=${fields}`, { headers: { Authorization: `Bearer ${token}` } });
85
+ if (!response.ok) {
86
+ throw new SpotifyApiError(response.status, await response.text());
87
+ }
88
+ return toPlaylistFull(await response.json(), playlistId);
89
+ }
90
+ function toPlaylistFull(data, playlistId) {
91
+ return {
92
+ id: data.id ?? playlistId,
93
+ name: data.name ?? null,
94
+ description: data.description ?? null,
95
+ public: data.public ?? null,
96
+ followers: { total: data.followers?.total ?? 0 },
97
+ tracks: { total: data.tracks?.total ?? 0 },
98
+ trackPopularity: trackItems(data.tracks?.items).map(item => item.popularity),
99
+ trackItems: trackItems(data.tracks?.items),
100
+ images: Array.isArray(data.images) ? data.images : [],
101
+ owner: {
102
+ id: data.owner?.id,
103
+ display_name: data.owner?.display_name ?? null,
104
+ external_urls: data.owner?.external_urls,
105
+ },
106
+ external_urls: data.external_urls,
107
+ };
108
+ }
109
+ /**
110
+ * Cheap pre-filter, not the final answer: true when a playlist id sits in
111
+ * Spotify's own reserved namespace for playlists it generates itself
112
+ * (editorial ones like Today's Top Hits and New Music Friday, and
113
+ * personalised ones like Discover Weekly). Real third-party playlists never
114
+ * land in this namespace (verified: 1PmwMQY86pJuAm7veFt3u2, a 59k-follower
115
+ * independent playlist, is outside it), so a false positive here isn't a
116
+ * live risk. But a match still only means "worth confirming", not "is
117
+ * Spotify's". Confirm with lookupPlaylistOwnerFromPublicPage before telling
118
+ * anyone why their check failed.
119
+ */
120
+ export function isSpotifyGeneratedPlaylistId(playlistId) {
121
+ return playlistId.startsWith('37i9dQZ');
122
+ }
123
+ /**
124
+ * Confirms who owns a playlist using Spotify's own public web page, with no
125
+ * API token needed. It's the one check left when the authenticated API 404s
126
+ * without a body: `fetchPlaylist` throws on a Today's Top Hits id with
127
+ * `{"error":{"status":404,"message":"Resource not found"}}` and nothing
128
+ * else, the same shape a genuinely deleted playlist returns, so there is no
129
+ * owner field to read off that failure. The public page at
130
+ * open.spotify.com/playlist/<id> carries a `music:creator` meta tag naming
131
+ * the real owning account directly, unauthenticated.
132
+ *
133
+ * Verified live on 11 Sep 2026: Today's Top Hits and New Music Friday both
134
+ * report `music:creator` as `open.spotify.com/user/spotify`; the real
135
+ * independent playlist above reports its actual username; a genuinely
136
+ * nonexistent id 404s the page itself, same as the API.
137
+ *
138
+ * Best-effort: Spotify doesn't document or support this page's markup, so a
139
+ * layout change or a fetch failure returns `unknown` rather than a guess.
140
+ * Callers must treat `unknown` and `owned_by_other` as "can't tell", never
141
+ * as evidence either way.
142
+ */
143
+ export async function lookupPlaylistOwnerFromPublicPage(playlistId) {
144
+ try {
145
+ const response = await fetch(`https://open.spotify.com/playlist/${playlistId}`, {
146
+ headers: {
147
+ 'User-Agent': 'spotcheck-oss (+https://github.com/chrisschouk/spotcheck-oss)',
148
+ },
149
+ });
150
+ if (response.status === 404)
151
+ return { kind: 'not_found' };
152
+ if (!response.ok)
153
+ return { kind: 'unknown' };
154
+ const html = await response.text();
155
+ const match = html.match(/name="music:creator"\s+content="https:\/\/open\.spotify\.com\/user\/([^"]+)"/);
156
+ if (!match)
157
+ return { kind: 'unknown' };
158
+ return match[1] === 'spotify'
159
+ ? { kind: 'owned_by_spotify' }
160
+ : { kind: 'owned_by_other', ownerId: match[1] };
161
+ }
162
+ catch {
163
+ return { kind: 'unknown' };
164
+ }
165
+ }
166
+ /** Wording for a 404 on a playlist that is private or deleted. */
167
+ export const PLAYLIST_NOT_FOUND_MESSAGE = 'Playlist not found. It may be private or deleted.';
168
+ /** Shared wording for a 404 confirmed as Spotify's own generated playlist. */
169
+ export const SPOTIFY_GENERATED_PLAYLIST_MESSAGE = "Spotify doesn't make its own editorial and algorithmic playlists, such as Today's Top " +
170
+ "Hits, New Music Friday or Discover Weekly, available to outside tools. That's a Spotify " +
171
+ 'restriction, not a problem with your link. Try a playlist that takes outside submissions ' +
172
+ 'instead. Those are the ones curators actually run, and the ones worth checking before you ' +
173
+ 'pay for a placement.';
174
+ /** Shared wording for a 404 we can neither confirm nor rule out as Spotify's own. */
175
+ export const PLAYLIST_UNVERIFIABLE_MESSAGE = "We couldn't check this playlist. Spotify didn't return data for it and we can't confirm " +
176
+ "why, so this isn't necessarily a problem with your link. Try again shortly, or try a " +
177
+ 'different playlist.';
178
+ /** Extract a playlist id from a Spotify URL, URI or bare id. Null when invalid. */
179
+ export function extractPlaylistId(input) {
180
+ const trimmed = (input || '').trim();
181
+ if (!trimmed)
182
+ return null;
183
+ // open.spotify.com/playlist/<id> (optionally /intl-xx/ or query/hash)
184
+ const urlMatch = trimmed.match(/playlist[/:]([a-zA-Z0-9]{22})/);
185
+ if (urlMatch)
186
+ return urlMatch[1];
187
+ // bare 22-char base62 id
188
+ if (/^[a-zA-Z0-9]{22}$/.test(trimmed))
189
+ return trimmed;
190
+ return null;
191
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Stream-farm signals, measured but not scored.
3
+ *
4
+ * The scorer in bot-scorer.ts looks for bought followers: big audiences that
5
+ * do not play what they follow. A distributor's artificial streaming warning
6
+ * is about bought streams, which can look the other way round: tracks played
7
+ * far more than their artists' own fanbase explains, on playlists that churn
8
+ * paid placements.
9
+ *
10
+ * These numbers are reported next to a warning scan so they can be calibrated
11
+ * against playlists from real warnings. Nothing here changes a verdict until
12
+ * that data shows which thresholds separate farms from real lists.
13
+ */
14
+ import type { TrackItem } from './spotify.js';
15
+ /** An artist this small has almost no fanbase of their own to stream them. */
16
+ export declare const FANLESS_MAX_ARTIST_FOLLOWERS = 1000;
17
+ /** Popularity this high means real volume of recent plays. */
18
+ export declare const FANLESS_MIN_POPULARITY = 25;
19
+ export declare const RECENT_ADD_DAYS = 30;
20
+ export declare const MIN_TRACKS_FOR_SIGNALS = 10;
21
+ export type StreamFarmSignals = {
22
+ /** Tracks with a known artist follower count. */
23
+ sampled: number;
24
+ medianPopularity: number;
25
+ medianArtistFollowers: number;
26
+ /** Share of tracks played well beyond what their artist's fanbase explains. */
27
+ fanlessPlayShare: number;
28
+ /** Share of tracks added in the last RECENT_ADD_DAYS: placement churn. */
29
+ recentAddShare: number;
30
+ };
31
+ /** Null when too few tracks have a known artist for the shares to mean anything. */
32
+ export declare function streamFarmSignals(items: TrackItem[], artistFollowers: Map<string, number>, now?: Date): StreamFarmSignals | null;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Stream-farm signals, measured but not scored.
3
+ *
4
+ * The scorer in bot-scorer.ts looks for bought followers: big audiences that
5
+ * do not play what they follow. A distributor's artificial streaming warning
6
+ * is about bought streams, which can look the other way round: tracks played
7
+ * far more than their artists' own fanbase explains, on playlists that churn
8
+ * paid placements.
9
+ *
10
+ * These numbers are reported next to a warning scan so they can be calibrated
11
+ * against playlists from real warnings. Nothing here changes a verdict until
12
+ * that data shows which thresholds separate farms from real lists.
13
+ */
14
+ /** An artist this small has almost no fanbase of their own to stream them. */
15
+ export const FANLESS_MAX_ARTIST_FOLLOWERS = 1_000;
16
+ /** Popularity this high means real volume of recent plays. */
17
+ export const FANLESS_MIN_POPULARITY = 25;
18
+ export const RECENT_ADD_DAYS = 30;
19
+ export const MIN_TRACKS_FOR_SIGNALS = 10;
20
+ function median(values) {
21
+ const sorted = [...values].sort((a, b) => a - b);
22
+ const mid = Math.floor(sorted.length / 2);
23
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
24
+ }
25
+ function share(count, total) {
26
+ return total ? Math.round((count / total) * 100) / 100 : 0;
27
+ }
28
+ function isRecent(addedAt, now) {
29
+ if (!addedAt)
30
+ return false;
31
+ const added = Date.parse(addedAt);
32
+ return Number.isFinite(added) && now.getTime() - added <= RECENT_ADD_DAYS * 86_400_000;
33
+ }
34
+ /** Null when too few tracks have a known artist for the shares to mean anything. */
35
+ export function streamFarmSignals(items, artistFollowers, now = new Date()) {
36
+ const known = items.flatMap(item => {
37
+ const followers = item.artistId ? artistFollowers.get(item.artistId) : undefined;
38
+ return followers === undefined ? [] : [{ ...item, followers }];
39
+ });
40
+ if (known.length < MIN_TRACKS_FOR_SIGNALS)
41
+ return null;
42
+ const fanless = known.filter(t => t.followers < FANLESS_MAX_ARTIST_FOLLOWERS && t.popularity >= FANLESS_MIN_POPULARITY).length;
43
+ return {
44
+ sampled: known.length,
45
+ medianPopularity: median(known.map(t => t.popularity)),
46
+ medianArtistFollowers: median(known.map(t => t.followers)),
47
+ fanlessPlayShare: share(fanless, known.length),
48
+ recentAddShare: share(items.filter(t => isRecent(t.addedAt, now)).length, items.length),
49
+ };
50
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Artificial streaming warning scan: the pure half.
3
+ *
4
+ * An artist whose distributor flagged a track pastes the playlists from their
5
+ * Spotify for Artists page. This module turns that paste into playlist ids,
6
+ * orders the scored results, and drafts the messages the artist needs to send.
7
+ * scan.ts does the fetching and scoring.
8
+ */
9
+ import type { ScoreFactor, ScoreLevel } from './bot-scorer.js';
10
+ export declare const MAX_SCAN_LINKS = 50;
11
+ export type SkipReason = 'invalid' | 'duplicate' | 'spotify_owned' | 'not_found' | 'error';
12
+ export type ScoredRow = {
13
+ kind: 'scored';
14
+ playlistId: string;
15
+ url: string;
16
+ name: string;
17
+ owner: string;
18
+ followers: number;
19
+ tracks: number;
20
+ score: number;
21
+ level: ScoreLevel;
22
+ reason: string;
23
+ };
24
+ export type SkippedRow = {
25
+ kind: 'skipped';
26
+ input: string;
27
+ playlistId: string | null;
28
+ why: SkipReason;
29
+ };
30
+ export type FullRow = ScoredRow | SkippedRow;
31
+ type Counts = {
32
+ flagged: number;
33
+ scanned: number;
34
+ scannedAt: string;
35
+ };
36
+ /** Every verdict, ranked by score, with the playlists that could not be scored after them. */
37
+ export type FullReport = Counts & {
38
+ rows: FullRow[];
39
+ };
40
+ export type DraftFields = {
41
+ artistName: string;
42
+ trackName: string;
43
+ distributor: string;
44
+ };
45
+ export type ParsedScanInput = {
46
+ ids: string[];
47
+ skipped: SkippedRow[];
48
+ /** Valid, distinct links past MAX_SCAN_LINKS that were left out. */
49
+ overCap: number;
50
+ };
51
+ export declare const CLEAN_REASON = "No warning signs in public data";
52
+ export declare function parseScanInput(text: string): ParsedScanInput;
53
+ /** The label of the most severe factor, or the clean wording when none warns. */
54
+ export declare function reasonFor(factors: ScoreFactor[]): string;
55
+ export declare function isFlagged(row: FullRow): row is ScoredRow;
56
+ export declare function orderRows(rows: FullRow[]): FullRow[];
57
+ export declare function buildReport(rows: FullRow[], scannedAt?: Date): FullReport;
58
+ export declare function distributorReply(report: FullReport, fields: DraftFields): string;
59
+ export declare function removalRequest(row: ScoredRow, fields: DraftFields): string;
60
+ export {};
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Artificial streaming warning scan: the pure half.
3
+ *
4
+ * An artist whose distributor flagged a track pastes the playlists from their
5
+ * Spotify for Artists page. This module turns that paste into playlist ids,
6
+ * orders the scored results, and drafts the messages the artist needs to send.
7
+ * scan.ts does the fetching and scoring.
8
+ */
9
+ import { extractPlaylistId } from './spotify.js';
10
+ export const MAX_SCAN_LINKS = 50;
11
+ export const CLEAN_REASON = 'No warning signs in public data';
12
+ export function parseScanInput(text) {
13
+ const ids = [];
14
+ const seen = new Set();
15
+ const skipped = [];
16
+ let overCap = 0;
17
+ for (const input of text.split(/[\s,]+/).filter(Boolean)) {
18
+ const playlistId = extractPlaylistId(input);
19
+ if (!playlistId) {
20
+ skipped.push({ kind: 'skipped', input, playlistId: null, why: 'invalid' });
21
+ }
22
+ else if (seen.has(playlistId)) {
23
+ skipped.push({ kind: 'skipped', input, playlistId, why: 'duplicate' });
24
+ }
25
+ else if (ids.length >= MAX_SCAN_LINKS) {
26
+ seen.add(playlistId);
27
+ overCap++;
28
+ }
29
+ else {
30
+ seen.add(playlistId);
31
+ ids.push(playlistId);
32
+ }
33
+ }
34
+ return { ids, skipped, overCap };
35
+ }
36
+ const FACTOR_SEVERITY = { danger: 2, warning: 1 };
37
+ /** The label of the most severe factor, or the clean wording when none warns. */
38
+ export function reasonFor(factors) {
39
+ let worst = CLEAN_REASON;
40
+ let worstSeverity = 0;
41
+ for (const factor of factors) {
42
+ const severity = FACTOR_SEVERITY[factor.level] ?? 0;
43
+ if (severity > worstSeverity) {
44
+ worst = factor.label;
45
+ worstSeverity = severity;
46
+ }
47
+ }
48
+ return worst;
49
+ }
50
+ export function isFlagged(row) {
51
+ return row.kind === 'scored' && row.level !== 'low';
52
+ }
53
+ export function orderRows(rows) {
54
+ const scored = rows.filter((r) => r.kind === 'scored');
55
+ const skipped = rows.filter((r) => r.kind === 'skipped');
56
+ return [...[...scored].sort((a, b) => b.score - a.score), ...skipped];
57
+ }
58
+ export function buildReport(rows, scannedAt = new Date()) {
59
+ const ordered = orderRows(rows);
60
+ return {
61
+ rows: ordered,
62
+ flagged: ordered.filter(isFlagged).length,
63
+ scanned: ordered.filter(row => row.kind === 'scored').length,
64
+ scannedAt: scannedAt.toISOString(),
65
+ };
66
+ }
67
+ function filled(fields) {
68
+ return {
69
+ artistName: fields.artistName.trim() || '[Your name]',
70
+ trackName: fields.trackName.trim() || '[Track name]',
71
+ distributor: fields.distributor.trim(),
72
+ };
73
+ }
74
+ export function distributorReply(report, fields) {
75
+ const f = filled(fields);
76
+ const flagged = report.rows.filter(isFlagged);
77
+ const findings = flagged.length > 0
78
+ ? [
79
+ 'I\'ve checked the playlists my music is on with SpotCheck, which scores public playlist data for signs of bot activity. These show warning signs:',
80
+ flagged
81
+ .map(r => `- ${r.name} by ${r.owner}, risk ${r.score}/100 (${r.reason}): ${r.url}`)
82
+ .join('\n'),
83
+ 'I\'m contacting these curators to ask for my music to be removed. If you can tell me which playlist or source Spotify flagged, I\'ll deal with it directly.',
84
+ ]
85
+ : [
86
+ `I've checked the ${report.scanned} ${report.scanned === 1 ? 'playlist' : 'playlists'} my music is on with SpotCheck, which scores public playlist data for signs of bot activity. None show warning signs, so I'd be grateful if you could tell me which playlist or source Spotify flagged.`,
87
+ ];
88
+ return [
89
+ f.distributor ? `Hi ${f.distributor} team,` : 'Hi there,',
90
+ `Thanks for letting me know about the artificial streaming flag on ${f.trackName}. I haven't bought streams or used any service that guarantees streams.`,
91
+ ...findings,
92
+ `Thanks,\n${f.artistName}`,
93
+ ].join('\n\n');
94
+ }
95
+ export function removalRequest(row, fields) {
96
+ const f = filled(fields);
97
+ return [
98
+ `Hi ${row.owner},`,
99
+ `My track ${f.trackName} is on your playlist ${row.name}. Please could you remove it? My distributor has flagged unusual streaming activity, and I'm taking my music off playlists I can't verify.`,
100
+ `Thanks,\n${f.artistName}`,
101
+ ].join('\n\n');
102
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@totalaudiopromo/spotcheck",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Check a Spotify playlist for bot-farm patterns using public data. Library, command line tool and local MCP server.",
5
+ "license": "MIT",
6
+ "author": "Total Audio Promo Ltd",
7
+ "homepage": "https://github.com/chrisschouk/spotcheck-oss#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/chrisschouk/spotcheck-oss.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/chrisschouk/spotcheck-oss/issues"
14
+ },
15
+ "keywords": [
16
+ "spotify",
17
+ "playlist",
18
+ "bot-detection",
19
+ "mcp",
20
+ "music"
21
+ ],
22
+ "type": "module",
23
+ "engines": {
24
+ "node": ">=22"
25
+ },
26
+ "main": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js"
32
+ }
33
+ },
34
+ "bin": {
35
+ "spotcheck": "./dist/cli.js"
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "scripts": {
43
+ "build": "tsc -p tsconfig.build.json",
44
+ "typecheck": "tsc --noEmit",
45
+ "test": "vitest run",
46
+ "prepublishOnly": "npm run build && npm test"
47
+ },
48
+ "dependencies": {
49
+ "@modelcontextprotocol/sdk": "^1.32.2",
50
+ "zod": "^4.6.7"
51
+ },
52
+ "devDependencies": {
53
+ "@types/node": "^22.20.6",
54
+ "typescript": "^5.9.3",
55
+ "vitest": "^5.1.1"
56
+ }
57
+ }