@audiofool/moondog 0.4.0-beta.2 → 0.4.0-beta.4

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 (96) hide show
  1. package/README.md +19 -8
  2. package/package.json +1 -1
  3. package/scripts/moondog.mjs +130 -106
  4. package/src/core/apple-library-source-status.mjs +64 -18
  5. package/src/core/apple-projection-domain-services.mjs +67 -52
  6. package/src/core/capability-catalog.mjs +18 -2
  7. package/src/core/import-source-history.mjs +28 -0
  8. package/src/core/library-draft.mjs +16 -0
  9. package/src/core/library-names.mjs +12 -0
  10. package/src/core/library-store.mjs +361 -23
  11. package/src/core/listener-avoids.mjs +31 -0
  12. package/src/core/listening-action.mjs +41 -0
  13. package/src/core/listening-moment.mjs +67 -0
  14. package/src/core/listening-now.mjs +69 -28
  15. package/src/core/listening-profile-domain-services.mjs +32 -18
  16. package/src/core/listening-scope.mjs +119 -0
  17. package/src/core/moondog-application.mjs +1045 -270
  18. package/src/core/play-follower.mjs +104 -0
  19. package/src/core/portable-playlist.mjs +125 -0
  20. package/src/core/profile-discovery-draft.mjs +35 -0
  21. package/src/core/track-title.mjs +70 -4
  22. package/src/i18n/import-history.mjs +647 -0
  23. package/src/i18n/messages/de.mjs +3 -3
  24. package/src/i18n/messages/en.mjs +3 -3
  25. package/src/i18n/messages/es.mjs +3 -3
  26. package/src/i18n/messages/fr.mjs +3 -3
  27. package/src/i18n/messages/it.mjs +3 -3
  28. package/src/i18n/messages/ja.mjs +3 -3
  29. package/src/i18n/messages/ko.mjs +3 -3
  30. package/src/i18n/messages/pt.mjs +3 -3
  31. package/src/i18n/messages/zh-Hant.mjs +3 -3
  32. package/src/i18n/messages/zh.mjs +3 -3
  33. package/src/i18n/screen/es.mjs +90 -26
  34. package/src/i18n/screen/ja.mjs +89 -25
  35. package/src/i18n/screen/pt.mjs +90 -26
  36. package/src/i18n/screen/zh.mjs +89 -25
  37. package/src/importers/apple-music-library/import-batch.mjs +64 -32
  38. package/src/importers/apple-music-library/normalize.mjs +36 -6
  39. package/src/importers/apple-music-library/save-time.mjs +17 -0
  40. package/src/importers/zip-reader.mjs +24 -2
  41. package/src/integrations/apple-music/catalog-playlist-reader.mjs +111 -0
  42. package/src/integrations/apple-music/catalog.mjs +84 -25
  43. package/src/integrations/apple-music/music-app-listening.mjs +107 -0
  44. package/src/integrations/apple-music/music-app.mjs +6 -2
  45. package/src/integrations/apple-music/song-id.mjs +13 -0
  46. package/src/integrations/apple-music/terminal-preview-player.mjs +154 -44
  47. package/src/integrations/listenbrainz/history-file.mjs +63 -35
  48. package/src/integrations/netease/ncm-cli-player.mjs +355 -68
  49. package/src/integrations/netease/queue-occurrence.mjs +138 -0
  50. package/src/integrations/playlist-links.mjs +93 -30
  51. package/src/integrations/public-playlists.mjs +21 -15
  52. package/src/integrations/spotify/account-data-history.mjs +9 -10
  53. package/src/integrations/spotify/account-data-profile.mjs +1 -0
  54. package/src/integrations/spotify/extended-streaming-history.mjs +57 -52
  55. package/src/integrations/spotify/history-archive.mjs +8 -18
  56. package/src/integrations/spotify/library-snapshot.mjs +2 -1
  57. package/src/integrations/spotify/service.mjs +29 -11
  58. package/src/integrations/spotify/web-api-client.mjs +2 -2
  59. package/src/integrations/stable-audio/local-generator.mjs +13 -5
  60. package/src/integrations/youtube-music/takeout.mjs +12 -8
  61. package/src/memory/local-memory-store.mjs +479 -27
  62. package/src/memory/reflection-worker.mjs +19 -0
  63. package/src/profile/apple-library-import.mjs +56 -2
  64. package/src/profile/history-import.mjs +58 -27
  65. package/src/profile/listener-corrections.mjs +2 -4
  66. package/src/profile/listener-profile-build.mjs +133 -46
  67. package/src/profile/listener-profile-store.mjs +57 -4
  68. package/src/profile/listener-profile-verification.mjs +11 -5
  69. package/src/profile/listener-profile-worker.mjs +36 -10
  70. package/src/profile/listening-history-store.mjs +975 -354
  71. package/src/profile/listening-profile-projection.mjs +130 -160
  72. package/src/profile/local-file-import.mjs +172 -0
  73. package/src/profile/moondog-suggestions.mjs +40 -11
  74. package/src/profile/profile-exploration.mjs +36 -6
  75. package/src/profile/recorded-measures.mjs +5 -0
  76. package/src/profile/spotify-archive-taste.mjs +41 -65
  77. package/src/runtime/pi/agent-runtime.mjs +368 -221
  78. package/src/runtime/pi/custom-endpoints.mjs +30 -8
  79. package/src/runtime/pi/memory-agent-runtime.mjs +45 -3
  80. package/src/runtime/pi/moondog-model.mjs +6 -0
  81. package/src/runtime/pi/playback-rules.mjs +100 -0
  82. package/src/runtime/pi/profile-build-runtime.mjs +85 -24
  83. package/src/surfaces/cli/brand-components.mjs +9 -6
  84. package/src/surfaces/cli/command-completions.mjs +8 -1
  85. package/src/surfaces/cli/format-output.mjs +207 -34
  86. package/src/surfaces/cli/history-import-view.mjs +130 -21
  87. package/src/surfaces/cli/listenbrainz-command.mjs +7 -2
  88. package/src/surfaces/cli/listener-profile-command.mjs +67 -8
  89. package/src/surfaces/cli/listening-menu.mjs +3 -0
  90. package/src/surfaces/cli/profile-command.mjs +1 -0
  91. package/src/surfaces/cli/spotify-command.mjs +17 -25
  92. package/src/surfaces/cli/taste-period.mjs +22 -0
  93. package/src/surfaces/cli/taste-profile-model.mjs +52 -32
  94. package/src/surfaces/cli/tui.mjs +557 -170
  95. package/src/surfaces/html/tasteprint.mjs +181 -93
  96. package/src/surfaces/import-source-history.mjs +80 -0
