import type { BlocklistMeta, BlocklistRule, BlocklistValue, ControlSymbols, ControlSymbolsEntry, CSSEntries, CSSEntriesInput, CSSEntry, CSSObject, CSSProcessorContext, CSSValueInput, ExtendedTokenInfo, ExtractorContext, GenerateOptions, GenerateResult, ParsedUtil, PreflightContext, PreparedRule, RawUtil, ResolvedConfig, Rule, RuleContext, RuleMeta, SafeListContext, Shortcut, ShortcutInlineValue, ShortcutValue, StringifiedUtil, UserConfig, UserConfigDefaults, UtilObject, Variant, VariantContext, VariantHandler, VariantHandlerContext, VariantMatchedResult } from './types' import { version } from '../package.json' import { resolveConfig } from './config' import { LAYER_DEFAULT, LAYER_PREFLIGHTS } from './constants' import { BetterMap, CountableSet, e, entriesToCss, expandVariantGroup, isCountableSet, isRawUtil, isStaticShortcut, isString, noop, normalizeCSSEntries, normalizeCSSValues, notNull, toArray, TwoKeyMap, uniq, VirtualKey, warnOnce } from './utils' import { createNanoEvents } from './utils/events' export const symbols: ControlSymbols = { shortcutsNoMerge: '$$symbol-shortcut-no-merge' as unknown as ControlSymbols['shortcutsNoMerge'], noMerge: '$$symbol-no-merge' as unknown as ControlSymbols['noMerge'], noScope: '$$symbol-no-scope' as unknown as ControlSymbols['noScope'], variants: '$$symbol-variants' as unknown as ControlSymbols['variants'], parent: '$$symbol-parent' as unknown as ControlSymbols['parent'], selector: '$$symbol-selector' as unknown as ControlSymbols['selector'], layer: '$$symbol-layer' as unknown as ControlSymbols['layer'], sort: '$$symbol-sort' as unknown as ControlSymbols['sort'], body: '$$symbol-body' as unknown as ControlSymbols['body'], } // Chosen from benchmarks on a 24k-token project: 4096 retained most of the // benefit of smaller batches, outperformed 8192, and keeps smaller generations // on the existing single-batch path. This limits event-loop pressure rather // than CPU parallelism, so it is intentionally not based on the CPU count. const TOKEN_PARSE_BATCH_SIZE = 4096 class TokenProcessor { private cache = new Map[] | null>() private blocked = new Set() private parentOrders = new Map() private activatedRules = new Set>() async parse( generator: UnoGeneratorInternal, raw: string, alias?: string, ): Promise[] | undefined | null> { if (this.blocked.has(raw)) return const cacheKey = `${raw}${alias ? ` ${alias}` : ''}` if (this.cache.has(cacheKey)) return this.cache.get(cacheKey) const current = generator.config.preprocess.reduce((acc, p) => p(acc) ?? acc, raw) if (generator.isBlocked(current)) { this.blocked.add(raw) this.cache.set(cacheKey, null) return } const variantResults = await generator.matchVariants(raw, current) if (variantResults.every(i => !i || generator.isBlocked(i[1]))) { this.blocked.add(raw) this.cache.set(cacheKey, null) return } const data = (await Promise.all(variantResults.map(async (matched) => { const context = generator.makeContext(raw, [alias || matched[0], matched[1], matched[2], matched[3]]) if (generator.config.details) context.variants = [...matched[3]] const expanded = await generator.expandShortcut(context.currentSelector, context, 5, true) return expanded ? await generator.stringifyShortcuts(context.variantMatch, context, expanded[0], expanded[1]) : (await generator.parseUtil(context.variantMatch, context))?.flatMap(i => generator.stringifyUtil(i, context)).filter(notNull) }))).flat().filter(notNull) this.cache.set(cacheKey, data.length ? data : null) return data.length ? data : undefined } isBlocked(raw: string, blocklist: BlocklistRule[]) { if (!raw) return true for (const rule of blocklist) { const value = Array.isArray(rule) ? rule[0] : rule if (typeof value === 'function' ? value(raw) : isString(value) ? value === raw : value.test(raw)) return true } return false } getBlocked(raw: string, blocklist: BlocklistRule[]) { const rule = blocklist.find((e) => { const value = Array.isArray(e) ? e[0] : e return typeof value === 'function' ? value(raw) : isString(value) ? value === raw : value.test(raw) }) return rule ? (Array.isArray(rule) ? rule : [rule, undefined]) as [BlocklistValue, BlocklistMeta | undefined] : undefined } setParentOrder(parent: string, order: number) { this.parentOrders.set(parent, order) } getParentOrder(parent: string) { return this.parentOrders.get(parent) } activateRule(rule: Rule) { this.activatedRules.add(rule) } getActivatedRules(): ReadonlySet> { return this.activatedRules } getCachedTokens(input: string) { const tokens: string[] = [] for (const [token, result] of this.cache) { if (result && token.startsWith(input)) tokens.push(token) } return tokens } getCachedAliases(token: string) { const target = this.cache.get(token) if (!target) return const aliases: string[] = [] for (const [alias, utilities] of this.cache) { if (utilities?.length === target.length && utilities.every((utility, index) => utility[2] === target[index][2])) aliases.push(alias) } return aliases } block(tokens: Iterable) { for (const token of tokens) this.blocked.add(token) } invalidate(token: string) { this.cache.delete(token) this.blocked.delete(token) } } /** * Marks the handlers of the variants of a utility, as opposed to the ones injected by its rule * (`symbols.parent`, `symbols.variants`, ...). Set on a copy owned by the generator, so the objects * of the variants are never mutated, and as an own property so that it survives cloning. */ const SymbolUtilityVariant: unique symbol = Symbol('unocss-utility-variant') interface UtilityVariantHandler extends VariantHandler { [SymbolUtilityVariant]?: true } function markUtilityVariant(handler: VariantHandler): VariantHandler { return isUtilityVariant(handler) ? handler : { ...handler, [SymbolUtilityVariant]: true } as UtilityVariantHandler } function isUtilityVariant(handler: VariantHandler) { return (handler as UtilityVariantHandler)[SymbolUtilityVariant] === true } function unmarkUtilityVariant(handler: VariantHandler): VariantHandler { if (!isUtilityVariant(handler)) return handler const { [SymbolUtilityVariant]: _, ...rest } = handler as UtilityVariantHandler return rest } class UnoGeneratorInternal { public readonly version = version public readonly events = createNanoEvents<{ config: (config: ResolvedConfig) => void }>() public config: ResolvedConfig = undefined! private tokenProcessor = new TokenProcessor() protected constructor( public userConfig: UserConfig = {}, public defaults: UserConfigDefaults = {}, ) {} static async create( userConfig: UserConfig = {}, defaults: UserConfigDefaults = {}, ): Promise> { const uno = new UnoGeneratorInternal(userConfig, defaults) uno.config = await resolveConfig(uno.userConfig, uno.defaults) uno.events.emit('config', uno.config) return uno } async setConfig( userConfig?: UserConfig, defaults?: UserConfigDefaults, ): Promise { if (!userConfig) return if (defaults) this.defaults = defaults this.userConfig = userConfig this.config = await resolveConfig(userConfig, this.defaults) this.resetTokenProcessing() this.events.emit('config', this.config) } applyExtractors( code: string, id?: string, extracted?: Set, ): Promise> applyExtractors( code: string, id?: string, extracted?: CountableSet, ): Promise> async applyExtractors( code: string, id?: string, extracted: Set | CountableSet = new Set(), ): Promise | CountableSet> { const context: ExtractorContext = { original: code, code, id, extracted, envMode: this.config.envMode, } for (const extractor of this.config.extractors) { const result = await extractor.extract?.(context) if (!result) continue if (isCountableSet(result) && isCountableSet(extracted)) { for (const token of result) extracted.setCount(token, extracted.getCount(token) + result.getCount(token)) } else { for (const token of result) extracted.add(token) } } return extracted } makeContext(raw: string, applied: VariantMatchedResult): RuleContext { const context: RuleContext = { rawSelector: raw, currentSelector: applied[1], theme: this.config.theme, generator: this, symbols, variantHandlers: applied[2], constructCSS: (...args) => this.constructCustomCSS(context, ...args), variantMatch: applied, } return context } /** @internal */ resetTokenProcessing() { this.tokenProcessor = new TokenProcessor() } getParentOrder(parent: string) { return this.tokenProcessor.getParentOrder(parent) } getActivatedRules(): ReadonlySet> { return new Set(this.tokenProcessor.getActivatedRules()) } getCachedTokens(input: string) { return this.tokenProcessor.getCachedTokens(input) } getCachedAliases(token: string) { return this.tokenProcessor.getCachedAliases(token) } blockTokens(tokens: Iterable) { this.tokenProcessor.block(tokens) } invalidateToken(token: string) { this.tokenProcessor.invalidate(token) } async parseToken( raw: string, alias?: string, ): Promise[] | undefined | null> { return this.tokenProcessor.parse(this, raw, alias) } generate( input: string | Set | CountableSet | string[], options?: GenerateOptions ): Promise>> generate( input: string | Set | CountableSet | string[], options?: GenerateOptions ): Promise>>> async generate( input: string | Set | CountableSet | string[], options: GenerateOptions = {}, ): Promise> { const { id, scope, preflights = true, safelist = true, minify = false, extendedInfo = false, } = options const tokens: Readonly | CountableSet> = isString(input) ? await this.applyExtractors( input, id, extendedInfo ? new CountableSet() : new Set(), ) : Array.isArray(input) ? new Set(input) : input if (safelist) { const safelistContext: SafeListContext = { generator: this, theme: this.config.theme, } this.config.safelist .flatMap(s => typeof s === 'function' ? s(safelistContext) : s) .forEach((s) => { // We don't want to increment count if token is already in the set const trimmedS = s.trim() if (trimmedS && !tokens.has(trimmedS)) tokens.add(trimmedS) }) } const nl = minify ? '' : '\n' const layerSet = new Set([LAYER_DEFAULT]) const matched = extendedInfo ? new Map>() : new Set() const sheet = new Map[]>() let preflightsMap: Record = {} const tokenList = Array.from(tokens) for (let offset = 0; offset < tokenList.length; offset += TOKEN_PARSE_BATCH_SIZE) { const batchSize = Math.min(TOKEN_PARSE_BATCH_SIZE, tokenList.length - offset) const tokenPromises: Promise[] = [] for (let index = 0; index < batchSize; index++) { const raw = tokenList[offset + index] tokenPromises[index] = (async () => { if (matched.has(raw)) return const payload = await this.parseToken(raw) if (payload == null) return if (matched instanceof Map) { matched.set(raw, { data: payload, count: isCountableSet(tokens) ? tokens.getCount(raw) : -1, }) } else { matched.add(raw) } for (const item of payload) { const parent = item[3] || '' const layer = item[4]?.layer if (!sheet.has(parent)) sheet.set(parent, []) sheet.get(parent)!.push(item) if (layer) layerSet.add(layer) } })() } await Promise.all(tokenPromises) } await (async () => { if (!preflights) return const preflightContext: PreflightContext = { generator: this, theme: this.config.theme, } const preflightLayerSet = new Set([]) this.config.preflights.forEach(({ layer = LAYER_PREFLIGHTS }) => { layerSet.add(layer) preflightLayerSet.add(layer) }) preflightsMap = Object.fromEntries( await Promise.all(Array.from(preflightLayerSet).map( async (layer) => { const preflights = await Promise.all( this.config.preflights .filter(i => (i.layer || LAYER_PREFLIGHTS) === layer) .map(async i => await i.getCSS(preflightContext)), ) const css = preflights .filter(Boolean) .join(nl) return [layer, css] }, )), ) })() const sortLayers = (layers: string[]) => this.config.sortLayers(layers.sort((a, b) => ((this.config.layers[a] ?? 0) - (this.config.layers[b] ?? 0)) || a.localeCompare(b))) const layers = sortLayers(Array.from(layerSet)) const rawLayerCache: Record = {} const processedLayerCache: Record = {} const outputCssLayers = this.config.outputToCssLayers const getLayerAlias = (layer: string) => { let alias: string | undefined | null = layer if (typeof outputCssLayers === 'object') { alias = outputCssLayers.cssLayerName?.(layer) } return alias === null ? null : alias ?? layer } // in `left-to-right` mode the at-rules are nested in the written order, so the blocks with more // conditions are placed after the ones with fewer (`@dark:contrast-more:` after `contrast-more:`) // to keep the cascade instead of relying on the alphabetical order of the parents const leftToRight = this.config.variantApplyOrder === 'left-to-right' const parentDepth = (parent: string | undefined) => parent ? parent.split(' $$ ').length : 0 const getRawLayer = (layer: string = LAYER_DEFAULT) => { if (rawLayerCache[layer] != null) return rawLayerCache[layer] let css = Array.from(sheet) .sort((a, b) => ((this.tokenProcessor.getParentOrder(a[0]) ?? 0) - (this.tokenProcessor.getParentOrder(b[0]) ?? 0)) || (leftToRight ? parentDepth(a[0]) - parentDepth(b[0]) : 0) || (a[0] || '').localeCompare(b[0] || '') || 0) .map(([parent, items]) => { const sorted: PreparedRule[] = items .filter(i => (i[4]?.layer || LAYER_DEFAULT) === layer) .sort((a, b) => { return a[0] - b[0] // rule index || (a[4]?.sort || 0) - (b[4]?.sort || 0) // sort context || (a[5]?.currentSelector ?? '').localeCompare(b[5]?.currentSelector ?? '') // shortcuts || (a[1] || '').localeCompare(b[1] || '') // selector || (a[2] || '').localeCompare(b[2] || '') // body || 0 }) .map(([, selector, body, , meta, , variantNoMerge]) => { const scopedSelector = (selector && !meta?.noScope) ? applyScope(selector, scope) : selector return [ [[scopedSelector ?? '', meta?.sort ?? 0]], body, !!(variantNoMerge ?? meta?.noMerge), ] }) if (!sorted.length) return undefined sorted.reverse() const mergedRules = new Set() if (this.config.mergeSelectors) { const mergeIndex = new Map() for (let i = sorted.length - 1; i >= 0; i--) { const rule = sorted[i] const [selectorSortPair, body, noMerge] = rule if (noMerge) continue const selectorIndex = selectorSortPair ? 1 : 0 const candidates = mergeIndex.get(body) || [undefined, undefined] const candidate = candidates[selectorIndex] if (candidate) { if (selectorSortPair && candidate[0]) candidate[0].push(...selectorSortPair) mergedRules.add(rule) } else { candidates[selectorIndex] = rule mergeIndex.set(body, candidates) } } } const ruleLines = sorted .map(([selectorSortPair, body], idx) => { if (mergedRules.has(sorted[idx])) return null const selectors = selectorSortPair ? uniq(selectorSortPair .sort((a, b) => a[1] - b[1] || a[0]?.localeCompare(b[0] || '') || 0) .map(pair => pair[0]) .filter(Boolean)) : [] return selectors.length ? `${selectors.join(`,${nl}`)}{${body}}` : body }) .filter(Boolean) const css = Array.from(new Set(ruleLines)) .reverse() .join(nl) if (!parent) return css return wrapWithParent(parent, css, nl) }) .filter(Boolean) .join(nl) if (preflights) { css = [preflightsMap[layer], css] .filter(Boolean) .join(nl) } if (!css) return rawLayerCache[layer] = '' let alias if (outputCssLayers) { alias = getLayerAlias(layer) if (alias !== null) { css = `@layer ${alias}{${nl}${css}${nl}}` } } const layerMark = minify ? '' : `/* layer: ${layer}${alias && alias !== layer ? `, alias: ${alias}` : ''} */${nl}` css = layerMark + css return rawLayerCache[layer] = css } const processors = this.config.processors?.slice().sort((a, b) => (a.order || 0) - (b.order || 0)) ?? [] const processLayer = async (css: string, layer: string) => { let processed = css const context: CSSProcessorContext = { layer, theme: this.config.theme, envMode: this.config.envMode || 'build', } for (const processor of processors) processed = await processor.process(processed, context) return processed } const getLayer = (layer: string = LAYER_DEFAULT) => { return processedLayerCache[layer] ?? getRawLayer(layer) } const getLayers = (includes = layers, excludes?: string[]) => { const layers = includes.filter(i => !excludes?.includes(i)) const css = layers.map(layer => getLayer(layer)).filter(Boolean) if (outputCssLayers) { let layerNames = layers if (typeof outputCssLayers === 'object' && outputCssLayers.allLayers) { layerNames = sortLayers(Object.keys(this.config.layers)) } if (layerNames.length > 0) css.unshift(`@layer ${layerNames.map(getLayerAlias).filter(notNull).join(', ')};`) } return css.join(nl) } const setLayer = async (layer: string, callback: (content: string) => Promise) => { const raw = await callback(getRawLayer(layer)) const processed = await processLayer(raw, layer) rawLayerCache[layer] = raw processedLayerCache[layer] = processed return processed } await Promise.all(layers.map(async (layer) => { const raw = getRawLayer(layer) processedLayerCache[layer] = raw ? await processLayer(raw, layer) : raw })) return { get css() { return getLayers() }, layers, matched, getLayers, getLayer, setLayer, } } async matchVariants( raw: string, current?: string, ): Promise[]> { const context: VariantContext = { rawSelector: raw, theme: this.config.theme, generator: this, } // the handlers are stored in the order they are applied to the selector: // from the rightmost variant by default, or from the leftmost one const leftToRight = this.config.variantApplyOrder === 'left-to-right' const match = async (result: VariantMatchedResult): Promise[]> => { let applied = true const [,, handlers, variants] = result while (applied) { applied = false const processed = result[1] for (const v of this.config.variants) { if (!v.multiPass && variants.has(v)) continue let handler = await v.match(processed, context) if (!handler) continue if (isString(handler)) { if (handler === processed) continue handler = { matcher: handler } } handler = Array.isArray(handler) ? handler.map(markUtilityVariant) : markUtilityVariant(handler) // If variant return an array of handlers, // we clone the matched result and branch the matching items if (Array.isArray(handler)) { if (!handler.length) continue if (handler.length === 1) { handler = handler[0] } else { if (v.multiPass) throw new Error('multiPass can not be used together with array return variants') const clones = handler.map((h): VariantMatchedResult => { const _processed = h.matcher ?? processed const _handlers = leftToRight ? [...handlers, h] : [h, ...handlers] const _variants = new Set(variants) _variants.add(v) return [result[0], _processed, _handlers, _variants] }) return (await Promise.all(clones.map(c => match(c)))).flat() } } result[1] = handler.matcher ?? processed if (leftToRight) handlers.push(handler) else handlers.unshift(handler) variants.add(v) applied = true break } if (!applied) break if (handlers.length > 500) throw new Error(`Too many variants applied to "${raw}"`) } return [result] } return await match([ raw, current || raw, [], new Set>(), ]) } private applyVariants( parsed: ParsedUtil, variantHandlers = parsed[4], raw = parsed[1], ): UtilObject[] { const leftToRight = this.config.variantApplyOrder === 'left-to-right' const handlers = variantHandlers.slice() // identifies this application of the variants for the handlers, see `VariantHandlerContext.application` const application = {} // in `left-to-right` mode the `parentOrder`, `sort` and `layer` set by the handlers injected // by the rule are defaults, the first variant of the utility setting them decides const defaults: Partial> = {} const decided = { parentOrder: false, sort: false, layer: false } // a value decided by a variant is kept even when it is `undefined`, like the one of the leftmost // variant in `right-to-left` mode (an arbitrary `group-[...]` or a pseudo element resets the `sort`) const decide = (input: VariantHandlerContext, key: K): (typeof defaults)[K] => decided[key] ? input[key] : input[key] ?? defaults[key] const seed = (input: VariantHandlerContext): VariantHandlerContext => leftToRight ? { ...input, parentOrder: decide(input, 'parentOrder'), sort: decide(input, 'sort'), layer: decide(input, 'layer'), } : input const handler = handlers .sort((a, b) => (a.order || 0) - (b.order || 0)) .reduceRight( (previous, v) => (input: VariantHandlerContext) => { const entries = v.body?.(input.entries) || input.entries const parents: [string | undefined, number | undefined] = Array.isArray(v.parent) ? v.parent : [v.parent, undefined] const selector = v.selector?.(input.selector, entries) // the leftmost variant decides the position of the rule (`sort`), of its block (`parentOrder`) // and its layer: it is applied last by default, in `left-to-right` mode it is applied first // so its values are kept over the ones set by the following variants const next = (output: VariantHandlerContext) => { if (!leftToRight) return previous({ ...output, application }) const keep = (key: K): VariantHandlerContext[K] => { if (!isUtilityVariant(v)) { // a handler injected by the rule sets the default, also when it clears it if (key in output) defaults[key] = output[key] return input[key] } if (decided[key]) return input[key] // a handler setting the value decides it, also when it sets it to `undefined` if (key in output) decided[key] = true return output[key] } return previous({ ...output, application, parentOrder: keep('parentOrder'), sort: keep('sort'), layer: keep('layer') }) } // in `left-to-right` mode the handlers injected by the rule build on the defaults set before them const base = leftToRight && !isUtilityVariant(v) ? defaults : input const context: VariantHandlerContext = { ...input, entries, selector: selector || input.selector, parent: parents[0] || input.parent, parentOrder: parents[1] || base.parentOrder, layer: v.layer || base.layer, sort: v.sort || base.sort, } // in `left-to-right` mode the values still unset are left out, so that `keep` can tell a // handler setting one to `undefined` from a handler passing it through if (leftToRight) { for (const key of ['parentOrder', 'layer', 'sort'] as const) { if (context[key] === undefined) delete context[key] } } return (v.handle ?? defaultVariantHandler)(context, next) }, seed, ) const variantContextResult = handler({ prefix: '', selector: toEscapedSelector(raw), pseudo: '', entries: parsed[2], application, }) const { parent, parentOrder } = variantContextResult if (parent != null && parentOrder != null) this.tokenProcessor.setParentOrder(parent, parentOrder) const obj: UtilObject = { selector: [ variantContextResult.prefix, variantContextResult.selector, variantContextResult.pseudo, ].join(''), entries: variantContextResult.entries, parent, layer: variantContextResult.layer, sort: variantContextResult.sort, noMerge: variantContextResult.noMerge, } return this.config.postprocess.reduce( (utilities, p) => { const result: UtilObject[] = [] for (const util of utilities) { const processed = p(util) if (Array.isArray(processed)) { result.push(...processed.filter(notNull)) } else { result.push(processed || util) } } return result }, [obj], ) } constructCustomCSS( context: Readonly>, body: CSSObject | CSSEntries, overrideSelector?: string, ): string { const normalizedBody = normalizeCSSEntries(body) if (isString(normalizedBody)) return normalizedBody return this.applyVariants([0, overrideSelector || context.rawSelector, normalizedBody, undefined, context.variantHandlers]) .map(({ selector, entries, parent }) => { // Rules that return their CSS as a raw string bypass the scope // placeholder expansion applied to normal utilities at render time, // so expand the `$$` slots left by prefix- and parent-based variants // here. const css = `${applyScope(selector)}{${entriesToCss(entries)}}` if (parent) { return wrapWithParent(parent, css) } return css }) .join('') } async parseUtil( input: string | VariantMatchedResult, context: RuleContext, internal = false, shortcutPrefix?: string | string[] | undefined, ): Promise<(ParsedUtil | RawUtil)[] | undefined> { const variantResults = isString(input) ? await this.matchVariants(input) : [input] const parse = async ( [raw, processed, variantHandlers]: VariantMatchedResult, ): Promise<(ParsedUtil | RawUtil)[] | undefined> => { if (this.config.details) context.rules = context.rules ?? [] // Avoid context pollution in loop with await const scopeContext = { ...context, variantHandlers, } // use map to for static rules const staticMatch = this.config.rulesStaticMap[processed] if (staticMatch) { if (staticMatch[1] && (internal || !staticMatch[2]?.internal)) { return this.resolveCSSResult(raw, staticMatch[1], staticMatch, scopeContext) } } const dynamicRuleFilter = this.config.rulesDynamicFilter const dynamicRules = dynamicRuleFilter?.filters.length && !dynamicRuleFilter.filters.some(filter => filter.test(processed)) ? dynamicRuleFilter.fallback : this.config.rulesDynamic // match rules for (const rule of dynamicRules) { const [matcher, handler, meta] = rule // ignore internal rules if (meta?.internal && !internal) continue // match prefix let unprefixed = processed if (meta?.prefix) { const prefixes = toArray(meta.prefix) if (shortcutPrefix) { const shortcutPrefixes = toArray(shortcutPrefix) if (!prefixes.some(i => shortcutPrefixes.includes(i))) continue } else { const prefix = prefixes.find(i => processed.startsWith(i)) if (prefix == null) continue unprefixed = processed.slice(prefix.length) } } // match rule const match = unprefixed.match(matcher) if (!match) continue let result = await handler(match, scopeContext) if (!result) continue // Handle generator result if (typeof result !== 'string') { if (Symbol.asyncIterator in result) { const entries: (CSSValueInput | string)[] = [] for await (const r of result) { if (r) entries.push(r) } result = entries } else if (Symbol.iterator in result && !Array.isArray(result)) { result = Array.from(result) .filter(notNull) } } const resolvedResult = this.resolveCSSResult(raw, result, rule, scopeContext) if (resolvedResult) { return resolvedResult } } } const parsed = (await Promise.all(variantResults.map(i => parse(i)))).flat().filter(x => !!x) if (!parsed.length) return undefined return parsed } private resolveCSSResult = ( raw: string, result: CSSValueInput | string | (CSSValueInput | string)[], rule: Rule, context: RuleContext, ) => { const entries = normalizeCSSValues(result).filter(i => i.length) as (string | CSSEntriesInput)[] if (entries.length) { if (this.config.details) { context.rules!.push(rule) } this.tokenProcessor.activateRule(rule) const meta = rule[2] return entries.map((css): ParsedUtil | RawUtil => { if (isString(css)) return [meta!.__index!, css, meta] // Extract variants from special symbols const utilityVariants = [...context.variantHandlers] let variants = context.variantHandlers let entryMeta = meta const setVariant = (variant: (typeof variants)[number]) => { variants = [variant, ...variants] } const setMeta = (partial: Partial) => { entryMeta = { ...entryMeta, ...partial, } } for (const entry of css) { switch (entry[0]) { case symbols.variants: if (typeof entry[1] === 'function') { variants = entry[1](variants, context) || variants } else { variants = [ ...toArray(entry[1]), ...variants, ] } break case symbols.parent: setVariant({ parent: entry[1] }) break case symbols.selector: setVariant({ selector: entry[1] }) break case symbols.layer: setVariant({ layer: entry[1] }) break case symbols.sort: setMeta({ sort: entry[1] }) break case symbols.noMerge: setMeta({ noMerge: entry[1] }) break case symbols.noScope: setMeta({ noScope: entry[1] }) break case symbols.body: (entry as unknown as CSSEntry)[0] = VirtualKey break } } // the variants of the utility are the handlers matched for it and the ones a callback may // have cloned or rebuilt from them (a missing property and `undefined` being the same), // the other handlers are injected by the rule const sameHandler = (a: VariantHandler, b: VariantHandler) => { const keys = new Set([...Object.keys(a), ...Object.keys(b)]) return keys.size > 0 && [...keys].every(key => (a as Record)[key] === (b as Record)[key]) } const isDerived = (handler: VariantHandler) => utilityVariants.some(utility => utility === handler || sameHandler(handler, utility)) // a copy of a variant modified by a callback keeps its mark, drop it variants = variants.map(handler => isDerived(handler) ? markUtilityVariant(handler) : unmarkUtilityVariant(handler)) return [meta!.__index!, raw, css as CSSEntries, entryMeta, variants] }) } } stringifyUtil( parsed?: ParsedUtil | RawUtil, context?: RuleContext, ): StringifiedUtil[] | undefined { if (!parsed) return if (isRawUtil(parsed)) return [[parsed[0], undefined, parsed[1], undefined, parsed[2], this.config.details ? context : undefined, undefined]] const utilities = this.applyVariants(parsed) const result: StringifiedUtil[] = [] for (const util of utilities) { const { selector, entries, parent, layer: variantLayer, sort: variantSort, noMerge, } = util const body = entriesToCss(entries) if (!body) continue const { layer: metaLayer, sort: metaSort, ...meta } = parsed[3] ?? {} const ruleMeta = { ...meta, layer: variantLayer ?? metaLayer, sort: variantSort ?? metaSort, } result.push([parsed[0], selector, body, parent, ruleMeta, this.config.details ? context : undefined, noMerge]) } return result } async expandShortcut( input: string, context: RuleContext, depth = 5, skipVariantMatch = false, ): Promise<[(string | ShortcutInlineValue)[], RuleMeta | undefined] | undefined> { if (depth === 0) return const recordShortcut = this.config.details ? (s: Shortcut) => { context.shortcuts = context.shortcuts ?? [] context.shortcuts.push(s) } : noop let meta: RuleMeta | undefined let result: string | ShortcutValue[] | undefined let stringResult: string[] | undefined let inlineResult: ShortcutInlineValue[] | undefined for (const s of this.config.shortcuts) { let unprefixed = input if (s[2]?.prefix) { const prefixes = toArray(s[2].prefix) const prefix = prefixes.find(i => input.startsWith(i)) if (prefix == null) continue unprefixed = input.slice(prefix.length) } if (isStaticShortcut(s)) { if (s[0] === unprefixed) { meta = meta || s[2] result = s[1] recordShortcut(s) break } } else { const match = unprefixed.match(s[0]) if (match) result = s[1](match, context) if (result) { meta = meta || s[2] recordShortcut(s) break } } } if (result) { stringResult = uniq(toArray(result).filter(isString).map(s => expandVariantGroup(s.trim()).split(/\s+/g)).flat()) inlineResult = toArray(result).filter(i => !isString(i)).map(i => ({ handles: [], value: i })) } // expand nested shortcuts with variants if (!result && !skipVariantMatch) { const matched = isString(input) ? await this.matchVariants(input) : [input] for (const match of matched) { const [raw, inputWithoutVariant, handles] = match if (raw !== inputWithoutVariant) { const expanded = await this.expandShortcut(inputWithoutVariant, context, depth - 1) if (expanded) { // the matcher is always the last occurrence, the variants may contain // it as well (e.g. `[&_.btn]:btn`), so the earlier ones have to be kept const matcherIndex = raw.lastIndexOf(inputWithoutVariant) stringResult = expanded[0].filter(isString).map(item => matcherIndex === -1 ? raw : raw.slice(0, matcherIndex) + item + raw.slice(matcherIndex + inputWithoutVariant.length)) inlineResult = (expanded[0].filter(i => !isString(i)) as ShortcutInlineValue[]).map((item) => { // the variants of the shortcut wrap the ones of its utilities const shortcutFirst = this.config.variantApplyOrder === 'left-to-right' return { handles: shortcutFirst ? [...handles, ...item.handles] : [...item.handles, ...handles], value: item.value } }) } } } } if (!stringResult?.length && !inlineResult?.length) return return [ [ (await Promise.all(toArray(stringResult).map(async s => ((await this.expandShortcut(s, context, depth - 1))?.[0]) || [s]))), inlineResult!, ].flat(2).filter(x => !!x), meta, ] } async stringifyShortcuts( parent: VariantMatchedResult, context: RuleContext, expanded: (string | ShortcutInlineValue)[], meta: RuleMeta = { layer: this.config.shortcutsLayer }, ): Promise[] | undefined> { const layerMap = new BetterMap>() const parsed = ( await Promise.all(uniq(expanded) .map(async (i) => { const result = isString(i) // rule ? await this.parseUtil(i, context, true, meta.prefix) as ParsedUtil[] // inline CSS value in shortcut : [[Number.POSITIVE_INFINITY, '{inline}', normalizeCSSEntries(i.value), undefined, i.handles] as ParsedUtil] if (!result && this.config.warn) warnOnce(`unmatched utility "${i}" in shortcut "${parent[1]}"`) return result || [] }))) .flat(1) .filter(Boolean) .sort((a, b) => a[0] - b[0]) const [raw, , parentVariants] = parent const rawStringifiedUtil: StringifiedUtil[] = [] for (const item of parsed) { if (isRawUtil(item)) { rawStringifiedUtil.push([item[0], undefined, item[1], undefined, item[2], context, undefined]) continue } const isNoMerge = Object.fromEntries(item[2])[symbols.shortcutsNoMerge] const shortcutVariants = isNoMerge ? [] : parentVariants // the variants of the shortcut wrap the ones of its utilities, the handlers injected by // the rules keep being applied before all of them const variants = this.config.variantApplyOrder === 'left-to-right' && shortcutVariants.length ? [...item[4].filter(h => !isUtilityVariant(h)), ...shortcutVariants, ...item[4].filter(isUtilityVariant)] : [...item[4], ...shortcutVariants] for (const { selector, entries, parent, sort, noMerge, layer } of this.applyVariants(item, variants, raw)) { // find existing layer and merge const selectorMap = layerMap.getFallback(layer ?? meta.layer, new TwoKeyMap()) // find existing selector/mediaQuery pair and merge const mapItem = selectorMap.getFallback(selector, parent, [[], item[0]]) // add entries mapItem[0].push([entries, !!(noMerge ?? item[3]?.noMerge), sort ?? 0]) } } return rawStringifiedUtil.concat(layerMap .flatMap((selectorMap, layer) => selectorMap .map(([e, index], selector, joinedParents) => { const stringify = (flatten: boolean, noMerge: boolean, entrySortPair: [CSSEntries, number][]): (StringifiedUtil | undefined)[] => { const maxSort = Math.max(...entrySortPair.map(e => e[1])) const entriesList = entrySortPair.map(e => e[0]) return (flatten ? [entriesList.flat(1)] : entriesList).map((entries: CSSEntries): StringifiedUtil | undefined => { const body = entriesToCss(entries) if (body) return [index, selector, body, joinedParents, { ...meta, noMerge, sort: maxSort, layer }, context, undefined] return undefined }) } const merges = [ [e.filter(([, noMerge]) => noMerge).map(([entries, , sort]) => [entries, sort]), true], [e.filter(([, noMerge]) => !noMerge).map(([entries, , sort]) => [entries, sort]), false], ] as [[CSSEntries, number][], boolean][] return merges.map(([e, noMerge]) => [ ...stringify(false, noMerge, e.filter(([entries]) => entries.some(entry => (entry as unknown as ControlSymbolsEntry)[0] === symbols.shortcutsNoMerge))), ...stringify(true, noMerge, e.filter(([entries]) => entries.every(entry => (entry as unknown as ControlSymbolsEntry)[0] !== symbols.shortcutsNoMerge))), ]) }) .flat(2) .filter(Boolean) as StringifiedUtil[], )) } isBlocked(raw: string): boolean { return this.tokenProcessor.isBlocked(raw, this.config.blocklist) } getBlocked(raw: string): [BlocklistValue, BlocklistMeta | undefined] | undefined { return this.tokenProcessor.getBlocked(raw, this.config.blocklist) } } export class UnoGenerator extends UnoGeneratorInternal { /** * @deprecated `new UnoGenerator` is deprecated, please use `createGenerator()` instead */ constructor( userConfig: UserConfig = {}, defaults: UserConfigDefaults = {}, ) { super(userConfig, defaults) console.warn('`new UnoGenerator()` is deprecated, please use `createGenerator()` instead') } } export async function createGenerator( config?: UserConfig, defaults?: UserConfigDefaults, ): Promise> { return await UnoGeneratorInternal.create(config, defaults) } export const regexScopePlaceholder = /\s\$\$\s+/g export function hasScopePlaceholder(css: string) { return regexScopePlaceholder.test(css) } function applyScope(css: string, scope?: string) { if (hasScopePlaceholder(css)) return css.replace(regexScopePlaceholder, scope ? ` ${scope} ` : ' ') else return scope ? `${scope} ${css}` : css } function wrapWithParent(parent: string, css: string, nl = '') { const parents = parent.split(' $$ ') return `${parents.join('{')}{${nl}${css}${nl}${'}'.repeat(parents.length)}` } const attributifyRe = /^\[(.+?)(~?=)"(.*)"\]$/ export function toEscapedSelector(raw: string) { if (attributifyRe.test(raw)) return raw.replace(attributifyRe, (_, n, s, i) => `[${e(n)}${s}"${e(i)}"]`) return `.${e(raw)}` } function defaultVariantHandler(input: VariantHandlerContext, next: (input: VariantHandlerContext) => VariantHandlerContext) { return next(input) }