From b35fe46cf88094216f472059ae3d9a2314dd8385 Mon Sep 17 00:00:00 2001 From: codecaaron Date: Sat, 28 Nov 2026 05:50:52 -0500 Subject: [PATCH 1/3] fix(extract): two unsound prunings and an at-rule diagnostic position staticCss stopped protecting a variant with no defaultVariant once such variants were tracked: forced usage was only injected when a default existed. It is now always injected. A registered view transition was dropped in production unless a named import resolved to an analysed file, so a namespace import, a dynamic import or a system imported from a package lost its CSS. A collection is now kept whole whenever its use cannot be bounded, reusing the signal that already turns component pruning off. An unsupported at-rule was reported at its block's opening brace with the block's source as the value; it is reported at the at-rule's key. The unsupported-feature value field has one form, a failing theme-values script no longer fails the system load, and opacity modifiers in the theme values follow the Rust rules. Co-Authored-By: Claude Fable 5.2 --- .../__tests__/target-support.test.ts | 22 +++++ .../__tests__/view-transition-usage.test.ts | 46 +++++++--- .../crates/extractor/src/analyze_css.rs | 44 +++++++-- .../crates/extractor/src/forced_usage.rs | 28 +++--- .../crates/extractor/src/registered_uses.rs | 92 ++++++++++++++++++- .../crates/extractor/src/value_site.rs | 22 +++-- .../extract/crates/system-loader/src/lib.rs | 13 ++- 7 files changed, 218 insertions(+), 49 deletions(-) diff --git a/packages/_integration/__tests__/target-support.test.ts b/packages/_integration/__tests__/target-support.test.ts index 1f56d0f0..c5db8dee 100644 --- a/packages/_integration/__tests__/target-support.test.ts +++ b/packages/_integration/__tests__/target-support.test.ts @@ -62,3 +62,25 @@ export const App = () => ; `; expect(reported({ safari: 15 << 16 }, outlined)).toEqual([]); }); + +test("an unsupported at-rule is reported at the at-rule's key", () => { + const queried = `import { ds } from './setup'; +export const Grid = ds + .styles({ + '@container (min-width: 10px)': { display: 'grid' }, + }) + .asElement('div'); +export const App = () => ; +`; + const lacking = reported({ safari: 15 << 16 }, queried).filter( + (d) => d.reason === 'unsupported-at-rule' + ); + expect(lacking).toHaveLength(1); + expect(lacking[0]).toMatchObject({ + component: 'Grid', + line: 4, + column: 5, + value: "'@container (min-width: 10px)'", + }); + expect(lacking[0]!.property).toBeUndefined(); +}); diff --git a/packages/_integration/__tests__/view-transition-usage.test.ts b/packages/_integration/__tests__/view-transition-usage.test.ts index 61f6b533..93a5a255 100644 --- a/packages/_integration/__tests__/view-transition-usage.test.ts +++ b/packages/_integration/__tests__/view-transition-usage.test.ts @@ -11,25 +11,28 @@ const transitions = { }, }; -const sheetFor = (page: string): string => { +const system = { + path: 'fixtures/transitions.ts', + source: `import { createViewTransitions } from './setup';\nexport const transitions = createViewTransitions({ slide: { old: { animationDuration: '250ms' } } });\n`, +}; + +const rule = '::view-transition-old(*.animus-vt-slide)'; + +const sheetOf = (files: { path: string; source: string }[]): string => { clearAnalysisCache(); const manifest = JSON.parse( - analyzeProjectFull( - JSON.stringify([ - { - path: 'fixtures/transitions.ts', - source: `import { createViewTransitions } from './setup';\nexport const transitions = createViewTransitions({ slide: { old: { animationDuration: '250ms' } } });\n`, - }, - { path: 'fixtures/page.tsx', source: page }, - ]), - { viewTransitionsJson: JSON.stringify(transitions), devMode: false } - ) + analyzeProjectFull(JSON.stringify(files), { + viewTransitionsJson: JSON.stringify(transitions), + devMode: false, + }) ) as { sheets: { global: string } }; return manifest.sheets.global; }; +const sheetFor = (page: string): string => + sheetOf([system, { path: 'fixtures/page.tsx', source: page }]); + test('a view transition referenced only from keeps its CSS under pruning', () => { - const rule = '::view-transition-old(*.animus-vt-slide)'; const used = sheetFor( `import { ViewTransition } from '@animus-ui/react/view-transition';\nimport { transitions } from './transitions';\nexport const Page = () =>
;\n` ); @@ -40,3 +43,22 @@ test('a view transition referenced only from keeps its CSS unde expect(used).toContain(rule); expect(unused).not.toContain(rule); }); + +test('a view transition is kept whenever its collection is reached in a way the analysis cannot bound', () => { + const namespace = sheetFor( + `import { ViewTransition } from '@animus-ui/react/view-transition';\nimport * as sys from './transitions';\nexport const Page = () =>
;\n` + ); + const dynamic = sheetFor( + `export const load = () => import('./transitions').then((m) => m.transitions.slide);\n` + ); + const unanalysedPackage = sheetOf([ + { + path: 'fixtures/page.tsx', + source: `import { ViewTransition } from '@animus-ui/react/view-transition';\nimport { transitions } from '@acme/ds';\nexport const Page = () =>
;\n`, + }, + ]); + + expect(namespace).toContain(rule); + expect(dynamic).toContain(rule); + expect(unanalysedPackage).toContain(rule); +}); diff --git a/packages/extract/crates/extractor/src/analyze_css.rs b/packages/extract/crates/extractor/src/analyze_css.rs index 1e9d1dab..0496cebc 100644 --- a/packages/extract/crates/extractor/src/analyze_css.rs +++ b/packages/extract/crates/extractor/src/analyze_css.rs @@ -562,7 +562,9 @@ impl CssDiagnostic { if let Some(found) = site.find(source) { self.offset = Some(found.start); self.value = source.get(found.start as usize..found.end as usize).map(str::to_string); - self.property.get_or_insert(found.key); + if let Some(key) = found.key { + self.property.get_or_insert(key); + } } } } @@ -3595,7 +3597,7 @@ impl FeatureScan<'_> { let seek = |written: Written| Seek { key: Some(authored_key(property)), written, breakpoint: None, origin: origin.clone() }; if let Some(record) = self.finding(format!("property:{property}"), emitted.clone(), || format!("'{property}'")) { self.found.push( - record.concerning(property).written(&declaration.value).because("unsupported-property").seeking(seek(Written::Any)), + record.concerning(property).because("unsupported-property").seeking(seek(Written::Any)), ); } for function in value_functions(&declaration.value) { @@ -3604,7 +3606,6 @@ impl FeatureScan<'_> { self.found.push( record .concerning(property) - .written(&declaration.value) .because("unsupported-function") .seeking(seek(Written::Contains(format!("{function}(")))), ); @@ -3624,9 +3625,9 @@ impl FeatureScan<'_> { } for (name, prelude) in group.conditions.iter().filter_map(at_rule_of) { if let Some(record) = self.finding(format!("at-rule:{name}"), prelude.to_string(), || format!("@{name}")) { - self.found.push(record.written(prelude).because("unsupported-at-rule").seeking(Seek { + self.found.push(record.because("unsupported-at-rule").seeking(Seek { key: Some(prelude.to_string()), - written: Written::Any, + written: Written::Key, breakpoint: None, origin: origin.clone(), })); @@ -5299,10 +5300,18 @@ fn route_values<'u>( .collect() } -fn used_registered_blocks(blocks: &Value, files: &BTreeMap) -> Value { +fn used_registered_blocks( + blocks: &Value, + files: &BTreeMap, + inputs: &CssInputs, + links: &crate::link::ProjectLinks, +) -> Value { + let collections: FxHashSet<&str> = blocks.as_object().into_iter().flatten().map(|(name, _)| name.as_str()).collect(); + let open = crate::registered_uses::unbounded(&collections, files, inputs, links); let uses: FxHashSet<&crate::registered_uses::RegisteredUse> = files.values().flat_map(|ff| &ff.registered_uses).collect(); let used = |collection: &str, key: &str| { - uses.iter().any(|used| used.collection == collection && used.key.as_deref().is_none_or(|used| used == key)) + open.contains(collection) + || uses.iter().any(|used| used.collection == collection && used.key.as_deref().is_none_or(|used| used == key)) }; let kept: serde_json::Map = blocks .as_object() @@ -11330,10 +11339,10 @@ fn run_with_system_floor( }); } let mut combined_global = global_css_raw; - let view_transitions = if inputs.dev_mode { + let view_transitions = if inputs.dev_mode || !unseen.is_empty() { inputs.view_transition_blocks.clone() } else { - inputs.view_transition_blocks.as_ref().map(|blocks| used_registered_blocks(blocks, files)) + inputs.view_transition_blocks.as_ref().map(|blocks| used_registered_blocks(blocks, files, inputs, links)) }; let registered: [(&Option, crate::theme::BlockResolver, &str); 3] = [ (&inputs.keyframes_blocks, crate::theme::resolve_keyframes_block, "keyframes"), @@ -17479,6 +17488,23 @@ export const App = () => ", r#"{"components":{"R":{"variants":"*"}}}"#, vec!["sm", "md", "lg"]), + ("", r#"{"components":{"R":{"variants":{"size":"*"}}}}"#, vec!["sm", "md", "lg"]), + ("", r#"{"components":{"R":{"variants":{"size":["lg"]}}}}"#, vec!["sm", "lg"]), + ] { + let app = format!("import {{ R }} from './r';\nexport const App = () => {app};\n"); + let mut inputs = test_inputs(); + inputs.static_css = Some(crate::forced_usage::StaticCssConfig::parse(forced).unwrap()); + let kept = kept_options_with(&[("r.tsx", recipe.as_str()), ("app.tsx", app.as_str())], &inputs); + assert_eq!(kept.0, sizes, "{recipe}{app}{forced}"); + } + } + } + #[test] fn elements_code_outside_the_analysis_receives_keep_every_option() { let every = (vec!["sm", "md", "lg"], vec!["active", "busy"]); diff --git a/packages/extract/crates/extractor/src/forced_usage.rs b/packages/extract/crates/extractor/src/forced_usage.rs index 4a3c3fec..437daeed 100644 --- a/packages/extract/crates/extractor/src/forced_usage.rs +++ b/packages/extract/crates/extractor/src/forced_usage.rs @@ -201,7 +201,7 @@ pub fn build_forced_injection( ); } ListOrAll::List(options) => { - let (declared_options, default_option) = &cfg.variants[prop]; + let (declared_options, _) = &cfg.variants[prop]; for option in options { if !declared_options.contains(option) { warn( @@ -215,13 +215,11 @@ pub fn build_forced_injection( ); continue; } - if default_option.is_some() { - out.scan.variant_usages.push(VariantUsage { - component_binding: name.clone(), - variant_prop: prop.clone(), - value: VariantValue::Literal(option.clone()), - }); - } + out.scan.variant_usages.push(VariantUsage { + component_binding: name.clone(), + variant_prop: prop.clone(), + value: VariantValue::Literal(option.clone()), + }); record_forced_variant(&mut out, name, prop, option, observed); } } @@ -333,14 +331,12 @@ fn force_variant_prop_all( cfg: &ComponentUsageConfig, observed: &UsageLedger, ) { - let (options, default_option) = &cfg.variants[prop]; - if default_option.is_some() { - out.scan.variant_usages.push(VariantUsage { - component_binding: binding.to_string(), - variant_prop: prop.to_string(), - value: VariantValue::Dynamic, - }); - } + let (options, _) = &cfg.variants[prop]; + out.scan.variant_usages.push(VariantUsage { + component_binding: binding.to_string(), + variant_prop: prop.to_string(), + value: VariantValue::Dynamic, + }); let mut sorted: Vec<&String> = options.iter().collect(); sorted.sort(); for option in sorted { diff --git a/packages/extract/crates/extractor/src/registered_uses.rs b/packages/extract/crates/extractor/src/registered_uses.rs index db83bc9f..efee7efe 100644 --- a/packages/extract/crates/extractor/src/registered_uses.rs +++ b/packages/extract/crates/extractor/src/registered_uses.rs @@ -1,6 +1,14 @@ +use std::collections::BTreeMap; + +use animus_system_loader::module_table::{ExportLookup, ImportName, ModuleIndex, Terminal}; use oxc::ast::ast::{CallExpression, ExportSpecifier, Expression, IdentifierReference, Program, StaticMemberExpression}; use oxc::ast_visit::Visit; -use rustc_hash::FxHashMap; +use rustc_hash::{FxHashMap, FxHashSet}; + +use crate::analyze_css::CssInputs; +use crate::facts::FileFacts; +use crate::identity::LocalId; +use crate::link::ProjectLinks; #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct RegisteredUse { @@ -56,3 +64,85 @@ pub(crate) fn scan(program: &Program<'_>, locals: &FxHashMap) -> uses.found.dedup(); uses.found } + +fn terminals(lookup: ExportLookup) -> Vec> { + match lookup { + ExportLookup::Resolved(terminal) => vec![terminal], + ExportLookup::Ambiguous(known) | ExportLookup::Incomplete { known, .. } => known, + ExportLookup::Absent => Vec::new(), + } +} + +pub(crate) fn unbounded<'c>( + collections: &FxHashSet<&'c str>, + files: &BTreeMap, + inputs: &CssInputs, + links: &ProjectLinks, +) -> FxHashSet<&'c str> { + let mut declared: FxHashMap<(ModuleIndex, LocalId), &'c str> = FxHashMap::default(); + for module in links.modules() { + for (name, binding) in &links.record(module).local_exports { + if let Some(&collection) = collections.get(name.as_str()) { + declared.insert((module, *binding), collection); + } + } + } + let mut open: FxHashSet<&'c str> = + collections.iter().copied().filter(|collection| !declared.values().any(|held| held == collection)).collect(); + let exported_by = |module: ModuleIndex| -> Vec<&'c str> { + links + .exported_names(module) + .names + .iter() + .flat_map(|name| terminals(links.resolve_export_at(module, name))) + .filter_map(|terminal| match terminal { + Terminal::Local { module, binding } => declared.get(&(module, binding)).copied(), + _ => None, + }) + .collect() + }; + for module in links.modules() { + for name in links.exported_names(module).names { + for terminal in terminals(links.resolve_export_at(module, &name)) { + match terminal { + Terminal::Local { module: at, binding } => { + if let Some(&collection) = declared.get(&(at, binding)) { + if at != module || name != collection { + open.insert(collection); + } + } + } + Terminal::Namespace(target) => open.extend(exported_by(target)), + Terminal::External { .. } => {} + } + } + } + for import in &links.record(module).imports { + let named = match &import.name { + ImportName::Name(name) => collections.get(name.as_str()).copied(), + ImportName::Namespace => None, + }; + let mut bounded = false; + for terminal in terminals(links.resolve_request(module, import.request, &import.name)) { + match terminal { + Terminal::Local { module, binding } => bounded |= declared.contains_key(&(module, binding)), + Terminal::Namespace(target) => open.extend(exported_by(target)), + Terminal::External { .. } => {} + } + } + if let Some(collection) = named.filter(|_| !bounded) { + open.insert(collection); + } + } + } + for (path, ff) in files { + for load in &ff.module_loads { + for loaded in crate::analyze_css::loaded_modules(path, load, files, inputs) { + if let Some(module) = links.module(loaded) { + open.extend(exported_by(module)); + } + } + } + } + open +} diff --git a/packages/extract/crates/extractor/src/value_site.rs b/packages/extract/crates/extractor/src/value_site.rs index ef9f6eac..f4b2e29c 100644 --- a/packages/extract/crates/extractor/src/value_site.rs +++ b/packages/extract/crates/extractor/src/value_site.rs @@ -1,6 +1,6 @@ use oxc::allocator::Allocator; use oxc::ast::ast::{Expression, ObjectExpression, ObjectPropertyKind}; -use oxc::span::{GetSpan, SourceType}; +use oxc::span::{GetSpan, SourceType, Span}; use serde_json::Value; use crate::chain_walk::{unwrap_type_assertions, ChainStage}; @@ -10,6 +10,7 @@ pub(crate) enum Written { Equals(Value), Contains(String), Any, + Key, } #[derive(Debug, Clone, PartialEq)] @@ -29,7 +30,7 @@ pub(crate) struct ValueSite { pub(crate) struct Found { pub start: u32, pub end: u32, - pub key: String, + pub key: Option, } impl Seek { @@ -44,7 +45,7 @@ impl Seek { .map(|value| crate::eval::plain(&value)) }; match &self.written { - Written::Any => true, + Written::Any | Written::Key => true, Written::Equals(wanted) => literal().is_some_and(|found| same_value(&found, wanted)), Written::Contains(text) => literal().is_some_and(|found| found.as_str().is_some_and(|found| found.contains(text.as_str()))), } @@ -108,7 +109,10 @@ impl ValueSite { } fn in_object(&self, object: &ObjectExpression<'_>) -> Option { - for (key, value) in properties(object) { + for (key, key_span, value) in members(object) { + if self.seek.written == Written::Key && self.seek.key.as_deref() == Some(key.as_str()) { + return Some(Found { start: key_span.start, end: key_span.end, key: None }); + } if self.seek.key.as_deref().is_none_or(|wanted| wanted == key) { let candidate = match &self.seek.breakpoint { Some(breakpoint) => as_object(value).and_then(|entries| property(entries, breakpoint)), @@ -116,7 +120,7 @@ impl ValueSite { }; if let Some(candidate) = candidate.filter(|candidate| self.seek.matches(candidate)) { let span = candidate.span(); - return Some(Found { start: span.start, end: span.end, key }); + return Some(Found { start: span.start, end: span.end, key: Some(key) }); } } if let Some(found) = as_object(value).and_then(|nested| self.in_object(nested)) { @@ -133,15 +137,19 @@ impl Found { } } -fn properties<'o, 'a>(object: &'o ObjectExpression<'a>) -> impl Iterator)> { +fn members<'o, 'a>(object: &'o ObjectExpression<'a>) -> impl Iterator)> { object.properties.iter().filter_map(|member| match member { ObjectPropertyKind::ObjectProperty(member) if !member.computed => { - Some((crate::eval::property_name(&member.key)?.into_owned(), &member.value)) + Some((crate::eval::property_name(&member.key)?.into_owned(), member.key.span(), &member.value)) } _ => None, }) } +fn properties<'o, 'a>(object: &'o ObjectExpression<'a>) -> impl Iterator)> { + members(object).map(|(key, _, value)| (key, value)) +} + fn property<'o, 'a>(object: &'o ObjectExpression<'a>, name: &str) -> Option<&'o Expression<'a>> { properties(object).find(|(key, _)| key == name).map(|(_, value)| value) } diff --git a/packages/extract/crates/system-loader/src/lib.rs b/packages/extract/crates/system-loader/src/lib.rs index 39ad8442..6b56cf8a 100644 --- a/packages/extract/crates/system-loader/src/lib.rs +++ b/packages/extract/crates/system-loader/src/lib.rs @@ -1164,7 +1164,7 @@ fn extract_system_config<'js>( .map_err(|e| format!("contextualVarsJson not found: {}", e))?; let declaration_scales_json: Option = serialized.get("declarationScalesJson").ok(); let property_records_json: Option = serialized.get("propertyRecordsJson").ok(); - let theme_values = read_theme_values(ctx, &theme_obj)?; + let theme_values = read_theme_values(ctx, &theme_obj); if system_obj .get::<_, Function>("getVocabularyRecord") @@ -1505,7 +1505,9 @@ const THEME_VALUES: &str = r#"(() => { const root = (initial !== null && modes[initial]) || {}; const opacity = (base, modifier) => { if (modifier === undefined) return base; - const alpha = /^\d+(?:\.\d+)?$/.test(modifier) && Number(modifier) <= 100 ? Number(modifier) : Number.parseInt(modifier, 10); + const percentage = /^\d+(?:\.\d+)?$/.test(modifier) && Number(modifier) <= 100; + const integer = /^\+?\d+$/.test(modifier) && Number(modifier) <= 4294967295; + const alpha = percentage || integer ? Number(modifier) : Number.NaN; if (Number.isNaN(alpha)) return base; if (alpha === 0) return 'transparent'; return alpha === 100 ? base : `color-mix(in srgb, ${base} ${alpha}%, transparent)`; @@ -1544,11 +1546,14 @@ const THEME_VALUES: &str = r#"(() => { }); })()"#; -fn read_theme_values<'js>(ctx: &rquickjs::Ctx<'js>, theme: &Object<'js>) -> Result, String> { +fn read_theme_values<'js>(ctx: &rquickjs::Ctx<'js>, theme: &Object<'js>) -> Option { let _ = ctx.globals().set("__theme_ref", theme.clone()); let result = ctx.eval::, _>(THEME_VALUES.as_bytes()); let _ = ctx.globals().remove("__theme_ref"); - result.map_err(|e| format!("theme value record evaluation failed: {}", e)) + result.unwrap_or_else(|_| { + ctx.catch(); + None + }) } struct VocabularyWires { From 36644e886e2e29266a5097112fe00a44656d2488 Mon Sep 17 00:00:00 2001 From: codecaaron Date: Sat, 28 Nov 2026 05:50:52 -0500 Subject: [PATCH 2/3] fix(core,react,effect-ui): token import, contract and colour-mode defects fromDTCG: a document typed as a JSON import no longer loses its scales to typography inference; group $type resolves across the sources, sets and contexts of a resolver document; a path that is a token in one layer and a group in another is rejected instead of dropping the token. toDTCG: a stored hex is reused only while its colour is unchanged; an aliased token takes its target's type; one-layer shadow lists and $root-only typography groups survive; out-of-range alpha and cubic-bezier values and upper-case units are refused with the token path. Contracts: a boolean variant condition and its string form are equivalent and match a boolean or string prop, in the types and at run time in both bindings; before, React threw and Effect UI never matched. addColorModes rejects a mode alias that references an earlier mode alias, as the run time always did. Co-Authored-By: Claude Fable 5.2 --- packages/core/__tests__/dtcg.test.ts | 316 ++++++++++++++++++ packages/core/src/dtcg/export.ts | 50 ++- packages/core/src/dtcg/import.ts | 88 +++-- packages/core/src/dtcg/metadata.ts | 10 +- packages/core/src/dtcg/types.ts | 34 +- packages/core/src/dtcg/values.ts | 11 + packages/core/src/theme/createTheme.ts | 57 ++-- packages/core/src/types/contract.ts | 18 +- packages/core/types/published/dtcg.ts | 55 ++- packages/core/types/published/theme.ts | 18 + packages/effect-ui/src/runtime.ts | 11 +- .../effect-ui/types/published/builders.ts | 23 ++ .../react/__tests__/contract-attrs.test.tsx | 33 ++ packages/react/src/runtime/index.ts | 10 +- packages/react/types/published/contract.tsx | 28 ++ 15 files changed, 677 insertions(+), 85 deletions(-) create mode 100644 packages/react/__tests__/contract-attrs.test.tsx diff --git a/packages/core/__tests__/dtcg.test.ts b/packages/core/__tests__/dtcg.test.ts index dc0d2fb1..47367e73 100644 --- a/packages/core/__tests__/dtcg.test.ts +++ b/packages/core/__tests__/dtcg.test.ts @@ -1,7 +1,10 @@ import { describe, expect, it } from 'vitest'; +import { createTheme } from '../src'; import { fromDTCG, toDTCG } from '../src/dtcg'; +import type { DTCGObject } from '../src/dtcg'; + const px = (value: number) => ({ value, unit: 'px' }); const rgb = (r: number, g: number, b: number, hex?: string) => ({ colorSpace: 'srgb', @@ -226,6 +229,27 @@ const themed = { ], }; +const resolver = ( + base: DTCGObject[], + contexts: { [context: string]: DTCGObject[] } = {}, + after: DTCGObject[] = [] +) => ({ + version: '2025.10', + sets: { base: { sources: base }, after: { sources: after } }, + modifiers: Object.keys(contexts).length > 0 ? { mode: { contexts } } : {}, + resolutionOrder: [ + { $ref: '#/sets/base' }, + ...(Object.keys(contexts).length > 0 ? [{ $ref: '#/modifiers/mode' }] : []), + { $ref: '#/sets/after' }, + ], +}); + +const oklch = (components: number[], hex: string) => ({ + colorSpace: 'oklch', + components, + hex, +}); + function snapshot(theme: ReturnType['build']>) { return { data: { ...theme }, @@ -284,7 +308,299 @@ describe('DTCG import and export', () => { { colors: { fg: { $type: 'color', $value: '{colors.missing}' } } }, /'colors\.fg' aliases \{colors\.missing\}, which names no token/, ], + [ + 'colors.red, a token in one set and a group in a set after the modifier', + resolver( + [{ colors: { $type: 'color', red: { $value: rgb(255, 0, 0) } } }], + { light: [{}] }, + [ + { + colors: { red: { dark: { $type: 'color', $value: rgb(1, 0, 0) } } }, + }, + ] + ), + /'colors\.red' is a token in one source and a group in another/, + ], + [ + 'colors.red, a token in the base and a group in a context', + resolver( + [{ colors: { $type: 'color', red: { $value: rgb(255, 0, 0) } } }], + { + light: [ + { + colors: { + red: { dark: { $type: 'color', $value: rgb(1, 0, 0) } }, + }, + }, + ], + dark: [ + { + colors: { + red: { dark: { $type: 'color', $value: rgb(2, 0, 0) } }, + }, + }, + ], + } + ), + /'colors\.red' is a token in one source and a group in another/, + ], + [ + 'colors.red, a group in the base and a token in a context', + resolver( + [ + { + colors: { + $type: 'color', + red: { dark: { $value: rgb(1, 0, 0) } }, + }, + }, + ], + { + light: [ + { colors: { red: { $type: 'color', $value: rgb(255, 0, 0) } } }, + ], + } + ), + /'colors\.red' is a token in one source and a group in another/, + ], ])('rejects %s, naming its path', (_, source, message) => { expect(() => fromDTCG(source)).toThrow(message); }); + + it.each([ + [ + 'from a group in an earlier source of the set', + resolver([ + { colors: { $type: 'color', red: { $value: rgb(255, 0, 0) } } }, + { colors: { blue: { $value: rgb(0, 0, 255) } } }, + ]), + ], + [ + 'from a group in a later source of the set', + resolver([ + { colors: { red: { $value: rgb(255, 0, 0) } } }, + { colors: { $type: 'color', blue: { $value: rgb(0, 0, 255) } } }, + ]), + ], + [ + 'from a group in a set before the one holding the token', + resolver( + [{ colors: { $type: 'color', red: { $value: rgb(255, 0, 0) } } }], + {}, + [{ colors: { blue: { $value: rgb(0, 0, 255) } } }] + ), + ], + ])('resolves an inherited $type %s', (_, source) => { + expect(fromDTCG(source).build()).toMatchObject({ + colors: { red: '#ff0000', blue: '#0000ff' }, + }); + }); + + it('resolves the $type of a token a context adds to a base group', () => { + const theme = fromDTCG( + resolver( + [{ colors: { $type: 'color', red: { $value: rgb(255, 0, 0) } } }], + { + light: [{ colors: { fg: { $value: rgb(0, 0, 255) } } }], + dark: [{ colors: { fg: { $value: '{colors.red}' } } }], + } + ) + ).build(); + expect(theme).toMatchObject({ + modes: { light: { fg: '#0000ff' }, dark: { fg: 'red' } }, + }); + }); + + it.each([ + [ + 'a color', + { + colors: { + $type: 'color', + brand: { $value: oklch([0.7, 0.1, 200], '#12a4b0') }, + }, + }, + { name: 'colors', values: { brand: 'oklch(0.3 0.2 30)' } }, + { + colors: { + brand: { + $type: 'color', + $value: { colorSpace: 'oklch', components: [0.3, 0.2, 30] }, + }, + }, + }, + ], + [ + 'a shadow color', + { + shadows: { + lift: { + $type: 'shadow', + $value: { + color: oklch([0.7, 0.1, 200], '#12a4b0'), + offsetX: px(0), + offsetY: px(1), + blur: px(2), + spread: px(0), + }, + }, + }, + }, + { + name: 'shadows', + values: { lift: '0px 1px 2px 0px oklch(0.3 0.2 30)' }, + }, + { + shadows: { + lift: { + $type: 'shadow', + $value: { + offsetX: px(0), + offsetY: px(1), + blur: px(2), + spread: px(0), + color: { colorSpace: 'oklch', components: [0.3, 0.2, 30] }, + }, + }, + }, + }, + ], + [ + 'a shadow whose color is unchanged', + { + shadows: { + lift: { + $type: 'shadow', + $value: { + color: oklch([0.7, 0.1, 200], '#12a4b0'), + offsetX: px(0), + offsetY: px(1), + blur: px(2), + spread: px(0), + }, + }, + }, + }, + { + name: 'shadows', + values: { lift: '0px 4px 2px 0px oklch(0.7 0.1 200)' }, + }, + { + shadows: { + lift: { + $type: 'shadow', + $value: { + offsetX: px(0), + offsetY: px(4), + blur: px(2), + spread: px(0), + color: oklch([0.7, 0.1, 200], '#12a4b0'), + }, + }, + }, + }, + ], + ])( + 'exports the hex fallback of %s only while its value is the one imported', + (_, source, scale, expected) => { + const theme = fromDTCG(source) + .addScale({ + name: scale.name, + values: scale.values as { [key: string]: string }, + emit: true, + }) + .build(); + expect(toDTCG(theme)).toEqual(expected); + } + ); + + it('types a token by its alias target once its value becomes an alias', () => { + const theme = fromDTCG({ + space: { $type: 'dimension', 4: { $value: px(4) } }, + ratios: { $type: 'number', golden: { $value: 1.618 } }, + }) + .addScale({ name: 'ratios', values: { golden: '{space.4}' }, emit: true }) + .build(); + expect(toDTCG(theme)).toEqual({ + space: { 4: { $type: 'dimension', $value: px(4) } }, + ratios: { golden: { $type: 'dimension', $value: '{space.4}' } }, + }); + }); + + it.each([ + [ + 'a one-layer shadow list', + { + shadows: { + lift: { + $type: 'shadow', + $value: [ + { + color: oklch([0.5, 0.1, 200], '#336699'), + offsetX: px(0), + offsetY: px(1), + blur: px(2), + spread: px(0), + }, + ], + }, + }, + }, + ], + [ + 'a typography group holding only $root', + { + type: { + title: { + $description: 'Titles', + $root: { + $type: 'typography', + $value: { + fontFamily: 'Georgia', + fontSize: px(24), + fontWeight: 600, + letterSpacing: px(0), + lineHeight: 1.2, + }, + }, + }, + }, + }, + ], + ])('round-trips %s', (_, source) => { + expect(toDTCG(fromDTCG(source).build())).toEqual(source); + }); + + it.each([ + [ + 'space.s', + createTheme().addScale({ + name: 'space', + values: { s: '10PX' }, + emit: true, + }), + /'space\.s' holds "10PX", which has no DTCG type/, + ], + [ + 'colors.veil', + createTheme().addColors({ veil: 'oklch(0.5 0.1 200 / 1.5)' }), + /'colors\.veil' "oklch\(0\.5 0\.1 200 \/ 1\.5\)" has alpha 1\.5/, + ], + [ + 'colors.haze', + createTheme().addColors({ haze: 'rgb(0 0 0 / 150%)' }), + /'colors\.haze' "rgb\(0 0 0 \/ 150%\)" has alpha 1\.5/, + ], + [ + 'easings.out', + createTheme().addScale({ + name: 'easings', + values: { out: 'cubic-bezier(1.2, 0, 0.2, 1)' }, + emit: true, + }), + /'easings\.out' "cubic-bezier\(1\.2, 0, 0\.2, 1\)" has an x outside 0 to 1/, + ], + ])('refuses to export %s, which would not import', (_, builder, message) => { + expect(() => toDTCG(builder.build())).toThrow(message); + }); }); diff --git a/packages/core/src/dtcg/export.ts b/packages/core/src/dtcg/export.ts index 3be34975..8d070d68 100644 --- a/packages/core/src/dtcg/export.ts +++ b/packages/core/src/dtcg/export.ts @@ -27,6 +27,7 @@ import { import type { SerializedTheme, ThemeManifest } from '../types/theme'; import type { + ColorFallback, DTCGMetadata, GroupMetadata, LayerMetadata, @@ -68,7 +69,16 @@ const STRUCTURAL: ReadonlySet = new Set([ ]); const COLOR_SYNTAX = /^(?:#|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\()/; -const MEASURE = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?(px|rem|ms|s)$/i; +const MEASURE = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?(px|rem|ms|s)$/; + +function fallbackHex( + fallback: ColorFallback | undefined, + text: Leaf +): string | undefined { + return fallback !== undefined && fallback.css === String(text).trim() + ? fallback.hex + : undefined; +} function ownValue(theme: DTCGExportableTheme, key: string): DTCGJson { const descriptor: { value?: DTCGJson } | undefined = @@ -106,10 +116,15 @@ function leafSegments( } } -function keySegments(scale: string, keys: string[]): string[][] { +function keySegments( + scale: string, + keys: string[], + rooted: (path: string) => boolean +): string[][] { return keys.map((key) => { const segments = [scale, ...key.split('.')]; - return keys.some((other) => other.startsWith(`${key}.`)) + return keys.some((other) => other.startsWith(`${key}.`)) || + rooted(`${segments.join('.')}.$root`) ? [...segments, '$root'] : segments; }); @@ -210,12 +225,13 @@ class Exporter { } typeOf(token: ExportToken): DTCGTokenType { + const { value } = token; + const target = typeof value === 'string' ? aliasTarget(value) : undefined; const recorded = token.metadata?.$type; - if (recorded !== undefined) return recorded; + if (recorded !== undefined && target === undefined) return recorded; const fail: Fail = failure('toDTCG', token.path); if (token.kind === 'breakpoint') return 'dimension'; if (token.segments[0] === 'colors') return 'color'; - const { value } = token; if (token.kind === 'typography') { const fields = isRecord(value) ? Object.keys(value).sort().join(',') : ''; if (fields !== Object.keys(TYPOGRAPHY_FIELDS).sort().join(',')) { @@ -227,7 +243,6 @@ class Exporter { } if (typeof value === 'number') return 'number'; if (typeof value !== 'string') return fail('has no token value'); - const target = aliasTarget(value); if (target !== undefined) { const found = this.byAnimusPath.get(target); if (found === undefined) @@ -239,7 +254,7 @@ class Exporter { return type; } if (COLOR_SYNTAX.test(value)) return 'color'; - const unit = MEASURE.exec(value)?.[1]?.toLowerCase(); + const unit = MEASURE.exec(value)?.[1]; if (unit === 'px' || unit === 'rem') return 'dimension'; if (unit === 'ms' || unit === 's') return 'duration'; if (value.startsWith('cubic-bezier(')) return 'cubicBezier'; @@ -252,14 +267,14 @@ class Exporter { fail: Fail, text: Leaf, type: DTCGTokenType, - hex: string | undefined + fallback: ColorFallback | undefined ): DTCGJson { const target = typeof text === 'string' ? aliasTarget(text.trim()) : undefined; if (target !== undefined) return this.translate(fail, target); switch (type) { case 'color': - return cssToColor(fail, text, hex); + return cssToColor(fail, text, fallbackHex(fallback, text)); case 'dimension': return cssToMeasure(fail, text, DIMENSION_UNITS, 'dimension'); case 'duration': @@ -328,7 +343,9 @@ class Exporter { }; switch (type) { case 'shadow': { - const layers = splitTopLevel(text, ',').map((layer, index, all) => { + const texts = splitTopLevel(text, ','); + const listed = token.metadata?.list === true || texts.length > 1; + const layers = texts.map((layer, index) => { const layerTarget = aliasTarget(layer); if (layerTarget !== undefined) return this.translate(fail, layerTarget); @@ -338,7 +355,7 @@ class Exporter { inset ? words.slice(1) : words, 5 ); - const prefix = all.length > 1 ? `${index}.` : ''; + const prefix = listed ? `${index}.` : ''; const parts = this.fields( fail, token, @@ -348,7 +365,7 @@ class Exporter { ); return inset ? { ...parts, inset: true } : parts; }); - return layers.length === 1 ? layers[0] : layers; + return listed ? layers : layers[0]; } case 'border': { const [width, style, ...color] = minimum(splitTopLevel(text, ' '), 3); @@ -481,7 +498,7 @@ function modeValue( const inPalette = isRecord(palette) && walkDotPath(palette, value) !== undefined; return !inPalette - ? cssToColor(fail, value, token.metadata?.hex) + ? cssToColor(fail, value, fallbackHex(token.metadata?.hex, value)) : exporter.translate(fail, `colors.${value}`); } @@ -519,10 +536,15 @@ export function toDTCG(theme: DTCGExportableTheme): DTCGDocument { } const declarations = ownValue(theme, '__declarationScales'); if (isRecord(declarations)) { + const rooted = (path: string) => metadata.base.tokens[path] !== undefined; for (const [name, values] of Object.entries(declarations)) { if (!isRecord(values)) continue; const keys = Object.keys(values); - for (const [index, segments] of keySegments(name, keys).entries()) { + for (const [index, segments] of keySegments( + name, + keys, + rooted + ).entries()) { const value = values[keys[index]]; if (!isRecord(value)) continue; tokens.push({ diff --git a/packages/core/src/dtcg/import.ts b/packages/core/src/dtcg/import.ts index 95e089e2..130dddcb 100644 --- a/packages/core/src/dtcg/import.ts +++ b/packages/core/src/dtcg/import.ts @@ -54,6 +54,7 @@ interface SourceToken { interface Layer { tokens: Map; + groupTypes: Map; metadata: LayerMetadata; } @@ -147,12 +148,7 @@ function declaredType(fail: Fail, node: DTCGObject): DTCGTokenType | undefined { return type; } -function readGroup( - layer: Layer, - group: DTCGObject, - segments: string[], - inherited: DTCGTokenType | undefined -): void { +function readGroup(layer: Layer, group: DTCGObject, segments: string[]): void { const path = segments.join('.'); const fail: Fail = failure( 'fromDTCG', @@ -168,7 +164,8 @@ function readGroup( if (key === '$schema' && segments.length === 0) continue; if (!GROUP_KEYS.has(key)) fail(`has an unknown group property '${key}'`); } - const type = declaredType(fail, group) ?? inherited; + const type = declaredType(fail, group); + if (type !== undefined) layer.groupTypes.set(path, type); const metadata: GroupMetadata = annotations(fail, group); if (segments.length === 0 && typeof group.$schema === 'string') { metadata.$schema = group.$schema; @@ -202,21 +199,16 @@ function readGroup( 'is a token at the document root; Animus scales are top-level groups, so put it in one' ); } - readToken(layer, child, childSegments, type); + readToken(layer, child, childSegments); } else if (key === '$root') { childFail('must be a token'); } else { - readGroup(layer, child, childSegments, type); + readGroup(layer, child, childSegments); } } } -function readToken( - layer: Layer, - node: DTCGObject, - segments: string[], - inherited: DTCGTokenType | undefined -): void { +function readToken(layer: Layer, node: DTCGObject, segments: string[]): void { const path = segments.join('.'); const fail: Fail = failure('fromDTCG', path); for (const key of Object.keys(node)) { @@ -233,24 +225,31 @@ function readToken( segments, node, declared: declaredType(fail, node), - inherited, }); } function emptyLayer(): Layer { - return { tokens: new Map(), metadata: { tokens: {}, groups: {} } }; + return { + tokens: new Map(), + groupTypes: new Map(), + metadata: { tokens: {}, groups: {} }, + }; } function readLayer(documents: DTCGObject[]): Layer { const layer = emptyLayer(); - for (const document of documents) readGroup(layer, document, [], undefined); - for (const path of layer.tokens.keys()) { + for (const document of documents) readGroup(layer, document, []); + return layer; +} + +function assertTree(paths: ReadonlySet): void { + for (const path of paths) { for ( let dot = path.lastIndexOf('.'); dot > 0; dot = path.lastIndexOf('.', dot - 1) ) { - if (layer.tokens.has(path.slice(0, dot))) { + if (paths.has(path.slice(0, dot))) { failure( 'fromDTCG', path.slice(0, dot) @@ -260,7 +259,22 @@ function readLayer(documents: DTCGObject[]): Layer { } } } - return layer; +} + +function inheritTypes( + tokens: Iterable, + scopes: readonly ReadonlyMap[] +): void { + for (const token of tokens) { + for (let depth = token.segments.length - 1; depth >= 0; depth -= 1) { + const group = token.segments.slice(0, depth).join('.'); + const scope = scopes.findLast((types) => types.has(group)); + if (scope !== undefined) { + token.inherited = scope.get(group); + break; + } + } + } } function expandSources( @@ -560,7 +574,10 @@ class Importer { const color = colorToCss(fieldFail, value); if (color.hex !== undefined) { const entry = this.entry(token); - entry.fieldHex = { ...entry.fieldHex, [field]: color.hex }; + entry.fieldHex = { + ...entry.fieldHex, + [field]: { css: color.css, hex: color.hex }, + }; } return color.css; } @@ -632,12 +649,15 @@ class Importer { switch (type) { case 'color': { const color = colorToCss(fail, value); - if (color.hex !== undefined) this.entry(token).hex = color.hex; + if (color.hex !== undefined) { + this.entry(token).hex = { css: color.css, hex: color.hex }; + } return color.css; } case 'shadow': { const layers = isList(value) ? value : [value]; if (layers.length === 0) fail('is an empty shadow list'); + if (isList(value)) this.entry(token).list = true; return layers .map((layer, index) => { const layerTarget = aliasTarget(layer); @@ -735,6 +755,20 @@ export function fromDTCG< document, options?.sources ?? {} ); + const resolved = new Set([...base.tokens.keys(), ...after.tokens.keys()]); + assertTree(resolved); + inheritTypes( + [...base.tokens.values(), ...after.tokens.values()], + [base.groupTypes, after.groupTypes] + ); + for (const layer of modes?.contexts.values() ?? []) { + assertTree(new Set([...resolved, ...layer.tokens.keys()])); + inheritTypes(layer.tokens.values(), [ + base.groupTypes, + layer.groupTypes, + after.groupTypes, + ]); + } const modePaths = new Set(); for (const layer of modes?.contexts.values() ?? []) { for (const path of layer.tokens.keys()) modePaths.add(path); @@ -877,8 +911,12 @@ export function fromDTCG< let value: string; if (target === undefined) { const color = colorToCss(fail, token.node.$value); - if (color.hex !== undefined) - layer.metadata.tokens[path].hex = color.hex; + if (color.hex !== undefined) { + layer.metadata.tokens[path].hex = { + css: color.css, + hex: color.hex, + }; + } value = color.css; } else { if (modePaths.has(target)) { diff --git a/packages/core/src/dtcg/metadata.ts b/packages/core/src/dtcg/metadata.ts index ad54111b..9429b9da 100644 --- a/packages/core/src/dtcg/metadata.ts +++ b/packages/core/src/dtcg/metadata.ts @@ -1,12 +1,18 @@ import type { DTCGObject, DTCGTokenType } from './types'; +export interface ColorFallback { + css: string; + hex: string; +} + export interface TokenMetadata { $type: DTCGTokenType; $description?: string; $deprecated?: boolean | string; $extensions?: DTCGObject; - hex?: string; - fieldHex?: { [field: string]: string }; + hex?: ColorFallback; + fieldHex?: { [field: string]: ColorFallback }; + list?: true; } export interface GroupMetadata { diff --git a/packages/core/src/dtcg/types.ts b/packages/core/src/dtcg/types.ts index 73b241a4..cb3f7a18 100644 --- a/packages/core/src/dtcg/types.ts +++ b/packages/core/src/dtcg/types.ts @@ -98,9 +98,11 @@ type LeafValue = Token extends { readonly $value: `{${string}}`; } ? string - : OwnType extends 'number' | 'fontWeight' - ? number - : string; + : string extends OwnType + ? string | number + : OwnType extends 'number' | 'fontWeight' + ? number + : string; type ScaleValues = { -readonly [ @@ -289,11 +291,29 @@ type RootType = OwnType; type GroupName = Exclude; -type IsDeclaration = - 'typography' extends TokenTypes> +type TokenValues = { + [Key in ChildKey]: Group[Key] extends { readonly $value: infer Value } + ? Value + : TokenValues; +}[ChildKey]; + +type HoldsTypography = [ + Extract, { readonly fontFamily: unknown }>, +] extends [never] + ? false + : true; + +type DeclaresTypography = string extends Types + ? HoldsTypography + : 'typography' extends Types ? true : false; +type IsDeclaration = DeclaresTypography< + TokenTypes>, + Tree[Name] +>; + type ScalarName = { [Name in GroupName]: Name extends 'breakpoints' ? never @@ -382,5 +402,7 @@ export type DTCGEmittedOf = { export type DTCGThemeBuilder = ThemeBuilder< DTCGThemeOf, DTCGEmittedOf, - 'extend' + 'extend', + string, + `${ModeKeys & (string | number)}` >; diff --git a/packages/core/src/dtcg/values.ts b/packages/core/src/dtcg/values.ts index cb0cae37..6b275a0d 100644 --- a/packages/core/src/dtcg/values.ts +++ b/packages/core/src/dtcg/values.ts @@ -288,6 +288,12 @@ export function cssToColor( `${describe(css)} has no DTCG color form; write it as hex or as a color function with numeric components` ); } + const { alpha } = color; + if (typeof alpha === 'number' && (alpha < 0 || alpha > 1)) { + fail( + `${describe(css)} has alpha ${alpha}; a DTCG color alpha is from 0 to 1` + ); + } return color; } @@ -458,6 +464,11 @@ export function cssToCubicBezier(fail: Fail, css: string | number): number[] { ) { fail(`${describe(css)} is not a cubic-bezier() function`); } + if ([points[0], points[2]].some((x) => x === undefined || x < 0 || x > 1)) { + fail( + `${describe(css)} has an x outside 0 to 1, which a DTCG cubic Bézier cannot hold` + ); + } return points as number[]; } diff --git a/packages/core/src/theme/createTheme.ts b/packages/core/src/theme/createTheme.ts index dd8daa17..c19d8a3f 100644 --- a/packages/core/src/theme/createTheme.ts +++ b/packages/core/src/theme/createTheme.ts @@ -377,13 +377,17 @@ type VarRefPath = { : never; }[Exclude, `_${string}`>]; -type ColorPathOf = T extends { colors: infer Colors } +type ColorPathOf = T extends { + colors: infer Colors; +} ? { - [Key in keyof Colors & (string | number)]: [Colors[Key]] extends [never] - ? `${Key}` - : Colors[Key] extends `var(--${string})` - ? never - : `${Key}` | FoldedDefault<`${Key}`>; + [Key in keyof Colors & (string | number)]: `${Key}` extends ModeAliases + ? never + : [Colors[Key]] extends [never] + ? `${Key}` + : Colors[Key] extends `var(--${string})` + ? never + : `${Key}` | FoldedDefault<`${Key}`>; }[keyof Colors & (string | number)] : never; @@ -731,6 +735,7 @@ export class ThemeBuilder< Emitted extends EmittedNames = NoEmitted, Stage extends ThemeBuilderStage = 'inherit', Modes extends string = string, + ModeAliases extends string = never, > { declare readonly [THEME_STAGE_BRAND]?: Stage; @@ -752,7 +757,7 @@ export class ThemeBuilder< type Merged = OrderedOmit & Record<'breakpoints', { [K in keyof BP]: BP[K] }>; type Next = { [K in keyof Merged]: Merged[K] }; - return new ThemeBuilder( + return new ThemeBuilder( copyState(this._state, nextTheme) ); } @@ -802,7 +807,7 @@ export class ThemeBuilder< } extend( - this: ThemeBuilder, + this: ThemeBuilder, source: Source ): ThemeBuilder< WithDeclarationScales< @@ -961,7 +966,8 @@ export class ThemeBuilder< Next, WithEmitted>, 'extend', - Modes + Modes, + ModeAliases >(copyState(this._state, nextTheme)); next._state.emittedScales.add('colors'); return next; @@ -970,7 +976,7 @@ export class ThemeBuilder< addColorModes< Config extends Record< string, - ModeAliasTree | LiteralColor | (string & {})> + ModeAliasTree | LiteralColor | (string & {})> >, AliasKeys extends LiteralPaths< WidenModeAliases, @@ -981,10 +987,10 @@ export class ThemeBuilder< initialMode: (keyof Config & string) | Modes, modeConfig: Config extends ModeConfigCheck< Config, - ColorPathOf | LiteralColor + ColorPathOf | LiteralColor > ? Config - : ModeConfigCheck | LiteralColor>, + : ModeConfigCheck | LiteralColor>, options?: ColorModeOptions ) { const nestedColors = (this._state.theme.colors || {}) as Record< @@ -1041,7 +1047,8 @@ export class ThemeBuilder< Next, Emitted, 'extend', - Modes | (keyof Config & string) + Modes | (keyof Config & string), + ModeAliases | (keyof AliasKeys & string) >(copyState(this._state, nextTheme)); } @@ -1089,9 +1096,13 @@ export class ThemeBuilder< ? NewScale : Flatten>; type Next = Flatten & Record>; - const next = new ThemeBuilder( - copyState(this._state, nextTheme) - ); + const next = new ThemeBuilder< + Next, + NextEmitted, + 'extend', + Modes, + ModeAliases + >(copyState(this._state, nextTheme)); if (emit) next._state.emittedScales.add(name); if (replace && isObject(prior)) { const kept = new Set( @@ -1144,7 +1155,7 @@ export class ThemeBuilder< OrderedOmit & Record<'__declarationScales', NextScales> >; - const next = new ThemeBuilder( + const next = new ThemeBuilder( copyState(this._state, this._state.theme) ); const merged = replace @@ -1181,9 +1192,13 @@ export class ThemeBuilder< : T[K]; }; - const next = new ThemeBuilder( - copyState(this._state, this._state.theme) - ); + const next = new ThemeBuilder< + WithPhantoms, + Emitted, + 'extend', + Modes, + ModeAliases + >(copyState(this._state, this._state.theme)); const source: PropertySource = { method: 'declareContextualVars' }; for (const [scale, names] of Object.entries(vars)) { declareScaleNames( @@ -1217,7 +1232,7 @@ export class ThemeBuilder< }); type NextScale = Flatten>>; type Next = Flatten & Record>; - return new ThemeBuilder( + return new ThemeBuilder( copyState(this._state, nextTheme) ); } diff --git a/packages/core/src/types/contract.ts b/packages/core/src/types/contract.ts index 79dbed9d..1481f166 100644 --- a/packages/core/src/types/contract.ts +++ b/packages/core/src/types/contract.ts @@ -21,7 +21,7 @@ export interface ContractRule< export interface ContractRuleEntry { readonly when?: Readonly< - Record + Record >; readonly whenTag?: string | readonly string[]; readonly attrs?: Readonly>; @@ -50,11 +50,17 @@ export type VariantOptionMap = { : never; }; -export type ContractValues = T extends readonly (infer Item extends string)[] - ? Item - : T extends string - ? T - : never; +type ContractValue = Value extends true | 'true' + ? true | 'true' + : Value extends false | 'false' + ? false | 'false' + : Value extends string + ? Value + : never; + +export type ContractValues = ContractValue< + T extends readonly (infer Item)[] ? Item : T +>; export type ContractTagMatches = [ WhenTag, diff --git a/packages/core/types/published/dtcg.ts b/packages/core/types/published/dtcg.ts index fbef2128..834d92c4 100644 --- a/packages/core/types/published/dtcg.ts +++ b/packages/core/types/published/dtcg.ts @@ -7,7 +7,7 @@ import type { DTCGDocument } from '@animus-ui/core/dtcg'; const srgb = { colorSpace: 'srgb', components: [0, 0, 0] } as const; -const built = fromDTCG({ +const imported = fromDTCG({ version: '2025.10', sets: { base: { @@ -74,7 +74,18 @@ const built = fromDTCG({ }, }, resolutionOrder: [{ $ref: '#/sets/base' }, { $ref: '#/modifiers/theme' }], -}).build(); +}); +const built = imported.build(); + +export const modeOnPalette = imported.addColorModes('light', { + light: { line: 'ink' }, + dark: { line: 'brand.600' }, +}); +export const modeOnModeAlias = imported.addColorModes('light', { + // @ts-expect-error + light: { line: 'fg' }, + dark: { line: 'ink' }, +}); const handWritten = createTheme() .addBreakpoints({ sm: 640 }) @@ -127,6 +138,46 @@ export const unknownToken = built.varRef('colors.brand.700'); // @ts-expect-error export const unknownScale = built.varRef('sizes.4'); +declare const json: { + colors: { + $type: string; + red: { $value: { colorSpace: string; components: number[] } }; + }; + space: { $type: string; s: { $value: { value: number; unit: string } } }; + ratios: { golden: { $type: string; $value: number } }; + type: { + body: { + $type: string; + $value: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: number; + }; + }; + }; +}; +const fromJson = fromDTCG(json).build(); + +export type _Widened = [ + Assert>, + Assert>, + Assert>, + Assert>, + Assert>, + Assert< + Equal< + typeof fromJson.__emitted, + { colors: true; space: true; ratios: true } + > + >, +]; + +export const jsonRef = fromJson.varRef('colors.red'); +// @ts-expect-error +export const jsonUnknownRef = fromJson.varRef('colors.blue'); + type ColorProp = Scale<{ property: 'color'; scale: 'colors' }, typeof built>; export const brand: ColorProp = 'brand.600'; diff --git a/packages/core/types/published/theme.ts b/packages/core/types/published/theme.ts index 25788c11..47379ab9 100644 --- a/packages/core/types/published/theme.ts +++ b/packages/core/types/published/theme.ts @@ -162,6 +162,24 @@ export const basedOnUnknownBase = colored.addColorModes( // @ts-expect-error { basedOn: { midnight: 'nocturne' } } ); +const moded = colored.addColorModes('paper', { + paper: { fg: 'ink', surface: { _: 'bone', raised: 'ink' } }, + midnight: { fg: 'bone', surface: { _: 'ink', raised: 'bone' } }, +}); +export const modeOnPalette = moded.addColorModes('paper', { + paper: { line: 'brand.500' }, + midnight: { line: 'ink' }, +}); +export const modeOnModeAlias = moded.addColorModes('paper', { + // @ts-expect-error + paper: { line: 'fg' }, + midnight: { line: 'ink' }, +}); +export const modeOnNestedModeAlias = moded.addColorModes('paper', { + paper: { line: 'ink' }, + // @ts-expect-error + midnight: { line: 'surface.raised' }, +}); export const modeAccepted = colored .addColorModes( 'paper', diff --git a/packages/effect-ui/src/runtime.ts b/packages/effect-ui/src/runtime.ts index 37451f22..02e2b7fa 100644 --- a/packages/effect-ui/src/runtime.ts +++ b/packages/effect-ui/src/runtime.ts @@ -127,15 +127,16 @@ function readSlotBag(node: EffectUiBuilderLike, slotKey: string): StyleBag { function matchesExpected( actual: EffectUiStyleValue, - expected: string | readonly string[] + expected: string | boolean | readonly (string | boolean)[] ): boolean { - if (typeof actual !== 'string') { + if (typeof actual !== 'string' && typeof actual !== 'boolean') { return false; } - if (Array.isArray(expected)) { - return expected.includes(actual); + const value = String(actual); + if (typeof expected === 'object') { + return expected.some((option) => String(option) === value); } - return actual === expected; + return String(expected) === value; } function contractMatches( diff --git a/packages/effect-ui/types/published/builders.ts b/packages/effect-ui/types/published/builders.ts index d4dcc215..033134d2 100644 --- a/packages/effect-ui/types/published/builders.ts +++ b/packages/effect-ui/types/published/builders.ts @@ -55,6 +55,15 @@ const Alert = chain }) .asElement('div'); const Link = chain.asPart(['a', 'button']); +const flagChain = ds + .styles({}) + .variant({ prop: 'flag', variants: { true: {}, false: {} } }); +const Flagged = flagChain + .contract({ when: { flag: true }, require: { attrs: ['title'] } }) + .asElement('div'); +const FlaggedText = flagChain + .contract({ when: { flag: 'true' }, require: { attrs: ['title'] } }) + .asElement('div'); const alertClass = chain.asClass(); type AlertClassProps = NonNullable[0]>; @@ -202,8 +211,22 @@ export function verify(h: MockTags) { Link(h.a).intent('info').attr('href', '/'), Family.Title(h).children('Heading'), alertClass({ intent: 'info', busy: true, p: 'sm' }), + Flagged(h).flag(false).children('Off'), + Flagged(h).flag('false').children('Off'), + Flagged(h).flag(true).attr('title', 'On').children('On'), + FlaggedText(h).flag(false).children('Off'), + FlaggedText(h).flag('true').attr('title', 'On').children('On'), ]; + // @ts-expect-error + Flagged(h).flag(true).children('On'); + // @ts-expect-error + Flagged(h).flag('true').children('On'); + // @ts-expect-error + FlaggedText(h).flag(true).children('On'); + // @ts-expect-error + FlaggedText(h).flag('true').children('On'); + // @ts-expect-error Alert(h).intent('info').loading(); // @ts-expect-error diff --git a/packages/react/__tests__/contract-attrs.test.tsx b/packages/react/__tests__/contract-attrs.test.tsx new file mode 100644 index 00000000..b59e6fbd --- /dev/null +++ b/packages/react/__tests__/contract-attrs.test.tsx @@ -0,0 +1,33 @@ +import { createElement } from 'react'; + +import { renderToString } from 'react-dom/server'; +import { afterEach, expect, it, vi } from 'vitest'; + +import { ds } from './test-system'; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +it.each([ + ['true', true], + ["'true'", 'true'], + ['[true]', [true]], +] as const)( + 'a contract condition %s on a boolean variant sets its attributes for a true or "true" prop alone', + (_, condition) => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const Flagged = ds + .styles({}) + .variant({ prop: 'flag', variants: { true: {}, false: {} } }) + .contract({ when: { flag: condition }, attrs: { title: 'On' } }) + .asElement('span'); + const render = (flag?: boolean | 'true' | 'false') => + renderToString(createElement(Flagged, { flag })); + expect(render(true)).toContain('title="On"'); + expect(render('true')).toContain('title="On"'); + expect(render(false)).not.toContain('title='); + expect(render('false')).not.toContain('title='); + expect(render()).not.toContain('title='); + } +); diff --git a/packages/react/src/runtime/index.ts b/packages/react/src/runtime/index.ts index c10a6edb..c4cf8ae2 100644 --- a/packages/react/src/runtime/index.ts +++ b/packages/react/src/runtime/index.ts @@ -150,11 +150,13 @@ export function renderAsChild( function matchesExpected( actual: unknown, - expected: string | readonly string[] + expected: string | boolean | readonly (string | boolean)[] ): boolean { - return typeof expected === 'string' - ? actual === expected - : expected.includes(actual as string); + if (typeof actual !== 'string' && typeof actual !== 'boolean') return false; + const value = String(actual); + return typeof expected === 'object' + ? expected.some((option) => String(option) === value) + : String(expected) === value; } function contractAttrs( diff --git a/packages/react/types/published/contract.tsx b/packages/react/types/published/contract.tsx index 66894620..27b323ec 100644 --- a/packages/react/types/published/contract.tsx +++ b/packages/react/types/published/contract.tsx @@ -47,6 +47,18 @@ const ExtendedPicture = Picture.extend() const Plain = ds.styles({ display: 'flex' }).asElement('div'); +const Flagged = ds + .styles({}) + .variant({ prop: 'flag', variants: { true: {}, false: {} } }) + .contract({ when: { flag: true }, require: { attrs: ['title'] } }) + .asElement('span'); + +const FlaggedText = ds + .styles({}) + .variant({ prop: 'flag', variants: { true: {}, false: {} } }) + .contract({ when: { flag: 'true' }, require: { attrs: ['title'] } }) + .asElement('span'); + export const accepted = ( <> Save @@ -65,9 +77,25 @@ export const accepted = ( Docs Not a link Plain + + + + + + + ); +// @ts-expect-error +export const flaggedUntitled = ; +// @ts-expect-error +export const flaggedTextUntitled = ; +// @ts-expect-error +export const textFlaggedUntitled = ; +// @ts-expect-error +export const textFlaggedTextUntitled = ; + // @ts-expect-error export const iconOnlyUnlabelled = ×; export const iconOnlyUndefinedLabel = ( From 10761aa9c6d94a765a3bbaa34f1ad02ba267339f Mon Sep 17 00:00:00 2001 From: codecaaron Date: Sat, 28 Nov 2026 05:50:52 -0500 Subject: [PATCH 3/3] fix(extract,plugins,cli): source-map chaining, check parity with build, MCP versions A map composed with an incoming map keeps its sourceRoot and ignore lists and leaves code the incoming map does not cover unmapped. Hosts get a map when a define substitution or a stylesheet import moves code in a file the engine did not transform, and no map when the code they pass differs from the analysed source. animus check and the MCP check_source tool run through the same analysis path as the build, so they report the build's custom-property, system and kit diagnostics and use the same resolution evidence. The MCP server advertises only the current protocol revision as supported and accepts batches for clients that negotiated 2025-03-26. Verified at this commit: vp run verify:full (55 of 55 tasks) and the effect-ui app's verify. Co-Authored-By: Claude Fable 5.2 --- e2e/rollup-app/fixtures/check-root/Badge.tsx | 6 + e2e/rollup-app/fixtures/check-root/Card.tsx | 7 ++ .../fixtures/check-root/animus.config.json | 4 + e2e/rollup-app/fixtures/check-root/ds.ts | 12 ++ e2e/rollup-app/scripts/assert-agent.mjs | 38 ++++++ .../_integration/__tests__/source-map.test.ts | 39 ++++++ packages/cli/src/mcp.ts | 111 ++++++++++-------- packages/extract/pipeline/engine-adapter.ts | 7 +- packages/extract/pipeline/source-maps.ts | 57 ++++++++- .../extract/session/extraction-session.ts | 67 ++++++----- packages/next-plugin/src/loader-core.ts | 19 ++- packages/unplugin/src/core.ts | 3 +- 12 files changed, 277 insertions(+), 93 deletions(-) create mode 100644 e2e/rollup-app/fixtures/check-root/Badge.tsx create mode 100644 e2e/rollup-app/fixtures/check-root/Card.tsx create mode 100644 e2e/rollup-app/fixtures/check-root/animus.config.json create mode 100644 e2e/rollup-app/fixtures/check-root/ds.ts diff --git a/e2e/rollup-app/fixtures/check-root/Badge.tsx b/e2e/rollup-app/fixtures/check-root/Badge.tsx new file mode 100644 index 00000000..8c08f810 --- /dev/null +++ b/e2e/rollup-app/fixtures/check-root/Badge.tsx @@ -0,0 +1,6 @@ +import { ds } from './ds'; +import { label } from './generated/labels'; + +export const Badge = ds.styles({ color: 'ink' }).asElement('span'); + +export const App = () => {label}; diff --git a/e2e/rollup-app/fixtures/check-root/Card.tsx b/e2e/rollup-app/fixtures/check-root/Card.tsx new file mode 100644 index 00000000..99d02ba2 --- /dev/null +++ b/e2e/rollup-app/fixtures/check-root/Card.tsx @@ -0,0 +1,7 @@ +import { ds } from './ds'; + +export const Card = ds + .styles({ color: 'ink', '--gap': 'var(--gap)' }) + .asElement('div'); + +export const App = () => card; diff --git a/e2e/rollup-app/fixtures/check-root/animus.config.json b/e2e/rollup-app/fixtures/check-root/animus.config.json new file mode 100644 index 00000000..f943acc4 --- /dev/null +++ b/e2e/rollup-app/fixtures/check-root/animus.config.json @@ -0,0 +1,4 @@ +{ + "system": "./ds.ts", + "diagnostics": { "animus.property.self-reference": "error" } +} diff --git a/e2e/rollup-app/fixtures/check-root/ds.ts b/e2e/rollup-app/fixtures/check-root/ds.ts new file mode 100644 index 00000000..2f445fb5 --- /dev/null +++ b/e2e/rollup-app/fixtures/check-root/ds.ts @@ -0,0 +1,12 @@ +import { color } from '@animus-ui/core/groups'; +import { createSystem, createTheme } from '@animus-ui/react'; + +export const theme = createTheme() + .addColors({ gray: { 100: '#f5f5f5', 900: '#171717' } }) + .addColorModes('light', { + light: { ink: 'gray.900' }, + dark: { ink: 'gray.100' }, + }) + .build(); + +export const ds = createSystem().addGroup('color', color).build(theme).seal(); diff --git a/e2e/rollup-app/scripts/assert-agent.mjs b/e2e/rollup-app/scripts/assert-agent.mjs index ba87ef87..6d13e13f 100644 --- a/e2e/rollup-app/scripts/assert-agent.mjs +++ b/e2e/rollup-app/scripts/assert-agent.mjs @@ -1,4 +1,6 @@ import { spawnSync } from 'node:child_process'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -96,6 +98,42 @@ check( file?.components.some((component) => component.name === 'Draft') === true ); +const checkRoot = join(lane, 'fixtures', 'check-root'); +const checkOut = mkdtempSync(join(tmpdir(), 'animus-rollup-check-')); +try { + const built = run(['build', '--root', checkRoot, '--out-dir', checkOut]); + const fromBuild = [ + ...built.stderr.matchAll( + /^\[animus\] [⚠✖ℹ] (\S+?\.tsx)\b.*\[([\w.-]+)\]$/gmu + ), + ] + .map(([, path, code]) => `${path} ${code}`) + .sort(); + const rechecked = run([ + 'check', + '--root', + checkRoot, + join(checkRoot, 'Card.tsx'), + join(checkRoot, 'Badge.tsx'), + ]); + const fromCheck = (parsed(rechecked)?.files ?? []) + .flatMap((entry) => + [...entry.tokenMisses, ...entry.diagnostics].map( + (diagnostic) => `${entry.file} ${diagnostic.code}` + ) + ) + .sort(); + check( + 'check reports for a source what build reports for it', + fromBuild.includes('Card.tsx animus.property.self-reference') && + fromCheck.join() === fromBuild.join() && + rechecked.status === built.status, + `build ${built.status} ${JSON.stringify(fromBuild)}, check ${rechecked.status} ${JSON.stringify(fromCheck)}` + ); +} finally { + rmSync(checkOut, { recursive: true, force: true }); +} + const exported = run([ 'tokens', 'export', diff --git a/packages/_integration/__tests__/source-map.test.ts b/packages/_integration/__tests__/source-map.test.ts index ff7f368e..3f6f5846 100644 --- a/packages/_integration/__tests__/source-map.test.ts +++ b/packages/_integration/__tests__/source-map.test.ts @@ -1,3 +1,4 @@ +import { chainSourceMap } from '@animus-ui/extract/pipeline'; import { SourceMap } from 'node:module'; import { beforeAll, describe, expect, test } from 'vitest'; @@ -72,3 +73,41 @@ describe('a transformed module source map', () => { }); }); }); + +describe('a map composed with an incoming map', () => { + const ours = { + version: 3, + file: 'a.js', + sources: ['a.js'], + names: [], + mappings: 'AAAA,UACA', + }; + + test('keeps the incoming source root and ignore lists', () => { + const chained = chainSourceMap(ours, { + version: 3, + sourceRoot: '../src/', + sources: ['a.ts', 'vendor.ts'], + names: [], + mappings: 'AAAA;MACA', + ignoreList: [1], + x_google_ignoreList: [1], + }); + expect(chained).toMatchObject({ + sourceRoot: '../src/', + sources: ['a.ts', 'vendor.ts'], + ignoreList: [1], + x_google_ignoreList: [1], + }); + }); + + test('leaves code the incoming map does not cover unmapped', () => { + const chained = chainSourceMap(ours, { + version: 3, + sources: ['a.ts'], + names: [], + mappings: 'AAAA;MACA', + }); + expect(chained.mappings).toBe('AAAA,U'); + }); +}); diff --git a/packages/cli/src/mcp.ts b/packages/cli/src/mcp.ts index 0d9857bd..befcf297 100644 --- a/packages/cli/src/mcp.ts +++ b/packages/cli/src/mcp.ts @@ -41,7 +41,7 @@ const LEGACY_PROTOCOL_VERSIONS = [ '2025-03-26', '2024-11-05', ]; -const SUPPORTED = [...MODERN_PROTOCOL_VERSIONS, ...LEGACY_PROTOCOL_VERSIONS]; +const BATCHING_PROTOCOL_VERSION = '2025-03-26'; const PROTOCOL_VERSION_KEY = 'io.modelcontextprotocol/protocolVersion'; const SERVER_INFO_KEY = 'io.modelcontextprotocol/serverInfo'; const UNSUPPORTED_PROTOCOL_VERSION = -32022; @@ -253,20 +253,20 @@ export async function runMcpServer( const send = (message: JsonRecord): void => { output.write(`${JSON.stringify(message)}\n`); }; - const respond = ( + const response = ( id: string | number | null, outcome: { result: JsonRecord } | { error: RpcError } - ): void => { - send( - 'result' in outcome - ? { jsonrpc: '2.0', id, result: outcome.result } - : { - jsonrpc: '2.0', - id, - error: JSON.parse(JSON.stringify(outcome.error)) as JsonRecord, - } - ); - }; + ): JsonRecord => + 'result' in outcome + ? { jsonrpc: '2.0', id, result: outcome.result } + : { + jsonrpc: '2.0', + id, + error: JSON.parse(JSON.stringify(outcome.error)) as JsonRecord, + }; + const invalid = (): JsonRecord => + response(null, { error: { code: -32600, message: 'Invalid Request' } }); + let negotiated: string | null = null; const handle = async (message: RpcMessage): Promise => { const params = message.params; @@ -275,7 +275,7 @@ export async function runMcpServer( throw new ProtocolError( UNSUPPORTED_PROTOCOL_VERSION, 'Unsupported protocol version', - { supported: SUPPORTED, requested: modern } + { supported: MODERN_PROTOCOL_VERSIONS, requested: modern } ); } const finish = (result: JsonRecord): JsonRecord => @@ -289,12 +289,12 @@ export async function runMcpServer( switch (message.method) { case 'initialize': { const asked = params?.protocolVersion; + negotiated = + typeof asked === 'string' && LEGACY_PROTOCOL_VERSIONS.includes(asked) + ? asked + : LEGACY_PROTOCOL_VERSIONS[0]!; return { - protocolVersion: - typeof asked === 'string' && - LEGACY_PROTOCOL_VERSIONS.includes(asked) - ? asked - : LEGACY_PROTOCOL_VERSIONS[0]!, + protocolVersion: negotiated, capabilities: { tools: {} }, serverInfo, instructions: INSTRUCTIONS, @@ -302,7 +302,7 @@ export async function runMcpServer( } case 'server/discover': return finish({ - supportedVersions: SUPPORTED, + supportedVersions: MODERN_PROTOCOL_VERSIONS, capabilities: { tools: {} }, instructions: INSTRUCTIONS, }); @@ -352,44 +352,59 @@ export async function runMcpServer( } }; - let queue = Promise.resolve(); - const lines = createInterface({ input, crlfDelay: Infinity }); - for await (const line of lines) { - if (line.trim() === '') continue; - let message: RpcMessage; - try { - message = JSON.parse(line) as RpcMessage; - } catch { - respond(null, { error: { code: -32700, message: 'Parse error' } }); - continue; - } + const reply = async (message: JsonValue): Promise => { if ( message === null || typeof message !== 'object' || Array.isArray(message) ) { - respond(null, { error: { code: -32600, message: 'Invalid Request' } }); - continue; + return invalid(); } - if (typeof message.method !== 'string') { - if (message.id === undefined) { - respond(null, { error: { code: -32600, message: 'Invalid Request' } }); - } + const rpc: RpcMessage = message; + if (typeof rpc.method !== 'string') { + return rpc.id === undefined ? invalid() : null; + } + const id = rpc.id; + if (id === undefined) return null; + try { + return response(id, { result: await handle(rpc) }); + } catch (error) { + return response(id, { + error: + error instanceof ProtocolError + ? { code: error.code, message: error.message, data: error.data } + : { code: -32603, message: String(error) }, + }); + } + }; + + let queue = Promise.resolve(); + const lines = createInterface({ input, crlfDelay: Infinity }); + for await (const line of lines) { + if (line.trim() === '') continue; + let message: JsonValue; + try { + message = JSON.parse(line) as JsonValue; + } catch { + send(response(null, { error: { code: -32700, message: 'Parse error' } })); continue; } - const id = message.id; - if (id === undefined) continue; queue = queue.then(async () => { - try { - respond(id, { result: await handle(message) }); - } catch (error) { - respond(id, { - error: - error instanceof ProtocolError - ? { code: error.code, message: error.message, data: error.data } - : { code: -32603, message: String(error) }, - }); + if ( + Array.isArray(message) && + message.length > 0 && + negotiated === BATCHING_PROTOCOL_VERSION + ) { + const replies: JsonRecord[] = []; + for (const entry of message) { + const answer = await reply(entry); + if (answer !== null) replies.push(answer); + } + if (replies.length > 0) output.write(`${JSON.stringify(replies)}\n`); + return; } + const answer = await reply(message); + if (answer !== null) send(answer); }); } await queue; diff --git a/packages/extract/pipeline/engine-adapter.ts b/packages/extract/pipeline/engine-adapter.ts index 8bbcc26c..c9c2c4ba 100644 --- a/packages/extract/pipeline/engine-adapter.ts +++ b/packages/extract/pipeline/engine-adapter.ts @@ -247,7 +247,8 @@ export function createEngineApi(deps: EngineAdapterDeps): () => EngineApi { return { code: source, hasComponents: false }; } const sent = sentMap?.get(path); - if (sent !== undefined && sent !== source && !store.getDriftWarned()) { + const drifted = sent !== undefined && sent !== source; + if (drifted && !store.getDriftWarned()) { store.setDriftWarned(true); // eslint-disable-next-line no-console console.warn( @@ -255,9 +256,9 @@ export function createEngineApi(deps: EngineAdapterDeps): () => EngineApi { ); } const result = JSON.parse( - engine.transformFile(path, sourceMapSource) + engine.transformFile(path, drifted ? undefined : sourceMapSource) ) as TransformFileResult; - if (result.annotated && sent !== undefined && sent !== source) { + if (result.annotated && drifted) { return { code: source, hasComponents: false }; } return result; diff --git a/packages/extract/pipeline/source-maps.ts b/packages/extract/pipeline/source-maps.ts index 17e99380..5e9bfb9d 100644 --- a/packages/extract/pipeline/source-maps.ts +++ b/packages/extract/pipeline/source-maps.ts @@ -1,10 +1,13 @@ export interface SourceMap { version: number; file?: string; + sourceRoot?: string; sources: string[]; sourcesContent?: (string | null)[]; names: string[]; mappings: string; + ignoreList?: number[]; + x_google_ignoreList?: number[]; } export type CodeEdit = readonly [start: number, end: number, text: string]; @@ -136,10 +139,40 @@ function shiftMappings( return encode(lines); } +function identityMap( + code: string, + source: string, + edits: readonly CodeEdit[] +): SourceMap { + const starts = lineStarts(code); + const columns = starts.map(() => new Set([0])); + const offsets = [ + ...[...code.matchAll(/\w+|[^\w\s]/g)].map((match) => match.index), + ...edits.flatMap(([start, end]) => [start, end]), + ]; + for (const offset of offsets) { + const line = countAtOrBefore(starts, offset) - 1; + columns[line]!.add(offset - starts[line]!); + } + return { + version: 3, + sources: [source], + names: [], + mappings: encode( + columns.map((set, line) => + [...set] + .sort((a, b) => a - b) + .map((column) => [column, 0, line, column]) + ) + ), + }; +} + export function editCode( code: string, edits: readonly CodeEdit[], - map: SourceMap | null + map: SourceMap | null, + source?: string ): MappedCode { if (edits.length === 0) return { code, map }; const sorted = [...edits].sort((a, b) => a[0] - b[0] || a[1] - b[1]); @@ -150,12 +183,14 @@ export function editCode( cursor = end; } edited += code.slice(cursor); - if (map === null) return { code: edited, map: null }; + const base = + map ?? (source === undefined ? null : identityMap(code, source, sorted)); + if (base === null) return { code: edited, map: null }; return { code: edited, map: { - ...map, - mappings: shiftMappings(code, edited, sorted, map.mappings), + ...base, + mappings: shiftMappings(code, edited, sorted, base.mappings), }, }; } @@ -203,7 +238,13 @@ export function chainSourceMap( continue; } const origin = originalAt(inputLines, segment[2]!, segment[3]!); - if (origin === undefined) continue; + const last = chainedLine[chainedLine.length - 1]; + if (origin === undefined) { + if (last !== undefined && last.length !== 1) { + chainedLine.push([segment[0]!]); + } + continue; + } const name = origin.length === 5 ? previous.names[origin[4]!] @@ -212,7 +253,6 @@ export function chainSourceMap( : undefined; const chained = [segment[0]!, origin[1]!, origin[2]!, origin[3]!]; if (name !== undefined) chained.push(nameOf(name)); - const last = chainedLine[chainedLine.length - 1]; if ( last !== undefined && last.length === chained.length && @@ -231,6 +271,11 @@ export function chainSourceMap( mappings: encode(lines), }; if (map.file !== undefined) result.file = map.file; + if (previous.sourceRoot) result.sourceRoot = previous.sourceRoot; if (previous.sourcesContent) result.sourcesContent = previous.sourcesContent; + if (previous.ignoreList) result.ignoreList = previous.ignoreList; + if (previous.x_google_ignoreList) { + result.x_google_ignoreList = previous.x_google_ignoreList; + } return result; } diff --git a/packages/extract/session/extraction-session.ts b/packages/extract/session/extraction-session.ts index 400ca27e..b02e2efb 100644 --- a/packages/extract/session/extraction-session.ts +++ b/packages/extract/session/extraction-session.ts @@ -78,7 +78,6 @@ import { outputSourceDiagnostic, outputTreesDiagnostic, loweredDirDiagnostic, - parseFilesJson, postProcessCss, readTsconfigAliasPairs, projectExternalFileOwners, @@ -115,7 +114,6 @@ import { pruneStaleAssets, surfaceManifestDiagnostics, systemLoadReads, - withoutLoweredFeatures, } from '../pipeline/index'; import { parseInternalWire } from '../pipeline/internal-wire'; import { @@ -446,6 +444,11 @@ interface SystemDependencies { hashes: Map; } +type AnalysisReplay = Omit< + Parameters[1], + 'warn' | 'info' | 'reportErrors' | 'onDiagnostics' +>; + interface AssetFingerprints { ofFile: (path: string) => string; ofBytes: (bytes: Buffer) => string; @@ -531,20 +534,19 @@ export class ExtractionSession { return this.lastAnalysisInputs; } + private lastAnalysis: AnalysisReplay | null = null; + analyzeWith( sources: ReadonlyArray<{ path: string; source: string }>, options: { devMode?: boolean } = {} ): FullProjectManifest { - const inputs = this.lastAnalysisInputs; - if (inputs === null) { + const analysis = this.lastAnalysis; + if (analysis === null) { throw new Error( '[animus] analyzeWith needs a completed analysis of the project first' ); } const replaced = new Set(sources.map((entry) => entry.path)); - const kept = parseFilesJson(inputs.filesJson, 'analyzeWith').filter( - (entry) => !replaced.has(entry.path) - ); let engine: ExtractorEngine | null = null; const api = createEngineApi({ label: 'animus analyzeWith', @@ -559,27 +561,30 @@ export class ExtractionSession { getDriftWarned: () => true, setDriftWarned: () => {}, }, - })(); - api.analyzeProject({ - ...inputs, - filesJson: JSON.stringify([ - ...kept, + }); + let diagnostics: readonly ManifestDiagnostic[] = []; + const result = runProjectAnalysis(api, { + ...analysis, + fileEntries: [ + ...analysis.fileEntries.filter((entry) => !replaced.has(entry.path)), ...sources.map(({ path, source }) => ({ path, source, hash: contentHash(source), })), - ]), - devMode: options.devMode ?? inputs.devMode, + ], + devMode: options.devMode ?? analysis.devMode, + gitSkip: undefined, + warn: () => {}, + reportErrors: () => {}, + onDiagnostics: (all) => { + diagnostics = all; + }, }); - const manifest = JSON.parse(api.fullManifestJson!()) as FullProjectManifest; - const targetSupport = this.targetSupport(); - if (targetSupport && manifest.diagnostics) { - manifest.diagnostics = withoutLoweredFeatures( - manifest.diagnostics, - targetSupport - ); - } + const manifest = JSON.parse( + result.fullManifestJson() + ) as FullProjectManifest; + manifest.diagnostics = [...diagnostics]; return manifest; } private stagedPublication: Omit< @@ -2669,26 +2674,30 @@ export class ExtractionSession { }; this.writeAnalysisStatus('analyzing', pending); - const result = runProjectAnalysis(() => this.engine(), { + const replay: AnalysisReplay = { ...analysisOptions, - warn: (message) => this.warn(message), - info: (message) => this.log(message), strict: this.options.strict, diagnostics: this.options.diagnostics, - reportErrors: this.reportErrors(), extraDiagnostics: [ ...this.ingestionFailureDiagnostics, ...(await this.compareAliasesWithHost(fileEntries)), ], + kitDescriptors: this.kitDescriptors, + targetSupport: this.targetSupport(), + ...(devMode && { unitFallback: this.unitFallback }), + }; + const result = runProjectAnalysis(() => this.engine(), { + ...replay, + warn: (message) => this.warn(message), + info: (message) => this.log(message), + reportErrors: this.reportErrors(), ...(this.options.lintFiles === true && { onDiagnostics: (diagnostics: readonly ManifestDiagnostic[]) => this.publishDiagnostics(fileEntries, diagnostics), }), - kitDescriptors: this.kitDescriptors, - targetSupport: this.targetSupport(), - ...(devMode && { unitFallback: this.unitFallback }), }); this.lastAnalysisInputs = result.inputs; + this.lastAnalysis = replay; if (result.manifest) { assertRuntimeImportSuppliesTerminals(this.runtimeImport, result.manifest); } diff --git a/packages/next-plugin/src/loader-core.ts b/packages/next-plugin/src/loader-core.ts index e7b9370b..3d2449fb 100644 --- a/packages/next-plugin/src/loader-core.ts +++ b/packages/next-plugin/src/loader-core.ts @@ -160,10 +160,11 @@ export function transformWithManifest(args: { ); } - let mapped: MappedCode = - result.hasComponents || result.annotated - ? { code: result.code, map: result.map ?? null } - : { code: source, map: null }; + const transformed = result.hasComponents || result.annotated; + let mapped: MappedCode = transformed + ? { code: result.code, map: result.map ?? null } + : { code: source, map: null }; + const identity = transformed ? undefined : sourceMap?.source; mapped = editCode( mapped.code, @@ -172,11 +173,17 @@ export function transformWithManifest(args: { match.index + match[0].length, '', ]), - mapped.map + mapped.map, + identity ); if (isRootEntry && !mapped.code.includes(ANIMUS_CSS_MODULE_ID)) { - mapped = editCode(mapped.code, [cssImportEdit(mapped.code)], mapped.map); + mapped = editCode( + mapped.code, + [cssImportEdit(mapped.code)], + mapped.map, + identity + ); } return { diff --git a/packages/unplugin/src/core.ts b/packages/unplugin/src/core.ts index f6726fe3..49aeee29 100644 --- a/packages/unplugin/src/core.ts +++ b/packages/unplugin/src/core.ts @@ -1023,7 +1023,8 @@ export const unpluginFactory: UnpluginFactory = ( output = editCode( output.code, devDefineEdits(output.code, state.mode === 'development'), - output.map + output.map, + request.wanted && output.code === code ? filePath : undefined ); } if (output.code === code) return null;