vexy-vsvg-plugin-sdk 2.4.2

Plugin SDK for vexy-vsvg
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// this_file: crates/vexy-vsvg-plugin-sdk/src/registry.rs

//! Plugin registry factory for Vexy Vsvg's 52 optimization plugins.
//!
//! This module creates a pre-populated `PluginRegistry` with all SVGO-compatible plugins,
//! their default configurations, and name mappings. It serves as the single source of truth
//! for which plugins exist and how they're configured by default.
//!
//! # Architecture
//!
//! - **Registry creation**: `create_migrated_plugin_registry()` registers all 52 plugins
//!   by name with factory closures.
//! - **Default configs**: `get_default_plugin_configs()` returns SVGO-compatible JSON configs
//!   for each plugin, including enabled/disabled state and parameter defaults.
//! - **Name listing**: `get_migrated_plugin_names()` provides a canonical list of all plugin
//!   names for validation and testing.
//!
//! # SVGO Compatibility
//!
//! Plugin names match SVGO exactly (e.g., `removeComments`, `convertColors`). The config
//! format is identical to SVGO's JSON schema, enabling drop-in replacement for existing
//! SVGO configurations.

use crate::plugins::*;
use vexy_vsvg::plugin_registry::PluginRegistry;

/// Creates a plugin registry with all 52 SVGO-compatible plugins registered.
///
/// Each plugin is registered by its SVGO name (e.g., `removeComments`) with a factory
/// closure that constructs a fresh instance. The registry uses these factories to
/// instantiate plugins on-demand during optimization.
///
/// # Returns
///
/// A `PluginRegistry` with all plugins registered and ready for use.
///
/// # Example
///
/// ```no_run
/// use vexy_vsvg_plugin_sdk::registry::create_migrated_plugin_registry;
///
/// let registry = create_migrated_plugin_registry();
/// let plugin = registry.create_plugin("removeComments");
/// ```
pub fn create_migrated_plugin_registry() -> PluginRegistry {
    let mut registry = PluginRegistry::new();

    // Register all migrated plugins using the new API
    registry.register("removeComments", RemoveCommentsPlugin::new);
    registry.register("removeEmptyAttrs", RemoveEmptyAttrsPlugin::new);
    registry.register("removeUselessDefs", RemoveUselessDefsPlugin::new);
    registry.register("collapseGroups", CollapseGroupsPlugin::new);
    registry.register("moveElemsAttrsToGroup", MoveElemsAttrsToGroupPlugin::new);
    registry.register("moveGroupAttrsToElems", MoveGroupAttrsToElemsPlugin::new);
    registry.register(
        "removeUnknownsAndDefaults",
        RemoveUnknownsAndDefaultsPlugin::new,
    );
    registry.register("convertColors", ConvertColorsPlugin::new);
    registry.register("removeViewBox", RemoveViewBoxPlugin::new);
    registry.register("mergePaths", MergePathsPlugin::new);
    registry.register("inlineStyles", InlineStylesPlugin::new);
    registry.register("cleanupIds", CleanupIdsPlugin::new);
    registry.register("convertStyleToAttrs", ConvertStyleToAttrsPlugin::new);
    registry.register("removeEmptyContainers", RemoveEmptyContainersPlugin::new);
    registry.register("removeHiddenElems", RemoveHiddenElemsPlugin::new);
    registry.register("removeEditorsNSData", RemoveEditorsNSDataPlugin::new);
    registry.register("removeElementsByAttr", RemoveElementsByAttrPlugin::new);
    registry.register("removeUnusedNS", RemoveUnusedNSPlugin::new);
    registry.register("cleanupAttrs", CleanupAttrsPlugin::new);
    registry.register(
        "cleanupEnableBackground",
        CleanupEnableBackgroundPlugin::new,
    );
    // registry.register("cleanupListOfValues", CleanupListOfValuesPlugin::new); // Not implemented yet
    registry.register("mergeStyles", MergeStylesPlugin::new);
    registry.register("removeDoctype", RemoveDoctypePlugin::new);
    registry.register("removeDimensions", RemoveDimensionsPlugin::new);
    registry.register("removeXMLProcInst", RemoveXMLProcInstPlugin::new);
    registry.register("removeMetadata", RemoveMetadataPlugin::new);
    registry.register("removeEmptyText", RemoveEmptyTextPlugin::new);
    registry.register("convertEllipseToCircle", ConvertEllipseToCirclePlugin::new);
    registry.register(
        "convertOneStopGradients",
        ConvertOneStopGradientsPlugin::new,
    );
    registry.register("convertShapeToPath", ConvertShapeToPathPlugin::new);
    registry.register("convertPathData", ConvertPathDataPlugin::new);
    registry.register("convertTransform", ConvertTransformPlugin::new);
    registry.register("applyTransforms", ApplyTransformsPlugin::new);
    registry.register("cleanupNumericValues", CleanupNumericValuesPlugin::new);
    registry.register("minifyStyles", MinifyStylesPlugin::new);
    registry.register(
        "removeNonInheritableGroupAttrs",
        RemoveNonInheritableGroupAttrsPlugin::new,
    );
    registry.register("sortAttrs", SortAttrsPlugin::new);
    registry.register("sortDefsChildren", SortDefsChildrenPlugin::new);
    registry.register("removeTitle", RemoveTitlePlugin::new);
    registry.register("removeDesc", RemoveDescPlugin::new);
    registry.register(
        "addAttributesToSVGElement",
        AddAttributesToSVGElementPlugin::new,
    );
    registry.register("addClassesToSVGElement", AddClassesToSVGElementPlugin::new);
    registry.register("removeScripts", RemoveScriptsPlugin::new);
    registry.register("removeStyleElement", RemoveStyleElementPlugin::new);
    registry.register("removeRasterImages", RemoveRasterImagesPlugin::new);
    registry.register("removeOffCanvasPaths", RemoveOffCanvasPathsPlugin::new);
    registry.register("removeAttrs", RemoveAttrsPlugin::new);
    registry.register("removeDeprecatedAttrs", RemoveDeprecatedAttrsPlugin::new);
    registry.register(
        "removeUselessTransforms",
        RemoveUselessTransformsPlugin::new,
    );
    registry.register(
        "removeUselessStrokeAndFill",
        RemoveUselessStrokeAndFillPlugin::new,
    );
    registry.register("removeXlink", RemoveXlinkPlugin::new);
    registry.register("removeXMLNS", RemoveXmlnsPlugin::new);
    registry.register("prefixIds", PrefixIdsPlugin::new);
    registry.register("reusePaths", ReusePathsPlugin::new);
    registry.register(
        "removeAttributesBySelector",
        RemoveAttributesBySelectorPlugin::new,
    );
    registry.register("usvg", UsvgPlugin::new);

    registry
}

