webfont-generator 0.7.0

Generate webfonts (SVG, TTF, EOT, WOFF, WOFF2) from SVG icons
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
//! # webfont-generator
//!
//! Generate webfonts (SVG, TTF, EOT, WOFF, WOFF2) from SVG icon files.
//!
//! ## Library usage
//!
//! ```rust,no_run
//! use webfont_generator::{GenerateWebfontsOptions, FontType};
//!
//! // Async API (requires a tokio runtime)
//! # async fn example() -> std::io::Result<()> {
//! let options = GenerateWebfontsOptions {
//!     dest: "output".to_owned(),
//!     files: vec!["icons/add.svg".to_owned(), "icons/remove.svg".to_owned()],
//!     font_name: Some("my-icons".to_owned()),
//!     types: Some(vec![FontType::Woff2, FontType::Woff]),
//!     ..Default::default()
//! };
//!
//! let result = webfont_generator::generate(options, None).await?;
//! if let Some(woff2) = result.woff2_bytes() {
//!     println!("Generated WOFF2: {} bytes", woff2.len());
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ```rust,no_run
//! use webfont_generator::{GenerateWebfontsOptions, FontType};
//!
//! // Synchronous API
//! let options = GenerateWebfontsOptions {
//!     dest: "output".to_owned(),
//!     files: vec!["icons/add.svg".to_owned()],
//!     write_files: Some(false),
//!     ..Default::default()
//! };
//!
//! let result = webfont_generator::generate_sync(options, None).unwrap();
//! ```
//!
//! ## CLI
//!
//! Install the CLI binary with:
//!
//! ```sh
//! cargo install webfont-generator --features cli
//! ```
//!
//! Then run:
//!
//! ```sh
//! webfont-generator --dest ./dist/fonts ./icons/
//! ```
//!
//! ## Feature flags
//!
//! - **`cli`**: Builds the `webfont-generator` CLI binary (adds `clap` dependency).
//!   Not enabled by default — use `cargo install webfont-generator --features cli`.
//! - **`napi`**: Enables Node.js NAPI bindings for use as a native addon.

#[cfg(feature = "bench")]
pub mod bench_support;
mod byte_helpers;
mod formats;
mod incremental;
mod input;
mod output;
mod pipeline;
mod rendering;
mod result;
mod sfnt;
mod svg;
#[cfg(test)]
mod test_helpers;
mod types;

#[cfg(feature = "napi")]
use napi::Status;
#[cfg(feature = "napi")]
use napi::threadsafe_function::ThreadsafeFunction;
#[cfg(feature = "napi")]
use napi_derive::napi;
#[cfg(feature = "napi")]
use std::sync::Mutex;

use input::{
    ResolvedGenerateWebfontsOptions, build_variant_family_sources,
    finalize_generate_webfonts_options, load_svg_files, load_variant_svg_files,
    resolve_generate_webfonts_options, resolve_missing_glyphs, validate_generate_webfonts_options,
};
#[cfg(feature = "napi")]
use input::{load_svg_files_napi, load_variant_svg_files_napi};
use output::write_generate_webfonts_result;
use pipeline::{generate_variant_webfonts_sync, generate_webfonts_sync};
#[cfg(feature = "napi")]
use rendering::{
    CachedTemplateData, SharedTemplateData, apply_context_function, build_css_context,
    build_html_context, build_html_registry_and_dependencies,
};
#[cfg(feature = "napi")]
use result::to_napi_err;
pub use result::{GenerateWebfontsResult, RegenerateError};
pub use types::{
    CssContext, FontType, FontVariant, FormatOptions, GenerateWebfontsOptions, GlyphChange,
    GlyphChangeEntry, HtmlContext, MissingGlyphBehavior, MissingGlyphOptions, RegenerationFiles,
    SvgFormatOptions, TemplateVariant, TtfFormatOptions, VariantFileSet, Woff2FormatOptions,
    WoffFormatOptions,
};

type PreparedVariantInput = (
    svg::types::PreparedVariantFamily,
    Vec<input::LoadedSvgFile>,
    Option<svg::VariantGlyphCache>,
);

