url-parser.ts 2.18 KB
import { FigmaUrlInfo } from '../types/figma-types';

/**
 * Parse Figma URL and extract fileId, name, and nodeId in one pass
 * @param url - Figma URL to parse
 * @returns Object containing fileId, name, and nodeId
 * @example
 * parseFigmaUrl('https://www.figma.com/design/aONcu8L82l1PdcT304Q8Za/Intern?node-id=0-495')
 * // Returns: { fileId: 'aONcu8L82l1PdcT304Q8Za', name: 'intern', nodeId: '0-495' }
 */
export const parseFigmaUrl = (url: string): FigmaUrlInfo => {
    let fileId: string | null = null;
    let name = 'untitled';
    let nodeId: string | null = null;

    try {
        const urlObj = new URL(decodeURIComponent(url));
        const pathParts = urlObj.pathname.split('/').filter(Boolean);
        if (pathParts.length >= 3) {
            fileId = pathParts[pathParts.length - 2] || null;
            const fileName = pathParts[pathParts.length - 1];
            name = slugifyFigmaName(fileName ?? 'untitled');
            name = name.length > 20 ? name.substring(0, 20) : name;
        }

        nodeId = urlObj.searchParams.get('node-id') || null;
        nodeId = nodeId ? nodeId.replace(/-/g, ':') : null;
    } catch {}

    if (!fileId || !nodeId) {
        throw new Error('Invalid Figma URL');
    }

    return { fileId, name, nodeId, projectName: `${name}_${nodeId.replace(/:/g, '_')}` };
};

/**
 * Turn a Figma file name into a filesystem / package-safe slug.
 *
 * The Figma URL is already percent-decoded once by `new URL(decodeURIComponent(url))`,
 * but some URLs are double-encoded (e.g. `%25E3%2580%2590` instead of `%E3%80%90`).
 * We fully decode the name first, then keep unicode letters/digits and replace every
 * other character (spaces, brackets, `%`, etc.) with a single underscore.
 */
function slugifyFigmaName(raw: string): string {
    let decoded = raw;
    try {
        let prev: string;
        do {
            prev = decoded;
            decoded = decodeURIComponent(prev);
        } while (decoded !== prev);
    } catch {
        /* leave as the last successfully decoded value */
    }

    const slug = decoded
        .normalize('NFKC')
        .replace(/[^\p{L}\p{N}]+/gu, '_')
        .replace(/^_+|_+$/g, '')
        .toLowerCase();

    return slug || 'untitled';
}