@vllnt/convex-music 0.1.0-canary.09eea4e
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +169 -0
- package/dist/client/index.d.ts +284 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +166 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/types.d.ts +100 -0
- package/dist/client/types.d.ts.map +1 -0
- package/dist/client/types.js +2 -0
- package/dist/client/types.js.map +1 -0
- package/dist/component/_generated/api.d.ts +125 -0
- package/dist/component/_generated/api.d.ts.map +1 -0
- package/dist/component/_generated/api.js +31 -0
- package/dist/component/_generated/api.js.map +1 -0
- package/dist/component/_generated/component.d.ts +1143 -0
- package/dist/component/_generated/component.d.ts.map +1 -0
- package/dist/component/_generated/component.js +11 -0
- package/dist/component/_generated/component.js.map +1 -0
- package/dist/component/_generated/dataModel.d.ts +46 -0
- package/dist/component/_generated/dataModel.d.ts.map +1 -0
- package/dist/component/_generated/dataModel.js +11 -0
- package/dist/component/_generated/dataModel.js.map +1 -0
- package/dist/component/_generated/server.d.ts +133 -0
- package/dist/component/_generated/server.d.ts.map +1 -0
- package/dist/component/_generated/server.js +80 -0
- package/dist/component/_generated/server.js.map +1 -0
- package/dist/component/actions.d.ts +144 -0
- package/dist/component/actions.d.ts.map +1 -0
- package/dist/component/actions.js +125 -0
- package/dist/component/actions.js.map +1 -0
- package/dist/component/catalog/browse_order.d.ts +22 -0
- package/dist/component/catalog/browse_order.d.ts.map +1 -0
- package/dist/component/catalog/browse_order.js +37 -0
- package/dist/component/catalog/browse_order.js.map +1 -0
- package/dist/component/catalog/field_source_policy.d.ts +30 -0
- package/dist/component/catalog/field_source_policy.d.ts.map +1 -0
- package/dist/component/catalog/field_source_policy.js +36 -0
- package/dist/component/catalog/field_source_policy.js.map +1 -0
- package/dist/component/catalog/merge.d.ts +58 -0
- package/dist/component/catalog/merge.d.ts.map +1 -0
- package/dist/component/catalog/merge.js +74 -0
- package/dist/component/catalog/merge.js.map +1 -0
- package/dist/component/catalog/mutations.d.ts +78 -0
- package/dist/component/catalog/mutations.d.ts.map +1 -0
- package/dist/component/catalog/mutations.js +259 -0
- package/dist/component/catalog/mutations.js.map +1 -0
- package/dist/component/catalog/promote.d.ts +21 -0
- package/dist/component/catalog/promote.d.ts.map +1 -0
- package/dist/component/catalog/promote.js +25 -0
- package/dist/component/catalog/promote.js.map +1 -0
- package/dist/component/catalog/queries.d.ts +421 -0
- package/dist/component/catalog/queries.d.ts.map +1 -0
- package/dist/component/catalog/queries.js +168 -0
- package/dist/component/catalog/queries.js.map +1 -0
- package/dist/component/config/mutations.d.ts +11 -0
- package/dist/component/config/mutations.d.ts.map +1 -0
- package/dist/component/config/mutations.js +30 -0
- package/dist/component/config/mutations.js.map +1 -0
- package/dist/component/config/queries.d.ts +9 -0
- package/dist/component/config/queries.d.ts.map +1 -0
- package/dist/component/config/queries.js +20 -0
- package/dist/component/config/queries.js.map +1 -0
- package/dist/component/convex.config.d.ts +3 -0
- package/dist/component/convex.config.d.ts.map +1 -0
- package/dist/component/convex.config.js +30 -0
- package/dist/component/convex.config.js.map +1 -0
- package/dist/component/crons.d.ts +11 -0
- package/dist/component/crons.d.ts.map +1 -0
- package/dist/component/crons.js +41 -0
- package/dist/component/crons.js.map +1 -0
- package/dist/component/imports/actions.d.ts +119 -0
- package/dist/component/imports/actions.d.ts.map +1 -0
- package/dist/component/imports/actions.js +442 -0
- package/dist/component/imports/actions.js.map +1 -0
- package/dist/component/imports/dedupe.d.ts +29 -0
- package/dist/component/imports/dedupe.d.ts.map +1 -0
- package/dist/component/imports/dedupe.js +33 -0
- package/dist/component/imports/dedupe.js.map +1 -0
- package/dist/component/imports/mutations.d.ts +59 -0
- package/dist/component/imports/mutations.d.ts.map +1 -0
- package/dist/component/imports/mutations.js +151 -0
- package/dist/component/imports/mutations.js.map +1 -0
- package/dist/component/imports/queries.d.ts +68 -0
- package/dist/component/imports/queries.d.ts.map +1 -0
- package/dist/component/imports/queries.js +22 -0
- package/dist/component/imports/queries.js.map +1 -0
- package/dist/component/imports/state.d.ts +36 -0
- package/dist/component/imports/state.d.ts.map +1 -0
- package/dist/component/imports/state.js +62 -0
- package/dist/component/imports/state.js.map +1 -0
- package/dist/component/mutations.d.ts +55 -0
- package/dist/component/mutations.d.ts.map +1 -0
- package/dist/component/mutations.js +74 -0
- package/dist/component/mutations.js.map +1 -0
- package/dist/component/providers/actions.d.ts +26 -0
- package/dist/component/providers/actions.d.ts.map +1 -0
- package/dist/component/providers/actions.js +92 -0
- package/dist/component/providers/actions.js.map +1 -0
- package/dist/component/providers/apple/impl.d.ts +52 -0
- package/dist/component/providers/apple/impl.d.ts.map +1 -0
- package/dist/component/providers/apple/impl.js +127 -0
- package/dist/component/providers/apple/impl.js.map +1 -0
- package/dist/component/providers/apple/jwt.d.ts +32 -0
- package/dist/component/providers/apple/jwt.d.ts.map +1 -0
- package/dist/component/providers/apple/jwt.js +68 -0
- package/dist/component/providers/apple/jwt.js.map +1 -0
- package/dist/component/providers/apple/mappers.d.ts +20 -0
- package/dist/component/providers/apple/mappers.d.ts.map +1 -0
- package/dist/component/providers/apple/mappers.js +68 -0
- package/dist/component/providers/apple/mappers.js.map +1 -0
- package/dist/component/providers/apple/types.d.ts +80 -0
- package/dist/component/providers/apple/types.d.ts.map +1 -0
- package/dist/component/providers/apple/types.js +7 -0
- package/dist/component/providers/apple/types.js.map +1 -0
- package/dist/component/providers/deezer/impl.d.ts +37 -0
- package/dist/component/providers/deezer/impl.d.ts.map +1 -0
- package/dist/component/providers/deezer/impl.js +99 -0
- package/dist/component/providers/deezer/impl.js.map +1 -0
- package/dist/component/providers/deezer/mappers.d.ts +18 -0
- package/dist/component/providers/deezer/mappers.d.ts.map +1 -0
- package/dist/component/providers/deezer/mappers.js +53 -0
- package/dist/component/providers/deezer/mappers.js.map +1 -0
- package/dist/component/providers/deezer/types.d.ts +59 -0
- package/dist/component/providers/deezer/types.d.ts.map +1 -0
- package/dist/component/providers/deezer/types.js +7 -0
- package/dist/component/providers/deezer/types.js.map +1 -0
- package/dist/component/providers/fetch.d.ts +69 -0
- package/dist/component/providers/fetch.d.ts.map +1 -0
- package/dist/component/providers/fetch.js +145 -0
- package/dist/component/providers/fetch.js.map +1 -0
- package/dist/component/providers/musicbrainz/impl.d.ts +36 -0
- package/dist/component/providers/musicbrainz/impl.d.ts.map +1 -0
- package/dist/component/providers/musicbrainz/impl.js +74 -0
- package/dist/component/providers/musicbrainz/impl.js.map +1 -0
- package/dist/component/providers/musicbrainz/mappers.d.ts +10 -0
- package/dist/component/providers/musicbrainz/mappers.d.ts.map +1 -0
- package/dist/component/providers/musicbrainz/mappers.js +32 -0
- package/dist/component/providers/musicbrainz/mappers.js.map +1 -0
- package/dist/component/providers/musicbrainz/types.d.ts +24 -0
- package/dist/component/providers/musicbrainz/types.d.ts.map +1 -0
- package/dist/component/providers/musicbrainz/types.js +7 -0
- package/dist/component/providers/musicbrainz/types.js.map +1 -0
- package/dist/component/providers/registry.d.ts +22 -0
- package/dist/component/providers/registry.d.ts.map +1 -0
- package/dist/component/providers/registry.js +33 -0
- package/dist/component/providers/registry.js.map +1 -0
- package/dist/component/providers/spotify/client.d.ts +25 -0
- package/dist/component/providers/spotify/client.d.ts.map +1 -0
- package/dist/component/providers/spotify/client.js +30 -0
- package/dist/component/providers/spotify/client.js.map +1 -0
- package/dist/component/providers/spotify/impl.d.ts +51 -0
- package/dist/component/providers/spotify/impl.d.ts.map +1 -0
- package/dist/component/providers/spotify/impl.js +131 -0
- package/dist/component/providers/spotify/impl.js.map +1 -0
- package/dist/component/providers/spotify/mappers.d.ts +18 -0
- package/dist/component/providers/spotify/mappers.d.ts.map +1 -0
- package/dist/component/providers/spotify/mappers.js +60 -0
- package/dist/component/providers/spotify/mappers.js.map +1 -0
- package/dist/component/providers/spotify/types.d.ts +97 -0
- package/dist/component/providers/spotify/types.d.ts.map +1 -0
- package/dist/component/providers/spotify/types.js +7 -0
- package/dist/component/providers/spotify/types.js.map +1 -0
- package/dist/component/providers/types.d.ts +84 -0
- package/dist/component/providers/types.d.ts.map +1 -0
- package/dist/component/providers/types.js +10 -0
- package/dist/component/providers/types.js.map +1 -0
- package/dist/component/providers/wikidata/impl.d.ts +34 -0
- package/dist/component/providers/wikidata/impl.d.ts.map +1 -0
- package/dist/component/providers/wikidata/impl.js +88 -0
- package/dist/component/providers/wikidata/impl.js.map +1 -0
- package/dist/component/providers/wikidata/mappers.d.ts +11 -0
- package/dist/component/providers/wikidata/mappers.d.ts.map +1 -0
- package/dist/component/providers/wikidata/mappers.js +53 -0
- package/dist/component/providers/wikidata/mappers.js.map +1 -0
- package/dist/component/providers/wikidata/types.d.ts +35 -0
- package/dist/component/providers/wikidata/types.d.ts.map +1 -0
- package/dist/component/providers/wikidata/types.js +8 -0
- package/dist/component/providers/wikidata/types.js.map +1 -0
- package/dist/component/queries.d.ts +103 -0
- package/dist/component/queries.d.ts.map +1 -0
- package/dist/component/queries.js +45 -0
- package/dist/component/queries.js.map +1 -0
- package/dist/component/schema.d.ts +566 -0
- package/dist/component/schema.d.ts.map +1 -0
- package/dist/component/schema.js +59 -0
- package/dist/component/schema.js.map +1 -0
- package/dist/component/sources/actions.d.ts +51 -0
- package/dist/component/sources/actions.d.ts.map +1 -0
- package/dist/component/sources/actions.js +164 -0
- package/dist/component/sources/actions.js.map +1 -0
- package/dist/component/sources/mutations.d.ts +25 -0
- package/dist/component/sources/mutations.d.ts.map +1 -0
- package/dist/component/sources/mutations.js +64 -0
- package/dist/component/sources/mutations.js.map +1 -0
- package/dist/component/sources/queries.d.ts +19 -0
- package/dist/component/sources/queries.d.ts.map +1 -0
- package/dist/component/sources/queries.js +20 -0
- package/dist/component/sources/queries.js.map +1 -0
- package/dist/component/sync/lifecycle.d.ts +46 -0
- package/dist/component/sync/lifecycle.d.ts.map +1 -0
- package/dist/component/sync/lifecycle.js +87 -0
- package/dist/component/sync/lifecycle.js.map +1 -0
- package/dist/component/sync/mutations.d.ts +101 -0
- package/dist/component/sync/mutations.d.ts.map +1 -0
- package/dist/component/sync/mutations.js +132 -0
- package/dist/component/sync/mutations.js.map +1 -0
- package/dist/component/sync/queries.d.ts +69 -0
- package/dist/component/sync/queries.d.ts.map +1 -0
- package/dist/component/sync/queries.js +32 -0
- package/dist/component/sync/queries.js.map +1 -0
- package/dist/component/validators.d.ts +1112 -0
- package/dist/component/validators.d.ts.map +1 -0
- package/dist/component/validators.js +317 -0
- package/dist/component/validators.js.map +1 -0
- package/dist/react/index.d.ts +42 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +43 -0
- package/dist/react/index.js.map +1 -0
- package/dist/shared.d.ts +28 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +24 -0
- package/dist/shared.js.map +1 -0
- package/package.json +126 -0
- package/src/client/index.ts +558 -0
- package/src/client/types.ts +117 -0
- package/src/component/_generated/api.ts +141 -0
- package/src/component/_generated/component.ts +1814 -0
- package/src/component/_generated/dataModel.ts +60 -0
- package/src/component/_generated/server.ts +169 -0
- package/src/component/actions.ts +156 -0
- package/src/component/catalog/browse_order.test.ts +55 -0
- package/src/component/catalog/browse_order.ts +43 -0
- package/src/component/catalog/field_source_policy.test.ts +47 -0
- package/src/component/catalog/field_source_policy.ts +44 -0
- package/src/component/catalog/merge.test.ts +187 -0
- package/src/component/catalog/merge.ts +134 -0
- package/src/component/catalog/mutations.ts +328 -0
- package/src/component/catalog/promote.ts +40 -0
- package/src/component/catalog/queries.ts +220 -0
- package/src/component/config/mutations.ts +29 -0
- package/src/component/config/queries.ts +20 -0
- package/src/component/convex.config.ts +32 -0
- package/src/component/crons.test.ts +8 -0
- package/src/component/crons.ts +52 -0
- package/src/component/imports/actions.ts +553 -0
- package/src/component/imports/dedupe.test.ts +66 -0
- package/src/component/imports/dedupe.ts +54 -0
- package/src/component/imports/mutations.ts +203 -0
- package/src/component/imports/queries.ts +25 -0
- package/src/component/imports/state.test.ts +60 -0
- package/src/component/imports/state.ts +74 -0
- package/src/component/mutations.ts +96 -0
- package/src/component/providers/actions.ts +127 -0
- package/src/component/providers/apple/impl.test.ts +267 -0
- package/src/component/providers/apple/impl.ts +224 -0
- package/src/component/providers/apple/jwt.test.ts +153 -0
- package/src/component/providers/apple/jwt.ts +99 -0
- package/src/component/providers/apple/mappers.test.ts +190 -0
- package/src/component/providers/apple/mappers.ts +100 -0
- package/src/component/providers/apple/types.ts +77 -0
- package/src/component/providers/deezer/impl.test.ts +109 -0
- package/src/component/providers/deezer/impl.ts +179 -0
- package/src/component/providers/deezer/mappers.test.ts +78 -0
- package/src/component/providers/deezer/mappers.ts +72 -0
- package/src/component/providers/deezer/types.ts +59 -0
- package/src/component/providers/fetch.test.ts +282 -0
- package/src/component/providers/fetch.ts +190 -0
- package/src/component/providers/musicbrainz/impl.test.ts +79 -0
- package/src/component/providers/musicbrainz/impl.ts +132 -0
- package/src/component/providers/musicbrainz/mappers.test.ts +75 -0
- package/src/component/providers/musicbrainz/mappers.ts +34 -0
- package/src/component/providers/musicbrainz/types.ts +20 -0
- package/src/component/providers/registry.test.ts +14 -0
- package/src/component/providers/registry.ts +48 -0
- package/src/component/providers/spotify/client.test.ts +80 -0
- package/src/component/providers/spotify/client.ts +57 -0
- package/src/component/providers/spotify/impl.test.ts +311 -0
- package/src/component/providers/spotify/impl.ts +230 -0
- package/src/component/providers/spotify/mappers.test.ts +182 -0
- package/src/component/providers/spotify/mappers.ts +81 -0
- package/src/component/providers/spotify/types.ts +101 -0
- package/src/component/providers/types.ts +95 -0
- package/src/component/providers/wikidata/impl.test.ts +81 -0
- package/src/component/providers/wikidata/impl.ts +139 -0
- package/src/component/providers/wikidata/mappers.test.ts +62 -0
- package/src/component/providers/wikidata/mappers.ts +66 -0
- package/src/component/providers/wikidata/types.ts +28 -0
- package/src/component/queries.ts +51 -0
- package/src/component/schema.ts +81 -0
- package/src/component/sources/actions.ts +177 -0
- package/src/component/sources/mutations.ts +67 -0
- package/src/component/sources/queries.ts +21 -0
- package/src/component/sync/lifecycle.test.ts +72 -0
- package/src/component/sync/lifecycle.ts +121 -0
- package/src/component/sync/mutations.ts +154 -0
- package/src/component/sync/queries.ts +33 -0
- package/src/component/validators.ts +411 -0
- package/src/react/index.test.ts +78 -0
- package/src/react/index.ts +112 -0
- package/src/shared.ts +32 -0
- package/src/test.ts +22 -0
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resilient provider HTTP. Wraps `fetch` with a per-request timeout and retries
|
|
3
|
+
* on rate-limit (429) **and** overload 5xx (500/502/503/504/529) — honoring
|
|
4
|
+
* `Retry-After`, capped exponential backoff, and jitter. songtrivia retries only
|
|
5
|
+
* 429; a Spotify/Apple `529`/`503` must never hard-fail an import, so the
|
|
6
|
+
* component also retries transient overload. Every knob is config; the timer and
|
|
7
|
+
* RNG are injectable so the retry loop is deterministic under test.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Status codes worth retrying: rate-limit + transient overload. */
|
|
11
|
+
const RETRYABLE_STATUSES: ReadonlySet<number> = new Set([
|
|
12
|
+
429, 500, 502, 503, 504, 529,
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
/** Tunable retry/timeout policy for a provider call. */
|
|
16
|
+
export interface RetryConfig {
|
|
17
|
+
/** Max total attempts before giving up. */
|
|
18
|
+
maxAttempts: number;
|
|
19
|
+
/** Upper bound on any single backoff wait, in ms. */
|
|
20
|
+
maxWaitMs: number;
|
|
21
|
+
/** Random jitter added to each wait, in ms (`0..jitterMs`). */
|
|
22
|
+
jitterMs: number;
|
|
23
|
+
/** Per-request timeout before aborting, in ms. */
|
|
24
|
+
timeoutMs: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** songtrivia-derived defaults (all overridable via mount policy). */
|
|
28
|
+
export const DEFAULT_RETRY_CONFIG: RetryConfig = {
|
|
29
|
+
maxAttempts: 6,
|
|
30
|
+
maxWaitMs: 60_000,
|
|
31
|
+
jitterMs: 250,
|
|
32
|
+
timeoutMs: 15_000,
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** Injectable side-effects so the retry loop is deterministic under test. */
|
|
36
|
+
export interface FetchDeps {
|
|
37
|
+
/** The `fetch` implementation to call. */
|
|
38
|
+
fetch: (url: string, init: RequestInit) => Promise<Response>;
|
|
39
|
+
/** Sleep helper for backoff waits. */
|
|
40
|
+
sleep: (ms: number) => Promise<void>;
|
|
41
|
+
/** RNG in `[0, 1)` for jitter. */
|
|
42
|
+
random: () => number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Default deps bound to the runtime's real `fetch`, timer, and RNG. */
|
|
46
|
+
export const defaultFetchDeps: FetchDeps = {
|
|
47
|
+
fetch: (url, init) => globalThis.fetch(url, init),
|
|
48
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
49
|
+
random: () => Math.random(),
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/** A non-2xx provider response that is non-retryable or survived all retries. */
|
|
53
|
+
export class ProviderHttpError extends Error {
|
|
54
|
+
constructor(
|
|
55
|
+
readonly status: number,
|
|
56
|
+
readonly body: string,
|
|
57
|
+
readonly provider: string,
|
|
58
|
+
) {
|
|
59
|
+
super(`${provider} API error ${status}: ${body.slice(0, 256)}`);
|
|
60
|
+
this.name = "ProviderHttpError";
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A request that exceeded the per-attempt timeout (retried like an overload). */
|
|
65
|
+
export class ProviderTimeoutError extends Error {
|
|
66
|
+
constructor(
|
|
67
|
+
readonly provider: string,
|
|
68
|
+
readonly timeoutMs: number,
|
|
69
|
+
) {
|
|
70
|
+
super(`${provider} API timeout after ${timeoutMs}ms`);
|
|
71
|
+
this.name = "ProviderTimeoutError";
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Parse a `Retry-After` header (delta-seconds or HTTP-date) to ms, or undefined. */
|
|
76
|
+
function parseRetryAfterMs(
|
|
77
|
+
header: string | null,
|
|
78
|
+
now: number,
|
|
79
|
+
): number | undefined {
|
|
80
|
+
if (header === null) return undefined;
|
|
81
|
+
const seconds = Number(header);
|
|
82
|
+
if (!Number.isNaN(seconds)) return Math.max(0, Math.floor(seconds * 1000));
|
|
83
|
+
const dateMs = Date.parse(header);
|
|
84
|
+
return Number.isNaN(dateMs) ? undefined : Math.max(0, dateMs - now);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Capped exponential backoff for a 1-based attempt, before jitter. */
|
|
88
|
+
function backoffMs(attempt: number, cfg: RetryConfig): number {
|
|
89
|
+
return Math.min(cfg.maxWaitMs, 2 ** (attempt - 1) * 1000);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Wait for a retryable attempt: `Retry-After` (or backoff) + jitter, capped. */
|
|
93
|
+
function nextWaitMs(
|
|
94
|
+
retryAfterMs: number | undefined,
|
|
95
|
+
attempt: number,
|
|
96
|
+
cfg: RetryConfig,
|
|
97
|
+
deps: FetchDeps,
|
|
98
|
+
): number {
|
|
99
|
+
const base = retryAfterMs ?? backoffMs(attempt, cfg);
|
|
100
|
+
const jitter = Math.floor(deps.random() * cfg.jitterMs);
|
|
101
|
+
return Math.min(cfg.maxWaitMs, base + jitter);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Fetch JSON from a provider with timeout + bounded retries. Resolves the parsed
|
|
106
|
+
* body on a 2xx; throws {@link ProviderHttpError} on a non-retryable or
|
|
107
|
+
* retry-exhausted response, or {@link ProviderTimeoutError} if every attempt
|
|
108
|
+
* timed out.
|
|
109
|
+
*
|
|
110
|
+
* @param provider - provider id, for error messages.
|
|
111
|
+
* @param url - the absolute request URL (query already encoded).
|
|
112
|
+
* @param init - fetch init (headers, method); `signal` is managed internally.
|
|
113
|
+
* @param cfg - retry/timeout policy.
|
|
114
|
+
* @param deps - injectable fetch/sleep/random (defaults to the runtime).
|
|
115
|
+
*/
|
|
116
|
+
export async function fetchJson<T>(
|
|
117
|
+
provider: string,
|
|
118
|
+
url: string,
|
|
119
|
+
init: RequestInit = {},
|
|
120
|
+
cfg: RetryConfig = DEFAULT_RETRY_CONFIG,
|
|
121
|
+
deps: FetchDeps = defaultFetchDeps,
|
|
122
|
+
): Promise<T> {
|
|
123
|
+
let attempt = 0;
|
|
124
|
+
while (true) {
|
|
125
|
+
attempt += 1;
|
|
126
|
+
const isLast = attempt >= cfg.maxAttempts;
|
|
127
|
+
const controller = new AbortController();
|
|
128
|
+
const timeoutId = setTimeout(() => controller.abort(), cfg.timeoutMs);
|
|
129
|
+
let res: Response;
|
|
130
|
+
let body: string;
|
|
131
|
+
try {
|
|
132
|
+
res = await deps.fetch(url, { ...init, signal: controller.signal });
|
|
133
|
+
if (res.ok) {
|
|
134
|
+
return (await res.json()) as T;
|
|
135
|
+
}
|
|
136
|
+
// Read the body under the SAME timeout: a provider that sends headers fast
|
|
137
|
+
// then stalls the stream is aborted too, not just the headers wait.
|
|
138
|
+
body = await res.text();
|
|
139
|
+
} catch (err) {
|
|
140
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
141
|
+
if (isLast) throw new ProviderTimeoutError(provider, cfg.timeoutMs);
|
|
142
|
+
await deps.sleep(nextWaitMs(undefined, attempt, cfg, deps));
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
throw err;
|
|
146
|
+
} finally {
|
|
147
|
+
clearTimeout(timeoutId);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (RETRYABLE_STATUSES.has(res.status)) {
|
|
151
|
+
if (isLast) throw new ProviderHttpError(res.status, body, provider);
|
|
152
|
+
const retryAfter = parseRetryAfterMs(
|
|
153
|
+
res.headers.get("Retry-After"),
|
|
154
|
+
Date.now(),
|
|
155
|
+
);
|
|
156
|
+
await deps.sleep(nextWaitMs(retryAfter, attempt, cfg, deps));
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
throw new ProviderHttpError(res.status, body, provider);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Run async tasks with bounded concurrency, preserving input order. Mirrors
|
|
165
|
+
* songtrivia's album-fetch semaphore (default fan-out 5) so a large traversal
|
|
166
|
+
* never opens unbounded provider connections.
|
|
167
|
+
*
|
|
168
|
+
* @param items - inputs to map.
|
|
169
|
+
* @param limit - max in-flight tasks (must be > 0).
|
|
170
|
+
* @param task - async mapper.
|
|
171
|
+
*/
|
|
172
|
+
export async function mapWithConcurrency<T, R>(
|
|
173
|
+
items: readonly T[],
|
|
174
|
+
limit: number,
|
|
175
|
+
task: (item: T, index: number) => Promise<R>,
|
|
176
|
+
): Promise<R[]> {
|
|
177
|
+
if (limit <= 0) throw new Error(`Concurrency limit must be > 0, got ${limit}`);
|
|
178
|
+
const results = new Array<R>(items.length);
|
|
179
|
+
const shared = items.entries();
|
|
180
|
+
async function worker(): Promise<void> {
|
|
181
|
+
for (const [index, item] of shared) {
|
|
182
|
+
results[index] = await task(item, index);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
const workers = Array.from({ length: Math.min(limit, items.length) }, () =>
|
|
186
|
+
worker(),
|
|
187
|
+
);
|
|
188
|
+
await Promise.all(workers);
|
|
189
|
+
return results;
|
|
190
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import type { FetchDeps } from "../fetch.js";
|
|
3
|
+
import { MusicBrainzProvider } from "./impl.js";
|
|
4
|
+
|
|
5
|
+
interface Route {
|
|
6
|
+
match: RegExp;
|
|
7
|
+
body: unknown;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function makeProvider(routes: Route[]): MusicBrainzProvider {
|
|
11
|
+
const deps: FetchDeps = {
|
|
12
|
+
fetch: (url) => {
|
|
13
|
+
const route = routes.find((r) => r.match.test(url));
|
|
14
|
+
return Promise.resolve(
|
|
15
|
+
new Response(JSON.stringify(route?.body ?? {}), {
|
|
16
|
+
status: route === undefined ? 404 : 200,
|
|
17
|
+
headers: { "content-type": "application/json" },
|
|
18
|
+
}),
|
|
19
|
+
);
|
|
20
|
+
},
|
|
21
|
+
sleep: () => Promise.resolve(),
|
|
22
|
+
random: () => 0,
|
|
23
|
+
};
|
|
24
|
+
return new MusicBrainzProvider(undefined, deps);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
describe("MusicBrainzProvider", () => {
|
|
28
|
+
it("getArtist maps facts", async () => {
|
|
29
|
+
const p = makeProvider([
|
|
30
|
+
{
|
|
31
|
+
match: /\/artist\/mb1\?/,
|
|
32
|
+
body: {
|
|
33
|
+
id: "mb1",
|
|
34
|
+
name: "Daft Punk",
|
|
35
|
+
country: "FR",
|
|
36
|
+
type: "Group",
|
|
37
|
+
"life-span": { begin: "1993" },
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
]);
|
|
41
|
+
const artist = await p.getArtist("mb1");
|
|
42
|
+
expect(artist.externalId).toBe("mb1");
|
|
43
|
+
expect(artist.value.country).toBe("FR");
|
|
44
|
+
expect(artist.value.members).toBe("group");
|
|
45
|
+
expect(artist.value.debutYear).toBe(1993);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("search(artist) maps hits + tolerates an empty body", async () => {
|
|
49
|
+
const hit = makeProvider([
|
|
50
|
+
{
|
|
51
|
+
match: /\/artist\?.*query=daft/,
|
|
52
|
+
body: { artists: [{ id: "mb1", name: "Daft Punk", country: "FR" }] },
|
|
53
|
+
},
|
|
54
|
+
]);
|
|
55
|
+
const results = await hit.search("daft", "artist");
|
|
56
|
+
expect(results[0]).toMatchObject({
|
|
57
|
+
type: "artist",
|
|
58
|
+
data: { externalId: "mb1" },
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
const empty = makeProvider([{ match: /\/artist\?/, body: {} }]);
|
|
62
|
+
expect(await empty.search("none", "artist")).toEqual([]);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it("search(track) + searchByIsrc return empty (facts-only)", async () => {
|
|
66
|
+
const p = makeProvider([]);
|
|
67
|
+
expect(await p.search("x", "track")).toEqual([]);
|
|
68
|
+
expect(await p.searchByIsrc()).toEqual([]);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("rejects the track/album/playlist methods it does not serve", async () => {
|
|
72
|
+
const p = makeProvider([]);
|
|
73
|
+
await expect(p.getTrack()).rejects.toThrow(/not supported/);
|
|
74
|
+
await expect(p.getAlbum()).rejects.toThrow(/not supported/);
|
|
75
|
+
await expect(p.getPlaylist()).rejects.toThrow(/not supported/);
|
|
76
|
+
await expect(p.getArtistTopTracks()).rejects.toThrow(/not supported/);
|
|
77
|
+
await expect(p.getArtistAlbums()).rejects.toThrow(/not supported/);
|
|
78
|
+
});
|
|
79
|
+
});
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MusicBrainz adapter — a **no-auth, facts-only** provider. It supplies the
|
|
3
|
+
* artist facts Spotify/Apple lack (country, gender, solo/group, debut), which
|
|
4
|
+
* merge into the unified artist by name. It does NOT serve tracks/albums/
|
|
5
|
+
* playlists, so those `MusicProvider` methods reject; `search(track)` /
|
|
6
|
+
* `searchByIsrc` return empty rather than throwing (graceful for cross-provider
|
|
7
|
+
* fallback). No bearer token — requests carry a `User-Agent` per MB policy.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
DEFAULT_RETRY_CONFIG,
|
|
12
|
+
type FetchDeps,
|
|
13
|
+
type RetryConfig,
|
|
14
|
+
defaultFetchDeps,
|
|
15
|
+
fetchJson,
|
|
16
|
+
} from "../fetch.js";
|
|
17
|
+
import type {
|
|
18
|
+
ArtistAlbumsResult,
|
|
19
|
+
MusicProvider,
|
|
20
|
+
ProviderAlbum,
|
|
21
|
+
ProviderArtist,
|
|
22
|
+
ProviderPlaylist,
|
|
23
|
+
ProviderSearchResult,
|
|
24
|
+
ProviderTrack,
|
|
25
|
+
} from "../types.js";
|
|
26
|
+
import { mapMusicBrainzArtist } from "./mappers.js";
|
|
27
|
+
import type {
|
|
28
|
+
MusicBrainzArtist,
|
|
29
|
+
MusicBrainzArtistSearchResponse,
|
|
30
|
+
} from "./types.js";
|
|
31
|
+
|
|
32
|
+
/** Tunable MusicBrainz settings. */
|
|
33
|
+
export interface MusicBrainzConfig {
|
|
34
|
+
baseUrl: string;
|
|
35
|
+
/** Required by MB policy; identifies the client. */
|
|
36
|
+
userAgent: string;
|
|
37
|
+
retry: RetryConfig;
|
|
38
|
+
searchLimit: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Default MusicBrainz settings. */
|
|
42
|
+
export const DEFAULT_MUSICBRAINZ_CONFIG: MusicBrainzConfig = {
|
|
43
|
+
baseUrl: "https://musicbrainz.org/ws/2",
|
|
44
|
+
userAgent: "vllnt-convex-music/0.1 (https://github.com/vllnt/convex-music)",
|
|
45
|
+
retry: DEFAULT_RETRY_CONFIG,
|
|
46
|
+
searchLimit: 10,
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** A method MusicBrainz (facts-only) does not serve. */
|
|
50
|
+
function unsupported<T>(method: string): Promise<T> {
|
|
51
|
+
return Promise.reject(
|
|
52
|
+
new Error(`musicbrainz: ${method} not supported (facts-only provider)`),
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export class MusicBrainzProvider implements MusicProvider {
|
|
57
|
+
readonly id = "musicbrainz" as const;
|
|
58
|
+
|
|
59
|
+
constructor(
|
|
60
|
+
private readonly cfg: MusicBrainzConfig = DEFAULT_MUSICBRAINZ_CONFIG,
|
|
61
|
+
private readonly deps: FetchDeps = defaultFetchDeps,
|
|
62
|
+
) {}
|
|
63
|
+
|
|
64
|
+
private async api<T>(
|
|
65
|
+
path: string,
|
|
66
|
+
params: Record<string, string>,
|
|
67
|
+
): Promise<T> {
|
|
68
|
+
const url = new URL(this.cfg.baseUrl + path);
|
|
69
|
+
url.searchParams.set("fmt", "json");
|
|
70
|
+
for (const [key, value] of Object.entries(params)) {
|
|
71
|
+
url.searchParams.set(key, value);
|
|
72
|
+
}
|
|
73
|
+
return fetchJson<T>(
|
|
74
|
+
"musicbrainz",
|
|
75
|
+
url.toString(),
|
|
76
|
+
{ headers: { "User-Agent": this.cfg.userAgent } },
|
|
77
|
+
this.cfg.retry,
|
|
78
|
+
this.deps,
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async getArtist(externalId: string): Promise<ProviderArtist> {
|
|
83
|
+
const raw = await this.api<MusicBrainzArtist>(
|
|
84
|
+
`/artist/${encodeURIComponent(externalId)}`,
|
|
85
|
+
{ inc: "tags" },
|
|
86
|
+
);
|
|
87
|
+
return { externalId: raw.id, value: mapMusicBrainzArtist(raw) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async search(
|
|
91
|
+
query: string,
|
|
92
|
+
type: "artist" | "track",
|
|
93
|
+
): Promise<ProviderSearchResult[]> {
|
|
94
|
+
if (type === "artist") {
|
|
95
|
+
const res = await this.api<MusicBrainzArtistSearchResponse>("/artist", {
|
|
96
|
+
query,
|
|
97
|
+
limit: String(this.cfg.searchLimit),
|
|
98
|
+
});
|
|
99
|
+
return (res.artists ?? []).map(
|
|
100
|
+
(artist): ProviderSearchResult => ({
|
|
101
|
+
type: "artist",
|
|
102
|
+
data: { externalId: artist.id, value: mapMusicBrainzArtist(artist) },
|
|
103
|
+
}),
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
return [];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
searchByIsrc(): Promise<ProviderTrack[]> {
|
|
110
|
+
return Promise.resolve([]);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
getTrack(): Promise<ProviderTrack> {
|
|
114
|
+
return unsupported("getTrack");
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
getAlbum(): Promise<ProviderAlbum> {
|
|
118
|
+
return unsupported("getAlbum");
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
getPlaylist(): Promise<ProviderPlaylist> {
|
|
122
|
+
return unsupported("getPlaylist");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
getArtistTopTracks(): Promise<ProviderTrack[]> {
|
|
126
|
+
return unsupported("getArtistTopTracks");
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
getArtistAlbums(): Promise<ArtistAlbumsResult> {
|
|
130
|
+
return unsupported("getArtistAlbums");
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { mapMusicBrainzArtist } from "./mappers.js";
|
|
3
|
+
import type { MusicBrainzArtist } from "./types.js";
|
|
4
|
+
|
|
5
|
+
describe("mapMusicBrainzArtist", () => {
|
|
6
|
+
it("maps full facts (group, country, gender, debut, tags)", () => {
|
|
7
|
+
const raw: MusicBrainzArtist = {
|
|
8
|
+
id: "mb1",
|
|
9
|
+
name: "Daft Punk",
|
|
10
|
+
country: "FR",
|
|
11
|
+
gender: null,
|
|
12
|
+
type: "Group",
|
|
13
|
+
"life-span": { begin: "1993-05-01" },
|
|
14
|
+
tags: [{ name: "french house", count: 5 }, { name: "electronic" }],
|
|
15
|
+
};
|
|
16
|
+
expect(mapMusicBrainzArtist(raw)).toEqual({
|
|
17
|
+
name: "Daft Punk",
|
|
18
|
+
genres: ["french house", "electronic"],
|
|
19
|
+
country: "FR",
|
|
20
|
+
gender: undefined,
|
|
21
|
+
members: "group",
|
|
22
|
+
debutYear: 1993,
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it("maps a solo person with gender + year-only debut", () => {
|
|
27
|
+
expect(
|
|
28
|
+
mapMusicBrainzArtist({
|
|
29
|
+
id: "mb2",
|
|
30
|
+
name: "Beyoncé",
|
|
31
|
+
country: "US",
|
|
32
|
+
gender: "Female",
|
|
33
|
+
type: "Person",
|
|
34
|
+
"life-span": { begin: "1981" },
|
|
35
|
+
}),
|
|
36
|
+
).toEqual({
|
|
37
|
+
name: "Beyoncé",
|
|
38
|
+
genres: [],
|
|
39
|
+
country: "US",
|
|
40
|
+
gender: "Female",
|
|
41
|
+
members: "solo",
|
|
42
|
+
debutYear: 1981,
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("omits unknown facts (no type, no country, no begin)", () => {
|
|
47
|
+
expect(
|
|
48
|
+
mapMusicBrainzArtist({ id: "mb3", name: "Mystery", type: "Orchestra" }),
|
|
49
|
+
).toEqual({
|
|
50
|
+
name: "Mystery",
|
|
51
|
+
genres: [],
|
|
52
|
+
country: undefined,
|
|
53
|
+
gender: undefined,
|
|
54
|
+
members: undefined,
|
|
55
|
+
debutYear: undefined,
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("treats a null/blank begin as no debut year", () => {
|
|
60
|
+
expect(
|
|
61
|
+
mapMusicBrainzArtist({
|
|
62
|
+
id: "mb4",
|
|
63
|
+
name: "X",
|
|
64
|
+
"life-span": { begin: null },
|
|
65
|
+
}).debutYear,
|
|
66
|
+
).toBeUndefined();
|
|
67
|
+
expect(
|
|
68
|
+
mapMusicBrainzArtist({
|
|
69
|
+
id: "mb5",
|
|
70
|
+
name: "Y",
|
|
71
|
+
"life-span": { begin: "unknown" },
|
|
72
|
+
}).debutYear,
|
|
73
|
+
).toBeUndefined();
|
|
74
|
+
});
|
|
75
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Map raw MusicBrainz responses to the normalized artist schema. MusicBrainz
|
|
3
|
+
* supplies the facts Spotify/Apple lack — country, gender, solo/group, debut
|
|
4
|
+
* year — which merge into the unified artist by name.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { NormalizedArtist } from "../../../client/types.js";
|
|
8
|
+
import type { MusicBrainzArtist } from "./types.js";
|
|
9
|
+
|
|
10
|
+
/** Parse a leading 4-digit year from an MB `life-span.begin` (`YYYY[-MM-DD]`). */
|
|
11
|
+
function parseYear(begin: string | null | undefined): number | undefined {
|
|
12
|
+
if (begin === null || begin === undefined) return undefined;
|
|
13
|
+
const match = begin.match(/^(\d{4})/);
|
|
14
|
+
return match === null ? undefined : Number(match[1]);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** MB artist `type` → solo/group (undefined for other types). */
|
|
18
|
+
function membersOf(type: string | null | undefined): "solo" | "group" | undefined {
|
|
19
|
+
if (type === "Person") return "solo";
|
|
20
|
+
if (type === "Group") return "group";
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** MusicBrainz artist → normalized artist (facts only; no image/popularity). */
|
|
25
|
+
export function mapMusicBrainzArtist(raw: MusicBrainzArtist): NormalizedArtist {
|
|
26
|
+
return {
|
|
27
|
+
name: raw.name,
|
|
28
|
+
genres: (raw.tags ?? []).map((tag) => tag.name),
|
|
29
|
+
country: raw.country ?? undefined,
|
|
30
|
+
gender: raw.gender ?? undefined,
|
|
31
|
+
members: membersOf(raw.type),
|
|
32
|
+
debutYear: parseYear(raw["life-span"]?.begin),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Raw MusicBrainz API response shapes — private to the adapter. MusicBrainz is a
|
|
3
|
+
* no-auth, facts-focused provider (nationality, gender, solo/group, debut). Only
|
|
4
|
+
* the consumed fields are modeled.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export interface MusicBrainzArtist {
|
|
8
|
+
id: string;
|
|
9
|
+
name: string;
|
|
10
|
+
country?: string | null;
|
|
11
|
+
gender?: string | null;
|
|
12
|
+
/** "Person" | "Group" | "Orchestra" | … */
|
|
13
|
+
type?: string | null;
|
|
14
|
+
"life-span"?: { begin?: string | null };
|
|
15
|
+
tags?: Array<{ name: string; count?: number }>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface MusicBrainzArtistSearchResponse {
|
|
19
|
+
artists?: MusicBrainzArtist[];
|
|
20
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { createProvider } from "./registry.js";
|
|
3
|
+
import type { Provider } from "../../shared.js";
|
|
4
|
+
|
|
5
|
+
const getToken = () => Promise.resolve("tok");
|
|
6
|
+
|
|
7
|
+
describe("provider registry", () => {
|
|
8
|
+
it.each(["spotify", "apple", "musicbrainz", "deezer", "wikidata"] as const)(
|
|
9
|
+
"builds the %s adapter",
|
|
10
|
+
(id: Provider) => {
|
|
11
|
+
expect(createProvider(id, getToken).id).toBe(id);
|
|
12
|
+
},
|
|
13
|
+
);
|
|
14
|
+
});
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider registry. Maps each provider id to a factory that builds its adapter
|
|
3
|
+
* from an injected token resolver. Adding a provider = a new `Provider` union
|
|
4
|
+
* member + its entry here (TypeScript enforces exhaustiveness — a missing entry
|
|
5
|
+
* is a compile error) + its adapter folder; no edits elsewhere (open/closed).
|
|
6
|
+
* The token resolver + per-provider config are wired by the action layer
|
|
7
|
+
* (no-auth providers ignore the token and carry their own headers).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { Provider } from "../../shared.js";
|
|
11
|
+
import type { FetchDeps } from "./fetch.js";
|
|
12
|
+
import { AppleProvider } from "./apple/impl.js";
|
|
13
|
+
import { DeezerProvider } from "./deezer/impl.js";
|
|
14
|
+
import { MusicBrainzProvider } from "./musicbrainz/impl.js";
|
|
15
|
+
import { SpotifyProvider } from "./spotify/impl.js";
|
|
16
|
+
import { WikidataProvider } from "./wikidata/impl.js";
|
|
17
|
+
import type { MusicProvider } from "./types.js";
|
|
18
|
+
|
|
19
|
+
/** Builds a provider adapter from a token resolver (+ optional fetch deps). */
|
|
20
|
+
export type ProviderFactory = (
|
|
21
|
+
getToken: () => Promise<string>,
|
|
22
|
+
deps?: FetchDeps,
|
|
23
|
+
) => MusicProvider;
|
|
24
|
+
|
|
25
|
+
/** The registered adapters — one per `Provider` (exhaustive by type). */
|
|
26
|
+
const REGISTRY: Record<Provider, ProviderFactory> = {
|
|
27
|
+
spotify: (getToken, deps) => new SpotifyProvider(getToken, undefined, deps),
|
|
28
|
+
apple: (getToken, deps) => new AppleProvider(getToken, undefined, deps),
|
|
29
|
+
// No-auth: ignore the token (User-Agent / public REST).
|
|
30
|
+
musicbrainz: (_getToken, deps) => new MusicBrainzProvider(undefined, deps),
|
|
31
|
+
deezer: (_getToken, deps) => new DeezerProvider(undefined, deps),
|
|
32
|
+
wikidata: (_getToken, deps) => new WikidataProvider(undefined, deps),
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Build the adapter for a provider.
|
|
37
|
+
*
|
|
38
|
+
* @param id - provider id.
|
|
39
|
+
* @param getToken - resolves a bearer token (ignored by no-auth providers).
|
|
40
|
+
* @param deps - injectable fetch/sleep/random (tests).
|
|
41
|
+
*/
|
|
42
|
+
export function createProvider(
|
|
43
|
+
id: Provider,
|
|
44
|
+
getToken: () => Promise<string>,
|
|
45
|
+
deps?: FetchDeps,
|
|
46
|
+
): MusicProvider {
|
|
47
|
+
return REGISTRY[id](getToken, deps);
|
|
48
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { ProviderHttpError, type FetchDeps } from "../fetch.js";
|
|
3
|
+
import { fetchSpotifyToken } from "./client.js";
|
|
4
|
+
|
|
5
|
+
function deps(response: Response, spy?: (init: RequestInit) => void): FetchDeps {
|
|
6
|
+
return {
|
|
7
|
+
fetch: (_url, init) => {
|
|
8
|
+
spy?.(init);
|
|
9
|
+
return Promise.resolve(response);
|
|
10
|
+
},
|
|
11
|
+
sleep: () => Promise.resolve(),
|
|
12
|
+
random: () => 0,
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
describe("fetchSpotifyToken", () => {
|
|
17
|
+
it("exchanges credentials and maps the token + lifetime", async () => {
|
|
18
|
+
let seen: RequestInit | undefined;
|
|
19
|
+
const token = await fetchSpotifyToken(
|
|
20
|
+
"id",
|
|
21
|
+
"secret",
|
|
22
|
+
undefined,
|
|
23
|
+
deps(
|
|
24
|
+
new Response(
|
|
25
|
+
JSON.stringify({
|
|
26
|
+
access_token: "tok-123",
|
|
27
|
+
token_type: "Bearer",
|
|
28
|
+
expires_in: 3600,
|
|
29
|
+
}),
|
|
30
|
+
{ status: 200, headers: { "content-type": "application/json" } },
|
|
31
|
+
),
|
|
32
|
+
(init) => {
|
|
33
|
+
seen = init;
|
|
34
|
+
},
|
|
35
|
+
),
|
|
36
|
+
);
|
|
37
|
+
expect(token).toEqual({ accessToken: "tok-123", expiresInSec: 3600 });
|
|
38
|
+
expect(seen?.method).toBe("POST");
|
|
39
|
+
expect(seen?.body).toBe("grant_type=client_credentials");
|
|
40
|
+
const headers = seen?.headers as Record<string, string>;
|
|
41
|
+
expect(headers["Authorization"]).toBe(`Basic ${btoa("id:secret")}`);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it("throws on invalid credentials (400)", async () => {
|
|
45
|
+
await expect(
|
|
46
|
+
fetchSpotifyToken(
|
|
47
|
+
"id",
|
|
48
|
+
"bad",
|
|
49
|
+
undefined,
|
|
50
|
+
deps(new Response("invalid_client", { status: 400 })),
|
|
51
|
+
),
|
|
52
|
+
).rejects.toThrow(ProviderHttpError);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("works against the default deps + global fetch", async () => {
|
|
56
|
+
vi.stubGlobal(
|
|
57
|
+
"fetch",
|
|
58
|
+
vi.fn(() =>
|
|
59
|
+
Promise.resolve(
|
|
60
|
+
new Response(
|
|
61
|
+
JSON.stringify({
|
|
62
|
+
access_token: "g",
|
|
63
|
+
token_type: "Bearer",
|
|
64
|
+
expires_in: 10,
|
|
65
|
+
}),
|
|
66
|
+
{ status: 200, headers: { "content-type": "application/json" } },
|
|
67
|
+
),
|
|
68
|
+
),
|
|
69
|
+
),
|
|
70
|
+
);
|
|
71
|
+
try {
|
|
72
|
+
expect(await fetchSpotifyToken("id", "secret")).toEqual({
|
|
73
|
+
accessToken: "g",
|
|
74
|
+
expiresInSec: 10,
|
|
75
|
+
});
|
|
76
|
+
} finally {
|
|
77
|
+
vi.unstubAllGlobals();
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
});
|