/// Returns default SVGO-compatible configurations for all plugins.
///
/// Each config specifies whether the plugin is enabled by default and its parameter values.
/// These defaults match SVGO's behavior, ensuring identical optimization results.
///
/// # Configuration Format
///
/// Configs use two variants:
/// - `PluginConfig::Name(name)` - Plugin with no parameters
/// - `PluginConfig::WithParams { name, params }` - Plugin with JSON parameters
///
/// Many plugins are disabled by default (`enabled: false`) to match SVGO's conservative
/// optimization approach.
///
/// # Returns
///
/// A vector of 52 plugin configurations in execution order.
pub fn get_default_plugin_configs() -> Vec<vexy_vsvg::parser::config::PluginConfig> {
    use serde_json::json;
    use vexy_vsvg::parser::config::PluginConfig;

    vec![
        PluginConfig::WithParams {
            name: "removeComments".to_string(),
            params: json!({"preservePatterns": true}),
        },
        PluginConfig::Name("removeEmptyAttrs".to_string()),
        PluginConfig::Name("removeUselessDefs".to_string()),
        PluginConfig::Name("collapseGroups".to_string()),
        PluginConfig::Name("moveGroupAttrsToElems".to_string()),
        PluginConfig::WithParams {
            name: "removeUnknownsAndDefaults".to_string(),
            params: json!({
                "unknownContent": true,
                "unknownAttrs": true,
                "defaultAttrs": true,
                "defaultMarkupDeclarations": true,
                "uselessOverrides": true,
                "keepDataAttrs": true,
                "keepAriaAttrs": true,
                "keepRoleAttr": false
            }),
        },
        PluginConfig::WithParams {
            name: "convertColors".to_string(),
            params: json!({
                "currentColor": false,
                "names2hex": true,
                "rgb2hex": true,
                "convertCase": "lower",
                "shorthex": true,
                "shortname": true
            }),
        },
        PluginConfig::Name("removeViewBox".to_string()),
        PluginConfig::WithParams {
            name: "mergePaths".to_string(),
            params: json!({
                "force": false,
                "floatPrecision": 3,
                "noSpaceAfterFlags": false
            }),
        },
        PluginConfig::WithParams {
            name: "inlineStyles".to_string(),
            params: json!({
                "onlyMatchedOnce": true,
                "removeMatchedSelectors": true,
                "useMqs": true,
                "usePseudos": true
            }),
        },
        PluginConfig::WithParams {
            name: "cleanupIds".to_string(),
            params: json!({
                "remove": true,
                "minify": true,
                "preserve": [],
                "preservePrefixes": [],
                "force": false
            }),
        },
        PluginConfig::WithParams {
            name: "convertStyleToAttrs".to_string(),
            params: json!({
                "keepImportant": false
            }),
        },
        PluginConfig::Name("removeEmptyContainers".to_string()),
        PluginConfig::WithParams {
            name: "removeHiddenElems".to_string(),
            params: json!({
                "displayNone": true,
                "opacity0": true,
                "circleR0": true,
                "ellipseRX0": true,
                "ellipseRY0": true,
                "rectWidth0": true,
                "rectHeight0": true,
                "patternWidth0": true,
                "patternHeight0": true,
                "imageWidth0": true,
                "imageHeight0": true,
                "pathEmptyD": true,
                "polylineEmptyPoints": true,
                "polygonEmptyPoints": true
            }),
        },
        PluginConfig::WithParams {
            name: "removeEditorsNSData".to_string(),
            params: json!({
                "additionalNamespaces": []
            }),
        },
        PluginConfig::WithParams {
            name: "removeElementsByAttr".to_string(),
            params: json!({"enabled": false}),
        },
        PluginConfig::Name("removeUnusedNS".to_string()),
        PluginConfig::WithParams {
            name: "cleanupAttrs".to_string(),
            params: json!({
                "newlines": true,
                "trim": true,
                "spaces": true
            }),
        },
        PluginConfig::Name("cleanupEnableBackground".to_string()),
        PluginConfig::Name("mergeStyles".to_string()),
        PluginConfig::Name("removeDoctype".to_string()),
        PluginConfig::WithParams {
            name: "removeDimensions".to_string(),
            params: json!({"enabled": false}),
        },
        PluginConfig::Name("removeXMLProcInst".to_string()),
        PluginConfig::Name("removeMetadata".to_string()),
        PluginConfig::WithParams {
            name: "removeEmptyText".to_string(),
            params: json!({
                "text": true,
                "tspan": true,
                "tref": true
            }),
        },
        PluginConfig::Name("convertEllipseToCircle".to_string()),
        PluginConfig::WithParams {
            name: "convertOneStopGradients".to_string(),
            params: json!({"enabled": false}),
        },
        PluginConfig::WithParams {
            name: "convertShapeToPath".to_string(),
            params: json!({
                "convertArcs": false,
                "floatPrecision": null
            }),
        },
        PluginConfig::WithParams {
            name: "convertPathData".to_string(),
            params: json!({
                "floatPrecision": 3,
                "transformPrecision": 5,
                "removeUseless": true,
                "collapseRepeated": true,
                "utilizeAbsolute": true,
                "leadingZero": true,
                "negativeExtraSpace": true
            }),
        },
        PluginConfig::WithParams {
            name: "convertTransform".to_string(),
            params: json!({
                "convertToShorts": true,
                "floatPrecision": 3,
                "transformPrecision": 5,
                "matrixToTransform": true,
                "shortTranslate": true,
                "shortScale": true,
                "shortRotate": true,
                "removeUseless": true,
                "collapseIntoOne": true,
                "leadingZero": true,
                "negativeExtraSpace": false
            }),
        },
        PluginConfig::WithParams {
            name: "cleanupNumericValues".to_string(),
            params: json!({
                "floatPrecision": 3,
                "leadingZero": true,
                "defaultPx": true,
                "convertToPx": true
            }),
        },
        PluginConfig::WithParams {
            name: "minifyStyles".to_string(),
            params: json!({
                "restructure": true,
                "forceMediaMerge": false,
                "comments": false,
                "usage": null
            }),
        },
        PluginConfig::Name("removeNonInheritableGroupAttrs".to_string()),
        PluginConfig::WithParams {
            name: "sortAttrs".to_string(),
            params: json!({
                "order": ["id", "width", "height", "x", "x1", "x2", "y", "y1", "y2", "cx", "cy", "r", "fill", "stroke", "marker", "d", "points"],
                "xmlnsOrder": "front"
            }),
        },
        PluginConfig::Name("sortDefsChildren".to_string()),
        PluginConfig::Name("removeTitle".to_string()),
        PluginConfig::Name("removeDesc".to_string()),
        PluginConfig::WithParams {
            name: "addAttributesToSVGElement".to_string(),
            params: json!({"enabled": false}),
        },
        PluginConfig::WithParams {
            name: "addClassesToSVGElement".to_string(),
            params: json!({"enabled": false}),
        },
        PluginConfig::WithParams {
            name: "removeScripts".to_string(),
            params: json!({"enabled": false}),
        },
        PluginConfig::WithParams {
            name: "removeStyleElement".to_string(),
            params: json!({"enabled": false}),
        },
        PluginConfig::WithParams {
            name: "removeRasterImages".to_string(),
            params: json!({"enabled": false}),
        },
        PluginConfig::WithParams {
            name: "removeOffCanvasPaths".to_string(),
            params: json!({"enabled": false}),
        },
        PluginConfig::WithParams {
            name: "removeAttrs".to_string(),
            params: json!({"enabled": false}),
        },
        PluginConfig::WithParams {
            name: "removeDeprecatedAttrs".to_string(),
            params: json!({"enabled": false}),
        },
        PluginConfig::Name("removeUselessTransforms".to_string()),
        PluginConfig::Name("removeUselessStrokeAndFill".to_string()),
        PluginConfig::WithParams {
            name: "removeXlink".to_string(),
            params: json!({
                "enabled": false,
                "includeLegacy": true
            }),
        },
        PluginConfig::WithParams {
            name: "removeXMLNS".to_string(),
            params: json!({"enabled": false}),
        },
        PluginConfig::WithParams {
            name: "prefixIds".to_string(),
            params: json!({"enabled": false}),
        },
        PluginConfig::WithParams {
            name: "reusePaths".to_string(),
            params: json!({"enabled": false}),
        },
        PluginConfig::WithParams {
            name: "removeAttributesBySelector".to_string(),
            params: json!({"enabled": false}),
        },
    ]
}