@@ -0,0 +1,104 @@
1
+ // Follows the Music app's local listening and the desktop's Spotify plays from their player reads.
2
+ export const COUNTED_PLAY_MS = 30_000;
3
+ const HEARD_MS = 2_000;
4
+ const POSITION_SLACK_MS = 1_500;
5
+ const STOP_SLACK_MS = 2_000;
6
+ // The hidden window reads every 60 seconds. A longer interruption cannot establish a handoff.
7
+ const MAX_READ_GAP_MS = 65_000;
8
+ const RESTART_MS = 5_000;
9
+
10
+ const songKey = (song) => song.id ? `id:${song.id}` : `song:${song.title}\n${song.artists.join(", ")}\n${song.album ?? ""}`;
11
+
12
+ /**
13
+ * Each observed occurrence keeps the time it was first seen, the initial playhead when available,
14
+ * and the time actually supported by the player and clock. A stopped player or a changed song can
15
+ * show an end. Closing the observer only saves what it already heard.
16
+ */
17
+ export function createPlayFollower({ record }) {
18
+ let current = null;
19
+
20
+ function finish({ tail = null, observedEnd = true } = {}) {
21
+ const play = current;
22
+ current = null;
23
+ if (!play) return;
24
+ const playedMs = Math.round(Math.min(play.heard + play.runHeard + (tail ?? 0), play.duration ?? Infinity));
25
+ if (playedMs < HEARD_MS) return;
26
+ try {
27
+ record({ song: play.song, playlist: play.playlist, first_observed_at: play.firstAt, first_position_ms: play.firstPosition,
28
+ ended_at: tail > 0 ? play.at + tail : play.heardAt,
29
+ played_ms: playedMs, skipped: observedEnd && tail === null && playedMs < COUNTED_PLAY_MS, completed: tail !== null });
30
+ } catch { /* A play that can't be stored is let go; the next one tries again. */ }
31
+ }
32
+
33
+ // A new song's position tells how long ago it began. If that agrees with the previous
34
+ // song's remaining time, it corroborates a natural handoff between ordinary polls.
35
+ // Return the supported last milliseconds, zero for an observed stop, or null for no confirmed end.
36
+ function ending(at, nextPosition) {
37
+ const play = current;
38
+ const duration = play?.duration;
39
+ if (!play?.playing || play.position === null || duration === null) return null;
40
+ const elapsed = at - play.at;
41
+ if (elapsed < 0 || elapsed > MAX_READ_GAP_MS) return null;
42
+ const left = Math.max(0, duration - play.position);
43
+ const slack = Math.min(POSITION_SLACK_MS, duration / 10);
44
+ let tail = null;
45
+ if (nextPosition !== null) {
46
+ const beforeNext = elapsed - nextPosition;
47
+ if (beforeNext >= 0 && Math.abs(beforeNext - left) <= slack) tail = Math.min(beforeNext, left);
48
+ } else if (play.heard + play.runHeard >= HEARD_MS && left <= Math.min(10_000, duration / 10) && Math.abs(elapsed - left) <= STOP_SLACK_MS) {
49
+ // A stopped player has no successor timestamp. Keep only the directly observed duration.
50
+ tail = 0;
51
+ }
52
+ // After a seek or lost interval, require a counted play (or the short song) of reliable movement since it.
53
+ if (tail !== null && play.heardBeforeGap !== null &&
54
+ play.heard + play.runHeard + tail - play.heardBeforeGap < Math.min(COUNTED_PLAY_MS, duration - slack)) return null;
55
+ return tail;
56
+ }
57
+
58
+ function observe(answer, at) {
59
+ if (!Number.isFinite(at) || (current && at < current.at)) return;
60
+ const song = answer?.song;
61
+ if (!["playing", "paused"].includes(answer?.state) || !song?.title || !song.artists?.length) {
62
+ finish({ tail: answer?.state === "stopped" ? ending(at, null) : null,
63
+ observedEnd: ["stopped", "not_running"].includes(answer?.state) });
64
+ return;
65
+ }
66
+ const duration = Number.isSafeInteger(song.duration_ms) && song.duration_ms > 0 ? song.duration_ms : null;
67
+ const reported = Number.isFinite(answer.position_ms) && answer.position_ms >= 0 ? Math.round(answer.position_ms) : -1;
68
+ const position = Number.isSafeInteger(reported) && reported >= 0 && (duration === null || reported <= duration + POSITION_SLACK_MS)
69
+ ? Math.min(reported, duration ?? Infinity) : null;
70
+ const playing = answer.state === "playing";
71
+ const key = songKey(song);
72
+ if (current) {
73
+ const same = current.key === key;
74
+ const moved = position !== null && current.position !== null ? position - current.position : null;
75
+ const backwards = moved !== null && moved < -POSITION_SLACK_MS;
76
+ const tail = playing && position !== null && (!same || backwards) ? ending(at, position) : null;
77
+ const restarted = backwards && position < RESTART_MS && moved < -RESTART_MS;
78
+ if (!same || tail !== null || restarted) {
79
+ finish({ tail });
80
+ } else {
81
+ const elapsed = at - current.at;
82
+ const plausible = moved !== null && !backwards && moved <= elapsed + POSITION_SLACK_MS && elapsed <= MAX_READ_GAP_MS;
83
+ if (current.playing && plausible && position - current.runPosition <= at - current.runAt + POSITION_SLACK_MS) {
84
+ // Compare the whole uninterrupted stretch so integer-second rounding neither adds nor loses time on each read.
85
+ const supported = Math.min(position - current.runPosition, at - current.runAt);
86
+ if (supported > current.runHeard) {
87
+ current.runHeard = supported;
88
+ current.heardAt = at;
89
+ }
90
+ } else {
91
+ current.heard += current.runHeard;
92
+ if (current.playing || moved === null || Math.abs(moved) > POSITION_SLACK_MS) current.heardBeforeGap = current.heard;
93
+ Object.assign(current, { runHeard: 0, runAt: at, runPosition: position });
94
+ }
95
+ Object.assign(current, { at, position, playing });
96
+ return;
97
+ }
98
+ }
99
+ current = { key, song, duration, playlist: answer.playlist?.name ?? null, firstAt: at, firstPosition: position, at, position, playing,
100
+ heardAt: at, heard: 0, runHeard: 0, runAt: at, runPosition: position, heardBeforeGap: position === null ? 0 : null };
101
+ }
102
+
103
+ return { observe, finish: () => finish({ observedEnd: false }) };
104
+ }
@@ -0,0 +1,125 @@
1
+ import { createWriteStream } from "node:fs";
2
+ import { mkdir, open, rm, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { pipeline } from "node:stream/promises";
5
+ import { matchesLibrarySong } from "./track-title.mjs";
6
+
7
+ const oneLine = (value) => typeof value === "string"
8
+ ? value.toWellFormed().replace(/[\p{Cc}\p{Bidi_Control}\u2028\u2029]/gu, " ").replace(/\s+/gu, " ").trim()
9
+ : "";
10
+
11
+ // Both folder and audio names have a fixed prefix, including when a title is a Windows device name.
12
+ function fileLabel(title) {
13
+ const clean = oneLine(title).normalize("NFC").replace(/[<>:"/\\|?*#%]/gu, " ").replace(/\s+/gu, " ").trim();
14
+ let label = "";
15
+ for (const letter of clean) {
16
+ if (Buffer.byteLength(label + letter) > 120) break;
17
+ label += letter;
18
+ }
19
+ return label.replace(/[. ]+$/u, "") || "Untitled";
20
+ }
21
+
22
+ function catalogLinks(entry, storefront) {
23
+ const refs = entry.refs ?? {};
24
+ const links = {};
25
+ const spotify = typeof refs.spotify_uri === "string" && /^spotify:track:([a-zA-Z0-9]{22})$/u.exec(refs.spotify_uri);
26
+ if (spotify && (!(refs.spotify_title || refs.spotify_credit) ||
27
+ matchesLibrarySong(entry, refs.spotify_title || entry.title, [refs.spotify_credit || entry.artist_credit], true))) {
28
+ links.spotify = `https://open.spotify.com/track/${spotify[1]}`;
29
+ }
30
+ const numeric = (id) => typeof id === "string" && /^[1-9]\d{0,19}$/u.test(id);
31
+ if (numeric(refs.apple_music_id)) {
32
+ const region = typeof storefront === "string" && /^[a-z]{2}$/u.test(storefront) ? storefront + "/" : "";
33
+ links.apple_music = `https://music.apple.com/${region}song/${refs.apple_music_id}`;
34
+ }
35
+ if (numeric(refs.netease_id)) links.netease = `https://music.163.com/song?id=${refs.netease_id}`;
36
+ // QQ's public playlist can supply either a songmid or its older numeric songid.
37
+ const qq = refs.qq_music_id;
38
+ if (numeric(qq)) links.qq_music = `https://i.y.qq.com/v8/playsong.html?songid=${qq}`;
39
+ else if (typeof qq === "string" && /^[a-zA-Z0-9]{14}$/u.test(qq) && /[a-zA-Z]/u.test(qq)) {
40
+ links.qq_music = `https://y.qq.com/n/ryqq/songDetail/${qq}`;
41
+ }
42
+ return links;
43
+ }
44
+
45
+ async function copyAudio(source, destination, signal) {
46
+ if (!source) return false;
47
+ let input;
48
+ try { input = await open(source, "r"); }
49
+ catch (error) {
50
+ if (error.code === "ENOENT") return false; // Its audio was removed after the Library checked it.
51
+ throw error;
52
+ }
53
+ try {
54
+ await pipeline(input.createReadStream(), createWriteStream(destination, { flags: "wx", mode: 0o600 }), { signal });
55
+ return true;
56
+ } finally {
57
+ await input.close();
58
+ }
59
+ }
60
+
61
+ async function newExportFolder(directory, name, signal) {
62
+ const base = path.resolve(directory, `Moondog - ${fileLabel(name)}`);
63
+ for (let copy = 1; ; copy++) {
64
+ signal?.throwIfAborted();
65
+ const folder = copy === 1 ? base : `${base} (${copy})`;
66
+ try {
67
+ await mkdir(folder, { mode: 0o700 });
68
+ return folder;
69
+ } catch (error) {
70
+ if (error.code !== "EEXIST") throw error;
71
+ }
72
+ }
73
+ }
74
+
75
+ /** A movable folder containing the ordered playlist and the made tracks whose audio is still here. */
76
+ export async function writePortablePlaylist({ playlist, directory, trackFile, signal }) {
77
+ const name = oneLine(playlist?.name);
78
+ if (!name || !Array.isArray(playlist.entries)) throw new TypeError("Choose a Library playlist to export.");
79
+ if (typeof directory !== "string" || !directory.trim()) throw new TypeError("Choose a directory for the playlist.");
80
+ signal?.throwIfAborted();
81
+ const output = await newExportFolder(directory, name, signal);
82
+ try {
83
+ await mkdir(path.join(output, "audio"), { mode: 0o700 });
84
+ const entries = [];
85
+ const files = new Map();
86
+ const lines = ["#EXTM3U", `#PLAYLIST:${name}`, "# Catalog links open song pages on their music services."];
87
+ let catalogLinked = 0, madeCopied = 0, missingAudio = 0, unlinkedSongs = 0;
88
+ for (const entry of playlist.entries) {
89
+ signal?.throwIfAborted();
90
+ const title = oneLine(entry.title);
91
+ const artist = oneLine(entry.artist_credit);
92
+ const label = [artist, title].filter(Boolean).join(" - ");
93
+ let location;
94
+ if (entry.kind === "made") {
95
+ if (!files.has(entry.made_id)) {
96
+ const source = entry.made_id ? await trackFile?.(entry.made_id) : null;
97
+ const number = String(entries.length + 1).padStart(3, "0");
98
+ const audio = `audio/${number} - ${fileLabel(title)}.wav`;
99
+ files.set(entry.made_id, await copyAudio(source, path.join(output, audio), signal) ? audio : null);
100
+ }
101
+ location = files.get(entry.made_id);
102
+ entries.push({ kind: "made", title, artist_credit: artist, audio: location });
103
+ if (location) madeCopied++;
104
+ else { missingAudio++; lines.push(`# Audio unavailable: ${label}`); }
105
+ } else {
106
+ const links = catalogLinks(entry, playlist.storefront);
107
+ const album = oneLine(entry.album);
108
+ const isrc = typeof entry.isrc === "string" && /^[A-Z]{2}[A-Z0-9]{3}\d{7}$/u.test(entry.isrc) ? entry.isrc : null;
109
+ entries.push({ kind: "song", title, artist_credit: artist, ...(album && { album }), ...(isrc && { isrc }), links });
110
+ location = Object.hasOwn(links, playlist.origin) ? links[playlist.origin] : Object.values(links)[0];
111
+ if (location) catalogLinked++;
112
+ else { unlinkedSongs++; lines.push(`# No catalog link: ${label}`); }
113
+ }
114
+ if (location) lines.push(`#EXTINF:-1,${label}`, location);
115
+ }
116
+ const options = { flag: "wx", mode: 0o600, encoding: "utf8", signal };
117
+ await writeFile(path.join(output, "playlist.m3u8"), lines.join("\n") + "\n", options);
118
+ await writeFile(path.join(output, "playlist.json"), JSON.stringify({ version: 1, name, entries }, null, 2) + "\n", options);
119
+ signal?.throwIfAborted();
120
+ return { directory: output, entries: entries.length, catalogLinked, madeCopied, missingAudio, unlinkedSongs };
121
+ } catch (error) {
122
+ await rm(output, { recursive: true, force: true });
123
+ throw error;
124
+ }
125
+ }
@@ -0,0 +1,35 @@
1
+ // The profile chooser supplies the target. Text typed into the composer alone never creates one.
2
+ export function cleanProfileTrack(target) {
3
+ if (target?.entityType !== "track") return null;
4
+ const field = value => typeof value === "string"
5
+ ? value.replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/gu, " ").replace(/\s+/gu, " ").trim()
6
+ : "";
7
+ const label = field(target.label);
8
+ const artistCredit = field(target.artistCredit);
9
+ if (!label || !artistCredit || [...label].length > 512 || [...artistCredit].length > 512) return null;
10
+ return { entityType: "track", label, artistCredit };
11
+ }
12
+
13
+ const contextOf = track => `Track: ${JSON.stringify(track.label)}\nArtist: ${JSON.stringify(track.artistCredit)}`;
14
+
15
+ export function profileTrackContext(target) {
16
+ const track = cleanProfileTrack(target);
17
+ return track ? contextOf(track) : null;
18
+ }
19
+
20
+ export function profileSeedForDraft(draft, target) {
21
+ const track = cleanProfileTrack(target);
22
+ return track && typeof draft === "string" && `\n${draft}\n`.includes(`\n${contextOf(track)}\n`) ? track : null;
23
+ }
24
+
25
+ // Keep the listener's request when they pick a track. A second pick replaces only the
26
+ // two lines supplied by the chooser; hand-typed metadata remains part of the request.
27
+ export function draftWithProfileTrack(draft, previous, target, defaultRequest) {
28
+ const context = profileTrackContext(target);
29
+ if (!context) return null;
30
+ const selected = profileSeedForDraft(draft, previous);
31
+ if (selected) {
32
+ return `\n${draft}\n`.replace(`\n${contextOf(selected)}\n`, () => `\n${context}\n`).slice(1, -1);
33
+ }
34
+ return `${draft || defaultRequest}\n\n${context}`;
35
+ }
@@ -1,3 +1,5 @@
1
+ import { ARTIST_CREDIT_SEPARATORS } from "./listener-avoids.mjs";
2
+
1
3
  // A remaster, a live take or a guest credit names a recording of the same song, so knownness,
2
4
  // deduplication and Moondog's suggestion ledger compare titles without these suffixes:
3
5
  // " - 2011 Remaster", "(Remastered 2009)", " - Live", "(feat. X)", "[Deluxe]". A remix stays
@@ -5,15 +7,79 @@
5
7
  const DASH_SUFFIX = /\s+[-\u2013\u2014]\s+[^-\u2013\u2014]*\b(?:remaster(?:ed)?|live|mono|stereo|single|radio edit|edit|version|demo|acoustic|bonus track|\d{4} mix)\b[^-\u2013\u2014]*$/iu;
6
8
  const BRACKET_SUFFIX = /\s*[([][^()[\]]*\b(?:remaster(?:ed)?|live|feat\.?|ft\.?|featuring|with|deluxe|mono|stereo|version|edit|demo|acoustic|bonus track)(?:\b|(?<=\.))[^()[\]]*[)\]]$/iu;
7
9
 
8
- export function normalizedTrackTitle(value) {
10
+ // A title or artist may consist entirely of symbols. Keep its literal, width-normalized name.
11
+ export const catalogNameKey = value => foldedWords(value) || String(value ?? "").normalize("NFKC").trim();
12
+
13
+ // A solo name can match a guest credit. A requested joint credit needs every named artist.
14
+ export function sameCreditedArtist(wanted, artists) {
15
+ const literal = normalizedArtistName(wanted);
16
+ if (!literal) return false;
17
+ if (artists.some(artist => normalizedArtistName(artist) === literal)) return true;
18
+ const parts = credit => normalizedArtistName(credit).split(ARTIST_CREDIT_SEPARATORS).filter(Boolean);
19
+ const joint = name => name.split(/\s+(?:and|x|×)\s+/iu);
20
+ const required = parts(wanted).flatMap(joint).map(catalogNameKey).filter(Boolean);
21
+ if (!required.length) return false;
22
+ const available = new Set();
23
+ for (const artist of artists) {
24
+ available.add(catalogNameKey(artist));
25
+ const credits = parts(artist);
26
+ // A word like "and" inside a band's name is not evidence of a solo artist.
27
+ for (const name of required.length > 1 ? credits.flatMap(joint) : credits) available.add(catalogNameKey(name));
28
+ }
29
+ return required.every(name => available.has(name));
30
+ }
31
+
32
+ // A version tag with one of these words names another recording of the song, not another edition of it.
33
+ const OTHER_RECORDING = /\b(?:live|remix|acoustic|instrumental|demo|cover|karaoke|unplugged)\b/iu;
34
+ const GUEST_TAG = /^[([]\s*(?:feat\.?|ft\.?|featuring|with)\s+(.+?)\s*[)\]]$/iu;
35
+
36
+ // A title without its version tags, the tags that make it another recording, and the guests it credits.
37
+ function titleParts(value) {
9
38
  let title = String(value ?? "").normalize("NFKC").toLocaleLowerCase("und").replace(/\s+/gu, " ").trim();
39
+ const tags = [];
10
40
  for (let previous = null; previous !== title;) {
11
41
  previous = title;
12
- const stripped = title.replace(DASH_SUFFIX, "").replace(BRACKET_SUFFIX, "").trim();
42
+ const undashed = title.replace(DASH_SUFFIX, "");
43
+ const stripped = undashed.replace(BRACKET_SUFFIX, "").trim();
13
44
  // A title made only of a version word stays as it is.
14
- if (stripped) title = stripped;
45
+ if (!stripped) break;
46
+ tags.push(title.slice(undashed.length).trim(), undashed.slice(stripped.length).trim());
47
+ title = stripped;
15
48
  }
16
- return title;
49
+ const kept = tags.filter(Boolean);
50
+ return {
51
+ core: title,
52
+ kinds: kept.filter(tag => OTHER_RECORDING.test(tag)).map(foldedWords).sort().join("|"),
53
+ guests: kept.flatMap(tag => GUEST_TAG.exec(tag)?.[1].split(ARTIST_CREDIT_SEPARATORS) ?? []).filter(Boolean),
54
+ };
55
+ }
56
+
57
+ /** The exact title and a credited artist of a library song. */
58
+ export function exactLibrarySong(entry, title, artists) {
59
+ return catalogNameKey(title) === catalogNameKey(entry.title) && sameCreditedArtist(entry.artist_credit, artists);
60
+ }
61
+
62
+ /**
63
+ * Whether a service's song is the library song's recording: its exact title, or the same title under an
64
+ * edition's tag ("- Remastered 2011", "- Single Version") or with a guest moved into the title ("Stan (feat.
65
+ * Dido)" for "Stan" by "Eminem, Dido"). A live take, remix, acoustic or instrumental take, demo, cover or
66
+ * karaoke track matches only itself. With exactTitle false, any title by a credited artist matches. The song a
67
+ * stored ID names (byId) may also carry its storefront's title in another script ("ボヘミアン・ラプソディ");
68
+ * another title in the same script is a stale match ("Night" for "Night Ferry").
69
+ */
70
+ export function matchesLibrarySong(entry, title, artists, exactTitle = true, byId = false) {
71
+ if (!exactTitle) return sameCreditedArtist(entry.artist_credit, artists);
72
+ if (exactLibrarySong(entry, title, artists)) return true;
73
+ const wanted = titleParts(entry.title);
74
+ const found = titleParts(title);
75
+ return (catalogNameKey(wanted.core) === catalogNameKey(found.core) || (byId && isCjkText(wanted.core) !== isCjkText(found.core))) &&
76
+ wanted.kinds === found.kinds && sameCreditedArtist(entry.artist_credit, [...artists, ...found.guests]);
77
+ }
78
+
79
+ export const storedRecordingAgrees = (entry, title, artists) => matchesLibrarySong(entry, title, artists, true, true);
80
+
81
+ export function normalizedTrackTitle(value) {
82
+ return titleParts(value).core;
17
83
  }
18
84
 
19
85
  export function normalizedArtistName(value) {