@unocss/svelte-scoped 0.55.0 → 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.
@@ -0,0 +1,41 @@
1
+ import { Plugin } from 'vite';
2
+ import { PluginOptions } from '@unocss/core';
3
+ import { U as UnocssSveltePreprocessOptions } from './shared/svelte-scoped.a2ff5ce3.cjs';
4
+
5
+ interface UnocssSvelteScopedViteOptions extends UnocssSveltePreprocessOptions {
6
+ /**
7
+ * Prefix for compiled class names
8
+ * @default 'uno-'
9
+ */
10
+ classPrefix?: string
11
+ /**
12
+ * Inject reset to the beginning of the global stylesheet.
13
+ *
14
+ * You can pass one of the included resets from [@unocss/reset](https://unocss.dev/guide/style-reset):
15
+ * - `@unocss/reset/normalize.css`
16
+ * - `@unocss/reset/eric-meyer.css`
17
+ * - `@unocss/reset/sanitize/sanitize.css`
18
+ * - `@unocss/reset/tailwind.css`
19
+ * - `@unocss/reset/tailwind-compat.css`
20
+ *
21
+ * You can pass your own custom reset by passing the filepath relative to your project root as in `./src/reset.css`
22
+ *
23
+ * You can install a package then pass a path to the CSS file in your node_modules as in `@bob/my-tools/reset.css`.
24
+ * @default undefined
25
+ */
26
+ injectReset?: string
27
+ /**
28
+ * When building a component library using `@unocss/svelte-scoped/preprocessor` you can also use `@unocss/svelte-scoped/vite` with this set to `true` to add needed global styles for your library demo app: resets, preflights, and safelist
29
+ * @default false
30
+ */
31
+ onlyGlobal?: boolean
32
+ /**
33
+ * Process CSS files using UnoCSS transformers.
34
+ * @default undefined
35
+ */
36
+ cssFileTransformers?: PluginOptions['transformers']
37
+ }
38
+
39
+ declare function UnocssSvelteScopedVite(options?: UnocssSvelteScopedViteOptions): Plugin[];
40
+
41
+ export { UnocssSvelteScopedVite as default };
@@ -0,0 +1,41 @@
1
+ import { Plugin } from 'vite';
2
+ import { PluginOptions } from '@unocss/core';
3
+ import { U as UnocssSveltePreprocessOptions } from './shared/svelte-scoped.a2ff5ce3.mjs';
4
+
5
+ interface UnocssSvelteScopedViteOptions extends UnocssSveltePreprocessOptions {
6
+ /**
7
+ * Prefix for compiled class names
8
+ * @default 'uno-'
9
+ */
10
+ classPrefix?: string
11
+ /**
12
+ * Inject reset to the beginning of the global stylesheet.
13
+ *
14
+ * You can pass one of the included resets from [@unocss/reset](https://unocss.dev/guide/style-reset):
15
+ * - `@unocss/reset/normalize.css`
16
+ * - `@unocss/reset/eric-meyer.css`
17
+ * - `@unocss/reset/sanitize/sanitize.css`
18
+ * - `@unocss/reset/tailwind.css`
19
+ * - `@unocss/reset/tailwind-compat.css`
20
+ *
21
+ * You can pass your own custom reset by passing the filepath relative to your project root as in `./src/reset.css`
22
+ *
23
+ * You can install a package then pass a path to the CSS file in your node_modules as in `@bob/my-tools/reset.css`.
24
+ * @default undefined
25
+ */
26
+ injectReset?: string
27
+ /**
28
+ * When building a component library using `@unocss/svelte-scoped/preprocessor` you can also use `@unocss/svelte-scoped/vite` with this set to `true` to add needed global styles for your library demo app: resets, preflights, and safelist
29
+ * @default false
30
+ */
31
+ onlyGlobal?: boolean
32
+ /**
33
+ * Process CSS files using UnoCSS transformers.
34
+ * @default undefined
35
+ */
36
+ cssFileTransformers?: PluginOptions['transformers']
37
+ }
38
+
39
+ declare function UnocssSvelteScopedVite(options?: UnocssSvelteScopedViteOptions): Plugin[];
40
+
41
+ export { UnocssSvelteScopedVite as default };
package/dist/vite.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Plugin } from 'vite';
2
- import { U as UnocssSveltePreprocessOptions } from './types.d-20d48151.js';
3
2
  import { PluginOptions } from '@unocss/core';
