feat: parse YouTube video links and page types
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
05d8bff171
commit
8dbb0cf9ce
@@ -0,0 +1,34 @@
|
||||
const ID_RE = /^[A-Za-z0-9_-]{11}$/;
|
||||
const YOUTUBE_HOSTS = new Set(['www.youtube.com', 'youtube.com', 'm.youtube.com']);
|
||||
|
||||
export function isVideoId(value) {
|
||||
return typeof value === 'string' && ID_RE.test(value);
|
||||
}
|
||||
|
||||
// Returns { videoId, isShort } for a link to a single video, or null for anything else.
|
||||
export function parseVideoLink(href, base = 'https://www.youtube.com') {
|
||||
if (!href) return null;
|
||||
let url;
|
||||
try {
|
||||
url = new URL(href, base);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!YOUTUBE_HOSTS.has(url.hostname)) return null;
|
||||
|
||||
if (url.pathname === '/watch') {
|
||||
const id = url.searchParams.get('v');
|
||||
return isVideoId(id) ? { videoId: id, isShort: false } : null;
|
||||
}
|
||||
const shorts = url.pathname.match(/^\/shorts\/([^/]+)/);
|
||||
if (shorts && isVideoId(shorts[1])) return { videoId: shorts[1], isShort: true };
|
||||
return null;
|
||||
}
|
||||
|
||||
export function pageFromPath(pathname) {
|
||||
if (pathname === '/') return 'home';
|
||||
if (pathname === '/watch') return 'watch';
|
||||
if (pathname === '/results') return 'search';
|
||||
if (/^\/(@[^/]+|channel\/[^/]+|c\/[^/]+|user\/[^/]+)/.test(pathname)) return 'channel';
|
||||
return null;
|
||||
}
|
||||
Reference in New Issue
Block a user