UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

65 lines (64 loc) 2.94 kB
import path from 'path'; import {URL} from 'url'; const DEFAULT_BASE = '/new-path/'; function postcssFontUrlRewrite(opts = {}) { const { basePath = DEFAULT_BASE, sourceBase, verbose = false } = opts; const FONT_MARKER = '/fonts/'; const baseIsFullUrl = /^https?:\/\//.test(basePath); const normalizeBase = (str, isUrl) => isUrl ? str.replace(/\/+$/, '') + '/' : path.posix.normalize(str).replace(/\/+$/, '') + '/'; const normalizedTarget = normalizeBase(basePath, baseIsFullUrl); const normalizedSource = sourceBase && normalizeBase(sourceBase, /^https?:\/\//.test(sourceBase)); const defaultNormalizedBase = normalizeBase(DEFAULT_BASE, false); return { postcssPlugin: 'font-url-rewrite-plugin', AtRule: { 'font-face'(atRule) { atRule.walkDecls('src', decl => { decl.value = decl.value.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g, (fullMatch, _quote, rawUrl) => { const urlStr = rawUrl.replace(/\\+/g, '/'); let subPath; if (normalizedSource && urlStr.startsWith(normalizedSource)) { subPath = urlStr.slice(normalizedSource.length); } else if (urlStr.startsWith(normalizedTarget)) { subPath = urlStr.slice(normalizedTarget.length); } else if (urlStr.startsWith(defaultNormalizedBase)) { subPath = urlStr.slice(defaultNormalizedBase.length); } else if (/^https?:\/\//.test(urlStr)) { const parsed = new URL(urlStr); const pathname = parsed.pathname; const idx = pathname.lastIndexOf(FONT_MARKER); subPath = idx !== -1 ? pathname.slice(idx + FONT_MARKER.length) : path.posix.basename(pathname); } else { const idx = urlStr.lastIndexOf(FONT_MARKER); if (idx === -1) { if (verbose) console.warn(`Skipped (no fonts segment): ${urlStr}`); return fullMatch; } subPath = urlStr.slice(idx + FONT_MARKER.length); } subPath = subPath.replace(/^\d+\.\d+\.\d+\/(.+)/, '$1'); const filename = path.posix.basename(subPath); const cleaned = filename.replace(/-[a-f0-9]{6,}(?=\.[^.]+$)/, ''); const dir = path.posix.dirname(subPath); let finalUrl; if (baseIsFullUrl) { const hostOnly = normalizedTarget.replace(/\/$/, ''); finalUrl = [hostOnly].concat(dir && dir !== '.' ? [dir] : []).concat([cleaned]).join('/'); } else { finalUrl = path.posix.join(normalizedTarget, dir, cleaned); } if (verbose) console.log(`Rewriting: ${urlStr}${finalUrl}`); return `url("${finalUrl}")`; }); }); } } }; } postcssFontUrlRewrite.postcss = true; export default postcssFontUrlRewrite; //# sourceMappingURL=font-url-rewrite-plugin.js.map