@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.
Files changed (301) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +169 -0
  3. package/dist/client/index.d.ts +284 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +166 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +100 -0
  8. package/dist/client/types.d.ts.map +1 -0
  9. package/dist/client/types.js +2 -0
  10. package/dist/client/types.js.map +1 -0
  11. package/dist/component/_generated/api.d.ts +125 -0
  12. package/dist/component/_generated/api.d.ts.map +1 -0
  13. package/dist/component/_generated/api.js +31 -0
  14. package/dist/component/_generated/api.js.map +1 -0
  15. package/dist/component/_generated/component.d.ts +1143 -0
  16. package/dist/component/_generated/component.d.ts.map +1 -0
  17. package/dist/component/_generated/component.js +11 -0
  18. package/dist/component/_generated/component.js.map +1 -0
  19. package/dist/component/_generated/dataModel.d.ts +46 -0
  20. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  21. package/dist/component/_generated/dataModel.js +11 -0
  22. package/dist/component/_generated/dataModel.js.map +1 -0
  23. package/dist/component/_generated/server.d.ts +133 -0
  24. package/dist/component/_generated/server.d.ts.map +1 -0
  25. package/dist/component/_generated/server.js +80 -0
  26. package/dist/component/_generated/server.js.map +1 -0
  27. package/dist/component/actions.d.ts +144 -0
  28. package/dist/component/actions.d.ts.map +1 -0
  29. package/dist/component/actions.js +125 -0
  30. package/dist/component/actions.js.map +1 -0
  31. package/dist/component/catalog/browse_order.d.ts +22 -0
  32. package/dist/component/catalog/browse_order.d.ts.map +1 -0
  33. package/dist/component/catalog/browse_order.js +37 -0
  34. package/dist/component/catalog/browse_order.js.map +1 -0
  35. package/dist/component/catalog/field_source_policy.d.ts +30 -0
  36. package/dist/component/catalog/field_source_policy.d.ts.map +1 -0
  37. package/dist/component/catalog/field_source_policy.js +36 -0
  38. package/dist/component/catalog/field_source_policy.js.map +1 -0
  39. package/dist/component/catalog/merge.d.ts +58 -0
  40. package/dist/component/catalog/merge.d.ts.map +1 -0
  41. package/dist/component/catalog/merge.js +74 -0
  42. package/dist/component/catalog/merge.js.map +1 -0
  43. package/dist/component/catalog/mutations.d.ts +78 -0
  44. package/dist/component/catalog/mutations.d.ts.map +1 -0
  45. package/dist/component/catalog/mutations.js +259 -0
  46. package/dist/component/catalog/mutations.js.map +1 -0
  47. package/dist/component/catalog/promote.d.ts +21 -0
  48. package/dist/component/catalog/promote.d.ts.map +1 -0
  49. package/dist/component/catalog/promote.js +25 -0
  50. package/dist/component/catalog/promote.js.map +1 -0
  51. package/dist/component/catalog/queries.d.ts +421 -0
  52. package/dist/component/catalog/queries.d.ts.map +1 -0
  53. package/dist/component/catalog/queries.js +168 -0
  54. package/dist/component/catalog/queries.js.map +1 -0
  55. package/dist/component/config/mutations.d.ts +11 -0
  56. package/dist/component/config/mutations.d.ts.map +1 -0
  57. package/dist/component/config/mutations.js +30 -0
  58. package/dist/component/config/mutations.js.map +1 -0
  59. package/dist/component/config/queries.d.ts +9 -0
  60. package/dist/component/config/queries.d.ts.map +1 -0
  61. package/dist/component/config/queries.js +20 -0
  62. package/dist/component/config/queries.js.map +1 -0
  63. package/dist/component/convex.config.d.ts +3 -0
  64. package/dist/component/convex.config.d.ts.map +1 -0
  65. package/dist/component/convex.config.js +30 -0
  66. package/dist/component/convex.config.js.map +1 -0
  67. package/dist/component/crons.d.ts +11 -0
  68. package/dist/component/crons.d.ts.map +1 -0
  69. package/dist/component/crons.js +41 -0
  70. package/dist/component/crons.js.map +1 -0
  71. package/dist/component/imports/actions.d.ts +119 -0
  72. package/dist/component/imports/actions.d.ts.map +1 -0
  73. package/dist/component/imports/actions.js +442 -0
  74. package/dist/component/imports/actions.js.map +1 -0
  75. package/dist/component/imports/dedupe.d.ts +29 -0
  76. package/dist/component/imports/dedupe.d.ts.map +1 -0
  77. package/dist/component/imports/dedupe.js +33 -0
  78. package/dist/component/imports/dedupe.js.map +1 -0
  79. package/dist/component/imports/mutations.d.ts +59 -0
  80. package/dist/component/imports/mutations.d.ts.map +1 -0
  81. package/dist/component/imports/mutations.js +151 -0
  82. package/dist/component/imports/mutations.js.map +1 -0
  83. package/dist/component/imports/queries.d.ts +68 -0
  84. package/dist/component/imports/queries.d.ts.map +1 -0
  85. package/dist/component/imports/queries.js +22 -0
  86. package/dist/component/imports/queries.js.map +1 -0
  87. package/dist/component/imports/state.d.ts +36 -0
  88. package/dist/component/imports/state.d.ts.map +1 -0
  89. package/dist/component/imports/state.js +62 -0
  90. package/dist/component/imports/state.js.map +1 -0
  91. package/dist/component/mutations.d.ts +55 -0
  92. package/dist/component/mutations.d.ts.map +1 -0
  93. package/dist/component/mutations.js +74 -0
  94. package/dist/component/mutations.js.map +1 -0
  95. package/dist/component/providers/actions.d.ts +26 -0
  96. package/dist/component/providers/actions.d.ts.map +1 -0
  97. package/dist/component/providers/actions.js +92 -0
  98. package/dist/component/providers/actions.js.map +1 -0
  99. package/dist/component/providers/apple/impl.d.ts +52 -0
  100. package/dist/component/providers/apple/impl.d.ts.map +1 -0
  101. package/dist/component/providers/apple/impl.js +127 -0
  102. package/dist/component/providers/apple/impl.js.map +1 -0
  103. package/dist/component/providers/apple/jwt.d.ts +32 -0
  104. package/dist/component/providers/apple/jwt.d.ts.map +1 -0
  105. package/dist/component/providers/apple/jwt.js +68 -0
  106. package/dist/component/providers/apple/jwt.js.map +1 -0
  107. package/dist/component/providers/apple/mappers.d.ts +20 -0
  108. package/dist/component/providers/apple/mappers.d.ts.map +1 -0
  109. package/dist/component/providers/apple/mappers.js +68 -0
  110. package/dist/component/providers/apple/mappers.js.map +1 -0
  111. package/dist/component/providers/apple/types.d.ts +80 -0
  112. package/dist/component/providers/apple/types.d.ts.map +1 -0
  113. package/dist/component/providers/apple/types.js +7 -0
  114. package/dist/component/providers/apple/types.js.map +1 -0
  115. package/dist/component/providers/deezer/impl.d.ts +37 -0
  116. package/dist/component/providers/deezer/impl.d.ts.map +1 -0
  117. package/dist/component/providers/deezer/impl.js +99 -0
  118. package/dist/component/providers/deezer/impl.js.map +1 -0
  119. package/dist/component/providers/deezer/mappers.d.ts +18 -0
  120. package/dist/component/providers/deezer/mappers.d.ts.map +1 -0
  121. package/dist/component/providers/deezer/mappers.js +53 -0
  122. package/dist/component/providers/deezer/mappers.js.map +1 -0
  123. package/dist/component/providers/deezer/types.d.ts +59 -0
  124. package/dist/component/providers/deezer/types.d.ts.map +1 -0
  125. package/dist/component/providers/deezer/types.js +7 -0
  126. package/dist/component/providers/deezer/types.js.map +1 -0
  127. package/dist/component/providers/fetch.d.ts +69 -0
  128. package/dist/component/providers/fetch.d.ts.map +1 -0
  129. package/dist/component/providers/fetch.js +145 -0
  130. package/dist/component/providers/fetch.js.map +1 -0
  131. package/dist/component/providers/musicbrainz/impl.d.ts +36 -0
  132. package/dist/component/providers/musicbrainz/impl.d.ts.map +1 -0
  133. package/dist/component/providers/musicbrainz/impl.js +74 -0
  134. package/dist/component/providers/musicbrainz/impl.js.map +1 -0
  135. package/dist/component/providers/musicbrainz/mappers.d.ts +10 -0
  136. package/dist/component/providers/musicbrainz/mappers.d.ts.map +1 -0
  137. package/dist/component/providers/musicbrainz/mappers.js +32 -0
  138. package/dist/component/providers/musicbrainz/mappers.js.map +1 -0
  139. package/dist/component/providers/musicbrainz/types.d.ts +24 -0
  140. package/dist/component/providers/musicbrainz/types.d.ts.map +1 -0
  141. package/dist/component/providers/musicbrainz/types.js +7 -0
  142. package/dist/component/providers/musicbrainz/types.js.map +1 -0
  143. package/dist/component/providers/registry.d.ts +22 -0
  144. package/dist/component/providers/registry.d.ts.map +1 -0
  145. package/dist/component/providers/registry.js +33 -0
  146. package/dist/component/providers/registry.js.map +1 -0
  147. package/dist/component/providers/spotify/client.d.ts +25 -0
  148. package/dist/component/providers/spotify/client.d.ts.map +1 -0
  149. package/dist/component/providers/spotify/client.js +30 -0
  150. package/dist/component/providers/spotify/client.js.map +1 -0
  151. package/dist/component/providers/spotify/impl.d.ts +51 -0
  152. package/dist/component/providers/spotify/impl.d.ts.map +1 -0
  153. package/dist/component/providers/spotify/impl.js +131 -0
  154. package/dist/component/providers/spotify/impl.js.map +1 -0
  155. package/dist/component/providers/spotify/mappers.d.ts +18 -0
  156. package/dist/component/providers/spotify/mappers.d.ts.map +1 -0
  157. package/dist/component/providers/spotify/mappers.js +60 -0
  158. package/dist/component/providers/spotify/mappers.js.map +1 -0
  159. package/dist/component/providers/spotify/types.d.ts +97 -0
  160. package/dist/component/providers/spotify/types.d.ts.map +1 -0
  161. package/dist/component/providers/spotify/types.js +7 -0
  162. package/dist/component/providers/spotify/types.js.map +1 -0
  163. package/dist/component/providers/types.d.ts +84 -0
  164. package/dist/component/providers/types.d.ts.map +1 -0
  165. package/dist/component/providers/types.js +10 -0
  166. package/dist/component/providers/types.js.map +1 -0
  167. package/dist/component/providers/wikidata/impl.d.ts +34 -0
  168. package/dist/component/providers/wikidata/impl.d.ts.map +1 -0
  169. package/dist/component/providers/wikidata/impl.js +88 -0
  170. package/dist/component/providers/wikidata/impl.js.map +1 -0
  171. package/dist/component/providers/wikidata/mappers.d.ts +11 -0
  172. package/dist/component/providers/wikidata/mappers.d.ts.map +1 -0
  173. package/dist/component/providers/wikidata/mappers.js +53 -0
  174. package/dist/component/providers/wikidata/mappers.js.map +1 -0
  175. package/dist/component/providers/wikidata/types.d.ts +35 -0
  176. package/dist/component/providers/wikidata/types.d.ts.map +1 -0
  177. package/dist/component/providers/wikidata/types.js +8 -0
  178. package/dist/component/providers/wikidata/types.js.map +1 -0
  179. package/dist/component/queries.d.ts +103 -0
  180. package/dist/component/queries.d.ts.map +1 -0
  181. package/dist/component/queries.js +45 -0
  182. package/dist/component/queries.js.map +1 -0
  183. package/dist/component/schema.d.ts +566 -0
  184. package/dist/component/schema.d.ts.map +1 -0
  185. package/dist/component/schema.js +59 -0
  186. package/dist/component/schema.js.map +1 -0
  187. package/dist/component/sources/actions.d.ts +51 -0
  188. package/dist/component/sources/actions.d.ts.map +1 -0
  189. package/dist/component/sources/actions.js +164 -0
  190. package/dist/component/sources/actions.js.map +1 -0
  191. package/dist/component/sources/mutations.d.ts +25 -0
  192. package/dist/component/sources/mutations.d.ts.map +1 -0
  193. package/dist/component/sources/mutations.js +64 -0
  194. package/dist/component/sources/mutations.js.map +1 -0
  195. package/dist/component/sources/queries.d.ts +19 -0
  196. package/dist/component/sources/queries.d.ts.map +1 -0
  197. package/dist/component/sources/queries.js +20 -0
  198. package/dist/component/sources/queries.js.map +1 -0
  199. package/dist/component/sync/lifecycle.d.ts +46 -0
  200. package/dist/component/sync/lifecycle.d.ts.map +1 -0
  201. package/dist/component/sync/lifecycle.js +87 -0
  202. package/dist/component/sync/lifecycle.js.map +1 -0
  203. package/dist/component/sync/mutations.d.ts +101 -0
  204. package/dist/component/sync/mutations.d.ts.map +1 -0
  205. package/dist/component/sync/mutations.js +132 -0
  206. package/dist/component/sync/mutations.js.map +1 -0
  207. package/dist/component/sync/queries.d.ts +69 -0
  208. package/dist/component/sync/queries.d.ts.map +1 -0
  209. package/dist/component/sync/queries.js +32 -0
  210. package/dist/component/sync/queries.js.map +1 -0
  211. package/dist/component/validators.d.ts +1112 -0
  212. package/dist/component/validators.d.ts.map +1 -0
  213. package/dist/component/validators.js +317 -0
  214. package/dist/component/validators.js.map +1 -0
  215. package/dist/react/index.d.ts +42 -0
  216. package/dist/react/index.d.ts.map +1 -0
  217. package/dist/react/index.js +43 -0
  218. package/dist/react/index.js.map +1 -0
  219. package/dist/shared.d.ts +28 -0
  220. package/dist/shared.d.ts.map +1 -0
  221. package/dist/shared.js +24 -0
  222. package/dist/shared.js.map +1 -0
  223. package/package.json +126 -0
  224. package/src/client/index.ts +558 -0
  225. package/src/client/types.ts +117 -0
  226. package/src/component/_generated/api.ts +141 -0
  227. package/src/component/_generated/component.ts +1814 -0
  228. package/src/component/_generated/dataModel.ts +60 -0
  229. package/src/component/_generated/server.ts +169 -0
  230. package/src/component/actions.ts +156 -0
  231. package/src/component/catalog/browse_order.test.ts +55 -0
  232. package/src/component/catalog/browse_order.ts +43 -0
  233. package/src/component/catalog/field_source_policy.test.ts +47 -0
  234. package/src/component/catalog/field_source_policy.ts +44 -0
  235. package/src/component/catalog/merge.test.ts +187 -0
  236. package/src/component/catalog/merge.ts +134 -0
  237. package/src/component/catalog/mutations.ts +328 -0
  238. package/src/component/catalog/promote.ts +40 -0
  239. package/src/component/catalog/queries.ts +220 -0
  240. package/src/component/config/mutations.ts +29 -0
  241. package/src/component/config/queries.ts +20 -0
  242. package/src/component/convex.config.ts +32 -0
  243. package/src/component/crons.test.ts +8 -0
  244. package/src/component/crons.ts +52 -0
  245. package/src/component/imports/actions.ts +553 -0
  246. package/src/component/imports/dedupe.test.ts +66 -0
  247. package/src/component/imports/dedupe.ts +54 -0
  248. package/src/component/imports/mutations.ts +203 -0
  249. package/src/component/imports/queries.ts +25 -0
  250. package/src/component/imports/state.test.ts +60 -0
  251. package/src/component/imports/state.ts +74 -0
  252. package/src/component/mutations.ts +96 -0
  253. package/src/component/providers/actions.ts +127 -0
  254. package/src/component/providers/apple/impl.test.ts +267 -0
  255. package/src/component/providers/apple/impl.ts +224 -0
  256. package/src/component/providers/apple/jwt.test.ts +153 -0
  257. package/src/component/providers/apple/jwt.ts +99 -0
  258. package/src/component/providers/apple/mappers.test.ts +190 -0
  259. package/src/component/providers/apple/mappers.ts +100 -0
  260. package/src/component/providers/apple/types.ts +77 -0
  261. package/src/component/providers/deezer/impl.test.ts +109 -0
  262. package/src/component/providers/deezer/impl.ts +179 -0
  263. package/src/component/providers/deezer/mappers.test.ts +78 -0
  264. package/src/component/providers/deezer/mappers.ts +72 -0
  265. package/src/component/providers/deezer/types.ts +59 -0
  266. package/src/component/providers/fetch.test.ts +282 -0
  267. package/src/component/providers/fetch.ts +190 -0
  268. package/src/component/providers/musicbrainz/impl.test.ts +79 -0
  269. package/src/component/providers/musicbrainz/impl.ts +132 -0
  270. package/src/component/providers/musicbrainz/mappers.test.ts +75 -0
  271. package/src/component/providers/musicbrainz/mappers.ts +34 -0
  272. package/src/component/providers/musicbrainz/types.ts +20 -0
  273. package/src/component/providers/registry.test.ts +14 -0
  274. package/src/component/providers/registry.ts +48 -0
  275. package/src/component/providers/spotify/client.test.ts +80 -0
  276. package/src/component/providers/spotify/client.ts +57 -0
  277. package/src/component/providers/spotify/impl.test.ts +311 -0
  278. package/src/component/providers/spotify/impl.ts +230 -0
  279. package/src/component/providers/spotify/mappers.test.ts +182 -0
  280. package/src/component/providers/spotify/mappers.ts +81 -0
  281. package/src/component/providers/spotify/types.ts +101 -0
  282. package/src/component/providers/types.ts +95 -0
  283. package/src/component/providers/wikidata/impl.test.ts +81 -0
  284. package/src/component/providers/wikidata/impl.ts +139 -0
  285. package/src/component/providers/wikidata/mappers.test.ts +62 -0
  286. package/src/component/providers/wikidata/mappers.ts +66 -0
  287. package/src/component/providers/wikidata/types.ts +28 -0
  288. package/src/component/queries.ts +51 -0
  289. package/src/component/schema.ts +81 -0
  290. package/src/component/sources/actions.ts +177 -0
  291. package/src/component/sources/mutations.ts +67 -0
  292. package/src/component/sources/queries.ts +21 -0
  293. package/src/component/sync/lifecycle.test.ts +72 -0
  294. package/src/component/sync/lifecycle.ts +121 -0
  295. package/src/component/sync/mutations.ts +154 -0
  296. package/src/component/sync/queries.ts +33 -0
  297. package/src/component/validators.ts +411 -0
  298. package/src/react/index.test.ts +78 -0
  299. package/src/react/index.ts +112 -0
  300. package/src/shared.ts +32 -0
  301. package/src/test.ts +22 -0
