@unocss/svelte-scoped 0.52.7 → 0.53.0

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.
@@ -1,476 +1,12 @@
1
1
  'use strict';
2
2
 
3
- const core = require('@unocss/core');
4
- const presetUno = require('@unocss/preset-uno');
5
- const config = require('@unocss/config');
6
- const MagicString = require('magic-string');
7
- const cssTree = require('css-tree');
3
+ const index = require('./shared/svelte-scoped.2f74d0fb.cjs');
4
+ require('@unocss/core');
5
+ require('@unocss/preset-uno');
6
+ require('@unocss/config');
7
+ require('magic-string');
8
+ require('css-tree');
8
9
 
9
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
10
10
 
11
- const presetUno__default = /*#__PURE__*/_interopDefaultLegacy(presetUno);
12
- const MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
13
11
 
14
- const NOT_PRECEEDED_BY_DIGIT_OR_OPEN_PARENTHESIS_RE = /(?<![\d(])/;
15
- const SELECTOR_STARTING_WITH_BRACKET_OR_PERIOD_RE = /([[\.][\S\s]+?)/;
16
- const STYLES_RE = /({[\S\s]+?})/;
17
- const EXTRACT_SELECTOR_RE = new RegExp(NOT_PRECEEDED_BY_DIGIT_OR_OPEN_PARENTHESIS_RE.source + SELECTOR_STARTING_WITH_BRACKET_OR_PERIOD_RE.source + STYLES_RE.source, "g");
18
- function wrapSelectorsWithGlobal(css) {
19
- return css.replace(EXTRACT_SELECTOR_RE, ":global($1)$2");
20
- }
21
-
22
- const classesRE$1 = /class=(["'\`])([\S\s]*?)\1/g;
23
- const classDirectivesRE = /class:([\S]+?)={/g;
24
- const classDirectivesShorthandRE = /class:([^=>\s/]+)[{>\s/]/g;
25
- function findClasses(code) {
26
- const matchedClasses = [...code.matchAll(classesRE$1)];
27
- const matchedClassDirectives = [...code.matchAll(classDirectivesRE)];
28
- const matchedClassDirectivesShorthand = [...code.matchAll(classDirectivesShorthandRE)];
29
- const classes = parseMatches(matchedClasses, "regular", 'class="'.length);
30
- const classDirectives = parseMatches(matchedClassDirectives, "directive", "class:".length);
31
- const classDirectivesShorthand = parseMatches(matchedClassDirectivesShorthand, "directiveShorthand", "class:".length);
32
- return [...classes, ...classDirectives, ...classDirectivesShorthand];
33
- }
34
- function parseMatches(matches, type, prefixLength) {
35
- return matches.map((match) => {
36
- const body = match[type === "regular" ? 2 : 1];
37
- const start = match.index + prefixLength;
38
- return {
39
- body: body.trim(),
40
- start,
41
- end: start + body.length,
42
- type
43
- };
44
- }).filter(hasBody);
45
- }
46
- function hasBody(foundClass) {
47
- return foundClass.body;
48
- }
49
-
50
- const notInCommentRE = /(?<!<!--\s*)/;
51
- const stylesTagWithCapturedDirectivesRE = /<style([^>]*)>[\s\S]*?<\/style\s*>/;
52
- const actualStylesTagWithCapturedDirectivesRE = new RegExp(notInCommentRE.source + stylesTagWithCapturedDirectivesRE.source, "g");
53
- const captureOpeningStyleTagWithAttributesRE = /(<style[^>]*>)/;
54
- function addGeneratedStylesIntoStyleBlock(code, styles) {
55
- const preExistingStylesTag = code.match(actualStylesTagWithCapturedDirectivesRE);
56
- if (preExistingStylesTag)
57
- return code.replace(captureOpeningStyleTagWithAttributesRE, `$1${styles}`);
58
- return `${code}
59
- <style>${styles}</style>`;
60
- }
61
-
62
- async function needsGenerated(token, uno) {
63
- const inSafelist = uno.config.safelist.includes(token);
64
- if (inSafelist)
65
- return false;
66
- const result = await uno.parseToken(token);
67
- return !!result;
68
- }
69
-
70
- function hash(str) {
71
- let i;
72
- let l;
73
- let hval = 2166136261;
74
- for (i = 0, l = str.length; i < l; i++) {
75
- hval ^= str.charCodeAt(i);
76
- hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
77
- }
78
- return `00000${(hval >>> 0).toString(36)}`.slice(-6);
79
- }
80
-
81
- function generateClassName(body, options, filename) {
82
- const {
83
- classPrefix = "uno-",
84
- combine = true,
85
- hashFn = hash
86
- } = options;
87
- if (combine) {
88
- const classPlusFilenameHash = hashFn(body + filename);
89
- return `${classPrefix}${classPlusFilenameHash}`;
90
- } else {
91
- const filenameHash = hashFn(filename);
92
- return `_${body}_${filenameHash}`;
93
- }
94
- }
95
-
96
- function isShortcut(token, shortcuts) {
97
- return shortcuts.some((s) => s[0] === token);
98
- }
99
-
100
- async function processDirective({ body: token, start, end, type }, options, uno, filename) {
101
- const isShortcutOrUtility = isShortcut(token, uno.config.shortcuts) || await needsGenerated(token, uno);
102
- if (!isShortcutOrUtility)
103
- return;
104
- const generatedClassName = generateClassName(token, options, filename);
105
- const content = type === "directiveShorthand" ? `${generatedClassName}={${token}}` : generatedClassName;
106
- return {
107
- rulesToGenerate: { [generatedClassName]: [token] },
108
- codeUpdate: { content, start, end }
109
- };
110
- }
111
-
112
- async function sortClassesIntoCategories(body, options, uno, filename) {
113
- const { combine = true } = options;
114
- const rulesToGenerate = {};
115
- const ignore = [];
116
- const classes = body.trim().split(/\s+/);
117
- const knownClassesToCombine = [];
118
- for (const token of classes) {
119
- const isShortcutOrUtility = isShortcut(token, uno.config.shortcuts) || await needsGenerated(token, uno);
120
- if (!isShortcutOrUtility) {
121
- ignore.push(token);
122
- continue;
123
- }
124
- if (combine) {
125
- knownClassesToCombine.push(token);
126
- } else {
127
- const generatedClassName = generateClassName(token, options, filename);
128
- rulesToGenerate[generatedClassName] = [token];
129
- }
130
- }
131
- if (knownClassesToCombine.length) {
132
- const generatedClassName = generateClassName(knownClassesToCombine.join(" "), options, filename);
133
- rulesToGenerate[generatedClassName] = knownClassesToCombine;
134
- }
135
- return { rulesToGenerate, ignore };
136
- }
137
-
138
- const expressionsRE = /\S*{[^{}]+?}\S*/g;
139
- const classesRE = /(["'\`])([\S\s]+?)\1/g;
140
- async function processExpressions(body, options, uno, filename) {
141
- const rulesToGenerate = {};
142
- const updatedExpressions = [];
143
- let restOfBody = body;
144
- const expressions = [...body.matchAll(expressionsRE)];
145
- for (let [expression] of expressions) {
146
- restOfBody = restOfBody.replace(expression, "").trim();
147
- const classes = [...expression.matchAll(classesRE)];
148
- for (const [withQuotes, quoteMark, withoutQuotes] of classes) {
149
- const { rulesToGenerate: rulesFromExpression, ignore } = await sortClassesIntoCategories(withoutQuotes, options, uno, filename);
150
- Object.assign(rulesToGenerate, rulesFromExpression);
151
- const updatedClasses = Object.keys(rulesFromExpression).concat(ignore).join(" ");
152
- expression = expression.replace(withQuotes, quoteMark + updatedClasses + quoteMark);
153
- }
154
- updatedExpressions.push(expression);
155
- }
156
- return { rulesToGenerate, updatedExpressions, restOfBody };
157
- }
158
-
159
- async function processClassBody({ body, start, end }, options, uno, filename) {
160
- const expandedBody = core.expandVariantGroup(body);
161
- const { rulesToGenerate: rulesFromExpressions, restOfBody, updatedExpressions } = await processExpressions(expandedBody, options, uno, filename);
162
- const { rulesToGenerate: rulesFromRegularClasses, ignore } = await sortClassesIntoCategories(restOfBody, options, uno, filename);
163
- const rulesToGenerate = { ...rulesFromExpressions, ...rulesFromRegularClasses };
164
- if (!Object.keys(rulesToGenerate).length)
165
- return {};
166
- const content = Object.keys(rulesFromRegularClasses).concat(ignore).concat(updatedExpressions).join(" ");
167
- const codeUpdate = {
168
- content,
169
- start,
170
- end
171
- };
172
- return { rulesToGenerate, codeUpdate };
173
- }
174
-
175
- async function processClasses(classes, options, uno, filename) {
176
- const result = {
177
- rulesToGenerate: {},
178
- codeUpdates: []
179
- };
180
- for (const foundClass of classes) {
181
- if (foundClass.type === "regular") {
182
- const { rulesToGenerate, codeUpdate } = await processClassBody(foundClass, options, uno, filename);
183
- if (rulesToGenerate)
184
- Object.assign(result.rulesToGenerate, rulesToGenerate);
185
- if (codeUpdate)
186
- result.codeUpdates.push(codeUpdate);
187
- } else {
188
- const { rulesToGenerate, codeUpdate } = await processDirective(foundClass, options, uno, filename) || {};
189
- if (rulesToGenerate)
190
- Object.assign(result.rulesToGenerate, rulesToGenerate);
191
- if (codeUpdate)
192
- result.codeUpdates.push(codeUpdate);
193
- }
194
- }
195
- return result;
196
- }
197
-
198
- async function transformClasses({ content, filename, uno, options }) {
199
- const classesToProcess = findClasses(content);
200
- if (!classesToProcess.length)
201
- return;
202
- const { rulesToGenerate, codeUpdates } = await processClasses(classesToProcess, options, uno, filename);
203
- if (!Object.keys(rulesToGenerate).length)
204
- return;
205
- const { map, code } = updateTemplateCodeIfNeeded(codeUpdates, content, filename);
206
- const generatedStyles = await generateStyles(rulesToGenerate, uno);
207
- const codeWithGeneratedStyles = addGeneratedStylesIntoStyleBlock(code, generatedStyles);
208
- return {
209
- code: codeWithGeneratedStyles,
210
- map
211
- };
212
- }
213
- function updateTemplateCodeIfNeeded(codeUpdates, source, filename) {
214
- if (!codeUpdates.length)
215
- return { code: source, map: void 0 };
216
- const s = new MagicString__default(source);
217
- for (const { start, end, content } of codeUpdates)
218
- s.overwrite(start, end, content);
219
- return {
220
- code: s.toString(),
221
- map: s.generateMap({ hires: true, source: filename })
222
- };
223
- }
224
- const removeCommentsToMakeGlobalWrappingEasy = true;
225
- async function generateStyles(rulesToGenerate, uno) {
226
- const originalShortcuts = uno.config.shortcuts;
227
- const shortcutsForThisComponent = Object.entries(rulesToGenerate);
228
- uno.config.shortcuts = [...originalShortcuts, ...shortcutsForThisComponent];
229
- const selectorsToGenerate = Object.keys(rulesToGenerate);
230
- const { css } = await uno.generate(
231
- selectorsToGenerate,
232
- {
233
- preflights: false,
234
- safelist: false,
235
- minify: removeCommentsToMakeGlobalWrappingEasy
236
- }
237
- );
238
- uno.config.shortcuts = originalShortcuts;
239
- const cssPreparedForSvelteCompiler = wrapSelectorsWithGlobal(css);
240
- return cssPreparedForSvelteCompiler;
241
- }
242
-
243
- function removeOuterQuotes(input) {
244
- if (!input)
245
- return "";
246
- const match = input.match(/^(['"]).*\1$/);
247
- return match ? input.slice(1, -1) : input;
248
- }
249
-
250
- function writeUtilStyles([, selector, body, parent], s, node, childNode) {
251
- if (!selector)
252
- return;
253
- const selectorChanged = selector !== ".\\-";
254
- if (!parent && !selectorChanged)
255
- return s.appendRight(childNode.loc.end.offset, body);
256
- const originalSelector = cssTree.generate(node.prelude);
257
- if (parent && !selectorChanged) {
258
- const css2 = `${parent}{${originalSelector}{${body}}}`;
259
- return s.appendLeft(node.loc.end.offset, css2);
260
- }
261
- const utilSelector = selector.replace(core.regexScopePlaceholder, " ");
262
- const updatedSelector = generateUpdatedSelector(utilSelector, node.prelude);
263
- const svelteCompilerReadySelector = surroundAllButOriginalSelectorWithGlobal(originalSelector, updatedSelector);
264
- const rule = `${svelteCompilerReadySelector}{${body}}`;
265
- const css = parent ? `${parent}{${rule}}` : rule;
266
- s.appendLeft(node.loc.end.offset, css);
267
- }
268
- function generateUpdatedSelector(selector, _prelude) {
269
- const selectorAST = cssTree.parse(selector, {
270
- context: "selector"
271
- });
272
- const prelude = cssTree.clone(_prelude);
273
- prelude.children.forEach((child) => {
274
- const parentSelectorAst = cssTree.clone(selectorAST);
275
- parentSelectorAst.children.forEach((i) => {
276
- if (i.type === "ClassSelector" && i.name === "\\-")
277
- Object.assign(i, cssTree.clone(child));
278
- });
279
- Object.assign(child, parentSelectorAst);
280
- });
281
- return cssTree.generate(prelude);
282
- }
283
- function surroundAllButOriginalSelectorWithGlobal(originalSelector, updatedSelector) {
284
- const wrapWithGlobal = (str) => `:global(${str})`;
285
- const originalSelectors = originalSelector.split(",").map((s) => s.trim());
286
- const updatedSelectors = updatedSelector.split(",").map((s) => s.trim());
287
- const resultSelectors = originalSelectors.map((original, index) => {
288
- const updated = updatedSelectors[index];
289
- const [prefix, suffix] = updated.split(original).map((s) => s.trim());
290
- const wrappedPrefix = prefix ? wrapWithGlobal(prefix) : "";
291
- if (!suffix)
292
- return `${wrappedPrefix} ${original}`.trim();
293
- const indexOfFirstCombinator = findFirstCombinatorIndex(suffix);
294
- if (indexOfFirstCombinator === -1)
295
- return `${wrappedPrefix} ${original}${suffix}`.trim();
296
- const pseudo = suffix.substring(0, indexOfFirstCombinator).trim();
297
- const siblingsOrDescendants = suffix.substring(indexOfFirstCombinator).trim();
298
- return `${wrappedPrefix} ${original}${pseudo} ${wrapWithGlobal(siblingsOrDescendants)}`.trim();
299
- });
300
- return resultSelectors.join(", ");
301
- }
302
- function findFirstCombinatorIndex(input) {
303
- const combinators = [" ", ">", "~", "+"];
304
- for (const c of combinators) {
305
- const indexOfFirstCombinator = input.indexOf(c);
306
- if (indexOfFirstCombinator !== -1)
307
- return indexOfFirstCombinator;
308
- }
309
- return -1;
310
- }
311
-
312
- async function getUtils(body, uno) {
313
- const classNames = core.expandVariantGroup(body).split(/\s+/g).map((className) => className.trim().replace(/\\/, ""));
314
- const utils = await parseUtils(classNames, uno);
315
- const sortedByRankIndex = utils.sort(([aIndex], [bIndex]) => aIndex - bIndex);
316
- const sortedByParentOrders = sortedByRankIndex.sort(([, , , aParent], [, , , bParent]) => (aParent ? uno.parentOrders.get(aParent) ?? 0 : 0) - (bParent ? uno.parentOrders.get(bParent) ?? 0 : 0));
317
- return sortedByParentOrders.reduce((acc, item) => {
318
- const [, selector, body2, parent] = item;
319
- const sibling = acc.find(([, targetSelector, , targetParent]) => targetSelector === selector && targetParent === parent);
320
- if (sibling)
321
- sibling[2] += body2;
322
- else
323
- acc.push([...item]);
324
- return acc;
325
- }, []);
326
- }
327
- async function parseUtils(classNames, uno) {
328
- const foundUtils = [];
329
- for (const token of classNames) {
330
- const util = await uno.parseToken(token, "-");
331
- if (util)
332
- foundUtils.push(util);
333
- else
334
- core.warnOnce(`'${token}' not found. You have a typo or need to add a preset.`);
335
- }
336
- return foundUtils.flat();
337
- }
338
-
339
- async function transformApply(ctx) {
340
- const ast = cssTree.parse(ctx.s.original, {
341
- parseAtrulePrelude: false,
342
- positions: true
343
- });
344
- if (ast.type !== "StyleSheet")
345
- return ctx.s;
346
- const stack = [];
347
- cssTree.walk(ast, (node) => {
348
- if (node.type === "Rule")
349
- stack.push(handleApply(ctx, node));
350
- });
351
- await Promise.all(stack);
352
- return ctx.s;
353
- }
354
- async function handleApply(ctx, node) {
355
- const parsePromises = node.block.children.map(async (childNode) => {
356
- await parseApply(ctx, node, childNode);
357
- });
358
- await Promise.all(parsePromises);
359
- }
360
- async function parseApply({ s, uno, applyVariables }, node, childNode) {
361
- const body = getChildNodeValue(childNode, applyVariables);
362
- if (!body)
363
- return;
364
- const utils = await getUtils(body, uno);
365
- if (!utils.length)
366
- return;
367
- for (const util of utils)
368
- writeUtilStyles(util, s, node, childNode);
369
- s.remove(childNode.loc.start.offset, childNode.loc.end.offset);
370
- }
371
- function getChildNodeValue(childNode, applyVariables) {
372
- if (childNode.type === "Atrule" && childNode.name === "apply" && childNode.prelude && childNode.prelude.type === "Raw")
373
- return childNode.prelude.value.trim();
374
- if (childNode.type === "Declaration" && applyVariables.includes(childNode.property) && childNode.value.type === "Raw")
375
- return removeOuterQuotes(childNode.value.value.trim());
376
- }
377
-
378
- const themeRE = /theme\((.+?)\)/g;
379
- function transformTheme(s, theme) {
380
- return s.replace(themeRE, (_, match) => {
381
- const argumentsWithoutQuotes = match.slice(1, -1);
382
- return getThemeValue(argumentsWithoutQuotes, theme);
383
- });
384
- }
385
- function getThemeValue(rawArguments, theme) {
386
- const keys = rawArguments.split(".");
387
- let current = theme;
388
- for (const key of keys) {
389
- if (current[key] === void 0)
390
- throw new Error(`"${rawArguments}" is not found in your theme`);
391
- else
392
- current = current[key];
393
- }
394
- return current;
395
- }
396
-
397
- const DEFAULT_APPLY_VARIABLES = ["--at-apply"];
398
- async function transformStyle({ content, uno, prepend, applyVariables, filename }) {
399
- applyVariables = core.toArray(applyVariables || DEFAULT_APPLY_VARIABLES);
400
- const hasApply = content.includes("@apply") || applyVariables.some((v) => content.includes(v));
401
- const hasThemeFn = content.match(themeRE);
402
- if (!hasApply && !hasThemeFn)
403
- return;
404
- const s = new MagicString__default(content);
405
- if (hasApply)
406
- await transformApply({ s, uno, applyVariables });
407
- if (hasThemeFn)
408
- transformTheme(s, uno.config.theme);
409
- if (!s.hasChanged())
410
- return;
411
- if (prepend)
412
- s.prepend(prepend);
413
- return {
414
- code: s.toString(),
415
- map: s.generateMap({ hires: true, source: filename || "" })
416
- };
417
- }
418
-
419
- function UnocssSveltePreprocess(options = {}, unoContextFromVite, isViteBuild) {
420
- if (!options.classPrefix)
421
- options.classPrefix = "spu-";
422
- let uno;
423
- return {
424
- markup: async ({ content, filename }) => {
425
- if (!uno)
426
- uno = await getGenerator(options.configOrPath, unoContextFromVite);
427
- if (isViteBuild && !options.combine)
428
- options.combine = isViteBuild();
429
- return await transformClasses({ content, filename: filename || "", uno, options });
430
- },
431
- style: async ({ content, attributes, filename }) => {
432
- const addPreflights = !!attributes["uno:preflights"];
433
- const addSafelist = !!attributes["uno:safelist"];
434
- const checkForApply = options.applyVariables !== false;
435
- const hasThemeFn = content.match(themeRE);
436
- const changeNeeded = addPreflights || addSafelist || checkForApply || hasThemeFn;
437
- if (!changeNeeded)
438
- return;
439
- if (!uno)
440
- uno = await getGenerator(options.configOrPath);
441
- let preflightsSafelistCss = "";
442
- if (addPreflights || addSafelist) {
443
- if (unoContextFromVite)
444
- core.warnOnce("Do not place preflights or safelist within an individual component as they already placed in your global styles injected into the head tag. These options are only for component libraries.");
445
- const { css } = await uno.generate([], { preflights: addPreflights, safelist: addSafelist, minify: true });
446
- preflightsSafelistCss = css;
447
- }
448
- if (checkForApply || hasThemeFn) {
449
- return await transformStyle({
450
- content,
451
- prepend: preflightsSafelistCss,
452
- uno,
453
- applyVariables: options.applyVariables,
454
- filename
455
- });
456
- }
457
- if (preflightsSafelistCss)
458
- return { code: preflightsSafelistCss };
459
- }
460
- };
461
- }
462
- async function getGenerator(configOrPath, unoContextFromVite) {
463
- if (unoContextFromVite) {
464
- await unoContextFromVite.ready;
465
- return unoContextFromVite.uno;
466
- }
467
- const defaults = {
468
- presets: [
469
- presetUno__default()
470
- ]
471
- };
472
- const { config: config$1 } = await config.loadConfig(process.cwd(), configOrPath);
473
- return core.createGenerator(config$1, defaults);
474
- }
475
-
476
- module.exports = UnocssSveltePreprocess;
12
+ module.exports = index.UnocssSveltePreprocess;
@@ -1,6 +1,6 @@
1
1
  import { PreprocessorGroup } from 'svelte/types/compiler/preprocess';
2
- import { U as UnocssSveltePreprocessOptions, S as SvelteScopedContext } from './types.d-48b837f0.js';
3
- export { S as SvelteScopedContext, a as TransformApplyOptions, T as TransformClassesOptions, U as UnocssSveltePreprocessOptions } from './types.d-48b837f0.js';
2
+ import { U as UnocssSveltePreprocessOptions, S as SvelteScopedContext } from './types.d-20d48151.js';
3
+ export { S as SvelteScopedContext, a as TransformApplyOptions, T as TransformClassesOptions, U as UnocssSveltePreprocessOptions } from './types.d-20d48151.js';
4
4
  import '@unocss/core';
5
5
 
6
6
  declare function UnocssSveltePreprocess(options?: UnocssSveltePreprocessOptions, unoContextFromVite?: SvelteScopedContext, isViteBuild?: () => boolean): PreprocessorGroup;