### Install svgson package Source: https://github.com/elrumordelaluz/svgson/blob/master/README.md Command to install the svgson library using the yarn package manager. ```bash yarn add svgson ``` -------------------------------- ### Define custom node transformation Source: https://github.com/elrumordelaluz/svgson/blob/master/README.md Example of a default transformNode function that returns the node as-is during the parsing or stringifying process. ```javascript function(node) { return node; } ``` -------------------------------- ### Utilize INode Interface for Type-Safe SVG Manipulation Source: https://context7.com/elrumordelaluz/svgson/llms.txt Provides the INode TypeScript interface definition and examples of how to use it for type-safe manipulation of SVG AST nodes. It demonstrates both asynchronous and synchronous parsing workflows. ```typescript import { parse, parseSync, stringify, INode } from 'svgson' interface INode { name: string type: string value: string attributes: Record children: INode[] } async function processSvg(svgString: string): Promise { const ast: INode = await parse(svgString) ast.children.forEach((child: INode) => { if (child.name === 'circle') { child.attributes.fill = 'red' } }) return stringify(ast) } function processSvgSync(svgString: string): INode { return parseSync(svgString, { camelcase: true }) } ``` -------------------------------- ### Define custom attribute transformation Source: https://github.com/elrumordelaluz/svgson/blob/master/README.md Example of a default transformAttr function used during stringification to format attributes as key-value pairs. ```javascript function(key, value, escape) { return `${key}="${escape(value)}"`; } ``` -------------------------------- ### Integrate svgson with SVGO for Optimized Parsing Source: https://context7.com/elrumordelaluz/svgson/llms.txt Demonstrates how to optimize SVG content using SVGO before parsing it into an AST with svgson. It includes configuration for SVGO plugins and shows how to manipulate the resulting JSON structure before stringifying it back to SVG. ```javascript const { parse, stringify } = require('svgson') const { optimize } = require('svgo') const svg = ` ` const svgoConfig = { plugins: [ { name: 'preset-default', params: { overrides: { removeViewBox: false } } }, 'removeStyleElement', { name: 'removeAttrs', params: { attrs: '(stroke-width|stroke-linecap|stroke-linejoin|class)' } } ], multipass: true } const optimized = optimize(svg, svgoConfig) parse(optimized.data) .then((json) => { console.log('Optimized AST:', JSON.stringify(json, null, 2)) json.children[0].attributes.fill = '#ff6b6b' const finalSvg = stringify(json) console.log('Final SVG:', finalSvg) }) ``` -------------------------------- ### Parsing and Optimizing SVG Source: https://context7.com/elrumordelaluz/svgson/llms.txt Demonstrates how to integrate svgson with SVGO to optimize an SVG string before parsing it into an AST for manipulation. ```APIDOC ## POST /svg/parse-optimized ### Description Parses an SVG string into a JSON AST after applying SVGO optimization rules. ### Method POST ### Endpoint /svg/parse-optimized ### Parameters #### Request Body - **svg** (string) - Required - The raw SVG markup string. - **svgoConfig** (object) - Optional - Configuration object for SVGO optimization. ### Request Example { "svg": "...", "svgoConfig": { "plugins": ["preset-default"] } } ### Response #### Success Response (200) - **ast** (object) - The resulting JSON AST structure of the optimized SVG. #### Response Example { "name": "svg", "type": "element", "children": [], "attributes": {} } ``` -------------------------------- ### Configure Self-Closing Tags Source: https://context7.com/elrumordelaluz/svgson/llms.txt Demonstrates how to toggle between self-closing tags and explicit closing tags using the selfClose option. ```javascript const { parse, stringify } = require('svgson') const svg = `` parse(svg) .then((json) => { const selfClosing = stringify(json, { selfClose: true }) console.log(selfClosing) const explicitClose = stringify(json, { selfClose: false }) console.log(explicitClose) }) ``` -------------------------------- ### Asynchronous SVG Parsing with Options Source: https://context7.com/elrumordelaluz/svgson/llms.txt Demonstrates parsing SVG with options like `camelcase` for attribute conversion and `transformNode` for custom AST manipulation. ```APIDOC ## Asynchronous SVG Parsing with Options ### Description Parses SVG with automatic conversion of hyphenated attribute names to camelCase format, while preserving `data-*` and `aria-*` attributes in their original format. Also demonstrates using `transformNode` to reshape the AST. ### Method `parse(svgString, options)` ### Parameters - `svgString` (string) - Required - The SVG content to parse. - `options` (object) - Required - Configuration options. - `camelcase` (boolean) - Optional - Converts hyphenated attribute names to camelCase. Defaults to `false`. - `transformNode` (function) - Optional - A function to transform each node during parsing. ### Request Example (camelcase) ```javascript const { parse } = require('svgson') const svg = ` ` parse(svg, { camelcase: true }) .then((json) => { console.log(json.children[0].attributes) }) ``` ### Response Example (camelcase) ```json { "strokeWidth": "2", "strokeLinecap": "round", "strokeLinejoin": "miter", "data-custom-id": "line1", "aria-label": "decorative line", "x1": "0", "y1": "0", "x2": "100", "y2": "100" } ``` ### Request Example (transformNode) ```javascript const { parse } = require('svgson') const svg = ` ` parse(svg, { transformNode: (node) => ({ tag: node.name, props: node.attributes, ...(node.children && node.children.length > 0 ? { children: node.children } : {}) }) }) .then((json) => { console.log(JSON.stringify(json, null, 2)) }) ``` ### Response Example (transformNode) ```json { "tag": "svg", "props": { "viewBox": "0 0 100 100", "width": "100", "height": "100" }, "children": [ { "tag": "circle", "props": { "r": "15", "cx": "50", "cy": "50", "fill": "red" } } ] } ``` ``` -------------------------------- ### Transform Nodes with transformNode Source: https://context7.com/elrumordelaluz/svgson/llms.txt Explains how to use the transformNode option to map custom AST structures into the standard svgson format before stringification. ```javascript const { stringify } = require('svgson') const customAst = { tag: 'svg', attrs: { viewBox: '0 0 100 100', width: '100', height: '100' }, childs: [ { tag: 'circle', attrs: { r: '15', cx: '50', cy: '50', fill: 'green' }, childs: [] } ] } const svg = stringify(customAst, { transformNode: (node) => ({ name: node.tag, type: 'element', value: '', attributes: node.attrs, children: node.childs || [] }) }) console.log(svg) ``` -------------------------------- ### Convert SVG to JSON and back Source: https://github.com/elrumordelaluz/svgson/blob/master/README.md Demonstrates parsing an SVG string into a JSON AST using the parse method and converting it back to an SVG string using the stringify method. ```javascript const { parse, stringify } = require('svgson'); parse(``).then((json) => { console.log(JSON.stringify(json, null, 2)); const mysvg = stringify(json); }); ``` -------------------------------- ### stringify Source: https://context7.com/elrumordelaluz/svgson/llms.txt Converts a JSON AST back into an SVG string. ```APIDOC ## stringify(ast, options) ### Description Converts a JSON AST (from parse/parseSync) back into an SVG string. Supports custom attribute transformation and self-closing tag configuration. ### Parameters #### Request Body - **ast** (Object/Array) - Required - The JSON AST object or array of nodes to convert. - **options** (Object) - Optional - Configuration object for stringification. ### Response - **string** - The resulting SVG string. ``` -------------------------------- ### Convert JSON AST to SVG String Source: https://context7.com/elrumordelaluz/svgson/llms.txt Demonstrates the basic usage of the stringify function to convert a modified JSON AST back into a valid SVG string. ```javascript const { parse, stringify } = require('svgson') const svg = ` ` parse(svg) .then((json) => { json.children[0].attributes.fill = '#ff0000' json.children[0].attributes.r = '25' const modifiedSvg = stringify(json) console.log(modifiedSvg) }) ``` -------------------------------- ### Customize Attributes with transformAttr Source: https://context7.com/elrumordelaluz/svgson/llms.txt Shows how to use the transformAttr option to conditionally modify, remove, or preserve attributes during the stringification process. ```javascript const { parse, stringify } = require('svgson') const svg = ` ` parse(svg) .then((json) => { const result = stringify(json, { transformAttr: (key, value, escape, elementName) => { if (elementName === 'svg' && /(width|height)/.test(key)) { return null } if (/^data-/.test(key)) { return `${key}="${value}"` } return `${key}="${escape(value)}"` } }) console.log(result) }) ``` -------------------------------- ### stringify with transformNode Source: https://context7.com/elrumordelaluz/svgson/llms.txt Transforms each node during stringification. ```APIDOC ## stringify(ast, { transformNode }) ### Description Transforms each node during stringification, useful for converting custom AST structures back to the standard format or modifying values on output. ### Parameters #### Request Body - **transformNode** (Function) - Optional - Callback function: (node) => Object. ``` -------------------------------- ### stringify with transformAttr Source: https://context7.com/elrumordelaluz/svgson/llms.txt Customizes how attributes are rendered during stringification. ```APIDOC ## stringify(ast, { transformAttr }) ### Description Customizes how attributes are rendered during stringification, with access to an escape function for proper XML encoding. Return `null` to remove an attribute. ### Parameters #### Request Body - **transformAttr** (Function) - Optional - Callback function: (key, value, escape, elementName) => string|null. ``` -------------------------------- ### INode Interface and Type Definitions Source: https://context7.com/elrumordelaluz/svgson/llms.txt Defines the structure of the AST nodes returned by svgson, useful for TypeScript implementations. ```APIDOC ## GET /types/inode ### Description Retrieves the TypeScript interface definition for the INode structure used in svgson ASTs. ### Method GET ### Endpoint /types/inode ### Response #### Success Response (200) - **interface** (object) - The INode structure containing name, type, value, attributes, and children. #### Response Example { "interface": { "name": "string", "type": "string", "value": "string", "attributes": "Record", "children": "INode[]" } } ``` -------------------------------- ### parse Source: https://context7.com/elrumordelaluz/svgson/llms.txt Parses an SVG string into a JSON AST. ```APIDOC ## parse(svgString) ### Description Parses an SVG string into a JSON AST. If the input contains multiple SVG elements, it returns an array of AST nodes. ### Parameters #### Request Body - **svgString** (String) - Required - The raw SVG string to parse. ### Response - **Object/Array** - The resulting AST node or array of nodes. ``` -------------------------------- ### SVGSON Stringify API Source: https://github.com/elrumordelaluz/svgson/blob/master/README.md This section covers the API endpoint for converting a JSON AST back into an SVG string. ```APIDOC ## svgson.stringify ### Description Converts a JSON Abstract Syntax Tree (AST) back into an SVG string. ### Method `svgson.stringify(ast[, options])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ast** (Object) - The JSON AST generated by `svgson.parse` or `svgson.parseSync`. - **options.transformAttr** (Function) - Optional. A function to apply on each attribute when stringifying. It should return the transformed attribute string (key="value"). Default: `function(key, value, escape) { return `${key}="${escape(value)}"` }` - **options.transformNode** (Function) - Optional. A function to apply on each node when stringifying. It should return the transformed node. Default: `function(node){ return node }` - **options.selfClose** (Boolean) - Optional. If true, self-closing tags will be used where appropriate. Default: `true` ### Response #### Success Response (String) - Returns the SVG content as a string. ### Request Example ```javascript const { parse, stringify } = require('svgson'); const svgString = ``; parse(svgString).then((json) => { const svg = stringify(json); console.log(svg); }); ``` ### Pretty Printing To generate pretty-formatted SVG output, you can use the `pretty` npm module: ```javascript const pretty = require('pretty'); const formattedSvg = pretty(svg); console.log(formattedSvg); ``` ``` -------------------------------- ### stringify with selfClose Source: https://context7.com/elrumordelaluz/svgson/llms.txt Controls whether empty elements are rendered as self-closing tags. ```APIDOC ## stringify(ast, { selfClose }) ### Description Controls whether empty elements are rendered as self-closing tags or with explicit closing tags. ### Parameters #### Request Body - **selfClose** (Boolean) - Optional - Default is true. Set to false to force explicit closing tags. ``` -------------------------------- ### Asynchronous SVG Parsing Source: https://context7.com/elrumordelaluz/svgson/llms.txt Asynchronously parses an SVG string and returns a Promise that resolves to a JSON AST representation. Supports optional configuration for node transformations and camelCase attribute conversion. ```APIDOC ## Asynchronous SVG Parsing ### Description Asynchronously parses an SVG string and returns a Promise that resolves to a JSON AST representation. The function accepts an optional configuration object for transforming nodes and converting attribute names to camelCase. ### Method `parse` ### Parameters - `svgString` (string) - Required - The SVG content to parse. - `options` (object) - Optional - Configuration options. - `camelcase` (boolean) - Optional - Converts hyphenated attribute names to camelCase. Defaults to `false`. - `transformNode` (function) - Optional - A function to transform each node during parsing. ### Request Example ```javascript const { parse } = require('svgson') const svg = ` ` parse(svg) .then((json) => { console.log(JSON.stringify(json, null, 2)) }) .catch((error) => { console.error('Failed to parse SVG:', error.message) }) ``` ### Response #### Success Response (Promise resolves to JSON AST) - `name` (string) - The name of the SVG element (e.g., 'svg', 'circle', 'rect'). - `type` (string) - The type of the node (e.g., 'element', 'text'). - `value` (string) - The text content of the node (if applicable). - `attributes` (object) - An object containing the attributes of the SVG element. - `children` (array) - An array of child nodes. #### Response Example ```json { "name": "svg", "type": "element", "value": "", "attributes": { "viewBox": "0 0 100 100", "width": "100", "height": "100" }, "children": [ { "name": "circle", "type": "element", "value": "", "attributes": { "r": "15", "data-name": "circle", "stroke-linecap": "round" }, "children": [] }, { "name": "rect", "type": "element", "value": "", "attributes": { "x": "10", "y": "10", "width": "50", "height": "50", "fill": "#bada55" }, "children": [] } ] } ``` ``` -------------------------------- ### Synchronous SVG Parsing Source: https://context7.com/elrumordelaluz/svgson/llms.txt Synchronously parses an SVG string and returns the JSON AST directly. Accepts the same options as the async `parse` function and throws an error if the input is invalid. ```APIDOC ## Synchronous SVG Parsing ### Description Synchronously parses an SVG string and returns the JSON AST directly without a Promise wrapper. Accepts the same options as the async `parse` function. Throws an error if the input is invalid. ### Method `parseSync(svgString, options)` ### Parameters - `svgString` (string) - Required - The SVG content to parse. - `options` (object) - Optional - Configuration options. - `camelcase` (boolean) - Optional - Converts hyphenated attribute names to camelCase. Defaults to `false`. - `transformNode` (function) - Optional - A function to transform each node during parsing. ### Request Example ```javascript const { parseSync } = require('svgson') const svg = ` Hello ` try { const json = parseSync(svg, { camelcase: false }) console.log('Root element:', json.name) console.log('Number of children:', json.children.length) console.log('First child:', json.children[0].name) console.log('Path data:', json.children[0].attributes.d) json.children.forEach((child) => { console.log(`Element: ${child.name}, Attributes:`, child.attributes) }) } catch (error) { console.error('Invalid SVG:', error.message) } ``` ### Response #### Success Response (JSON AST) - `name` (string) - The name of the SVG element (e.g., 'svg', 'circle', 'rect'). - `type` (string) - The type of the node (e.g., 'element', 'text'). - `value` (string) - The text content of the node (if applicable). - `attributes` (object) - An object containing the attributes of the SVG element. - `children` (array) - An array of child nodes. #### Error Response - Throws an error if the SVG string is invalid. ``` -------------------------------- ### SVGSON Parsing API Source: https://github.com/elrumordelaluz/svgson/blob/master/README.md This section covers the API endpoints for parsing SVG content into a JSON AST. ```APIDOC ## svgson.parse ### Description Parses an SVG string into a JSON Abstract Syntax Tree (AST). ### Method `svgson.parse(input[, options])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (String) - The SVG content to parse. - **options.transformNode** (Function) - Optional. A function to apply on each node during parsing. It should return the transformed node. Default: `function(node){ return node }` - **options.camelcase** (Boolean) - Optional. If true, attributes will be converted to camelCase. Default: `false` ### Response #### Success Response (Promise) - Returns a `Promise` that resolves with the JSON AST of the SVG. ### Request Example ```javascript const { parse } = require('svgson'); parse(``) .then((json) => { console.log(JSON.stringify(json, null, 2)); }); ``` ## svgson.parseSync ### Description Synchronously parses an SVG string into a JSON Abstract Syntax Tree (AST). This is a synchronous version of `svgson.parse`. ### Method `svgson.parseSync(input[, options])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (String) - The SVG content to parse. - **options.transformNode** (Function) - Optional. A function to apply on each node during parsing. It should return the transformed node. Default: `function(node){ return node }` - **options.camelcase** (Boolean) - Optional. If true, attributes will be converted to camelCase. Default: `false` ### Response #### Success Response (Object) - Returns the JSON AST of the SVG directly (not wrapped in a Promise). ### Request Example ```javascript const { parseSync } = require('svgson'); const json = parseSync(``); console.log(JSON.stringify(json, null, 2)); ``` ``` -------------------------------- ### Parse Multiple SVG Elements Source: https://context7.com/elrumordelaluz/svgson/llms.txt Handles inputs containing multiple SVG elements, which results in an array of AST nodes, and iterates through them. ```javascript const { parse, stringify } = require('svgson') const multipleSvgs = ` Second SVG ` parse(multipleSvgs) .then((result) => { if (Array.isArray(result)) { result.forEach((svg, index) => { console.log(`SVG ${index + 1}:`, svg.attributes.viewBox) console.log(' Output:', stringify(svg)) }) } }) ``` -------------------------------- ### Parse SVG string to JSON AST Source: https://context7.com/elrumordelaluz/svgson/llms.txt Asynchronously parses an SVG string into a JSON AST representation using the parse function. This method returns a Promise that resolves with the parsed object structure. ```javascript const { parse } = require('svgson') const svg = ` ` parse(svg) .then((json) => { console.log(JSON.stringify(json, null, 2)) }) .catch((error) => { console.error('Failed to parse SVG:', error.message) }) ``` -------------------------------- ### Parse SVG with camelCase attributes Source: https://context7.com/elrumordelaluz/svgson/llms.txt Demonstrates parsing an SVG string while converting hyphenated attribute names to camelCase. It preserves data-* and aria-* attributes in their original format. ```javascript const { parse } = require('svgson') const svg = ` ` parse(svg, { camelcase: true }) .then((json) => { console.log(json.children[0].attributes) }) ``` -------------------------------- ### Synchronously parse SVG string Source: https://context7.com/elrumordelaluz/svgson/llms.txt Uses the parseSync function to parse an SVG string immediately without a Promise. It is useful for blocking operations where the result is needed before continuing execution. ```javascript const { parseSync } = require('svgson') const svg = ` Hello ` try { const json = parseSync(svg, { camelcase: false }) console.log('Root element:', json.name) json.children.forEach((child) => { console.log(`Element: ${child.name}, Attributes:`, child.attributes) }) } catch (error) { console.error('Invalid SVG:', error.message) } ``` -------------------------------- ### Transform SVG nodes during parsing Source: https://context7.com/elrumordelaluz/svgson/llms.txt Uses the transformNode option to reshape the AST structure during the parsing process. This is useful for mapping SVG nodes to custom formats like React-like component structures. ```javascript const { parse } = require('svgson') const svg = ` ` parse(svg, { transformNode: (node) => ({ tag: node.name, props: node.attributes, ...(node.children && node.children.length > 0 ? { children: node.children } : {}) }) }) .then((json) => { console.log(JSON.stringify(json, null, 2)) }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.