fn prepare_variant_family(
    options: &mut ResolvedGenerateWebfontsOptions,
    source_files: Vec<Vec<input::LoadedSvgFile>>,
) -> std::io::Result<PreparedVariantInput> {
    let mut cache = options.incremental.then(svg::VariantGlyphCache::default);
    let family = prepare_variant_family_cached(
        options,
        source_files.iter().map(Vec::as_slice).collect(),
        cache.as_mut(),
    )?;
    let sources = source_files.into_iter().flatten().collect();
    Ok((family, sources, cache))
}

fn prepare_variant_family_cached(
    options: &mut ResolvedGenerateWebfontsOptions,
    source_files: Vec<&[input::LoadedSvgFile]>,
    cache: Option<&mut svg::VariantGlyphCache>,
) -> std::io::Result<svg::types::PreparedVariantFamily> {
    let (mut family, codepoints) = build_variant_family_sources(
        source_files,
        &options.explicit_codepoints,
        options.start_codepoint,
    )?;
    let variants = options
        .variants
        .as_ref()
        .expect("variant source preparation requires resolved variants");
    let variant_names = variants
        .variants
        .iter()
        .map(|variant| variant.name.as_str())
        .collect::<Vec<_>>();
    let fallback_index = options.missing_glyphs.variant.as_deref().map(|name| {
        variant_names
            .iter()
            .position(|variant_name| *variant_name == name)
            .expect("validated fallback must name a resolved variant")
    });
    resolve_missing_glyphs(
        &mut family,
        options.missing_glyphs.behavior,
        fallback_index,
        &variant_names,
    )?;
    options.codepoints = codepoints;
    let svg_options = svg::svg_options_from_options(options);
    let prepared = match cache {
        Some(cache) => svg::prepare_variant_svg_family_cached(&svg_options, &family, Some(cache))?,
        None => svg::prepare_variant_svg_family(&svg_options, &family)?,
    };
    Ok(prepared)
}

#[cfg(feature = "napi")]
fn variant_preparation_join_error(error: tokio::task::JoinError) -> napi::Error {
    napi::Error::new(
        Status::GenericFailure,
        format!("Native variant preparation task failed: {error}"),
    )
}

#[cfg(all(test, feature = "napi"))]
#[unsafe(no_mangle)]
extern "C" fn napi_call_threadsafe_function(
    _: napi::sys::napi_threadsafe_function,
    _: *mut std::ffi::c_void,
    _: napi::sys::napi_threadsafe_function_call_mode,
) -> napi::sys::napi_status {
    0
}

#[cfg(all(test, feature = "napi"))]
#[unsafe(no_mangle)]
extern "C" fn napi_release_threadsafe_function(
    _: napi::sys::napi_threadsafe_function,
    _: napi::sys::napi_threadsafe_function_release_mode,
) -> napi::sys::napi_status {
    0
}

#[cfg(all(test, feature = "napi"))]
#[tokio::test]
async fn napi_variant_preparation_reports_panicking_worker() {
    let join_error = tokio::task::spawn_blocking(|| panic!("variant preparation panic"))
        .await
        .unwrap_err();
    let error = variant_preparation_join_error(join_error);

    assert!(
        error
            .reason
            .starts_with("Native variant preparation task failed:")
    );
}

#[cfg(all(test, feature = "napi"))]
#[tokio::test]
async fn napi_variant_generation_succeeds_after_preparing_sources() {
    let path = test_helpers::webfont_fixture("add.svg");
    let variants = vec![
        FontVariant {
            name: "small".to_owned(),
            files: vec![path.clone()],
            weight: Some(300),
            default: Some(true),
        },
        FontVariant {
            name: "large".to_owned(),
            files: vec![path.clone()],
            weight: Some(700),
            default: None,
        },
    ];
    let options = GenerateWebfontsOptions {
        dest: "artifacts".to_owned(),
        files: vec![],
        types: Some(vec![FontType::Woff2]),
        variants: Some(variants.clone()),
        write_files: Some(false),
        ..Default::default()
    };

    let result = generate_webfonts(options, None, None, None)
        .await
        .expect("variant generation should succeed");
    assert!(result.woff2_bytes().is_some());
    assert!(result.eot_bytes().is_none());

    let mut duplicate = variants;
    duplicate[0].files.push(path);
    let error = generate_webfonts(
        GenerateWebfontsOptions {
            dest: "artifacts".to_owned(),
            files: vec![],
            types: Some(vec![FontType::Woff2]),
            variants: Some(duplicate),
            ..Default::default()
        },
        None,
        None,
        None,
    )
    .await
    .err()
    .expect("duplicate names within one variant should fail");
    assert!(error.reason.contains("must be unique"));
}

