@unocss/core 0.58.9 → 0.59.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs DELETED
@@ -1,1180 +0,0 @@
1
- 'use strict';
2
-
3
- function escapeRegExp(string) {
4
- return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5
- }
6
- function escapeSelector(str) {
7
- const length = str.length;
8
- let index = -1;
9
- let codeUnit;
10
- let result = "";
11
- const firstCodeUnit = str.charCodeAt(0);
12
- while (++index < length) {
13
- codeUnit = str.charCodeAt(index);
14
- if (codeUnit === 0) {
15
- result += "\uFFFD";
16
- continue;
17
- }
18
- if (codeUnit === 37) {
19
- result += "\\%";
20
- continue;
21
- }
22
- if (codeUnit === 44) {
23
- result += "\\,";
24
- continue;
25
- }
26
- if (
27
- // If the character is in the range [\1-\1F] (U+0001 to U+001F) or is
28
- // U+007F, […]
29
- codeUnit >= 1 && codeUnit <= 31 || codeUnit === 127 || index === 0 && codeUnit >= 48 && codeUnit <= 57 || index === 1 && codeUnit >= 48 && codeUnit <= 57 && firstCodeUnit === 45
30
- ) {
31
- result += `\\${codeUnit.toString(16)} `;
32
- continue;
33
- }
34
- if (
35
- // If the character is the first character and is a `-` (U+002D), and
36
- // there is no second character, […]
37
- index === 0 && length === 1 && codeUnit === 45
38
- ) {
39
- result += `\\${str.charAt(index)}`;
40
- continue;
41
- }
42
- if (codeUnit >= 128 || codeUnit === 45 || codeUnit === 95 || codeUnit >= 48 && codeUnit <= 57 || codeUnit >= 65 && codeUnit <= 90 || codeUnit >= 97 && codeUnit <= 122) {
43
- result += str.charAt(index);
44
- continue;
45
- }
46
- result += `\\${str.charAt(index)}`;
47
- }
48
- return result;
49
- }
50
- const e = escapeSelector;
51
-
52
- function toArray(value = []) {
53
- return Array.isArray(value) ? value : [value];
54
- }
55
- function uniq(value) {
56
- return Array.from(new Set(value));
57
- }
58
- function uniqueBy(array, equalFn) {
59
- return array.reduce((acc, cur) => {
60
- const index = acc.findIndex((item) => equalFn(cur, item));
61
- if (index === -1)
62
- acc.push(cur);
63
- return acc;
64
- }, []);
65
- }
66
- function isString(s) {
67
- return typeof s === "string";
68
- }
69
-
70
- function normalizeCSSEntries(obj) {
71
- if (isString(obj))
72
- return obj;
73
- return (!Array.isArray(obj) ? Object.entries(obj) : obj).filter((i) => i[1] != null);
74
- }
75
- function normalizeCSSValues(obj) {
76
- if (Array.isArray(obj)) {
77
- if (obj.find((i) => !Array.isArray(i) || Array.isArray(i[0])))
78
- return obj.map((i) => normalizeCSSEntries(i));
79
- else
80
- return [obj];
81
- } else {
82
- return [normalizeCSSEntries(obj)];
83
- }
84
- }
85
- function clearIdenticalEntries(entry) {
86
- return entry.filter(([k, v], idx) => {
87
- if (k.startsWith("$$"))
88
- return false;
89
- for (let i = idx - 1; i >= 0; i--) {
90
- if (entry[i][0] === k && entry[i][1] === v)
91
- return false;
92
- }
93
- return true;
94
- });
95
- }
96
- function entriesToCss(arr) {
97
- if (arr == null)
98
- return "";
99
- return clearIdenticalEntries(arr).map(([key, value]) => value != null ? `${key}:${value};` : void 0).filter(Boolean).join("");
100
- }
101
- function isObject(item) {
102
- return item && typeof item === "object" && !Array.isArray(item);
103
- }
104
- function mergeDeep(original, patch, mergeArray = false) {
105
- const o = original;
106
- const p = patch;
107
- if (Array.isArray(p)) {
108
- if (mergeArray && Array.isArray(p))
109
- return [...o, ...p];
110
- else
111
- return [...p];
112
- }
113
- const output = { ...o };
114
- if (isObject(o) && isObject(p)) {
115
- Object.keys(p).forEach((key) => {
116
- if (isObject(o[key]) && isObject(p[key]) || Array.isArray(o[key]) && Array.isArray(p[key]))
117
- output[key] = mergeDeep(o[key], p[key], mergeArray);
118
- else
119
- Object.assign(output, { [key]: p[key] });
120
- });
121
- }
122
- return output;
123
- }
124
- function clone(val) {
125
- let k, out, tmp;
126
- if (Array.isArray(val)) {
127
- out = Array(k = val.length);
128
- while (k--)
129
- out[k] = (tmp = val[k]) && typeof tmp === "object" ? clone(tmp) : tmp;
130
- return out;
131
- }
132
- if (Object.prototype.toString.call(val) === "[object Object]") {
133
- out = {};
134
- for (k in val) {
135
- if (k === "__proto__") {
136
- Object.defineProperty(out, k, {
137
- value: clone(val[k]),
138
- configurable: true,
139
- enumerable: true,
140
- writable: true
141
- });
142
- } else {
143
- out[k] = (tmp = val[k]) && typeof tmp === "object" ? clone(tmp) : tmp;
144
- }
145
- }
146
- return out;
147
- }
148
- return val;
149
- }
150
- function isStaticRule(rule) {
151
- return isString(rule[0]);
152
- }
153
- function isStaticShortcut(sc) {
154
- return isString(sc[0]);
155
- }
156
-
157
- const attributifyRE = /^\[(.+?)~?="(.*)"\]$/;
158
- const cssIdRE = /\.(css|postcss|sass|scss|less|stylus|styl)($|\?)/;
159
- const validateFilterRE = /[\w\u00A0-\uFFFF-_:%-?]/;
160
- const CONTROL_SHORTCUT_NO_MERGE = "$$shortcut-no-merge";
161
- function isAttributifySelector(selector) {
162
- return selector.match(attributifyRE);
163
- }
164
- function isValidSelector(selector = "") {
165
- return validateFilterRE.test(selector);
166
- }
167
- function normalizeVariant(variant) {
168
- return typeof variant === "function" ? { match: variant } : variant;
169
- }
170
- function isRawUtil(util) {
171
- return util.length === 3;
172
- }
173
- function notNull(value) {
174
- return value != null;
175
- }
176
- function noop() {
177
- }
178
-
179
- var __defProp$2 = Object.defineProperty;
180
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
181
- var __publicField$2 = (obj, key, value) => {
182
- __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
183
- return value;
184
- };
185
- class TwoKeyMap {
186
- constructor() {
187
- __publicField$2(this, "_map", /* @__PURE__ */ new Map());
188
- }
189
- get(key1, key2) {
190
- const m2 = this._map.get(key1);
191
- if (m2)
192
- return m2.get(key2);
193
- }
194
- getFallback(key1, key2, fallback) {
195
- let m2 = this._map.get(key1);
196
- if (!m2) {
197
- m2 = /* @__PURE__ */ new Map();
198
- this._map.set(key1, m2);
199
- }
200
- if (!m2.has(key2))
201
- m2.set(key2, fallback);
202
- return m2.get(key2);
203
- }
204
- set(key1, key2, value) {
205
- let m2 = this._map.get(key1);
206
- if (!m2) {
207
- m2 = /* @__PURE__ */ new Map();
208
- this._map.set(key1, m2);
209
- }
210
- m2.set(key2, value);
211
- return this;
212
- }
213
- has(key1, key2) {
214
- return this._map.get(key1)?.has(key2);
215
- }
216
- delete(key1, key2) {
217
- return this._map.get(key1)?.delete(key2) || false;
218
- }
219
- deleteTop(key1) {
220
- return this._map.delete(key1);
221
- }
222
- map(fn) {
223
- return Array.from(this._map.entries()).flatMap(([k1, m2]) => Array.from(m2.entries()).map(([k2, v]) => {
224
- return fn(v, k1, k2);
225
- }));
226
- }
227
- }
228
- class BetterMap extends Map {
229
- getFallback(key, fallback) {
230
- const v = this.get(key);
231
- if (v === void 0) {
232
- this.set(key, fallback);
233
- return fallback;
234
- }
235
- return v;
236
- }
237
- map(mapFn) {
238
- const result = [];
239
- this.forEach((v, k) => {
240
- result.push(mapFn(v, k));
241
- });
242
- return result;
243
- }
244
- flatMap(mapFn) {
245
- const result = [];
246
- this.forEach((v, k) => {
247
- result.push(...mapFn(v, k));
248
- });
249
- return result;
250
- }
251
- }
252
-
253
- var __defProp$1 = Object.defineProperty;
254
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
255
- var __publicField$1 = (obj, key, value) => {
256
- __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
257
- return value;
258
- };
259
- class CountableSet extends Set {
260
- constructor(values) {
261
- super(values);
262
- __publicField$1(this, "_map");
263
- this._map ?? (this._map = /* @__PURE__ */ new Map());
264
- }
265
- add(key) {
266
- this._map ?? (this._map = /* @__PURE__ */ new Map());
267
- this._map.set(key, (this._map.get(key) ?? 0) + 1);
268
- return super.add(key);
269
- }
270
- delete(key) {
271
- this._map.delete(key);
272
- return super.delete(key);
273
- }
274
- clear() {
275
- this._map.clear();
276
- super.clear();
277
- }
278
- getCount(key) {
279
- return this._map.get(key) ?? 0;
280
- }
281
- setCount(key, count) {
282
- this._map.set(key, count);
283
- return super.add(key);
284
- }
285
- }
286
- function isCountableSet(value) {
287
- return value instanceof CountableSet;
288
- }
289
-
290
- function withLayer(layer, rules) {
291
- rules.forEach((r) => {
292
- if (!r[2])
293
- r[2] = { layer };
294
- else
295
- r[2].layer = layer;
296
- });
297
- return rules;
298
- }
299
-
300
- const regexCache = {};
301
- function makeRegexClassGroup(separators = ["-", ":"]) {
302
- const key = separators.join("|");
303
- if (!regexCache[key])
304
- regexCache[key] = new RegExp(`((?:[!@<~\\w+:_/-]|\\[&?>?:?\\S*\\])+?)(${key})\\(((?:[~!<>\\w\\s:/\\\\,%#.$?-]|\\[.*?\\])+?)\\)(?!\\s*?=>)`, "gm");
305
- regexCache[key].lastIndex = 0;
306
- return regexCache[key];
307
- }
308
- function parseVariantGroup(str, separators = ["-", ":"], depth = 5) {
309
- const regexClassGroup = makeRegexClassGroup(separators);
310
- let hasChanged;
311
- let content = str.toString();
312
- const prefixes = /* @__PURE__ */ new Set();
313
- const groupsByOffset = /* @__PURE__ */ new Map();
314
- do {
315
- hasChanged = false;
316
- content = content.replace(
317
- regexClassGroup,
318
- (from, pre, sep, body, groupOffset) => {
319
- if (!separators.includes(sep))
320
- return from;
321
- hasChanged = true;
322
- prefixes.add(pre + sep);
323
- const bodyOffset = groupOffset + pre.length + sep.length + 1;
324
- const group = { length: from.length, items: [] };
325
- groupsByOffset.set(groupOffset, group);
326
- for (const itemMatch of [...body.matchAll(/\S+/g)]) {
327
- const itemOffset = bodyOffset + itemMatch.index;
328
- let innerItems = groupsByOffset.get(itemOffset)?.items;
329
- if (innerItems) {
330
- groupsByOffset.delete(itemOffset);
331
- } else {
332
- innerItems = [{
333
- offset: itemOffset,
334
- length: itemMatch[0].length,
335
- className: itemMatch[0]
336
- }];
337
- }
338
- for (const item of innerItems) {
339
- item.className = item.className === "~" ? pre : item.className.replace(/^(!?)(.*)/, `$1${pre}${sep}$2`);
340
- group.items.push(item);
341
- }
342
- }
343
- return "$".repeat(from.length);
344
- }
345
- );
346
- depth -= 1;
347
- } while (hasChanged && depth);
348
- let expanded;
349
- if (typeof str === "string") {
350
- expanded = "";
351
- let prevOffset = 0;
352
- for (const [offset, group] of groupsByOffset) {
353
- expanded += str.slice(prevOffset, offset);
354
- expanded += group.items.map((item) => item.className).join(" ");
355
- prevOffset = offset + group.length;
356
- }
357
- expanded += str.slice(prevOffset);
358
- } else {
359
- expanded = str;
360
- for (const [offset, group] of groupsByOffset) {
361
- expanded.overwrite(
362
- offset,
363
- offset + group.length,
364
- group.items.map((item) => item.className).join(" ")
365
- );
366
- }
367
- }
368
- return {
369
- prefixes: Array.from(prefixes),
370
- hasChanged,
371
- groupsByOffset,
372
- // Computed lazily because MagicString's toString does a lot of work
373
- get expanded() {
374
- return expanded.toString();
375
- }
376
- };
377
- }
378
- function collapseVariantGroup(str, prefixes) {
379
- const collection = /* @__PURE__ */ new Map();
380
- const sortedPrefix = prefixes.sort((a, b) => b.length - a.length);
381
- return str.split(/\s+/g).map((part) => {
382
- const prefix = sortedPrefix.find((prefix2) => part.startsWith(prefix2));
383
- if (!prefix)
384
- return part;
385
- const body = part.slice(prefix.length);
386
- if (collection.has(prefix)) {
387
- collection.get(prefix).push(body);
388
- return null;
389
- } else {
390
- const items = [body];
391
- collection.set(prefix, items);
392
- return {
393
- prefix,
394
- items
395
- };
396
- }
397
- }).filter(notNull).map((i) => {
398
- if (typeof i === "string")
399
- return i;
400
- return `${i.prefix}(${i.items.join(" ")})`;
401
- }).join(" ");
402
- }
403
- function expandVariantGroup(str, separators = ["-", ":"], depth = 5) {
404
- const res = parseVariantGroup(str, separators, depth);
405
- return typeof str === "string" ? res.expanded : str;
406
- }
407
-
408
- const warned = /* @__PURE__ */ new Set();
409
- function warnOnce(msg) {
410
- if (warned.has(msg))
411
- return;
412
- console.warn("[unocss]", msg);
413
- warned.add(msg);
414
- }
415
-
416
- const defaultSplitRE = /[\\:]?[\s'"`;{}]+/g;
417
- const splitWithVariantGroupRE = /([\\:]?[\s"'`;<>]|:\(|\)"|\)\s)/g;
418
- function splitCode(code) {
419
- return code.split(defaultSplitRE);
420
- }
421
- const extractorSplit = {
422
- name: "@unocss/core/extractor-split",
423
- order: 0,
424
- extract({ code }) {
425
- return splitCode(code);
426
- }
427
- };
428
-
429
- function createNanoEvents() {
430
- return {
431
- events: {},
432
- emit(event, ...args) {
433
- (this.events[event] || []).forEach((i) => i(...args));
434
- },
435
- on(event, cb) {
436
- (this.events[event] = this.events[event] || []).push(cb);
437
- return () => this.events[event] = (this.events[event] || []).filter((i) => i !== cb);
438
- }
439
- };
440
- }
441
-
442
- const LAYER_DEFAULT = "default";
443
- const LAYER_PREFLIGHTS = "preflights";
444
- const LAYER_SHORTCUTS = "shortcuts";
445
- const LAYER_IMPORTS = "imports";
446
- const DEFAULT_LAYERS = {
447
- [LAYER_IMPORTS]: -200,
448
- [LAYER_PREFLIGHTS]: -100,
449
- [LAYER_SHORTCUTS]: -10,
450
- [LAYER_DEFAULT]: 0
451
- };
452
-
453
- function resolveShortcuts(shortcuts) {
454
- return toArray(shortcuts).flatMap((s) => {
455
- if (Array.isArray(s))
456
- return [s];
457
- return Object.entries(s);
458
- });
459
- }
460
- const __RESOLVED = "_uno_resolved";
461
- function resolvePreset(presetInput) {
462
- let preset = typeof presetInput === "function" ? presetInput() : presetInput;
463
- if (__RESOLVED in preset)
464
- return preset;
465
- preset = { ...preset };
466
- Object.defineProperty(preset, __RESOLVED, {
467
- value: true,
468
- enumerable: false
469
- });
470
- const shortcuts = preset.shortcuts ? resolveShortcuts(preset.shortcuts) : void 0;
471
- preset.shortcuts = shortcuts;
472
- if (preset.prefix || preset.layer) {
473
- const apply = (i) => {
474
- if (!i[2])
475
- i[2] = {};
476
- const meta = i[2];
477
- if (meta.prefix == null && preset.prefix)
478
- meta.prefix = toArray(preset.prefix);
479
- if (meta.layer == null && preset.layer)
480
- meta.layer = preset.layer;
481
- };
482
- shortcuts?.forEach(apply);
483
- preset.rules?.forEach(apply);
484
- }
485
- return preset;
486
- }
487
- function resolvePresets(preset) {
488
- const root = resolvePreset(preset);
489
- if (!root.presets)
490
- return [root];
491
- const nested = (root.presets || []).flatMap(toArray).flatMap(resolvePresets);
492
- return [root, ...nested];
493
- }
494
- function resolveConfig(userConfig = {}, defaults = {}) {
495
- const config = Object.assign({}, defaults, userConfig);
496
- const rawPresets = uniqueBy((config.presets || []).flatMap(toArray).flatMap(resolvePresets), (a, b) => a.name === b.name);
497
- const sortedPresets = [
498
- ...rawPresets.filter((p) => p.enforce === "pre"),
499
- ...rawPresets.filter((p) => !p.enforce),
500
- ...rawPresets.filter((p) => p.enforce === "post")
501
- ];
502
- const sources = [
503
- ...sortedPresets,
504
- config
505
- ];
506
- const sourcesReversed = [...sources].reverse();
507
- const layers = Object.assign({}, DEFAULT_LAYERS, ...sources.map((i) => i.layers));
508
- function getMerged(key) {
509
- return uniq(sources.flatMap((p) => toArray(p[key] || [])));
510
- }
511
- const extractors = getMerged("extractors");
512
- let extractorDefault = sourcesReversed.find((i) => i.extractorDefault !== void 0)?.extractorDefault;
513
- if (extractorDefault === void 0)
514
- extractorDefault = extractorSplit;
515
- if (extractorDefault && !extractors.includes(extractorDefault))
516
- extractors.unshift(extractorDefault);
517
- extractors.sort((a, b) => (a.order || 0) - (b.order || 0));
518
- const rules = getMerged("rules");
519
- const rulesStaticMap = {};
520
- const rulesSize = rules.length;
521
- const rulesDynamic = rules.map((rule, i) => {
522
- if (isStaticRule(rule)) {
523
- const prefixes = toArray(rule[2]?.prefix || "");
524
- prefixes.forEach((prefix) => {
525
- rulesStaticMap[prefix + rule[0]] = [i, rule[1], rule[2], rule];
526
- });
527
- return void 0;
528
- }
529
- return [i, ...rule];
530
- }).filter(Boolean).reverse();
531
- let theme = mergeThemes(sources.map((p) => p.theme));
532
- const extendThemes = getMerged("extendTheme");
533
- for (const extendTheme of extendThemes)
534
- theme = extendTheme(theme) || theme;
535
- const autocomplete = {
536
- templates: uniq(sources.flatMap((p) => toArray(p.autocomplete?.templates))),
537
- extractors: sources.flatMap((p) => toArray(p.autocomplete?.extractors)).sort((a, b) => (a.order || 0) - (b.order || 0)),
538
- shorthands: mergeAutocompleteShorthands(sources.map((p) => p.autocomplete?.shorthands || {}))
539
- };
540
- let separators = getMerged("separators");
541
- if (!separators.length)
542
- separators = [":", "-"];
543
- const resolved = {
544
- mergeSelectors: true,
545
- warn: true,
546
- sortLayers: (layers2) => layers2,
547
- ...config,
548
- blocklist: getMerged("blocklist"),
549
- presets: sortedPresets,
550
- envMode: config.envMode || "build",
551
- shortcutsLayer: config.shortcutsLayer || "shortcuts",
552
- layers,
553
- theme,
554
- rulesSize,
555
- rulesDynamic,
556
- rulesStaticMap,
557
- preprocess: getMerged("preprocess"),
558
- postprocess: getMerged("postprocess"),
559
- preflights: getMerged("preflights"),
560
- autocomplete,
561
- variants: getMerged("variants").map(normalizeVariant).sort((a, b) => (a.order || 0) - (b.order || 0)),
562
- shortcuts: resolveShortcuts(getMerged("shortcuts")).reverse(),
563
- extractors,
564
- safelist: getMerged("safelist"),
565
- separators,
566
- details: config.details ?? config.envMode === "dev"
567
- };
568
- for (const p of sources)
569
- p?.configResolved?.(resolved);
570
- return resolved;
571
- }
572
- function mergeConfigs(configs) {
573
- const maybeArrays = ["shortcuts", "preprocess", "postprocess"];
574
- const config = configs.map((config2) => Object.entries(config2).reduce((acc, [key, value]) => ({
575
- ...acc,
576
- [key]: maybeArrays.includes(key) ? toArray(value) : value
577
- }), {})).reduce(({ theme: themeA, ...a }, { theme: themeB, ...b }) => {
578
- const c = mergeDeep(a, b, true);
579
- if (themeA || themeB)
580
- c.theme = mergeThemes([themeA, themeB]);
581
- return c;
582
- }, {});
583
- return config;
584
- }
585
- function mergeThemes(themes) {
586
- return themes.map((theme) => theme ? clone(theme) : {}).reduce((a, b) => mergeDeep(a, b), {});
587
- }
588
- function mergeAutocompleteShorthands(shorthands) {
589
- return shorthands.reduce((a, b) => {
590
- const rs = {};
591
- for (const key in b) {
592
- const value = b[key];
593
- if (Array.isArray(value))
594
- rs[key] = `(${value.join("|")})`;
595
- else
596
- rs[key] = value;
597
- }
598
- return {
599
- ...a,
600
- ...rs
601
- };
602
- }, {});
603
- }
604
- function definePreset(preset) {
605
- return preset;
606
- }
607
-
608
- const version = "0.58.9";
609
-
610
- var __defProp = Object.defineProperty;
611
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
612
- var __publicField = (obj, key, value) => {
613
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
614
- return value;
615
- };
616
- class UnoGenerator {
617
- constructor(userConfig = {}, defaults = {}) {
618
- this.userConfig = userConfig;
619
- this.defaults = defaults;
620
- __publicField(this, "version", version);
621
- __publicField(this, "_cache", /* @__PURE__ */ new Map());
622
- __publicField(this, "config");
623
- __publicField(this, "blocked", /* @__PURE__ */ new Set());
624
- __publicField(this, "parentOrders", /* @__PURE__ */ new Map());
625
- __publicField(this, "events", createNanoEvents());
626
- this.config = resolveConfig(userConfig, defaults);
627
- this.events.emit("config", this.config);
628
- }
629
- setConfig(userConfig, defaults) {
630
- if (!userConfig)
631
- return;
632
- if (defaults)
633
- this.defaults = defaults;
634
- this.userConfig = userConfig;
635
- this.blocked.clear();
636
- this.parentOrders.clear();
637
- this._cache.clear();
638
- this.config = resolveConfig(userConfig, this.defaults);
639
- this.events.emit("config", this.config);
640
- }
641
- async applyExtractors(code, id, extracted = /* @__PURE__ */ new Set()) {
642
- const context = {
643
- original: code,
644
- code,
645
- id,
646
- extracted,
647
- envMode: this.config.envMode
648
- };
649
- for (const extractor of this.config.extractors) {
650
- const result = await extractor.extract?.(context);
651
- if (!result)
652
- continue;
653
- if (isCountableSet(result) && isCountableSet(extracted)) {
654
- for (const token of result)
655
- extracted.setCount(token, extracted.getCount(token) + result.getCount(token));
656
- } else {
657
- for (const token of result)
658
- extracted.add(token);
659
- }
660
- }
661
- return extracted;
662
- }
663
- makeContext(raw, applied) {
664
- const context = {
665
- rawSelector: raw,
666
- currentSelector: applied[1],
667
- theme: this.config.theme,
668
- generator: this,
669
- variantHandlers: applied[2],
670
- constructCSS: (...args) => this.constructCustomCSS(context, ...args),
671
- variantMatch: applied
672
- };
673
- return context;
674
- }
675
- async parseToken(raw, alias) {
676
- if (this.blocked.has(raw))
677
- return;
678
- const cacheKey = `${raw}${alias ? ` ${alias}` : ""}`;
679
- if (this._cache.has(cacheKey))
680
- return this._cache.get(cacheKey);
681
- let current = raw;
682
- for (const p of this.config.preprocess)
683
- current = p(raw);
684
- if (this.isBlocked(current)) {
685
- this.blocked.add(raw);
686
- this._cache.set(cacheKey, null);
687
- return;
688
- }
689
- const applied = await this.matchVariants(raw, current);
690
- if (!applied || this.isBlocked(applied[1])) {
691
- this.blocked.add(raw);
692
- this._cache.set(cacheKey, null);
693
- return;
694
- }
695
- const context = this.makeContext(raw, [alias || applied[0], applied[1], applied[2], applied[3]]);
696
- if (this.config.details)
697
- context.variants = [...applied[3]];
698
- const expanded = await this.expandShortcut(context.currentSelector, context);
699
- const utils = expanded ? await this.stringifyShortcuts(context.variantMatch, context, expanded[0], expanded[1]) : (await this.parseUtil(context.variantMatch, context))?.map((i) => this.stringifyUtil(i, context)).filter(notNull);
700
- if (utils?.length) {
701
- this._cache.set(cacheKey, utils);
702
- return utils;
703
- }
704
- this._cache.set(cacheKey, null);
705
- }
706
- async generate(input, options = {}) {
707
- const {
708
- id,
709
- scope,
710
- preflights = true,
711
- safelist = true,
712
- minify = false,
713
- extendedInfo = false
714
- } = options;
715
- const outputCssLayers = this.config.outputToCssLayers;
716
- const tokens = isString(input) ? await this.applyExtractors(
717
- input,
718
- id,
719
- extendedInfo ? new CountableSet() : /* @__PURE__ */ new Set()
720
- ) : Array.isArray(input) ? new Set(input) : input;
721
- if (safelist) {
722
- this.config.safelist.forEach((s) => {
723
- if (!tokens.has(s))
724
- tokens.add(s);
725
- });
726
- }
727
- const nl = minify ? "" : "\n";
728
- const layerSet = /* @__PURE__ */ new Set([LAYER_DEFAULT]);
729
- const matched = extendedInfo ? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Set();
730
- const sheet = /* @__PURE__ */ new Map();
731
- let preflightsMap = {};
732
- const tokenPromises = Array.from(tokens).map(async (raw) => {
733
- if (matched.has(raw))
734
- return;
735
- const payload = await this.parseToken(raw);
736
- if (payload == null)
737
- return;
738
- if (matched instanceof Map) {
739
- matched.set(raw, {
740
- data: payload,
741
- count: isCountableSet(tokens) ? tokens.getCount(raw) : -1
742
- });
743
- } else {
744
- matched.add(raw);
745
- }
746
- for (const item of payload) {
747
- const parent = item[3] || "";
748
- const layer = item[4]?.layer;
749
- if (!sheet.has(parent))
750
- sheet.set(parent, []);
751
- sheet.get(parent).push(item);
752
- if (layer)
753
- layerSet.add(layer);
754
- }
755
- });
756
- await Promise.all(tokenPromises);
757
- await (async () => {
758
- if (!preflights)
759
- return;
760
- const preflightContext = {
761
- generator: this,
762
- theme: this.config.theme
763
- };
764
- const preflightLayerSet = /* @__PURE__ */ new Set([]);
765
- this.config.preflights.forEach(({ layer = LAYER_PREFLIGHTS }) => {
766
- layerSet.add(layer);
767
- preflightLayerSet.add(layer);
768
- });
769
- preflightsMap = Object.fromEntries(
770
- await Promise.all(Array.from(preflightLayerSet).map(
771
- async (layer) => {
772
- const preflights2 = await Promise.all(
773
- this.config.preflights.filter((i) => (i.layer || LAYER_PREFLIGHTS) === layer).map(async (i) => await i.getCSS(preflightContext))
774
- );
775
- const css = preflights2.filter(Boolean).join(nl);
776
- return [layer, css];
777
- }
778
- ))
779
- );
780
- })();
781
- const layers = this.config.sortLayers(Array.from(layerSet).sort((a, b) => (this.config.layers[a] ?? 0) - (this.config.layers[b] ?? 0) || a.localeCompare(b)));
782
- const layerCache = {};
783
- const getLayer = (layer = LAYER_DEFAULT) => {
784
- if (layerCache[layer])
785
- return layerCache[layer];
786
- let css = Array.from(sheet).sort((a, b) => (this.parentOrders.get(a[0]) ?? 0) - (this.parentOrders.get(b[0]) ?? 0) || a[0]?.localeCompare(b[0] || "") || 0).map(([parent, items]) => {
787
- const size = items.length;
788
- const sorted = items.filter((i) => (i[4]?.layer || LAYER_DEFAULT) === layer).sort((a, b) => {
789
- return a[0] - b[0] || (a[4]?.sort || 0) - (b[4]?.sort || 0) || a[5]?.currentSelector?.localeCompare(b[5]?.currentSelector ?? "") || a[1]?.localeCompare(b[1] || "") || a[2]?.localeCompare(b[2] || "") || 0;
790
- }).map(([, selector, body, , meta, , variantNoMerge]) => {
791
- const scopedSelector = selector ? applyScope(selector, scope) : selector;
792
- return [
793
- [[scopedSelector ?? "", meta?.sort ?? 0]],
794
- body,
795
- !!(variantNoMerge ?? meta?.noMerge)
796
- ];
797
- });
798
- if (!sorted.length)
799
- return void 0;
800
- const rules = sorted.reverse().map(([selectorSortPair, body, noMerge], idx) => {
801
- if (!noMerge && this.config.mergeSelectors) {
802
- for (let i = idx + 1; i < size; i++) {
803
- const current = sorted[i];
804
- if (current && !current[2] && (selectorSortPair && current[0] || selectorSortPair == null && current[0] == null) && current[1] === body) {
805
- if (selectorSortPair && current[0])
806
- current[0].push(...selectorSortPair);
807
- return null;
808
- }
809
- }
810
- }
811
- const selectors = selectorSortPair ? uniq(selectorSortPair.sort((a, b) => a[1] - b[1] || a[0]?.localeCompare(b[0] || "") || 0).map((pair) => pair[0]).filter(Boolean)) : [];
812
- return selectors.length ? `${selectors.join(`,${nl}`)}{${body}}` : body;
813
- }).filter(Boolean).reverse().join(nl);
814
- if (!parent)
815
- return rules;
816
- const parents = parent.split(" $$ ");
817
- return `${parents.join("{")}{${nl}${rules}${nl}${"}".repeat(parents.length)}`;
818
- }).filter(Boolean).join(nl);
819
- if (preflights) {
820
- css = [preflightsMap[layer], css].filter(Boolean).join(nl);
821
- }
822
- if (outputCssLayers && css) {
823
- let cssLayer = typeof outputCssLayers === "object" ? outputCssLayers.cssLayerName?.(layer) : void 0;
824
- if (cssLayer !== null) {
825
- if (!cssLayer)
826
- cssLayer = layer;
827
- css = `@layer ${cssLayer}{${nl}${css}${nl}}`;
828
- }
829
- }
830
- const layerMark = minify ? "" : `/* layer: ${layer} */${nl}`;
831
- return layerCache[layer] = css ? layerMark + css : "";
832
- };
833
- const getLayers = (includes = layers, excludes) => {
834
- return includes.filter((i) => !excludes?.includes(i)).map((i) => getLayer(i) || "").filter(Boolean).join(nl);
835
- };
836
- return {
837
- get css() {
838
- return getLayers();
839
- },
840
- layers,
841
- matched,
842
- getLayers,
843
- getLayer
844
- };
845
- }
846
- async matchVariants(raw, current) {
847
- const variants = /* @__PURE__ */ new Set();
848
- const handlers = [];
849
- let processed = current || raw;
850
- let applied = true;
851
- const context = {
852
- rawSelector: raw,
853
- theme: this.config.theme,
854
- generator: this
855
- };
856
- while (applied) {
857
- applied = false;
858
- for (const v of this.config.variants) {
859
- if (!v.multiPass && variants.has(v))
860
- continue;
861
- let handler = await v.match(processed, context);
862
- if (!handler)
863
- continue;
864
- if (isString(handler)) {
865
- if (handler === processed)
866
- continue;
867
- handler = { matcher: handler };
868
- }
869
- processed = handler.matcher;
870
- handlers.unshift(handler);
871
- variants.add(v);
872
- applied = true;
873
- break;
874
- }
875
- if (!applied)
876
- break;
877
- if (handlers.length > 500)
878
- throw new Error(`Too many variants applied to "${raw}"`);
879
- }
880
- return [raw, processed, handlers, variants];
881
- }
882
- applyVariants(parsed, variantHandlers = parsed[4], raw = parsed[1]) {
883
- const handler = variantHandlers.slice().sort((a, b) => (a.order || 0) - (b.order || 0)).reduceRight(
884
- (previous, v) => (input) => {
885
- const entries = v.body?.(input.entries) || input.entries;
886
- const parents = Array.isArray(v.parent) ? v.parent : [v.parent, void 0];
887
- return (v.handle ?? defaultVariantHandler)({
888
- ...input,
889
- entries,
890
- selector: v.selector?.(input.selector, entries) || input.selector,
891
- parent: parents[0] || input.parent,
892
- parentOrder: parents[1] || input.parentOrder,
893
- layer: v.layer || input.layer,
894
- sort: v.sort || input.sort
895
- }, previous);
896
- },
897
- (input) => input
898
- );
899
- const variantContextResult = handler({
900
- prefix: "",
901
- selector: toEscapedSelector(raw),
902
- pseudo: "",
903
- entries: parsed[2]
904
- });
905
- const { parent, parentOrder } = variantContextResult;
906
- if (parent != null && parentOrder != null)
907
- this.parentOrders.set(parent, parentOrder);
908
- const obj = {
909
- selector: [
910
- variantContextResult.prefix,
911
- variantContextResult.selector,
912
- variantContextResult.pseudo
913
- ].join(""),
914
- entries: variantContextResult.entries,
915
- parent,
916
- layer: variantContextResult.layer,
917
- sort: variantContextResult.sort,
918
- noMerge: variantContextResult.noMerge
919
- };
920
- for (const p of this.config.postprocess)
921
- p(obj);
922
- return obj;
923
- }
924
- constructCustomCSS(context, body, overrideSelector) {
925
- const normalizedBody = normalizeCSSEntries(body);
926
- if (isString(normalizedBody))
927
- return normalizedBody;
928
- const { selector, entries, parent } = this.applyVariants([0, overrideSelector || context.rawSelector, normalizedBody, void 0, context.variantHandlers]);
929
- const cssBody = `${selector}{${entriesToCss(entries)}}`;
930
- if (parent)
931
- return `${parent}{${cssBody}}`;
932
- return cssBody;
933
- }
934
- async parseUtil(input, context, internal = false, shortcutPrefix) {
935
- const [raw, processed, variantHandlers] = isString(input) ? await this.matchVariants(input) : input;
936
- if (this.config.details)
937
- context.rules = context.rules ?? [];
938
- const staticMatch = this.config.rulesStaticMap[processed];
939
- if (staticMatch) {
940
- if (staticMatch[1] && (internal || !staticMatch[2]?.internal)) {
941
- if (this.config.details)
942
- context.rules.push(staticMatch[3]);
943
- const index = staticMatch[0];
944
- const entry = normalizeCSSEntries(staticMatch[1]);
945
- const meta = staticMatch[2];
946
- if (isString(entry))
947
- return [[index, entry, meta]];
948
- else
949
- return [[index, raw, entry, meta, variantHandlers]];
950
- }
951
- }
952
- context.variantHandlers = variantHandlers;
953
- const { rulesDynamic } = this.config;
954
- for (const [i, matcher, handler, meta] of rulesDynamic) {
955
- if (meta?.internal && !internal)
956
- continue;
957
- let unprefixed = processed;
958
- if (meta?.prefix) {
959
- const prefixes = toArray(meta.prefix);
960
- if (shortcutPrefix) {
961
- const shortcutPrefixes = toArray(shortcutPrefix);
962
- if (!prefixes.some((i2) => shortcutPrefixes.includes(i2)))
963
- continue;
964
- } else {
965
- const prefix = prefixes.find((i2) => processed.startsWith(i2));
966
- if (prefix == null)
967
- continue;
968
- unprefixed = processed.slice(prefix.length);
969
- }
970
- }
971
- const match = unprefixed.match(matcher);
972
- if (!match)
973
- continue;
974
- const result = await handler(match, context);
975
- if (!result)
976
- continue;
977
- if (this.config.details)
978
- context.rules.push([matcher, handler, meta]);
979
- const entries = normalizeCSSValues(result).filter((i2) => i2.length);
980
- if (entries.length) {
981
- return entries.map((e2) => {
982
- if (isString(e2))
983
- return [i, e2, meta];
984
- else
985
- return [i, raw, e2, meta, variantHandlers];
986
- });
987
- }
988
- }
989
- }
990
- stringifyUtil(parsed, context) {
991
- if (!parsed)
992
- return;
993
- if (isRawUtil(parsed))
994
- return [parsed[0], void 0, parsed[1], void 0, parsed[2], this.config.details ? context : void 0, void 0];
995
- const { selector, entries, parent, layer: variantLayer, sort: variantSort, noMerge } = this.applyVariants(parsed);
996
- const body = entriesToCss(entries);
997
- if (!body)
998
- return;
999
- const { layer: metaLayer, sort: metaSort, ...meta } = parsed[3] ?? {};
1000
- const ruleMeta = {
1001
- ...meta,
1002
- layer: variantLayer ?? metaLayer,
1003
- sort: variantSort ?? metaSort
1004
- };
1005
- return [parsed[0], selector, body, parent, ruleMeta, this.config.details ? context : void 0, noMerge];
1006
- }
1007
- async expandShortcut(input, context, depth = 5) {
1008
- if (depth === 0)
1009
- return;
1010
- const recordShortcut = this.config.details ? (s) => {
1011
- context.shortcuts = context.shortcuts ?? [];
1012
- context.shortcuts.push(s);
1013
- } : noop;
1014
- let meta;
1015
- let result;
1016
- for (const s of this.config.shortcuts) {
1017
- let unprefixed = input;
1018
- if (s[2]?.prefix) {
1019
- const prefixes = toArray(s[2].prefix);
1020
- const prefix = prefixes.find((i) => input.startsWith(i));
1021
- if (prefix == null)
1022
- continue;
1023
- unprefixed = input.slice(prefix.length);
1024
- }
1025
- if (isStaticShortcut(s)) {
1026
- if (s[0] === unprefixed) {
1027
- meta = meta || s[2];
1028
- result = s[1];
1029
- recordShortcut(s);
1030
- break;
1031
- }
1032
- } else {
1033
- const match = unprefixed.match(s[0]);
1034
- if (match)
1035
- result = s[1](match, context);
1036
- if (result) {
1037
- meta = meta || s[2];
1038
- recordShortcut(s);
1039
- break;
1040
- }
1041
- }
1042
- }
1043
- if (isString(result))
1044
- result = expandVariantGroup(result.trim()).split(/\s+/g);
1045
- if (!result) {
1046
- const [raw, inputWithoutVariant] = isString(input) ? await this.matchVariants(input) : input;
1047
- if (raw !== inputWithoutVariant) {
1048
- const expanded = await this.expandShortcut(inputWithoutVariant, context, depth - 1);
1049
- if (expanded)
1050
- result = expanded[0].map((item) => isString(item) ? raw.replace(inputWithoutVariant, item) : item);
1051
- }
1052
- }
1053
- if (!result)
1054
- return;
1055
- return [
1056
- (await Promise.all(result.map(async (r) => (isString(r) ? (await this.expandShortcut(r, context, depth - 1))?.[0] : void 0) || [r]))).flat(1).filter(Boolean),
1057
- meta
1058
- ];
1059
- }
1060
- async stringifyShortcuts(parent, context, expanded, meta = { layer: this.config.shortcutsLayer }) {
1061
- const layerMap = new BetterMap();
1062
- const parsed = (await Promise.all(uniq(expanded).map(async (i) => {
1063
- const result = isString(i) ? await this.parseUtil(i, context, true, meta.prefix) : [[Number.POSITIVE_INFINITY, "{inline}", normalizeCSSEntries(i), void 0, []]];
1064
- if (!result && this.config.warn)
1065
- warnOnce(`unmatched utility "${i}" in shortcut "${parent[1]}"`);
1066
- return result || [];
1067
- }))).flat(1).filter(Boolean).sort((a, b) => a[0] - b[0]);
1068
- const [raw, , parentVariants] = parent;
1069
- const rawStringifiedUtil = [];
1070
- for (const item of parsed) {
1071
- if (isRawUtil(item)) {
1072
- rawStringifiedUtil.push([item[0], void 0, item[1], void 0, item[2], context, void 0]);
1073
- continue;
1074
- }
1075
- const { selector, entries, parent: parent2, sort, noMerge, layer } = this.applyVariants(item, [...item[4], ...parentVariants], raw);
1076
- const selectorMap = layerMap.getFallback(layer ?? meta.layer, new TwoKeyMap());
1077
- const mapItem = selectorMap.getFallback(selector, parent2, [[], item[0]]);
1078
- mapItem[0].push([entries, !!(noMerge ?? item[3]?.noMerge), sort ?? 0]);
1079
- }
1080
- return rawStringifiedUtil.concat(layerMap.flatMap(
1081
- (selectorMap, layer) => selectorMap.map(([e2, index], selector, joinedParents) => {
1082
- const stringify = (flatten, noMerge, entrySortPair) => {
1083
- const maxSort = Math.max(...entrySortPair.map((e3) => e3[1]));
1084
- const entriesList = entrySortPair.map((e3) => e3[0]);
1085
- return (flatten ? [entriesList.flat(1)] : entriesList).map((entries) => {
1086
- const body = entriesToCss(entries);
1087
- if (body)
1088
- return [index, selector, body, joinedParents, { ...meta, noMerge, sort: maxSort, layer }, context, void 0];
1089
- return void 0;
1090
- });
1091
- };
1092
- const merges = [
1093
- [e2.filter(([, noMerge]) => noMerge).map(([entries, , sort]) => [entries, sort]), true],
1094
- [e2.filter(([, noMerge]) => !noMerge).map(([entries, , sort]) => [entries, sort]), false]
1095
- ];
1096
- return merges.map(([e3, noMerge]) => [
1097
- ...stringify(false, noMerge, e3.filter(([entries]) => entries.some((entry) => entry[0] === CONTROL_SHORTCUT_NO_MERGE))),
1098
- ...stringify(true, noMerge, e3.filter(([entries]) => entries.every((entry) => entry[0] !== CONTROL_SHORTCUT_NO_MERGE)))
1099
- ]);
1100
- }).flat(2).filter(Boolean)
1101
- ));
1102
- }
1103
- isBlocked(raw) {
1104
- return !raw || this.config.blocklist.some((e2) => typeof e2 === "function" ? e2(raw) : isString(e2) ? e2 === raw : e2.test(raw));
1105
- }
1106
- }
1107
- function createGenerator(config, defaults) {
1108
- return new UnoGenerator(config, defaults);
1109
- }
1110
- const regexScopePlaceholder = /\s\$\$\s+/g;
1111
- function hasScopePlaceholder(css) {
1112
- return regexScopePlaceholder.test(css);
1113
- }
1114
- function applyScope(css, scope) {
1115
- if (hasScopePlaceholder(css))
1116
- return css.replace(regexScopePlaceholder, scope ? ` ${scope} ` : " ");
1117
- else
1118
- return scope ? `${scope} ${css}` : css;
1119
- }
1120
- const attributifyRe = /^\[(.+?)(~?=)"(.*)"\]$/;
1121
- function toEscapedSelector(raw) {
1122
- if (attributifyRe.test(raw))
1123
- return raw.replace(attributifyRe, (_, n, s, i) => `[${e(n)}${s}"${e(i)}"]`);
1124
- return `.${e(raw)}`;
1125
- }
1126
- function defaultVariantHandler(input, next) {
1127
- return next(input);
1128
- }
1129
-
1130
- exports.BetterMap = BetterMap;
1131
- exports.CONTROL_SHORTCUT_NO_MERGE = CONTROL_SHORTCUT_NO_MERGE;
1132
- exports.CountableSet = CountableSet;
1133
- exports.TwoKeyMap = TwoKeyMap;
1134
- exports.UnoGenerator = UnoGenerator;
1135
- exports.attributifyRE = attributifyRE;
1136
- exports.clearIdenticalEntries = clearIdenticalEntries;
1137
- exports.clone = clone;
1138
- exports.collapseVariantGroup = collapseVariantGroup;
1139
- exports.createGenerator = createGenerator;
1140
- exports.cssIdRE = cssIdRE;
1141
- exports.defaultSplitRE = defaultSplitRE;
1142
- exports.definePreset = definePreset;
1143
- exports.e = e;
1144
- exports.entriesToCss = entriesToCss;
1145
- exports.escapeRegExp = escapeRegExp;
1146
- exports.escapeSelector = escapeSelector;
1147
- exports.expandVariantGroup = expandVariantGroup;
1148
- exports.extractorDefault = extractorSplit;
1149
- exports.extractorSplit = extractorSplit;
1150
- exports.hasScopePlaceholder = hasScopePlaceholder;
1151
- exports.isAttributifySelector = isAttributifySelector;
1152
- exports.isCountableSet = isCountableSet;
1153
- exports.isObject = isObject;
1154
- exports.isRawUtil = isRawUtil;
1155
- exports.isStaticRule = isStaticRule;
1156
- exports.isStaticShortcut = isStaticShortcut;
1157
- exports.isString = isString;
1158
- exports.isValidSelector = isValidSelector;
1159
- exports.makeRegexClassGroup = makeRegexClassGroup;
1160
- exports.mergeConfigs = mergeConfigs;
1161
- exports.mergeDeep = mergeDeep;
1162
- exports.noop = noop;
1163
- exports.normalizeCSSEntries = normalizeCSSEntries;
1164
- exports.normalizeCSSValues = normalizeCSSValues;
1165
- exports.normalizeVariant = normalizeVariant;
1166
- exports.notNull = notNull;
1167
- exports.parseVariantGroup = parseVariantGroup;
1168
- exports.regexScopePlaceholder = regexScopePlaceholder;
1169
- exports.resolveConfig = resolveConfig;
1170
- exports.resolvePreset = resolvePreset;
1171
- exports.resolvePresets = resolvePresets;
1172
- exports.resolveShortcuts = resolveShortcuts;
1173
- exports.splitWithVariantGroupRE = splitWithVariantGroupRE;
1174
- exports.toArray = toArray;
1175
- exports.toEscapedSelector = toEscapedSelector;
1176
- exports.uniq = uniq;
1177
- exports.uniqueBy = uniqueBy;
1178
- exports.validateFilterRE = validateFilterRE;
1179
- exports.warnOnce = warnOnce;
1180
- exports.withLayer = withLayer;