Catch artist names written in lowercase right after a cue phrase ("check out devourment",
"by cattle decapitation", "fan of ...") — the Title-Case/ALL-CAPS pass missed those.
- extension/extract.js (new): pure extraction (matchesIn + new cueMatchesIn + allMatchesIn),
UMD so it loads as a content script AND require()s in node for tests. The cue pass uses the
regex `d` flag to map matches back to positions for in-place wrapping; a small cue-stoplist
drops "the/this/new/..." right after the cue.
- extension/content.js: extraction now comes from globalThis.RSLExtract.allMatchesIn
(Title-Case + cue union), keeping the existing position-based wrapping.
- extension/manifest.json: load extract.js before content.js.
- extension/extract.test.cjs (new) + scripts/check.sh: 6 node:test cases for the extraction
logic; check.sh now runs the extension tests too (16 total, green).
- README: updated the detection limitation note.
Deferred (design item 2): merging names split across inline formatting (cross-node) — more
involved; left as a follow-up.
Verified: scripts/check.sh green (16 tests). In-browser behavior is logic-verified only (no
headless Firefox); additive to the pending background-fix re-test — the [rsl] logs distinguish
"candidates found" from "resolve failed".
Source: task/smarter-candidate-extraction (objective/linker-improvements).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
158 lines
6.1 KiB
JavaScript
158 lines
6.1 KiB
JavaScript
// Reddit -> Spotify/Bandcamp linker (content script).
|
|
//
|
|
// On a reddit thread page it: pulls candidate artist names out of comment text,
|
|
// asks the local resolver service which ones are real artists, and rewrites those
|
|
// occurrences in place into links. The resolver does the hard "is this an artist"
|
|
// part; this script only handles extraction + DOM rewriting.
|
|
|
|
(() => {
|
|
"use strict";
|
|
|
|
const api = globalThis.browser ?? globalThis.chrome;
|
|
const log = (...a) => console.log("[rsl]", ...a);
|
|
|
|
// Candidate extraction is pure + lives in extract.js (loaded first per manifest order;
|
|
// defines globalThis.RSLExtract) so it can be unit-tested in node. allMatchesIn(text)
|
|
// returns {name,index,length} for Title-Case runs AND cue-phrase ("check out <x>") names.
|
|
const Extract = globalThis.RSLExtract;
|
|
|
|
// ---- DOM walking ----------------------------------------------------------
|
|
const SKIP_TAGS = new Set([
|
|
"A", "SCRIPT", "STYLE", "CODE", "PRE", "TEXTAREA", "INPUT", "BUTTON", "TIME", "NOSCRIPT", "SVG", "SELECT",
|
|
]);
|
|
|
|
function inSkippable(node) {
|
|
for (let el = node.parentElement; el; el = el.parentElement) {
|
|
if (SKIP_TAGS.has(el.tagName)) return true;
|
|
if (el.classList && el.classList.contains("rsl-link")) return true;
|
|
if (el.isContentEditable) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function collectTextNodes(root) {
|
|
const nodes = [];
|
|
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
|
|
acceptNode(node) {
|
|
const v = node.nodeValue;
|
|
if (!v || v.length > 5000 || !/[A-Za-z]/.test(v)) return NodeFilter.FILTER_REJECT;
|
|
if (inSkippable(node)) return NodeFilter.FILTER_REJECT;
|
|
return NodeFilter.FILTER_ACCEPT;
|
|
},
|
|
});
|
|
let n;
|
|
while ((n = walker.nextNode())) nodes.push(n);
|
|
return nodes;
|
|
}
|
|
|
|
// ---- link building / rewriting --------------------------------------------
|
|
// Per the user's "if on spotify, link that, else bandcamp" rule: one link to the
|
|
// primary platform, colour-coded so you can tell which at a glance.
|
|
function makeLink(label, links) {
|
|
const primary = links.primary || { platform: "spotify", url: links.spotify };
|
|
const a = document.createElement("a");
|
|
a.className = `rsl-link rsl-${primary.platform}`;
|
|
a.textContent = label;
|
|
a.href = primary.url;
|
|
a.target = "_blank";
|
|
a.rel = "noopener noreferrer";
|
|
a.title = `Open on ${primary.platform === "spotify" ? "Spotify" : "Bandcamp"}`;
|
|
return a;
|
|
}
|
|
|
|
function wrapNode(node) {
|
|
const text = node.nodeValue;
|
|
const ms = Extract.allMatchesIn(text).filter((m) => {
|
|
const links = resolved.get(m.name);
|
|
return links && ((links.primary && links.primary.url) || links.spotify);
|
|
});
|
|
if (!ms.length) return;
|
|
const frag = document.createDocumentFragment();
|
|
let last = 0;
|
|
for (const m of ms) {
|
|
if (m.index < last) continue; // skip overlaps
|
|
if (m.index > last) frag.appendChild(document.createTextNode(text.slice(last, m.index)));
|
|
frag.appendChild(makeLink(text.substr(m.index, m.length), resolved.get(m.name)));
|
|
last = m.index + m.length;
|
|
}
|
|
if (last < text.length) frag.appendChild(document.createTextNode(text.slice(last)));
|
|
node.parentNode && node.parentNode.replaceChild(frag, node);
|
|
}
|
|
|
|
// ---- resolver client ------------------------------------------------------
|
|
const resolved = new Map(); // candidate string -> { spotify, bandcamp } | null
|
|
|
|
// The network call goes through the background script — a page-context fetch to
|
|
// http://localhost is blocked by reddit's CSP / mixed-content rules.
|
|
async function resolve(names) {
|
|
log("resolving", names.length, "candidate(s) via background:", names.slice(0, 8));
|
|
try {
|
|
const resp = await api.runtime.sendMessage({ type: "resolve", candidates: names });
|
|
if (!resp) throw new Error("no response from background script");
|
|
if (!resp.ok) throw new Error(resp.error || "resolve failed");
|
|
const hits = Object.values(resp.data).filter(Boolean).length;
|
|
log("resolver returned", hits, "artist(s) of", names.length);
|
|
return resp.data;
|
|
} catch (e) {
|
|
console.warn("[rsl] resolve failed (is the resolver running on :8787?):", e.message);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// ---- scan orchestration ---------------------------------------------------
|
|
function getRoot() {
|
|
return (
|
|
document.querySelector("main, .content[role='main'], shreddit-comment-tree, .commentarea") ||
|
|
document.body
|
|
);
|
|
}
|
|
|
|
async function scan() {
|
|
const root = getRoot();
|
|
const nodes = collectTextNodes(root);
|
|
log("scan: root", root.tagName || root.nodeName, "| text nodes", nodes.length);
|
|
if (!nodes.length) return;
|
|
|
|
const seen = new Set();
|
|
for (const node of nodes) for (const m of Extract.allMatchesIn(node.nodeValue)) seen.add(m.name);
|
|
log("candidates found:", seen.size);
|
|
|
|
const ask = [...seen].filter((c) => !resolved.has(c));
|
|
if (ask.length) {
|
|
const res = await resolve(ask);
|
|
if (res) for (const c of ask) resolved.set(c, res[c] || null); // negative-cache misses
|
|
}
|
|
for (const node of nodes) if (node.isConnected) wrapNode(node);
|
|
|
|
const total = document.querySelectorAll("a.rsl-link").length;
|
|
api.runtime.sendMessage({ type: "badge", count: total }).catch(() => {});
|
|
log("scan done; links on page:", total);
|
|
}
|
|
|
|
// serialize scans; coalesce overlapping triggers
|
|
let running = false;
|
|
let pending = false;
|
|
function schedule() {
|
|
if (running) { pending = true; return; }
|
|
running = true;
|
|
scan()
|
|
.catch((e) => console.warn("[rsl]", e))
|
|
.finally(() => {
|
|
running = false;
|
|
if (pending) { pending = false; setTimeout(schedule, 300); }
|
|
});
|
|
}
|
|
|
|
function debounce(fn, ms) {
|
|
let t;
|
|
return () => { clearTimeout(t); t = setTimeout(fn, ms); };
|
|
}
|
|
|
|
const onThread = () => /\/comments\//.test(location.pathname);
|
|
|
|
log("content script loaded:", location.href, "| thread page:", onThread());
|
|
if (onThread()) schedule();
|
|
new MutationObserver(debounce(() => { if (onThread()) schedule(); }, 600))
|
|
.observe(document.documentElement, { childList: true, subtree: true });
|
|
})();
|