archivo del paquete→ .shtukbase/packages/icons/lib/svg.ts
lib/svg.ts
233 líneas, 12.1 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // The SVG contract of page icons: validate and sanitize. Pure: text in, findings or text out; no file IO.
- // An icon is shown through <img>, so a script would not run there anyway; the contract is stricter on purpose:
- // the same file may be opened directly, inlined by another front or sent to a model, and it must be safe and
- // small everywhere. The parser is a small tokenizer, enough for the flat drawings the contract allows.
- export type Finding = { level: 'error' | 'warn'; text: string };
- /** What a style adds to the contract (from an IconStyle page); all optional. */
- export type StyleRules = { viewBox?: string; colors?: string[]; gradients?: boolean };
- /** The elements an icon may use. Everything else (script, style, text, image, foreignObject, animate, filter...) is refused. */
- export const ELEMENT_NAMES = [
- 'svg', 'g', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon',
- 'defs', 'linearGradient', 'radialGradient', 'stop', 'clipPath', 'mask', 'use', 'symbol', 'title', 'desc',
- ];
- export const ELEMENTS = new Set(ELEMENT_NAMES.map((n) => n.toLowerCase()));
- /** Elements sanitize removes but keeps the children of (a link around a shape). The rest is dropped whole. */
- const UNWRAP = new Set(['a', 'switch']);
- const GRADIENTS = new Set(['lineargradient', 'radialgradient', 'stop']);
- const COLOR_ATTRS = new Set(['fill', 'stroke', 'stop-color', 'color', 'flood-color', 'lighting-color']);
- const NAMED_OK = new Set(['none', 'transparent']);
- export const PROVENANCE = /^<!--\s*icon:/;
- type Tok =
- | { t: 'open'; name: string; attrs: [string, string][]; self: boolean; raw: string }
- | { t: 'close'; name: string; raw: string }
- | { t: 'comment'; raw: string }
- | { t: 'pi'; raw: string }
- | { t: 'decl'; raw: string }
- | { t: 'text'; raw: string }
- | { t: 'bad'; raw: string };
- const ATTR_RE = /([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+)))?/g;
- const OPEN_RE = /^<([A-Za-z_][\w:.-]*)((?:\s+[^\s=/>]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>"']+))?)*)\s*(\/?)>/;
- export function tokenize(src: string): Tok[] {
- const out: Tok[] = [];
- let i = 0;
- while (i < src.length) {
- const lt = src.indexOf('<', i);
- if (lt < 0) { out.push({ t: 'text', raw: src.slice(i) }); break; }
- if (lt > i) out.push({ t: 'text', raw: src.slice(i, lt) });
- const rest = src.slice(lt);
- let m: RegExpExecArray | null;
- let end = -1;
- if (rest.startsWith('<!--')) {
- end = rest.indexOf('-->');
- if (end < 0) { out.push({ t: 'bad', raw: rest }); break; }
- out.push({ t: 'comment', raw: rest.slice(0, end + 3) });
- i = lt + end + 3;
- } else if (rest.startsWith('<?')) {
- end = rest.indexOf('?>');
- if (end < 0) { out.push({ t: 'bad', raw: rest }); break; }
- out.push({ t: 'pi', raw: rest.slice(0, end + 2) });
- i = lt + end + 2;
- } else if (rest.startsWith('<!')) {
- const sub = /^<!DOCTYPE[^>\[]*\[/i.test(rest) ? rest.indexOf(']') : 0;
- end = sub < 0 ? -1 : rest.indexOf('>', sub);
- if (end < 0) { out.push({ t: 'bad', raw: rest }); break; }
- out.push({ t: 'decl', raw: rest.slice(0, end + 1) });
- i = lt + end + 1;
- } else if ((m = /^<\/\s*([A-Za-z_][\w:.-]*)\s*>/.exec(rest))) {
- out.push({ t: 'close', name: m[1], raw: m[0] });
- i = lt + m[0].length;
- } else if ((m = OPEN_RE.exec(rest))) {
- const attrs: [string, string][] = [];
- for (const a of m[2].matchAll(ATTR_RE)) attrs.push([a[1], a[2] ?? a[3] ?? a[4] ?? '']);
- out.push({ t: 'open', name: m[1], attrs, self: m[3] === '/', raw: m[0] });
- i = lt + m[0].length;
- } else {
- out.push({ t: 'bad', raw: rest.slice(0, 40) });
- break;
- }
- }
- return out;
- }
- const local = (name: string) => name.toLowerCase().replace(/^svg:/, '');
- const short = (s: string, n = 40) => (s.length > n ? s.slice(0, n - 1) + '…' : s);
- /** Why an attribute is unsafe, or null. Keeps only local references (#id) and no event handlers. */
- function unsafeAttr(name: string, value: string): string | null {
- const n = name.toLowerCase();
- const v = value.trim().toLowerCase();
- if (n.startsWith('on')) return `an event handler (${name})`;
- if (n === 'href' || n.endsWith(':href')) return v.startsWith('#') ? null : `a link out of the file (${name}="${short(value)}")`;
- if (/javascript:|vbscript:|data:/.test(v)) return `a script or data address in ${name}`;
- if (/url\(\s*['"]?(?!#)/.test(v)) return `an external url() in ${name}`;
- if (/@import|expression\s*\(/.test(v)) return `a CSS import or expression in ${name}`;
- return null;
- }
- /** An attribute that only editors need (inkscape:*, sodipodi:*, data-*): dropped by sanitize. */
- const editorAttr = (name: string) => /^(inkscape|sodipodi|sketch|serif|figma|data-)/i.test(name) || /^xmlns:(inkscape|sodipodi|sketch|serif|figma|rdf|cc|dc)$/i.test(name);
- /** Colours an attribute or a style declaration uses: hex in upper case, or a name. */
- function colorsOf(name: string, value: string): string[] {
- const out: string[] = [];
- const add = (v: string) => {
- const s = v.trim();
- if (!s || NAMED_OK.has(s.toLowerCase()) || s.toLowerCase().startsWith('url(')) return;
- out.push(/^#[0-9a-f]{3,8}$/i.test(s) ? normHex(s) : s);
- };
- if (COLOR_ATTRS.has(name.toLowerCase())) add(value);
- else if (name.toLowerCase() === 'style') {
- for (const decl of value.split(';')) {
- const [k, ...v] = decl.split(':');
- if (k && COLOR_ATTRS.has(k.trim().toLowerCase())) add(v.join(':'));
- }
- }
- return out;
- }
- export function normHex(h: string): string {
- let s = h.trim().toUpperCase();
- if (/^#[0-9A-F]{3}$/.test(s)) s = '#' + [...s.slice(1)].map((c) => c + c).join('');
- return s;
- }
- /** Checks the text of an SVG icon against the contract. maxBytes: the size budget. */
- export function validate(src: string, maxBytes: number, style: StyleRules = {}): Finding[] {
- const f: Finding[] = [];
- const err = (text: string) => f.push({ level: 'error', text });
- const warn = (text: string) => f.push({ level: 'warn', text });
- const bytes = new TextEncoder().encode(src).length;
- if (bytes > maxBytes) err(`${bytes} bytes, the budget is ${maxBytes}`);
- const palette = style.colors && style.colors.length ? new Set(style.colors.map(normHex)) : null;
- const stack: string[] = [];
- let roots = 0;
- let root: Tok | null = null;
- const seen = new Set<string>();
- for (const tk of tokenize(src)) {
- if (tk.t === 'bad') { err(`not well-formed near "${short(tk.raw.replace(/\s+/g, ' '))}"`); break; }
- if (tk.t === 'decl') { err(`a declaration ${short(tk.raw)} (DOCTYPE and ENTITY are refused)`); continue; }
- if (tk.t === 'pi') { if (!/^<\?xml\s/.test(tk.raw)) err(`a processing instruction ${short(tk.raw)}`); continue; }
- if (tk.t === 'comment') continue;
- if (tk.t === 'text') {
- const top = stack[stack.length - 1] ?? '';
- if (tk.raw.trim() && (!top || ELEMENTS.has(top)) && !['title', 'desc'].includes(top)) err(`text outside <title>/<desc>: "${short(tk.raw.trim())}"`);
- continue;
- }
- const name = local(tk.name);
- if (tk.t === 'close') {
- if (stack.pop() !== name) { err(`</${tk.name}> does not close the open element`); break; }
- continue;
- }
- if (stack.length === 0) { roots++; root = tk; if (roots > 1) err('more than one root element'); }
- if (!ELEMENTS.has(name)) {
- const why = name === 'text' || name === 'tspan' ? 'text in an icon (it is unreadable at 16 px and needs fonts)'
- : name === 'image' ? 'a raster or an external picture' : name === 'script' ? 'a script' : name === 'style' ? 'a <style> sheet (use attributes)'
- : name === 'foreignobject' ? 'foreign HTML' : 'an element outside the contract';
- if (!seen.has(name)) err(`<${tk.name}>: ${why}`);
- seen.add(name);
- }
- if (GRADIENTS.has(name) && style.gradients === false && !seen.has('gradient')) { err('a gradient: the style draws flat'); seen.add('gradient'); }
- for (const [an, av] of tk.attrs) {
- const bad = unsafeAttr(an, av);
- if (bad) err(`<${tk.name}>: ${bad}`);
- if (/currentcolor/i.test(av)) { if (!seen.has('cc')) err('currentColor: it is black inside <img>; give the colour'); seen.add('cc'); }
- for (const c of colorsOf(an, av)) {
- if (/^currentcolor$/i.test(c)) continue;
- if (!c.startsWith('#')) { if (!seen.has('n' + c)) err(`colour "${c}" by name: write it as hex`); seen.add('n' + c); }
- else if (palette && !palette.has(c) && !seen.has(c)) { err(`colour ${c} is not in the style's palette`); seen.add(c); }
- }
- if (editorAttr(an) && !seen.has('ed')) { warn(`editor attributes (${an}): sanitize drops them`); seen.add('ed'); }
- }
- if (!tk.self) stack.push(name);
- }
- if (stack.length) err(`<${stack[stack.length - 1]}> is not closed`);
- if (!root || root.t !== 'open' || local(root.name) !== 'svg') err('the root element is not <svg>');
- else {
- const vb = root.attrs.find(([k]) => k === 'viewBox')?.[1];
- const n = (vb ?? '').trim().split(/[\s,]+/).map(Number);
- if (!vb) err('no viewBox');
- else if (n.length !== 4 || n.some((x) => !Number.isFinite(x)) || n[2] <= 0) err(`viewBox "${vb}" is not four numbers`);
- else if (n[2] !== n[3]) err(`viewBox "${vb}" is not square`);
- else if (style.viewBox && vb.trim().replace(/\s+/g, ' ') !== style.viewBox) warn(`viewBox "${vb}", the style draws on "${style.viewBox}"`);
- if (!root.attrs.some(([k, v]) => k === 'xmlns' && v === 'http://www.w3.org/2000/svg')) err('no xmlns="http://www.w3.org/2000/svg" (an <img> will not show it)');
- }
- return f;
- }
- /** Makes an SVG fit the contract where that is safe to do: drops what is refused, keeps the drawing. */
- export function sanitize(src: string): string {
- const out: string[] = [];
- let skip = 0; // depth inside a dropped element
- const stack: string[] = [];
- for (const tk of tokenize(src)) {
- if (tk.t === 'bad') break;
- if (tk.t === 'decl' || tk.t === 'pi') continue;
- if (tk.t === 'comment') { if (!skip && PROVENANCE.test(tk.raw)) out.push(tk.raw); continue; }
- if (tk.t === 'text') {
- if (!skip && ['title', 'desc'].includes(stack[stack.length - 1] ?? '')) out.push(tk.raw.trim());
- continue;
- }
- const name = local(tk.name);
- if (tk.t === 'close') {
- if (skip) { skip--; if (skip) continue; stack.pop(); continue; }
- if (stack.pop()?.startsWith('#')) continue; // an unwrapped element: its children stay
- out.push(`</${tk.name}>`);
- continue;
- }
- if (!skip && UNWRAP.has(name)) { if (!tk.self) stack.push('#' + name); continue; }
- if (skip || !ELEMENTS.has(name)) { if (!tk.self) skip++; if (!tk.self && skip === 1) stack.push(name); continue; }
- const attrs: string[] = [];
- let hasNs = false;
- for (const [an, av] of tk.attrs) {
- if (unsafeAttr(an, av) || editorAttr(an)) continue;
- if (/currentcolor/i.test(av)) continue;
- if (an === 'xmlns') hasNs = true;
- attrs.push(`${an}="${av.replace(/"/g, '"')}"`);
- }
- if (name === 'svg' && stack.length === 0) {
- if (!hasNs) attrs.unshift('xmlns="http://www.w3.org/2000/svg"');
- if (!tk.attrs.some(([k]) => k === 'viewBox')) {
- const w = Number(tk.attrs.find(([k]) => k === 'width')?.[1]), hh = Number(tk.attrs.find(([k]) => k === 'height')?.[1]);
- if (w > 0 && w === hh) attrs.push(`viewBox="0 0 ${w} ${hh}"`);
- }
- }
- out.push(`<${tk.name}${attrs.length ? ' ' + attrs.join(' ') : ''}${tk.self ? '/' : ''}>`);
- if (!tk.self) stack.push(name);
- }
- return out.join('\n').replace(/\n(?=<\/(title|desc)>)/g, '').replace(/(<(title|desc)[^>]*>)\n/g, '$1') + '\n';
- }
- /** A short icon that is not a path: an emoji (or a few symbols), no letters, at most 4 graphemes. */
- export function isGlyph(v: string): boolean {
- const s = v.trim();
- // letters, spaces and path characters are text, not an icon; plain ASCII ("1", "->") is not an emoji, a keycap "1️⃣" is
- if (!s || /[\p{L}\s/\\<>]/u.test(s) || !/[^\x00-\x7F]/.test(s)) return false;
- const seg = typeof Intl !== 'undefined' && 'Segmenter' in Intl ? [...new Intl.Segmenter().segment(s)].length : [...s].length;
- return seg <= 4;
- }
- /** A path to an SVG file (root-absolute "/assets/icons/x.svg" or relative to the page). */
- export const isSvgPath = (v: unknown): v is string => typeof v === 'string' && /^[^\s<>:]+\.svg$/i.test(v.trim());