3
+ import { U as UnocssSveltePreprocessOptions } from './shared/svelte-scoped.a2ff5ce3.js';
4
4
 
5
5
  interface UnocssSvelteScopedViteOptions extends UnocssSveltePreprocessOptions {
6
6
  /**
package/dist/vite.mjs CHANGED
@@ -2,7 +2,7 @@ import process from 'node:process';
2
2
  import { cssIdRE, createGenerator } from '@unocss/core';
3
3
  import { loadConfig } from '@unocss/config';
4
4
  import presetUno from '@unocss/preset-uno';
5
- import { U as UnocssSveltePreprocess } from './shared/svelte-scoped.2a355a56.mjs';
5
+ import UnocssSveltePreprocess from './preprocess.mjs';
6
6
  import { readFileSync, existsSync, statSync } from 'node:fs';
7
7
  import { dirname, resolve } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
@@ -104,7 +104,9 @@ function GlobalStylesPlugin({ ready, uno }, injectReset) {
104
104
  await ready;
105
105
  isSvelteKit = viteConfig.plugins.some((p) => p.name.includes("sveltekit"));
106
106
  },
107
+ // serve
107
108
  configureServer: (server) => checkTransformPageChunkHook(server, isSvelteKit),
109
+ // serve
108
110
  async transform(code, id) {
109
111
  if (isSvelteKit && viteConfig.command === "serve" && isServerHooksFile(id)) {
110
112
  const css = await generateGlobalCss(uno, injectReset);
@@ -113,6 +115,7 @@ function GlobalStylesPlugin({ ready, uno }, injectReset) {
113
115
  };
114
116
  }
115
117
  },
118
+ // build
116
119
  async buildStart() {
117
120
  if (viteConfig.command === "build") {
118
121
  const css = await generateGlobalCss(uno, injectReset);
@@ -123,15 +126,18 @@ function GlobalStylesPlugin({ ready, uno }, injectReset) {
123
126
  });
124
127
  }
125
128
  },
129
+ // build
126
130
  renderStart() {
127
131
  const unoCssFileName = this.getFileName(unoCssFileReferenceId);
128
132
  const base = viteConfig.base ?? "/";
129
133
  unoCssHashedLinkTag = `<link href="${base}${unoCssFileName}" rel="stylesheet" />`;
130
134
  },
135
+ // build
131
136
  renderChunk(code, chunk) {
132
137
  if (isSvelteKit && chunk.moduleIds.some((id) => isServerHooksFile(id)))
133
138
  return replaceGlobalStylesPlaceholder(code, unoCssHashedLinkTag);
134
139
  },
140
+ // serve and build
135
141
  async transformIndexHtml(html) {
136
142
  if (!isSvelteKit) {
137
143
  if (viteConfig.command === "build")
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unocss/svelte-scoped",
3
3
  "type": "module",
4
- "version": "0.55.0",
4
+ "version": "0.55.2",
5
5
  "description": "Use UnoCSS in a modular fashion with styles being stored only in the Svelte component they are used in: Vite plugin for apps, preprocessor for component libraries",
6
6
  "author": "Jacob Bowdoin",
7
7
  "license": "MIT",
@@ -54,12 +54,12 @@
54
54
  "dependencies": {
55
55
  "css-tree": "^2.3.1",
56
56
  "magic-string": "^0.30.2",
57
- "@unocss/config": "0.55.0",
58
- "@unocss/reset": "0.55.0"
57
+ "@unocss/config": "0.55.2",
58
+ "@unocss/reset": "0.55.2"
59
59
  },
60
60
  "devDependencies": {
61
61
  "prettier-plugin-svelte": "^2.10.1",
62
- "svelte": "^4.1.2"
62
+ "svelte": "^4.2.0"
63
63
  },
64
64
  "scripts": {
65
65
  "build": "unbuild",
@@ -1,480 +0,0 @@
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 U };