|
| 1 | +use anyhow::{Context, Result, anyhow}; |
| 2 | +use atlaspack_js_swc_core::{ |
| 3 | + Config, emit, parse, utils::ErrorBuffer, utils::error_buffer_to_diagnostics, |
| 4 | +}; |
| 5 | +use serde::Serialize; |
| 6 | +use swc_atlaskit_tokens::{ |
| 7 | + design_system_tokens_visitor, token_map::get_or_load_token_map_from_json, |
| 8 | +}; |
| 9 | +use swc_core::{ |
| 10 | + common::{ |
| 11 | + FileName, SourceMap, |
| 12 | + errors::{self, Handler}, |
| 13 | + source_map::SourceMapGenConfig, |
| 14 | + sync::Lrc, |
| 15 | + }, |
| 16 | + ecma::ast::{Module, ModuleItem, Program}, |
| 17 | +}; |
| 18 | + |
| 19 | +#[derive(Clone)] |
| 20 | +pub struct TokensPluginOptions { |
| 21 | + pub token_data_path: String, |
| 22 | + pub should_use_auto_fallback: bool, |
| 23 | + pub should_force_auto_fallback: bool, |
| 24 | + pub force_auto_fallback_exemptions: Vec<String>, |
| 25 | + pub default_theme: String, |
| 26 | +} |
| 27 | + |
| 28 | +#[derive(Clone)] |
| 29 | +pub struct TokensConfig { |
| 30 | + pub filename: String, |
| 31 | + pub project_root: String, |
| 32 | + pub is_source: bool, |
| 33 | + pub source_maps: bool, |
| 34 | + pub tokens_options: TokensPluginOptions, |
| 35 | +} |
| 36 | + |
| 37 | +#[derive(Clone, Debug, Serialize)] |
| 38 | +pub struct TokensPluginResult { |
| 39 | + pub code: String, |
| 40 | + pub map: Option<String>, |
| 41 | +} |
| 42 | + |
| 43 | +// Exclude macro expansions from source maps. |
| 44 | +struct SourceMapConfig; |
| 45 | +impl SourceMapGenConfig for SourceMapConfig { |
| 46 | + fn file_name_to_source(&self, f: &FileName) -> String { |
| 47 | + f.to_string() |
| 48 | + } |
| 49 | + |
| 50 | + fn skip(&self, f: &FileName) -> bool { |
| 51 | + matches!(f, FileName::MacroExpansion | FileName::Internal(..)) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +/// Process tokens in a single piece of code - designed to be called from somewhere that orchestrates it |
| 56 | +pub fn process_tokens_sync(code: &str, config: &TokensConfig) -> Result<TokensPluginResult> { |
| 57 | + if code.trim().is_empty() { |
| 58 | + return Err(anyhow!("Empty code input")); |
| 59 | + } |
| 60 | + |
| 61 | + let swc_config = Config { |
| 62 | + is_type_script: true, |
| 63 | + is_jsx: true, |
| 64 | + decorators: false, |
| 65 | + ..Default::default() |
| 66 | + }; |
| 67 | + |
| 68 | + let error_buffer = ErrorBuffer::default(); |
| 69 | + let handler = Handler::with_emitter(true, false, Box::new(error_buffer.clone())); |
| 70 | + errors::HANDLER.set(&handler, || { |
| 71 | + let source_map = Lrc::new(SourceMap::default()); |
| 72 | + |
| 73 | + // Parse and handle parsing errors |
| 74 | + let (module, comments) = match parse( |
| 75 | + code, |
| 76 | + &config.project_root, |
| 77 | + &config.filename, |
| 78 | + &source_map, |
| 79 | + &swc_config, |
| 80 | + ) { |
| 81 | + Ok(result) => result, |
| 82 | + Err(_parsing_errors) => { |
| 83 | + let diagnostics = error_buffer_to_diagnostics(&error_buffer, &source_map); |
| 84 | + let error_msg = diagnostics |
| 85 | + .iter() |
| 86 | + .map(|d| &d.message) |
| 87 | + .cloned() |
| 88 | + .collect::<Vec<_>>() |
| 89 | + .join("\n"); |
| 90 | + return Err(anyhow!("Parse error: {}", error_msg)); |
| 91 | + } |
| 92 | + }; |
| 93 | + |
| 94 | + let module = match module { |
| 95 | + Program::Module(module) => Program::Module(module), |
| 96 | + Program::Script(script) => Program::Module(Module { |
| 97 | + span: script.span, |
| 98 | + shebang: None, |
| 99 | + body: script.body.into_iter().map(ModuleItem::Stmt).collect(), |
| 100 | + }), |
| 101 | + }; |
| 102 | + |
| 103 | + let token_map = get_or_load_token_map_from_json(Some(&config.tokens_options.token_data_path)) |
| 104 | + .with_context(|| { |
| 105 | + format!( |
| 106 | + "Failed to load token map from: {}", |
| 107 | + config.tokens_options.token_data_path |
| 108 | + ) |
| 109 | + })?; |
| 110 | + |
| 111 | + let mut passes = design_system_tokens_visitor( |
| 112 | + comments.clone(), |
| 113 | + config.tokens_options.should_use_auto_fallback, |
| 114 | + config.tokens_options.should_force_auto_fallback, |
| 115 | + config.tokens_options.force_auto_fallback_exemptions.clone(), |
| 116 | + config.tokens_options.default_theme.clone(), |
| 117 | + !config.is_source, |
| 118 | + token_map.as_ref().map(|t| t.as_ref()), |
| 119 | + ); |
| 120 | + let module = module.apply(&mut passes); |
| 121 | + let module_result = module |
| 122 | + .module() |
| 123 | + .ok_or_else(|| anyhow!("Failed to get transformed module"))?; |
| 124 | + let (code_bytes, line_pos_buffer) = emit( |
| 125 | + source_map.clone(), |
| 126 | + comments, |
| 127 | + &module_result, |
| 128 | + config.source_maps, |
| 129 | + Some(false), // Preserve Unicode characters in tokens |
| 130 | + ) |
| 131 | + .with_context(|| "Failed to emit transformed code")?; |
| 132 | + |
| 133 | + let code = |
| 134 | + String::from_utf8(code_bytes).with_context(|| "Failed to convert emitted code to UTF-8")?; |
| 135 | + let map_json = if config.source_maps && !line_pos_buffer.is_empty() { |
| 136 | + let mut output_map_buffer = vec![]; |
| 137 | + if source_map |
| 138 | + .build_source_map_with_config(&line_pos_buffer, None, SourceMapConfig) |
| 139 | + .to_writer(&mut output_map_buffer) |
| 140 | + .is_ok() |
| 141 | + { |
| 142 | + Some(String::from_utf8(output_map_buffer).unwrap_or_default()) |
| 143 | + } else { |
| 144 | + None |
| 145 | + } |
| 146 | + } else { |
| 147 | + None |
| 148 | + }; |
| 149 | + |
| 150 | + Ok(TokensPluginResult { |
| 151 | + code, |
| 152 | + map: map_json, |
| 153 | + }) |
| 154 | + }) |
| 155 | +} |
0 commit comments