#[cfg(all(test, feature = "napi"))]
#[tokio::test]
async fn napi_generation_keeps_the_ordinary_source_path() {
    let result = generate_webfonts(
        GenerateWebfontsOptions {
            css: Some(false),
            dest: "artifacts".to_owned(),
            files: vec![test_helpers::webfont_fixture("add.svg")],
            html: Some(false),
            types: Some(vec![FontType::Svg]),
            write_files: Some(false),
            ..Default::default()
        },
        None,
        None,
        None,
    )
    .await
    .expect("ordinary NAPI generation should succeed");

    assert!(result.svg_string().is_some());
}

/// Generate a webfont from a set of SVG files.
///
/// Loads the SVGs listed in `options.files`, builds the configured
/// `options.types` formats, optionally writes them (along with the CSS and
/// HTML preview) to `options.dest`, and returns a `GenerateWebfontsResult`
/// holding the font bytes and template-rendering methods.
///
/// Multi-variant input generates one shared variable font per requested modern format.
///
/// Optional callbacks:
/// - `rename(paths)` — derive custom glyph names for the batch of SVG file paths.
/// - `cssContext(ctx)` — mutate the Handlebars context before CSS rendering;
///   return the (possibly mutated) context.
/// - `htmlContext(ctx)` — same, but for the HTML preview.
#[cfg(feature = "napi")]
#[napi]
#[allow(clippy::type_complexity)] // NAPI proc macro requires the verbose ThreadsafeFunction type
pub async fn generate_webfonts(
    options: GenerateWebfontsOptions,
    rename: Option<ThreadsafeFunction<Vec<String>, Vec<String>, Vec<String>, Status, false>>,
    css_context: Option<
        ThreadsafeFunction<
            serde_json::Map<String, serde_json::Value>,
            serde_json::Map<String, serde_json::Value>,
            serde_json::Map<String, serde_json::Value>,
            Status,
            false,
        >,
    >,
    html_context: Option<
        ThreadsafeFunction<
            serde_json::Map<String, serde_json::Value>,
            serde_json::Map<String, serde_json::Value>,
            serde_json::Map<String, serde_json::Value>,
            Status,
            false,
        >,
    >,
) -> napi::Result<GenerateWebfontsResult> {
    validate_generate_webfonts_options(&options)?;
    let mut result = if options.variants.is_some() {
        let mut resolved_options = resolve_generate_webfonts_options(options)?;
        let variant_paths = resolved_options
            .variants
            .as_ref()
            .expect("validated variant options must resolve variants")
            .variants
            .iter()
            .map(|variant| variant.files.clone())
            .collect::<Vec<_>>();
        let source_files = load_variant_svg_files_napi(&variant_paths, rename.as_ref()).await?;
        let generation = tokio::task::spawn_blocking(move || {
            let (family, source_files, cache) =
                prepare_variant_family(&mut resolved_options, source_files)?;
            generate_variant_webfonts_sync(resolved_options, source_files, family, cache)
        });
        generation.await.map_err(variant_preparation_join_error)??
    } else {
        let source_files = load_svg_files_napi(&options.files, rename.as_ref(), true).await?;
        let mut resolved_options = resolve_generate_webfonts_options(options)?;
        finalize_generate_webfonts_options(&mut resolved_options, &source_files)?;
        tokio::task::spawn_blocking(move || generate_webfonts_sync(resolved_options, source_files))
            .await
            .map_err(|error| {
                napi::Error::new(
                    Status::GenericFailure,
                    format!("Native webfont generation task failed: {error}"),
                )
            })??
    };

    // Pre-compute mutated contexts via ThreadsafeFunction (async-safe).
    // When callbacks are present, we build SharedTemplateData here and seed the
    // OnceLock cache so it isn't re-created in get_cached() / writeFiles.
    if css_context.is_some() || html_context.is_some() {
        let shared =
            SharedTemplateData::new(&result.options, &result.source_files).map_err(to_napi_err)?;

        let mut css_ctx = build_css_context(&result.options, &shared);
        if css_context.is_some() {
            css_ctx = apply_context_function(css_ctx, css_context.as_ref())
                .await
                .map_err(to_napi_err)?;
            css_ctx.insert(
                "__webfontVariantMode".to_owned(),
                serde_json::Value::Bool(result.options.variants.is_some()),
            );
            result.css_context = Some(css_ctx.clone());
        }

        let mut html_ctx =
            if result.options.html || html_context.is_some() || result.options.variants.is_some() {
                if result.options.variants.is_some() && css_context.is_some() {
                    rendering::build_html_context_with_css(
                        &result.options,
                        &shared,
                        &result.source_files,
                        &css_ctx,
                    )
                    .map_err(to_napi_err)?
                } else {
                    build_html_context(&result.options, &shared, &result.source_files, None)
                        .map_err(to_napi_err)?
                }
            } else {
                serde_json::Map::new()
            };
        if html_context.is_some() {
            html_ctx = apply_context_function(html_ctx, html_context.as_ref())
                .await
                .map_err(to_napi_err)?;
            result.html_context = Some(html_ctx.clone());
        }

        // Seed the OnceLock -- avoids re-creating SharedTemplateData in get_cached()
        let (html_registry, html_template_dependencies) =
            build_html_registry_and_dependencies(&result.options).map_err(to_napi_err)?;
        let css_hbs_context = handlebars::Context::wraps(&css_ctx).map_err(to_napi_err)?;
        let html_hbs_context = handlebars::Context::wraps(&html_ctx).map_err(to_napi_err)?;
        let _ = result.cached.set(Ok(CachedTemplateData {
            shared,
            css_context: css_ctx,
            css_hbs_context: Mutex::new(css_hbs_context),
            html_context: html_ctx,
            html_hbs_context: Mutex::new(html_hbs_context),
            html_template_dependencies,
            html_registry,
            render_cache: Mutex::new(Default::default()),
        }));
    }

    if result.options.write_files
        && let Some(written) = write_generate_webfonts_result(&result).await?
    {
        // Only incremental results can call `regenerate`, so only they need write-skip state.
        result.seed_written_outputs(written);
    }

    Ok(result)
}

