소스 정보
- 저장소
- dev-hann/song
- 최근 소스 활동
- 2026년 2월 18일 13:08
- 감지된 SKILL.md 언어
- 영어
- 스타
- 0
- 포크
- 0
설치 방법
기본적으로 소스를 먼저 확인하는 Prompt가 선택됩니다. 직접 명령으로 전환하거나 로컬 사본을 다운로드할 수도 있습니다.
소스 파일 검토
설치 여부를 결정하기 전에 SKILL.md와 SkillsMP에 표시된 보조 파일을 읽어 보세요.
메뉴
기본적으로 소스를 먼저 확인하는 Prompt가 선택됩니다. 직접 명령으로 전환하거나 로컬 사본을 다운로드할 수도 있습니다.
설치 여부를 결정하기 전에 SKILL.md와 SkillsMP에 표시된 보조 파일을 읽어 보세요.
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
직접 명령은 검토 Prompt를 거치지 않습니다. 실행하기 전에 소스를 확인하세요.
npx skills add https://github.com/dev-hann/song --skill parser-patterns명령은 한 줄로 유지됩니다. 복사하기 전에 가로로 스크롤해 전체 내용을 확인하세요.
로컬 사본을 원하시나요? SkillsMP에서 현재 제공할 수 있는 파일을 다운로드하세요.
SKILL.md 표시 중
| name | parser-patterns |
| description | Create parser functions for external data with basic and advanced patterns |
| license | MIT |
| compatibility | opencode |
| metadata | {"category":"development","complexity":"intermediate"} |
unknown parameter typeType | null for all parser functionsUse this when you need to:
I'll ask clarifying questions if:
export function parseVideo(item: unknown): Video | null {
// 1. Type guard: Check if object
if (!item || typeof item !== 'object') {
return null;
}
const obj = item as Record<string, unknown>;
// 2. Validate required fields
if (obj.type !== 'Video') {
return null;
}
if (!obj.id || typeof obj.id !== 'string') {
return null;
}
if (!obj.title || typeof obj.title !== 'string') {
return null;
}
// 3. Extract and transform data
return {
id: obj.id,
type: 'video',
title: obj.title,
description: String(obj.description ?? ''),
duration: typeof obj. === ? obj. : ,
: obj. === ? obj. : ,
: (obj.),
: (obj.)
};
}
function safeGet<T>(
obj: unknown,
key: string,
defaultValue: T
): T {
if (obj && typeof obj === 'object' && key in obj) {
const value = (obj as Record<string, unknown>)[key];
return value !== undefined && value !== null
? (value as T)
: defaultValue;
}
return defaultValue;
}
function safeGetString(obj: unknown, key: string): string {
const value = safeGet(obj, key, '');
return typeof value === 'string' ? value : String(value);
}
function safeGetNumber(obj: unknown, key: string): number {
const value = safeGet(obj, key, 0);
return typeof value === 'number' ? value : 0;
}
function safeGetArray<T>(obj: unknown, : ): T[] {
value = (obj, key, []);
.(value) ? value : [];
}
function extractText(text: string | { text: string }): string {
if (typeof text === 'string') {
return text;
}
if (typeof text === 'object' && text !== null && 'text' in text) {
return String(text.text);
}
return '';
}
export function parseVideo(item: unknown): Video | null {
if (!item || typeof item !== 'object') return null;
const obj = item as Record<string, unknown>;
return {
id: safeGetString(obj, 'id'),
title: extractText(obj.title),
description: extractText(obj.description)
};
}
function extractDuration(duration: number | { seconds: number }): number {
if (typeof duration === 'number') {
return duration;
}
if (typeof duration === 'object' && duration !== null && 'seconds' in duration) {
return typeof duration.seconds === 'number' ? duration.seconds : 0;
}
return 0;
}
export function parseVideo(item: unknown): Video | null {
if (!item || typeof item !== 'object') return null;
const obj = item as Record<string, unknown>;
return {
id: safeGetString(obj, 'id'),
title: safeGetString(obj, 'title'),
duration: extractDuration(obj.duration)
};
}
function getThumbnailUrl(thumbnail: unknown): string {
// Case 1: String URL
if (typeof thumbnail === 'string') {
return thumbnail;
}
// Case 2: Object with url property
if (typeof thumbnail === 'object' && thumbnail !== null && 'url' in thumbnail) {
const url = (thumbnail as { url: unknown }).url;
return typeof url === 'string' ? url : '';
}
// Case 3: Array of thumbnails
if (Array.isArray(thumbnail) && thumbnail.length > 0) {
const firstThumbnail = thumbnail[0];
return getThumbnailUrl(firstThumbnail);
}
// Case 4: Invalid
return '';
}
function getBestThumbnail(thumbnails: unknown): string {
if (!Array.isArray(thumbnails) || thumbnails.length === 0) {
return '';
}
// Sort by resolution (width * height) descending
const sorted = thumbnails
.filter((t) => typeof t === 'object' && t !== null && 'url' in t && 'width' in t && 'height' in t)
.sort((a, b) => {
const sizeA = (a.width as number) * (a.height as number);
const sizeB = (b.width as number) * (b.height as number);
return sizeB - sizeA;
});
if (sorted.length > 0) {
return String(sorted[0].url);
}
return ;
}
function parseChannelInfo(channel: unknown): ChannelInfo {
if (!channel || typeof channel !== 'object') {
return { id: '', name: '', thumbnail: '', subscribers: 0 };
}
const obj = channel as Record<string, unknown>;
return {
id: safeGetString(obj, 'id'),
name: extractText(obj.name),
thumbnail: getThumbnailUrl(obj.thumbnail),
subscribers: safeGetNumber(obj, 'subscriberCount')
};
}
export function parseSearchResult(item: unknown): SearchResult | null {
if (!item || typeof item !== 'object') {
return null;
}
const obj = item as Record<string, unknown>;
switch (obj.type) {
case 'Video':
return parseVideo(obj);
case 'Channel':
return parseChannel(obj);
case 'Playlist':
return parsePlaylist(obj);
default:
return null;
}
}
function parseChannelInfo(channel: unknown): ChannelInfo {
if (!channel || typeof channel !== 'object') {
return { id: '', name: '', thumbnail: '', subscribers: 0 };
}
const obj = channel as Record<string, unknown>;
return {
id: safeGetString(obj, 'id'),
name: extractText(obj.name),
thumbnail: getThumbnailUrl(obj.thumbnail),
subscribers: safeGetNumber(obj, 'subscriberCount')
};
}
export function parseVideo(item: unknown): Video | null {
if (!item || typeof item !== 'object') return null;
const obj = item as Record<string, unknown>;
{
: (obj, ),
: (obj, ),
: (obj.)
};
}
import { VideoSchema } from '@/schemas/video';
export function parseVideo(item: unknown): Video | null {
const result = VideoSchema.safeParse(item);
return result.success ? result.data : null;
}
// Basic array parser
export function parseVideos(items: unknown): Video[] {
if (!Array.isArray(items)) {
return [];
}
return items
.map((item) => parseVideo(item))
.filter((video): video is Video => video !== null);
}
// Array parser with validation
export function parseVideosWithValidation(items: unknown, maxItems = 100): Video[] {
if (!Array.isArray(items)) {
return [];
}
const videos: Video[] = [];
for (const item of items) {
if (videos.length >= maxItems) {
break;
}
const video = parseVideo(item);
if (video) {
videos.push(video);
}
}
return videos;
}
interface ParseResult<T> {
data: T[];
errors: Array<{ item: unknown; error: string }>;
}
export function parseVideosWithErrorCollection(items: unknown): ParseResult<Video> {
const result: ParseResult<Video> = { data: [], errors: [] };
if (!Array.isArray(items)) {
result.errors.push({ item: items, error: 'Not an array' });
return result;
}
for (const item of items) {
try {
const video = parseVideo(item);
if (video) {
result.data.push(video);
} else {
result.errors.push({ item, error: 'Failed to parse' });
}
} catch (error) {
result.errors.push({
item,
error: error instanceof ? error. :
});
}
}
result;
}
const parseCache = new WeakMap<unknown, Video | null>();
export function parseVideoWithCache(item: unknown): Video | null {
if (parseCache.has(item)) {
return parseCache.get(item)!;
}
const result = parseVideo(item);
parseCache.set(item, result);
return result;
}
export function parseVideoAndTransform(item: unknown): TransformedVideo | null {
const video = parseVideo(item);
if (!video) {
return null;
}
return {
...video,
formattedDuration: formatDuration(video.duration),
formattedViews: formatViewCount(video.viewCount),
thumbnailUrl: getBestThumbnail(video.thumbnail)
};
}
interface ValidationRule<T> {
validate: (value: T) => boolean;
error: string;
}
export function parseVideoWithRules(
item: unknown,
rules: ValidationRule<Video>[] = []
): Video | null {
const video = parseVideo(item);
if (!video) {
return null;
}
for (const rule of rules) {
if (!rule.validate(video)) {
console.error(`Validation error: ${rule.error}`);
return null;
}
}
return video;
}
export function parseSearchResults(items: unknown): {
videos: Video[];
channels: Channel[];
playlists: Playlist[];
} {
const videos: Video[] = [];
const channels: Channel[] = [];
const playlists: Playlist[] = [];
if (!Array.isArray(items)) {
return { videos, channels, playlists };
}
for (const item of items) {
const video = parseVideo(item);
if (video) {
videos.push(video);
continue;
}
const channel = parseChannel(item);
if (channel) {
channels.push(channel);
continue;
}
const playlist = parsePlaylist(item);
if (playlist) {
playlists.push(playlist);
}
}
return { videos, channels, playlists };
}
export async function parseVideoWithRetry(
item: unknown,
maxRetries = 3
): Promise<Video | null> {
let lastError: Error | null = null;
for (let i = 0; i < maxRetries; i++) {
try {
const video = await parseVideoAsync(item);
if (video) {
return video;
}
} catch (error) {
lastError = error instanceof Error ? error : new Error('Unknown error');
await sleep(1000 * (i + 1)); // Exponential backoff
}
}
throw lastError ?? new Error('Failed to parse after retries');
}
// Basic type guard
function isType<T>(value: unknown): value is T {
// Implementation
}
// Object type guard
function isObject(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object';
}
// Array type guard
function isArray<T>(value: unknown): value is T[] {
return Array.isArray(value);
}
// String validation
if (typeof value !== 'string') {
return null;
}
// Number validation
if (typeof value !== 'number') {
return defaultValue;
}
// Array validation
if (!Array.isArray(value)) {
return [];
}
// Object validation
if (!value || typeof value !== 'object') {
return defaultObject;
}
// Enum validation
const validTypes = ['Video', 'Channel', 'Playlist'] as const;
if (!validTypes.includes(obj.type as any)) {
return null;
}
export function parseData(input: unknown): ParsedType | null {
if (!input || typeof input !== 'object') {
return null;
}
const obj = input as Record<string, unknown>;
// Validate required fields
if (!('id' in obj)) {
return null;
}
return {
id: safeGetString(obj, 'id'),
name: safeGetString(obj, 'name'),
// ... other fields with safe access
};
}
Before committing parser code:
unknownType | null| Helper | Purpose |
|---|---|
safeGet() | Type-safe property access with default |
safeGetString() | Get string value, convert if needed |
safeGetNumber() | Get number value, convert if needed |
safeGetArray() | Get array, ensure it's an array |
| YouTube.js Type | Format | Parser |
|---|---|---|
| TextRun | string or { text: string } | extractText() |
| Duration | number or { seconds: number } | extractDuration() |
| Thumbnail | string, { url: string }, or array | getThumbnailUrl() |
| Channel | Object with id, name, thumbnail | parseChannelInfo() |
| Advanced Pattern | Use For |
|---|---|
| Discriminated Union | Type field discrimination |
| Nested Object | Complex object structures |
| Zod-Enhanced | Runtime validation |
| Array with Filtering | Filter invalid items |
| Error Collection | Collect all parse errors |
| Caching | Performance optimization |
| Transformation | Modify parsed data |
| Validation Rules | Custom validation logic |
| Composition | Parse multiple types |
| Async | Fetch additional data |
| Retry | Handle transient errors |
Related SKILLS: zod-validation.md, typescript-verification.md, utility-testing.md
SOC 직업 분류 기준