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