/// A glyph rename function that maps file stems to custom glyph names.
pub type RenameFn = Box<dyn Fn(&str) -> String + Send + Sync>;

/// Generate webfonts from SVG files.
///
/// This is the pure Rust async entry point. Requires a tokio runtime. Multi-variant input generates
/// one shared variable font per requested modern format.
pub async fn generate(
    options: GenerateWebfontsOptions,
    rename: Option<RenameFn>,
) -> std::io::Result<GenerateWebfontsResult> {
    validate_generate_webfonts_options(&options)?;
    let result = if options.variants.is_some() {
        let mut resolved_options = resolve_generate_webfonts_options(options)?;
        let variant_paths = resolved_options
            .variants
            .as_ref()
            .expect("validated variant options must resolve variants")
            .variants
            .iter()
            .map(|variant| variant.files.clone())
            .collect::<Vec<_>>();
        let source_files = load_variant_svg_files(&variant_paths, rename.as_deref()).await?;
        let generation = tokio::task::spawn_blocking(move || {
            let (family, source_files, cache) =
                prepare_variant_family(&mut resolved_options, source_files)?;
            generate_variant_webfonts_sync(resolved_options, source_files, family, cache)
        });
        generation.await.map_err(std::io::Error::other)??
    } else {
        let source_files = load_svg_files(&options.files, rename.as_deref()).await?;
        let mut resolved_options = resolve_generate_webfonts_options(options)?;
        finalize_generate_webfonts_options(&mut resolved_options, &source_files)?;
        tokio::task::spawn_blocking(move || generate_webfonts_sync(resolved_options, source_files))
            .await
            .map_err(std::io::Error::other)??
    };

    if result.options.write_files
        && let Some(written) = write_generate_webfonts_result(&result).await?
    {
        // Only incremental results can call `regenerate`, so only they need write-skip state.
        result.seed_written_outputs(written);
    }

    Ok(result)
}

/// Synchronous version of [`generate`]. Spawns a tokio runtime internally and has the same source
/// preparation behavior for multi-variant input.
pub fn generate_sync(
    options: GenerateWebfontsOptions,
    rename: Option<RenameFn>,
) -> std::io::Result<GenerateWebfontsResult> {
    tokio::runtime::Runtime::new()?.block_on(generate(options, rename))
}