@teacss/core
v0.5.2
Published
TeaCSS engine core — token parsing, condition resolution, rule matching, and CSS generation.
Readme
@teacss/core
The framework-neutral TeaCSS parser and generator.
@teacss/core parses colon-syntax tokens, resolves trailing conditions,
matches preset rules, and emits layered CSS. It owns mechanism; presets own
utility vocabulary.
bun add @teacss/core @teacss/preset-standardimport { createGenerator } from "@teacss/core";
import { presetStandard } from "@teacss/preset-standard";
const generator = await createGenerator({ presets: [presetStandard()] });
const { css } = await generator.generate("p:4 bg-color:red-500@hover");Most applications should install teacss and a build adapter instead. Use Core
directly for presets, generators, and tooling.
Rule declaration tuples use [property, value, operators?]. The optional third
slot is retained for custom processors; Core does not interpret or execute it.
Only the property and value are serialized into CSS.
Key APIs
| API | Purpose |
| ---------------------- | ---------------------------------------------------------------- |
| createGenerator | Resolves presets and creates a CSS generator. |
| splitClassTokens | Splits class whitespace while preserving attached [] literals. |
| expandGroups | Expands TeaCSS groups while scanning host source. |
| expandClassGroups | Expands groups in an already isolated class list. |
| compareParentAtRules | Applies the generator's deterministic parent-rule order. |
| comparableWidth | Normalizes comparable media-query widths. |
Width comparison includes svi, svb, lvi, lvb, dvi, dvb, rex,
rch, rcap, and ric. These relative units compare within their own scale,
not against pixels or other relative units. Numeric media ordering and
@screen at-* range selection share this comparison.
Values that overflow JavaScript's finite numeric range, including during pixel
conversion, return null and do not participate in numeric width comparison.
This does not reject or rewrite the authored CSS value.
Width parsing accepts only CSS whitespace (space, tab, LF, CR, and form feed).
Unicode spaces such as NBSP remain part of the input, so 768px followed by
NBSP is not silently treated as a valid pixel width or selected as a range bound.
Negated media queries stay outside numeric width ordering, including CSS-escaped
not keywords. Keyword checks use complete names, not fragments such as
not-feature; comments and strings do not contribute negation. Escapes are
decoded only for identity checks, without rewriting the emitted query.
Composed at-rule parents preserve escaped punctuation in their preludes.
An escaped bracket, parenthesis, or quote cannot swallow the next parent;
both ordinary generation and constructCSS() emit properly nested blocks.
The default extractor understands quoted and valid unquoted HTML classes. It keeps JavaScript, TypeScript, JSX, TSX, and MDX on their host-language paths so host expressions are not mistaken for TeaCSS groups.
Group expansion preserves CSS escapes in conditions, including escaped ;,
commas, and brackets. They remain part of each member's condition instead of
ending a group, splitting its members, or swallowing following classes.
The default extractor also protects escaped quotes, backticks, semicolons, and
braces in condition suffixes during its final token split. Ordinary host quotes
and whitespace remain source boundaries; escaped punctuation cannot silently
turn a condition into a shorter selector.
Quoted attributes on structural conditions, such as probe@_li[title="x"]
and [email protected][title=""], also stay intact during scanning and group
expansion. Ordinary host arrays and decorator indexes remain extractable.
Structural selector conditions preserve NBSP-like Unicode spaces before group
expansion and attribute masking, including escaped forms and unquoted HTML
class values. Ordinary source whitespace and U+2028/U+2029 line separators
remain boundaries; named conditions do not gain Unicode-space continuation.
The compatibility helpers parseVariantGroup() and expandVariantGroup()
accept a MagicStringLike buffer. They check all target ranges against the
original source before writing, so a pre-existing overlapping edit or unreadable
range rejects without partially expanding earlier groups. Edits outside the
groups are preserved. This does not roll back failures from a custom overwrite().
Compatibility group helpers snapshot only own separator and prefix entries,
rechecking ownership after earlier getters run. Deleted slots cannot introduce
inherited separators into matching or inherited prefixes into collapsing.
getPath(id) removes the first ? and everything after it, including any line
terminators in the query. The path before it is preserved verbatim.
applyExtractors() returns the supplied accumulator. Passing a CountableSet
preserves its counting methods in the inferred return type; omitting the
accumulator or passing undefined creates and returns a plain Set.
It commits only changes made by successful extraction. Unchanged
CountableSet members and counts are left alone, including zero, infinite, and NaN counts
and caller changes made while asynchronous extraction is pending.
Explicit zero-count members returned or set by extractors are retained when the
combined count is zero. Deletions and concurrent decrements that exhaust a
positive source count still remove the member.
Programmatic safelist entries and callback results accept {a;b}@condition
groups, like explicit token lists. Expanded members respect the blocklist and
do not increase existing source occurrence counts. Pass safelist: false to
generate() to omit the configured safelist.
Large direct-input builds may set a positive tokenConcurrency limit:
await generator.generate(tokens, { tokenConcurrency: 256 });Omitting the option preserves unbounded scheduling. Output order remains deterministic.
generate() infers matched as a Map when extendedInfo: true is required
by the supplied options type, and as a Set when known to be disabled or omitted. Runtime
booleans and optional GenerateOptions<true> return Set | Map; narrow with
matched instanceof Map before reading extended token information.
With outputToCssLayers: { allLayers: true }, the native layer-order declaration
includes both configured layers (even unused ones) and layers used by rules or
preflights. Custom layers retain their sorted cascade position, including when
getLayers() selects only part of the result. Aliases and null opt-outs apply
to this declaration as well as the layer blocks.
Adapters holding externally extracted tokens may pass
isInputCurrent: () => sourceRevision === extractedRevision. Core captures this
optional callback once per generate() call and checks it repeatedly across
generation boundaries, including config retries and diagnostic publication.
It must be synchronous and side-effect-free: false rejects with
Error("[@teacss/core] Generation input is no longer current."); callback errors
propagate, and invalid callback types or non-boolean results reject with
TypeError. An accidentally asynchronous check's rejection is observed; it does
not become an additional unhandled rejection. Re-extract before starting another
call. Omitting it preserves existing behavior. This is not cancellation of
running hooks or rollback of diagnostics already delivered while the input was current.
Selector merging isolates vendor-prefixed pseudo selectors, including those following escaped backslashes or comments after the colon, so unsupported pseudos cannot invalidate ordinary selectors. Escaped vendor-name characters receive the same protection; escaped standard pseudo names can still merge. Pseudo-like text inside escaped class names, comments, and attribute strings can still merge.
Structural subject and target conditions reject empty, CSS-whitespace-only, or
comment-only attribute selectors such as @.active[] and @_li[/**/].
Those tokens remain unmatched instead of invalidating merged rules. Empty
attribute values such as [title=""] remain supported.
Pseudo-element names must start CSS identifiers: @::5, @::-5, and @::-
remain unmatched, including on subject and target conditions. Names are not
restricted to a preset vocabulary; non-ASCII and escaped starts are supported.
Escaped legacy names such as :bef\ore keep their pseudo-element role and
per-token limit. Functional ::part() / ::slotted() chains compare decoded
names too, while emitted selectors preserve the authored spelling. Identifier
hex escapes consume at most six digits and one optional CSS whitespace terminator
(CRLF counts as one); extra top-level whitespace remains invalid.
Comments may separate a class dot or pseudo-class colon from its name, and
the two pseudo-element colons: ./**/active, :/**/hover, :/**/:before.
They cannot split a hash token (#/**/id), an identifier, or the name and opening
parenthesis of a function (:not/**/(...)). Part states follow the same rules.
Functional chain arguments preserve non-ASCII identifiers, including NBSP.
Between chained pseudo-elements, only comments or permitted part states are
allowed; neither CSS whitespace nor non-ASCII space-like characters are erased.
This chain check also applies to resolver-authored suffixes and pseudo-elements.
Structural identifiers preserve non-ASCII characters such as NBSP; JavaScript
whitespace is not interchangeable with CSS whitespace during selector validation.
Quoted structural strings reject raw LF, CR, and form-feed characters, while
preserving CSS escapes and backslash line continuations (including CRLF).
Outside quoted strings and comments, a backslash followed by LF, CR, or form-feed
is not a valid selector escape and leaves the structural condition unmatched.
The experimental scope generation option accepts a selector or selector list:
{ scope: ".app-a, .app-b" } scopes each generated selector to both roots,
preserving each scope arm's specificity. It does not style the roots themselves.
Rule metadata noScope bypasses scoping; raw CSS and preflights are not scoped.
An empty string disables scoping. Empty or comment-only list arms reject
generate() with a TypeError, even when there is no generated CSS; this
guards against accidental unscoped output, not all invalid selector syntax.
Selector-list cleanup preserves escaped whitespace, hexadecimal escape
terminators, and non-ASCII identifier characters such as NBSP.
Replacing an interior $$ scope placeholder retains a separating space,
including after escaped commas or braces. Scoped and unscoped output therefore
preserve the authored descendant relationship instead of joining compounds.
Adjacent $$ placeholders are all replaced, even when they share whitespace.
Each inserts the same scope independently; disabling scope removes them all.
Configuration lifecycle
Nested preset resolution tracks both factory/promise wrappers and resolved source
objects along each ancestor path. Fresh wrappers cannot hide a cycle; sibling
branches may still reuse the same preset. resolvePreset() resolves one preset
without traversing its children.
Prefer await createGenerator(). The deprecated constructor initializes lazily:
concurrent calls share one attempt; after it fails, a later call can retry.
The failed calls still reject, and no automatic background retry is scheduled.
Initialization publishes config only after rule snapshots succeed. A snapshot
failure leaves initialization retryable; a replacement committed during snapshot
reads stays active without a duplicate config event.
An explicit replacement via setConfig() or prepareConfig() does not first
initialize the unrelated constructor config, so invalid initial configs can be
replaced without rerunning their failing hooks.
setConfig() without a replacement stays a no-op, even before initialization.
prepareConfig(nextConfig) creates an isolated candidate generator.
commitConfig(prepared) switches the live generator only when that candidate
is still current. A successful commit preserves generator identity and reports
observer failures as diagnostics.
If the diagnostic sink itself throws, that logging failure is ignored: the
committed configuration stays successful and async observers leave no unhandled
rejection. This does not suppress configResolved() failures before commit.
Commit validation rechecks candidate identity after reading mutable configuration;
if a getter reconfigures the candidate, the commit is rejected without touching
the live configuration or dispatching its observers.
configResolved(config) hooks may be synchronous or asynchronous. Core awaits
them sequentially in resolved preset order, then awaits the user hook, and
rebuilds rule indexes afterward. Return values are ignored; modify config
directly. A throw or rejection aborts resolution, so failed setConfig() calls
leave the live configuration unchanged. Config-event observers remain separate.
Content pipeline filters merge across presets without expanding the source list into function arguments, so large compositions do not hit Node's argument limit. Filter order, deduplication, and regular-expression identity are preserved.
Themes are deep-merged only while they are plain objects. A non-plain theme is
atomic; replace it, reset to a plain object with { $reset: true }, or combine
it through extendTheme.
New plain-object branches also consume nested $reset markers, including when
replacing a scalar; the caller's patch is left unchanged.
mergeDeep() copies array-patch containers and retains only their own items,
including new fields and replacements of non-array values. Passing true as the
third argument concatenates only when both values are arrays.
toArray() treats optional undefined input as an empty array in its return
type, preserving array mutability and explicit undefined elements within arrays.
It captures array length once for both density checks and sparse compaction;
items appended by getters are not added to the current compacted result.
Shortcut grouping computes maximum rule and sort priorities incrementally, without depending on the JavaScript engine's function-argument limit.
Preset preflights receive the generator, theme, and the current call's generated
utilities through context.generated.
With preflights: false, the emission stage skips reading the preflight list;
configuration resolution and prepared-config validation still run normally.
isThenable() checks objects and functions for a callable then, without invoking
it. Primitive values are rejected without reading their prototypes; errors from
object getters still propagate.
Rule callbacks receive currentSelector and variantMatch for their local parse
branch, including shortcut leaves; rawSelector remains the outer styled token.
parseUtil() does not rewrite its caller's matching context. Its rule and
constructCSS() callbacks use the same captured configuration even if an async
variant replaces the generator configuration in between.
Direct parseUtil() calls retry both results and failures made obsolete by
in-place edits to the current prepared config. Unchanged-config failures still
reject with their original value; contexts for replaced configs stay bound.
Rule activation checks both config identity and runtime revision, so an obsolete
async result cannot repopulate activatedRules after another call refreshes
prepared-config indexes.
Late branches from an obsolete parse also skip rule-detail recording, so they
cannot append retired rules to the shared context.rules after a retry.
Direct parsing with a retained older configuration still records its own details.
Retained contexts for an older configuration use a separate condition cache:
neither resolved nor unrecognized conditions can leak between old and live
configurations. Live configuration revisions still invalidate their cache.
Copied contexts exposed by parseToken(), extended-info data, and preflight
utilities retain that configuration binding when reused with Core methods.
Dynamic-rule prefix enumeration and dispatch buckets append own array entries,
so inherited numeric setters cannot discard prefixes or rules. Keyed and
fallback rule order remains identical to the ordinary scan.
Condition results, delimiter stacks, and pseudo-element chains use the same
own-entry writes, preserving both resolved and unresolved conditions.
Group expansion/collapse and unmatched-token suggestions likewise preserve
collected items and edit-distance rows through inherited numeric setters.
Unmatched-token indexing captures the static rule map once for both contents
and cache identity, ignoring absent or deleted static entries. Dynamic rule and
metadata-prefix traversal reads only own array items, so inherited entries do
not create diagnostic vocabulary or trigger matcher probes.
Event dispatch reads its event store once and snapshots only own listener slots,
rechecking each slot after earlier getters run. Subscription changes made by
listeners apply to subsequent dispatches, not the current snapshot.
Generator configuration notifications use the same single-store, own-slot
snapshot while retaining their separate observer-error isolation.
If reading that snapshot fails, the committed configuration remains successful:
the error is reported, that notification batch is skipped, and later notifications
can proceed after the listener storage is repaired.
Unsubscription uses the same own-slot snapshot before filtering, so deletions
by getters cannot retain inherited listeners. A failed snapshot leaves listener
storage unchanged and permits retrying the unsubscribe function.
uniq(), uniqueBy(), and BetterMap.flatMap() likewise check slot ownership
at each read, so getters and comparison callbacks cannot expose inherited values.
These traversals capture the initial array length; toArray() still preserves
the identity of dense arrays.
Array patches and recursive $reset cleanup also recheck ownership while reading,
so getter-driven deletions cannot promote inherited items into merged config.
CSS entry normalization checks ownership as entries are filtered. CSS value-list
normalization snapshots own items once before classification and conversion,
avoiding repeated top-level getters and retaining entry-tuple metadata.
clone() uses the same captured array length for allocation and copying, retaining
own undefined slots when source entries disappear during the reverse traversal.
Extractor, preprocessor, variant, and postprocessor traversal rechecks own slots
after earlier callbacks, including async waits. Extractor-returned arrays use
the same own-slot reads, so deleted entries cannot introduce inherited tokens.
Variant branch results, handler snapshots, postprocessor result arrays, and
preflight grouping also recheck ownership after earlier getters run, preserving
authored ordering without promoting inherited branches, selectors, or preflights.
Generation input arrays, safelist result arrays, sorted layer results, and
getLayers() include/exclude lists use the same own-slot reads, so getters cannot
expose inherited tokens or alter layer selection through deleted entries.
Condition parsing, resolver traversal, and selector assembly likewise recheck
own array entries after earlier getters or callbacks, excluding inherited
conditions and resolver hooks exposed by deletions.
symbols.variants snapshots only own handlers in callback inputs, callback
results, and array values. Shortcut expansion snapshots each own result slot
once before separating tokens from inline declarations.
Copied rule metadata uses own descriptor fields and prototype-free descriptors,
so ambient descriptor properties cannot replace accessors or redirect layers.
withLayer() rechecks metadata-slot ownership after reading its getter. A deleted
slot is recreated as an own property without invoking inherited setters; existing
readonly metadata slots still reject writes.
Metadata prefix/autocomplete arrays and copied context handler arrays also
recheck item ownership while reading, excluding inherited items exposed by getters.
Configuration shortcut parsing, preset and rule prefix copies, and rule-list
cloning use own-slot reads too, including rule-index rebuilds after config hooks.
Rule and shortcut tuple cloning validates each required slot immediately before
reading it. A matcher getter cannot expose an inherited body; already captured
matcher values remain valid if their getter removes its own source slot.
Top-level and child preset lists use own-slot flattening for both list and
group entries. mergeConfigs() rechecks input ownership after reading each
configuration, so earlier getters cannot introduce inherited presets or configs.
Merged configuration lists, autocomplete templates/extractors and shorthand
alternatives, content sources, and pipeline filters snapshot only own items
before flattening or joining, excluding inherited values exposed during reads.
Shorthand dictionary keys are rechecked before each read. Nested autocomplete
and CLI normalization uses captured values even if later getters delete their
source properties, preserving singleton entries when configurations are merged.
Variants and postprocessors may edit their declaration tuples in place without
rewriting source rule bodies. Core isolates those inputs, including inline
shortcut declarations and the body passed to constructCSS.
normalizeVariant() preserves the input variant's theme type for both function
and object forms; normalization does not loosen typed theme requirements.
For multi-result variants, each branch's matcher is checked against blocklist
before rules or shortcuts run. Allowed branches still emit CSS; an entirely
blocked result stays excluded from unmatched diagnostics.
Regular-expression matching invokes custom exec callbacks with the matcher
as receiver, without reading the function's call property. This also applies
to global, sticky, and frozen matchers, preserving their existing index handling.
Extractor extract and preflight getCSS hooks likewise ignore an own call
property, retain their owner as receiver, and await results or propagate errors.
Variant match, body, selector, and handle callbacks also ignore an own
call property while retaining their variant or original handler receiver.
Only match supports asynchronous results; CSS handler callbacks remain synchronous.
sortLayers, outputToCssLayers.cssLayerName, and synchronous/asynchronous
rule iterator methods follow the same receiver-preserving invocation contract.
Functional symbols.variants values receive an independent handler array per
rule output, so adding, removing, or reordering handlers does not change sibling
outputs. Handler objects themselves retain their identity and prototype hooks.
Handler fields, including both parent-tuple slots, are captured before applying
callbacks; callback edits cannot change the current application’s parent or order.
Shortcut prefix matching ignores ambient Object.prototype.prefix values.
Explicit metadata prefixes, including metadata prototype accessors in prepared
configurations, remain supported for static and dynamic shortcuts.
Direct shortcut expansion checks edits to the current prepared configuration
before lookup, including renamed matchers and mutated prefix arrays.
External lists passed to expandConfiguredExpansions are indexed from their
current contents on each lookup, without replacing the cached config index.
Contexts retained by extension hooks resume normal prepared-config checks after
their generation parsing finishes, including when it fails.
Missing-utility warnings inside shortcuts wait until that shortcut finishes
stringification, and are discarded if its config becomes obsolete. Failed
stringification does not consume warning deduplication for a later retry.
This package does not load filesystem configuration, manage build-tool lifecycle, or provide runtime class composition.
Pre-1.0. Public engine APIs may change before the stable release.