@@ -0,0 +1,62 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { mapWikidataArtist } from "./mappers.js";
3
+ import type { WikidataSnakValue } from "./types.js";
4
+
5
+ const claim = (value: WikidataSnakValue) => [
6
+ { mainsnak: { datavalue: { value } } },
7
+ ];
8
+
9
+ describe("mapWikidataArtist", () => {
10
+ it("maps a solo female with debut year", () => {
11
+ expect(
12
+ mapWikidataArtist({
13
+ labels: { en: { value: "Beyoncé" } },
14
+ claims: {
15
+ P21: claim({ id: "Q6581072" }),
16
+ P31: claim({ id: "Q5" }),
17
+ P571: claim({ time: "+1981-09-04T00:00:00Z" }),
18
+ },
19
+ }),
20
+ ).toEqual({
21
+ name: "Beyoncé",
22
+ genres: [],
23
+ gender: "Female",
24
+ members: "solo",
25
+ debutYear: 1981,
26
+ });
27
+ });
28
+
29
+ it("maps a group (P31 band) with male unknown-mapped gender omitted", () => {
30
+ expect(
31
+ mapWikidataArtist({
32
+ labels: { en: { value: "Daft Punk" } },
33
+ claims: {
34
+ P31: claim({ id: "Q215380" }),
35
+ P21: claim({ id: "Q999999" }),
36
+ },
37
+ }),
38
+ ).toMatchObject({ name: "Daft Punk", members: "group", gender: undefined });
39
+ });
40
+
41
+ it("omits everything when claims/label are absent", () => {
42
+ expect(mapWikidataArtist({})).toEqual({
43
+ name: "",
44
+ genres: [],
45
+ gender: undefined,
46
+ members: undefined,
47
+ debutYear: undefined,
48
+ });
49
+ });
50
+
51
+ it("ignores claims with no datavalue + unparsable dates", () => {
52
+ expect(
53
+ mapWikidataArtist({
54
+ labels: { en: { value: "X" } },
55
+ claims: {
56
+ P31: [{ mainsnak: {} }],
57
+ P571: claim({ time: "unknown" }),
58
+ },
59
+ }),
60
+ ).toMatchObject({ members: undefined, debutYear: undefined });
61
+ });
62
+ });
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Map raw Wikidata entities to the normalized artist schema. Wikidata claims
3
+ * reference other entities by Q-id; we resolve the small, stable sets that
4
+ * matter for music facts (gender, person/group) and parse the inception date for
5
+ * debut year. Country is left to MusicBrainz (its Q-id needs a second lookup).
6
+ */
7
+
8
+ import type { NormalizedArtist } from "../../../client/types.js";
9
+ import type { WikidataClaim, WikidataEntity, WikidataSnakValue } from "./types.js";
10
+
11
+ /** Common gender Q-ids → label. */
12
+ const GENDER_BY_QID: Record<string, string> = {
13
+ Q6581072: "Female",
14
+ Q6581097: "Male",
15
+ };
16
+
17
+ /** P31 (instance-of) Q-ids that mark a group. */
18
+ const GROUP_QIDS = new Set(["Q215380", "Q2088357", "Q9212979"]);
19
+
20
+ /** P31 Q-id for a human (solo artist). */
21
+ const HUMAN_QID = "Q5";
22
+
23
+ /** First claim value for a property. */
24
+ function firstValue(
25
+ claims: Record<string, WikidataClaim[]> | undefined,
26
+ pid: string,
27
+ ): WikidataSnakValue | undefined {
28
+ return claims?.[pid]?.[0]?.mainsnak?.datavalue?.value;
29
+ }
30
+
31
+ /** All referenced entity Q-ids for a property. */
32
+ function entityIds(
33
+ claims: Record<string, WikidataClaim[]> | undefined,
34
+ pid: string,
35
+ ): string[] {
36
+ return (claims?.[pid] ?? [])
37
+ .map((claim) => claim.mainsnak?.datavalue?.value?.id)
38
+ .filter((id): id is string => id !== undefined);
39
+ }
40
+
41
+ /** Parse a 4-digit year from a Wikidata time literal (`+1993-00-00T…`). */
42
+ function parseYear(time: string | undefined): number | undefined {
43
+ if (time === undefined) return undefined;
44
+ const match = time.match(/(\d{4})/);
45
+ return match === null ? undefined : Number(match[1]);
46
+ }
47
+
48
+ /** Solo/group from the instance-of (P31) entities. */
49
+ function membersOf(instanceIds: string[]): "solo" | "group" | undefined {
50
+ if (instanceIds.includes(HUMAN_QID)) return "solo";
51
+ if (instanceIds.some((id) => GROUP_QIDS.has(id))) return "group";
52
+ return undefined;
53
+ }
54
+
55
+ /** Wikidata entity → normalized artist (facts only). */
56
+ export function mapWikidataArtist(entity: WikidataEntity): NormalizedArtist {
57
+ const claims = entity.claims;
58
+ const genderId = firstValue(claims, "P21")?.id;
59
+ return {
60
+ name: entity.labels?.en?.value ?? "",
61
+ genres: [],
62
+ gender: genderId === undefined ? undefined : GENDER_BY_QID[genderId],
63
+ members: membersOf(entityIds(claims, "P31")),
64
+ debutYear: parseYear(firstValue(claims, "P571")?.time),
65
+ };
66
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Raw Wikidata API shapes — private to the adapter. Wikidata is a no-auth,
3
+ * facts-only provider (an alternative source the field-source policy can prefer
4
+ * over MusicBrainz per field). Claim values are either a referenced entity
5
+ * (`{ id }`) or a time (`{ time }`); only consumed fields are modeled.
6
+ */
7
+
8
+ export interface WikidataSnakValue {
9
+ id?: string;
10
+ time?: string;
11
+ }
12
+
13
+ export interface WikidataClaim {
14
+ mainsnak?: { datavalue?: { value?: WikidataSnakValue } };
15
+ }
16
+
17
+ export interface WikidataEntity {
18
+ labels?: { en?: { value: string } };
19
+ claims?: Record<string, WikidataClaim[]>;
20
+ }
21
+
22
+ export interface WikidataEntitiesResponse {
23
+ entities?: Record<string, WikidataEntity>;
24
+ }
25
+
26
+ export interface WikidataSearchResponse {
27
+ search?: Array<{ id: string; label?: string }>;
28
+ }
@@ -0,0 +1,51 @@
1
+ import { v } from "convex/values";
2
+ import { query } from "./_generated/server.js";
3
+ import type { Doc } from "./_generated/dataModel.js";
4
+ import { cacheEntryDoc, entityKind, provider } from "./validators.js";
5
+
6
+ /** An entry is fresh while its expiry is still in the future. */
7
+ function isFresh(entry: Doc<"cacheEntries">, now: number): boolean {
8
+ return entry.expiresAt > now;
9
+ }
10
+
11
+ /** Fetch one cached entry by its provider key, or null if missing/expired. */
12
+ export const get = query({
13
+ args: { kind: entityKind, provider, externalId: v.string() },
14
+ returns: v.union(v.null(), cacheEntryDoc),
15
+ handler: async (ctx, args) => {
16
+ const entry = await ctx.db
17
+ .query("cacheEntries")
18
+ .withIndex("by_lookup", (q) =>
19
+ q
20
+ .eq("kind", args.kind)
21
+ .eq("provider", args.provider)
22
+ .eq("externalId", args.externalId),
23
+ )
24
+ .unique();
25
+ return entry !== null && isFresh(entry, Date.now()) ? entry : null;
26
+ },
27
+ });
28
+
29
+ /** Every fresh cached track for an ISRC, across providers. */
30
+ export const getByIsrc = query({
31
+ args: { isrc: v.string() },
32
+ returns: v.array(cacheEntryDoc),
33
+ handler: async (ctx, args) => {
34
+ const now = Date.now();
35
+ const entries = await ctx.db
36
+ .query("cacheEntries")
37
+ .withIndex("by_isrc", (q) => q.eq("kind", "track").eq("isrc", args.isrc))
38
+ .collect();
39
+ return entries.filter((entry) => isFresh(entry, now));
40
+ },
41
+ });
42
+
43
+ /** Count of cached entries (fresh + expired). */
44
+ export const stats = query({
45
+ args: {},
46
+ returns: v.object({ total: v.number() }),
47
+ handler: async (ctx) => {
48
+ const all = await ctx.db.query("cacheEntries").collect();
49
+ return { total: all.length };
50
+ },
51
+ });
@@ -0,0 +1,81 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import {
3
+ albumFields,
4
+ artistFields,
5
+ artistProviderLinkFields,
6
+ cacheEntryFields,
7
+ importRequestFields,
8
+ playlistFields,
9
+ providerConfigFields,
10
+ sourceFields,
11
+ trackClaimFields,
12
+ trackFields,
13
+ trackProviderLinkFields,
14
+ } from "./validators.js";
15
+
16
+ /**
17
+ * Sandboxed tables — the component's own concern only. Two layers:
18
+ * - `cacheEntries`: the raw provider-fetch cache (one provider's normalized facts
19
+ * per entity, TTL'd, keyed by provider id + ISRC for tracks).
20
+ * - `artists` / `tracks` / `playlists` / `albums`: the durable catalog — one
21
+ * unified canonical entity per identity (track by ISRC, artist by name,
22
+ * playlist + album by source-provider id) with per-provider `providers[]`
23
+ * provenance (artists/tracks) + sync/repair lifecycle columns. `*Providers` are
24
+ * reverse indexes (`(provider, providerId)` → row) since Convex can't index
25
+ * inside arrays. `trackClaims` guards concurrent track syncs.
26
+ *
27
+ * The component never reaches the host's tables; the host keeps gameplay +
28
+ * editorial, referencing catalog rows by id / ISRC.
29
+ */
30
+ export default defineSchema({
31
+ cacheEntries: defineTable(cacheEntryFields)
32
+ .index("by_lookup", ["kind", "provider", "externalId"])
33
+ .index("by_isrc", ["kind", "isrc"])
34
+ .index("by_expiry", ["expiresAt"]),
35
+
36
+ artists: defineTable(artistFields)
37
+ .index("by_name_key", ["nameKey"])
38
+ .index("by_sync", ["syncStatus", "nextSyncAt"])
39
+ .index("by_next_sync", ["nextSyncAt"])
40
+ .index("by_repair", ["repairStatus"])
41
+ .searchIndex("search_name", { searchField: "name" }),
42
+
43
+ tracks: defineTable(trackFields)
44
+ .index("by_isrc", ["isrc"])
45
+ .index("by_sync", ["syncStatus", "nextSyncAt"])
46
+ .index("by_next_sync", ["nextSyncAt"])
47
+ .index("by_repair", ["repairStatus"])
48
+ .searchIndex("search_title", { searchField: "title" }),
49
+
50
+ playlists: defineTable(playlistFields)
51
+ .index("by_provider", ["provider", "providerId"])
52
+ .index("by_sync", ["syncStatus", "nextSyncAt"]),
53
+
54
+ albums: defineTable(albumFields)
55
+ .index("by_provider", ["provider", "providerId"])
56
+ .index("by_sync", ["syncStatus", "nextSyncAt"]),
57
+
58
+ artistProviders: defineTable(artistProviderLinkFields)
59
+ .index("by_provider_id", ["provider", "providerId"])
60
+ .index("by_artist", ["artistId"]),
61
+
62
+ trackProviders: defineTable(trackProviderLinkFields)
63
+ .index("by_provider_id", ["provider", "providerId"])
64
+ .index("by_track", ["trackId"]),
65
+
66
+ trackClaims: defineTable(trackClaimFields)
67
+ .index("by_isrc", ["isrc"])
68
+ .index("by_lease", ["leaseUntil"]),
69
+
70
+ providerConfig: defineTable(providerConfigFields).index("by_provider", [
71
+ "provider",
72
+ ]),
73
+
74
+ importRequests: defineTable(importRequestFields)
75
+ .index("by_status", ["status", "requestedAt"])
76
+ .index("by_dedupe_status", ["dedupeKey", "status"]),
77
+
78
+ sources: defineTable(sourceFields)
79
+ .index("by_enabled", ["enabled", "lastImportedAt"])
80
+ .index("by_kind", ["kind"]),
81
+ });
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Auto-import sweep. Imports the **due** enabled sources (never imported, or past
3
+ * their cadence) via the matching import entry point, bounded per run, stamping
4
+ * each source's `lastImportedAt`. Opt-in by construction: no enabled sources →
5
+ * no-op. (The rate-limiter throughput budget + stale-row refresh are follow-ups;
6
+ * this is the new-source pull.)
7
+ */
8
+
9
+ import { HOUR, RateLimiter } from "@convex-dev/rate-limiter";
10
+ import { v } from "convex/values";
11
+ import { api, components } from "../_generated/api.js";
12
+ import type { Doc } from "../_generated/dataModel.js";
13
+ import { type ActionCtx, action } from "../_generated/server.js";
14
+ import type { Provider } from "../../shared.js";
15
+
16
+ /**
17
+ * Auto-import throughput budgets — token buckets decoupled from cron frequency,
18
+ * separate for new-source import vs stale-row refresh. Default 60/hour each.
19
+ */
20
+ export const AUTO_IMPORT_RATE_PER_HOUR = 60;
21
+ const rateLimiter = new RateLimiter(components.rateLimiter, {
22
+ autoImport: { kind: "token bucket", rate: AUTO_IMPORT_RATE_PER_HOUR, period: HOUR },
23
+ refresh: { kind: "token bucket", rate: AUTO_IMPORT_RATE_PER_HOUR, period: HOUR },
24
+ });
25
+
26
+ /** Whether a source is due: never imported, or past its cadence (one-shot if no cadence). */
27
+ function isDue(source: Doc<"sources">, now: number): boolean {
28
+ if (source.lastImportedAt === undefined) return true;
29
+ if (source.cadenceMs === undefined) return false;
30
+ return now - source.lastImportedAt > source.cadenceMs;
31
+ }
32
+
33
+ /** Dispatch a source to its import entry point. */
34
+ async function importSource(
35
+ ctx: ActionCtx,
36
+ source: Doc<"sources">,
37
+ prov: Provider,
38
+ ): Promise<void> {
39
+ if (source.kind === "artist") {
40
+ await ctx.runAction(api.imports.actions.importArtist, {
41
+ provider: prov,
42
+ targetMode: source.by === "name" ? "name" : "providerId",
43
+ name: source.by === "name" ? source.value : undefined,
44
+ providerId: source.by === "name" ? undefined : source.value,
45
+ withTracks: source.withTracks,
46
+ });
47
+ } else if (source.kind === "track") {
48
+ await ctx.runAction(api.imports.actions.importTrack, {
49
+ provider: prov,
50
+ providerId: source.value,
51
+ });
52
+ } else {
53
+ await ctx.runAction(api.imports.actions.importPlaylist, {
54
+ provider: prov,
55
+ providerId: source.value,
56
+ });
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Run the refresh sweep: re-import up to `limit` stale catalog rows of a kind
62
+ * from each provider already on their record (mode `refresh`), bringing them
63
+ * back to `synced`. The freshness mechanism `markStale` flips rows to `stale`;
64
+ * this re-syncs them. Opt-in by construction (no stale rows → no-op).
65
+ *
66
+ * `refreshed` counts rows claimed + dispatched, not necessarily re-synced: a row
67
+ * whose providers all fail stays `running` (the imports record their own failure
68
+ * but don't throw) until `recoverStuckSyncs` salvages it back to `stale` after the
69
+ * lease — the lease doubles as the retry backoff. A persistently-failing row thus
70
+ * retries slowly (lease-paced, rate-limited), never hot-loops.
71
+ */
72
+ export const runRefresh = action({
73
+ args: {
74
+ kind: v.union(v.literal("artist"), v.literal("track")),
75
+ limit: v.optional(v.number()),
76
+ },
77
+ returns: v.object({ refreshed: v.number() }),
78
+ handler: async (ctx, args): Promise<{ refreshed: number }> => {
79
+ const limit = args.limit ?? 10;
80
+ let refreshed = 0;
81
+ for (let i = 0; i < limit; i++) {
82
+ // Separate refresh budget (distinct from the new-source import budget).
83
+ const { ok } = await rateLimiter.limit(ctx, "refresh");
84
+ if (!ok) break;
85
+ // Atomically claim the next stale row as `running` in one mutation, so two
86
+ // overlapping sweeps can't both refresh it. `null` => nothing left stale.
87
+ // The re-import's upsert returns it to `synced`; `recoverStuckSyncs`
88
+ // salvages a lease whose holder crashed.
89
+ const row = await ctx.runMutation(api.sync.mutations.claimNextStale, {
90
+ kind: args.kind,
91
+ });
92
+ if (row === null) break;
93
+ const providers: ReadonlyArray<{ provider: Provider; providerId: string }> =
94
+ row.providers;
95
+ if (args.kind === "artist") {
96
+ await Promise.all(
97
+ providers.map((prov) =>
98
+ ctx.runAction(api.imports.actions.importArtist, {
99
+ provider: prov.provider,
100
+ targetMode: "providerId",
101
+ providerId: prov.providerId,
102
+ mode: "refresh",
103
+ }),
104
+ ),
105
+ );
106
+ } else {
107
+ await Promise.all(
108
+ providers.map((prov) =>
109
+ ctx.runAction(api.imports.actions.importTrack, {
110
+ provider: prov.provider,
111
+ providerId: prov.providerId,
112
+ mode: "refresh",
113
+ }),
114
+ ),
115
+ );
116
+ }
117
+ refreshed += 1;
118
+ }
119
+ return { refreshed };
120
+ },
121
+ });
122
+
123
+ /**
124
+ * Run the auto-import sweep: import up to `limit` due enabled sources, stamping
125
+ * each. Sources with no provider are skipped. Returns `{ imported, skipped }`.
126
+ */
127
+ export const runAutoImport = action({
128
+ args: { limit: v.optional(v.number()), now: v.optional(v.number()) },
129
+ returns: v.object({ imported: v.number(), skipped: v.number() }),
130
+ handler: async (ctx, args): Promise<{ imported: number; skipped: number }> => {
131
+ const now = args.now ?? Date.now();
132
+ const limit = args.limit ?? 10;
133
+ const sources = await ctx.runQuery(api.sources.queries.listSources, {
134
+ enabledOnly: true,
135
+ limit: 100,
136
+ });
137
+ const due = sources.filter((source) => isDue(source, now)).slice(0, limit);
138
+ let imported = 0;
139
+ let skipped = 0;
140
+ for (const source of due) {
141
+ if (source.provider === undefined) {
142
+ skipped += 1;
143
+ continue;
144
+ }
145
+ // Throughput budget: stop the sweep when the token bucket is drained
146
+ // (decoupled from how often the cron fires).
147
+ const { ok } = await rateLimiter.limit(ctx, "autoImport");
148
+ if (!ok) break;
149
+ await importSource(ctx, source, source.provider);
150
+ await ctx.runMutation(api.sources.mutations.touchSource, {
151
+ sourceId: source._id,
152
+ now,
153
+ });
154
+ imported += 1;
155
+ }
156
+ return { imported, skipped };
157
+ },
158
+ });
159
+
160
+ /**
161
+ * Consume `count` tokens from a named throughput budget (`autoImport` or
162
+ * `refresh`) — for host-side pacing (reserve budget before a manual burst).
163
+ * Returns whether the budget allowed it.
164
+ */
165
+ export const consumeBudget = action({
166
+ args: {
167
+ budget: v.union(v.literal("autoImport"), v.literal("refresh")),
168
+ count: v.number(),
169
+ },
170
+ returns: v.boolean(),
171
+ handler: async (ctx, args): Promise<boolean> => {
172
+ const { ok } = await rateLimiter.limit(ctx, args.budget, {
173
+ count: args.count,
174
+ });
175
+ return ok;
176
+ },
177
+ });
@@ -0,0 +1,67 @@
1
+ import { v } from "convex/values";
2
+ import { mutation } from "../_generated/server.js";
3
+ import { importEntityType, importTargetMode, provider } from "../validators.js";
4
+
5
+ /** Register an import source the engine keeps synced. Enabled by default. */
6
+ export const addSource = mutation({
7
+ args: {
8
+ kind: importEntityType,
9
+ by: importTargetMode,
10
+ value: v.string(),
11
+ provider: v.optional(provider),
12
+ withTracks: v.optional(v.boolean()),
13
+ cadenceMs: v.optional(v.number()),
14
+ enabled: v.optional(v.boolean()),
15
+ },
16
+ returns: v.id("sources"),
17
+ handler: async (ctx, args) => {
18
+ const now = Date.now();
19
+ return await ctx.db.insert("sources", {
20
+ kind: args.kind,
21
+ by: args.by,
22
+ value: args.value,
23
+ provider: args.provider,
24
+ withTracks: args.withTracks,
25
+ cadenceMs: args.cadenceMs,
26
+ enabled: args.enabled ?? true,
27
+ createdAt: now,
28
+ updatedAt: now,
29
+ });
30
+ },
31
+ });
32
+
33
+ /** Remove a registered source. */
34
+ export const removeSource = mutation({
35
+ args: { sourceId: v.id("sources") },
36
+ returns: v.null(),
37
+ handler: async (ctx, args) => {
38
+ await ctx.db.delete("sources", args.sourceId);
39
+ return null;
40
+ },
41
+ });
42
+
43
+ /** Enable or disable a source (disabled sources are skipped by the sweep). */
44
+ export const setSourceEnabled = mutation({
45
+ args: { sourceId: v.id("sources"), enabled: v.boolean() },
46
+ returns: v.null(),
47
+ handler: async (ctx, args) => {
48
+ await ctx.db.patch("sources", args.sourceId, {
49
+ enabled: args.enabled,
50
+ updatedAt: Date.now(),
51
+ });
52
+ return null;
53
+ },
54
+ });
55
+
56
+ /** Stamp a source's `lastImportedAt` after the sweep imports it. */
57
+ export const touchSource = mutation({
58
+ args: { sourceId: v.id("sources"), now: v.number() },
59
+ returns: v.null(),
60
+ handler: async (ctx, args) => {
61
+ await ctx.db.patch("sources", args.sourceId, {
62
+ lastImportedAt: args.now,
63
+ updatedAt: args.now,
64
+ });
65
+ return null;
66
+ },
67
+ });
@@ -0,0 +1,21 @@
1
+ import { v } from "convex/values";
2
+ import { query } from "../_generated/server.js";
3
+ import { sourceDoc } from "../validators.js";
4
+
5
+ /** Default page size for a source listing. */
6
+ const DEFAULT_LIMIT = 100;
7
+
8
+ /** List registered sources — all, or only enabled ones. */
9
+ export const listSources = query({
10
+ args: { enabledOnly: v.optional(v.boolean()), limit: v.optional(v.number()) },
11
+ returns: v.array(sourceDoc),
12
+ handler: async (ctx, args) => {
13
+ if (args.enabledOnly === true) {
14
+ return await ctx.db
15
+ .query("sources")
16
+ .withIndex("by_enabled", (q) => q.eq("enabled", true))
17
+ .take(args.limit ?? DEFAULT_LIMIT);
18
+ }
19
+ return await ctx.db.query("sources").take(args.limit ?? DEFAULT_LIMIT);
20
+ },
21
+ });
@@ -0,0 +1,72 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ MAX_SYNC_RETRIES,
4
+ STALENESS_MS,
5
+ assertRepairTransition,
6
+ assertSyncTransition,
7
+ canRepairTransition,
8
+ canSyncTransition,
9
+ isStale,
10
+ shouldSyncRetry,
11
+ stalenessWindowMs,
12
+ syncRetryDelayMs,
13
+ } from "./lifecycle.js";
14
+
15
+ describe("sync transitions", () => {
16
+ it("allows + rejects", () => {
17
+ expect(canSyncTransition("pending", "running")).toBe(true);
18
+ expect(canSyncTransition("failed", "stale")).toBe(true);
19
+ // freshness can lapse from synced, and a crashed lease salvages running→stale
20
+ expect(canSyncTransition("synced", "stale")).toBe(true);
21
+ expect(canSyncTransition("running", "stale")).toBe(true);
22
+ expect(canSyncTransition("synced", "running")).toBe(false);
23
+ });
24
+ it("asserts", () => {
25
+ expect(() => assertSyncTransition("running", "synced")).not.toThrow();
26
+ expect(() => assertSyncTransition("synced", "running")).toThrow(
27
+ /Invalid sync transition/,
28
+ );
29
+ });
30
+ });
31
+
32
+ describe("repair transitions", () => {
33
+ it("allows + rejects", () => {
34
+ expect(canRepairTransition("clean", "needs_repair")).toBe(true);
35
+ expect(canRepairTransition("repairing", "clean")).toBe(true);
36
+ expect(canRepairTransition("failed_repair", "clean")).toBe(false);
37
+ });
38
+ it("asserts", () => {
39
+ expect(() => assertRepairTransition("needs_repair", "repairing")).not.toThrow();
40
+ expect(() => assertRepairTransition("clean", "repairing")).toThrow(
41
+ /Invalid repair transition/,
42
+ );
43
+ });
44
+ });
45
+
46
+ describe("sync retry", () => {
47
+ it("backs off 1h, 6h, 24h, then 24h", () => {
48
+ expect(syncRetryDelayMs(0)).toBe(60 * 60 * 1000);
49
+ expect(syncRetryDelayMs(1)).toBe(6 * 60 * 60 * 1000);
50
+ expect(syncRetryDelayMs(2)).toBe(24 * 60 * 60 * 1000);
51
+ expect(syncRetryDelayMs(5)).toBe(24 * 60 * 60 * 1000);
52
+ });
53
+ it("budgets retries", () => {
54
+ expect(shouldSyncRetry(0)).toBe(true);
55
+ expect(shouldSyncRetry(MAX_SYNC_RETRIES)).toBe(false);
56
+ });
57
+ });
58
+
59
+ describe("staleness by popularity", () => {
60
+ it("maps popularity tiers", () => {
61
+ expect(stalenessWindowMs(80)).toBe(STALENESS_MS.high);
62
+ expect(stalenessWindowMs(50)).toBe(STALENESS_MS.medium);
63
+ expect(stalenessWindowMs(10)).toBe(STALENESS_MS.low);
64
+ expect(stalenessWindowMs(undefined)).toBe(STALENESS_MS.low);
65
+ });
66
+ it("isStale honors the window + treats never-synced as stale", () => {
67
+ const now = 1_000_000_000_000;
68
+ expect(isStale(undefined, 80, now)).toBe(true);
69
+ expect(isStale(now - 1000, 80, now)).toBe(false);
70
+ expect(isStale(now - STALENESS_MS.high - 1, 80, now)).toBe(true);
71
+ });
72
+ });