/// Returns the canonical list of all 52 plugin names.
///
/// This list is the single source of truth for which plugins exist. Used for validation,
/// testing, and documentation generation.
///
/// # Returns
///
/// A vector of SVGO-compatible plugin names in alphabetical order (excluding prefixes).
pub fn get_migrated_plugin_names() -> Vec<&'static str> {
    vec![
        "removeComments",
        "removeEmptyAttrs",
        "removeUselessDefs",
        "collapseGroups",
        "moveGroupAttrsToElems",
        "removeUnknownsAndDefaults",
        "convertColors",
        "removeViewBox",
        "mergePaths",
        "inlineStyles",
        "cleanupIds",
        "convertStyleToAttrs",
        "removeEmptyContainers",
        "removeHiddenElems",
        "removeEditorsNSData",
        "removeElementsByAttr",
        "removeUnusedNS",
        "cleanupAttrs",
        "cleanupEnableBackground",
        "mergeStyles",
        "removeDoctype",
        "removeDimensions",
        "removeXMLProcInst",
        "removeMetadata",
        "removeEmptyText",
        "convertEllipseToCircle",
        "convertOneStopGradients",
        "convertShapeToPath",
        "convertPathData",
        "convertTransform",
        "cleanupNumericValues",
        "minifyStyles",
        "removeNonInheritableGroupAttrs",
        "sortAttrs",
        "sortDefsChildren",
        "removeTitle",
        "removeDesc",
        "addAttributesToSVGElement",
        "addClassesToSVGElement",
        "removeScripts",
        "removeStyleElement",
        "removeRasterImages",
        "removeOffCanvasPaths",
        "removeAttrs",
        "removeDeprecatedAttrs",
        "removeUselessTransforms",
        "removeUselessStrokeAndFill",
        "removeXlink",
        "removeXMLNS",
        "prefixIds",
        "reusePaths",
        "removeAttributesBySelector",
    ]
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_create_migrated_plugin_registry() {
        let registry = create_migrated_plugin_registry();

        // Check that all migrated plugins are registered
        for plugin_name in get_migrated_plugin_names() {
            assert!(
                registry.create_plugin(plugin_name).is_some(),
                "Plugin {} should be registered",
                plugin_name
            );
        }
    }

    #[test]
    fn test_get_default_plugin_configs() {
        let configs = get_default_plugin_configs();

        // Check that we have configs for all migrated plugins
        assert_eq!(configs.len(), get_migrated_plugin_names().len());

        // Check that we have a config for each plugin name
        let config_names: Vec<&str> = configs.iter().map(|c| c.name()).collect();
        for plugin_name in get_migrated_plugin_names() {
            assert!(
                config_names.contains(&plugin_name),
                "Plugin {} should have a config",
                plugin_name
            );
        }
    }

    #[test]
    fn test_apply_migrated_plugins() {
        let registry = create_migrated_plugin_registry();
        let configs = get_default_plugin_configs();

        // Create a test document
        let mut doc = vexy_vsvg::ast::Document::new();

        // Apply all plugins - should not error
        let result = registry.apply_plugins(&mut doc, &configs);
        assert!(result.is_ok(), "Applying migrated plugins should succeed");
    }

    #[test]
    fn test_plugin_parameter_validation() {
        let registry = create_migrated_plugin_registry();

        // Test valid parameters
        let valid_config = vexy_vsvg::parser::config::PluginConfig::WithParams {
            name: "removeComments".to_string(),
            params: json!({"preservePatterns": false}),
        };

        let mut doc = vexy_vsvg::ast::Document::new();
        let result = registry.apply_plugin(&mut doc, &valid_config);
        assert!(result.is_ok(), "Valid parameters should be accepted");

        // Test invalid parameters
        let invalid_config = vexy_vsvg::parser::config::PluginConfig::WithParams {
            name: "removeComments".to_string(),
            params: json!({"preservePatterns": "invalid"}),
        };

        let mut doc2 = vexy_vsvg::ast::Document::new();
        let result = registry.apply_plugin(&mut doc2, &invalid_config);
        assert!(result.is_err(), "Invalid parameters should be rejected");
    }
}