@unocss/webpack 0.62.3 → 0.63.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.
package/dist/index.mjs CHANGED
@@ -1,453 +1,19 @@
1
- import process$1 from 'node:process';
2
- import { resolve, isAbsolute, normalize } from 'node:path';
3
- import { createUnplugin } from 'unplugin';
4
- import WebpackSources from 'webpack-sources';
5
- import { createFilter } from '@rollup/pluginutils';
6
- import { createRecoveryConfigLoader } from '@unocss/config';
7
- import { cssIdRE, createGenerator, BetterMap } from '@unocss/core';
8
- import fs from 'node:fs/promises';
9
- import { glob } from 'tinyglobby';
10
- import MagicString from 'magic-string';
11
- import remapping from '@ampproject/remapping';
12
- import { createHash } from 'node:crypto';
1
+ import { u as unplugin } from './shared/webpack.B0TbicgL.mjs';
2
+ import 'node:path';
3
+ import 'node:process';
4
+ import 'unplugin';
5
+ import 'webpack-sources';
6
+ import 'node:fs/promises';
7
+ import 'tinyglobby';
8
+ import '@ampproject/remapping';
9
+ import 'magic-string';
10
+ import '@unocss/core';
11
+ import '@rollup/pluginutils';
12
+ import '@unocss/config';
13
+ import 'node:crypto';
13
14
 
14
- const INCLUDE_COMMENT = "@unocss-include";
15
- const IGNORE_COMMENT = "@unocss-ignore";
16
- const CSS_PLACEHOLDER = "@unocss-placeholder";
17
- const SKIP_START_COMMENT = "@unocss-skip-start";
18
- const SKIP_END_COMMENT = "@unocss-skip-end";
19
- const SKIP_COMMENT_RE = new RegExp(`(//\\s*?${SKIP_START_COMMENT}\\s*?|\\/\\*\\s*?${SKIP_START_COMMENT}\\s*?\\*\\/|<!--\\s*?${SKIP_START_COMMENT}\\s*?-->)[\\s\\S]*?(//\\s*?${SKIP_END_COMMENT}\\s*?|\\/\\*\\s*?${SKIP_END_COMMENT}\\s*?\\*\\/|<!--\\s*?${SKIP_END_COMMENT}\\s*?-->)`, "g");
20
-
21
- const defaultPipelineExclude = [cssIdRE];
22
- const defaultPipelineInclude = [/\.(vue|svelte|[jt]sx|mdx?|astro|elm|php|phtml|html)($|\?)/];
23
-
24
- function deprecationCheck(config) {
25
- let warned = false;
26
- function warn(msg) {
27
- warned = true;
28
- console.warn(`[unocss] ${msg}`);
29
- }
30
- if (config.include)
31
- warn("`include` option is deprecated, use `content.pipeline.include` instead.");
32
- if (config.exclude)
33
- warn("`exclude` option is deprecated, use `content.pipeline.exclude` instead.");
34
- if (config.extraContent)
35
- warn("`extraContent` option is deprecated, use `content` instead.");
36
- if (config.content?.plain)
37
- warn("`content.plain` option is renamed to `content.inline`.");
38
- if (warned && typeof process !== "undefined" && process.env.CI)
39
- throw new Error("deprecation warning");
40
- }
41
-
42
- function createContext(configOrPath, defaults = {}, extraConfigSources = [], resolveConfigResult = () => {
43
- }) {
44
- let root = process$1.cwd();
45
- let rawConfig = {};
46
- let configFileList = [];
47
- const uno = createGenerator(rawConfig, defaults);
48
- let rollupFilter = createFilter(
49
- defaultPipelineInclude,
50
- defaultPipelineExclude,
51
- { resolve: typeof configOrPath === "string" ? configOrPath : root }
52
- );
53
- const invalidations = [];
54
- const reloadListeners = [];
55
- const modules = new BetterMap();
56
- const tokens = /* @__PURE__ */ new Set();
57
- const tasks = [];
58
- const affectedModules = /* @__PURE__ */ new Set();
59
- const loadConfig = createRecoveryConfigLoader();
60
- let ready = reloadConfig();
61
- async function reloadConfig() {
62
- const result = await loadConfig(root, configOrPath, extraConfigSources, defaults);
63
- resolveConfigResult(result);
64
- deprecationCheck(result.config);
65
- rawConfig = result.config;
66
- configFileList = result.sources;
67
- uno.setConfig(rawConfig);
68
- uno.config.envMode = "dev";
69
- rollupFilter = rawConfig.content?.pipeline === false ? () => false : createFilter(
70
- rawConfig.content?.pipeline?.include || rawConfig.include || defaultPipelineInclude,
71
- rawConfig.content?.pipeline?.exclude || rawConfig.exclude || defaultPipelineExclude,
72
- { resolve: typeof configOrPath === "string" ? configOrPath : root }
73
- );
74
- tokens.clear();
75
- await Promise.all(modules.map((code, id) => uno.applyExtractors(code.replace(SKIP_COMMENT_RE, ""), id, tokens)));
76
- invalidate();
77
- dispatchReload();
78
- const presets = /* @__PURE__ */ new Set();
79
- uno.config.presets.forEach((i) => {
80
- if (!i.name)
81
- return;
82
- if (presets.has(i.name))
83
- console.warn(`[unocss] duplication of preset ${i.name} found, there might be something wrong with your config.`);
84
- else
85
- presets.add(i.name);
86
- });
87
- return result;
88
- }
89
- async function updateRoot(newRoot) {
90
- if (newRoot !== root) {
91
- root = newRoot;
92
- ready = reloadConfig();
93
- }
94
- return await ready;
95
- }
96
- function invalidate() {
97
- invalidations.forEach((cb) => cb());
98
- }
99
- function dispatchReload() {
100
- reloadListeners.forEach((cb) => cb());
101
- }
102
- async function extract(code, id) {
103
- if (id)
104
- modules.set(id, code);
105
- const len = tokens.size;
106
- await uno.applyExtractors(code.replace(SKIP_COMMENT_RE, ""), id, tokens);
107
- if (tokens.size > len)
108
- invalidate();
109
- }
110
- function filter(code, id) {
111
- if (code.includes(IGNORE_COMMENT))
112
- return false;
113
- return code.includes(INCLUDE_COMMENT) || code.includes(CSS_PLACEHOLDER) || rollupFilter(id.replace(/\?v=\w+$/, ""));
114
- }
115
- async function getConfig() {
116
- await ready;
117
- return rawConfig;
118
- }
119
- async function flushTasks() {
120
- const _tasks = [...tasks];
121
- await Promise.all(_tasks);
122
- if (tasks[0] === _tasks[0])
123
- tasks.splice(0, _tasks.length);
124
- }
125
- return {
126
- get ready() {
127
- return ready;
128
- },
129
- tokens,
130
- modules,
131
- affectedModules,
132
- tasks,
133
- flushTasks,
134
- invalidate,
135
- onInvalidate(fn) {
136
- invalidations.push(fn);
137
- },
138
- filter,
139
- reloadConfig,
140
- onReload(fn) {
141
- reloadListeners.push(fn);
142
- },
143
- uno,
144
- extract,
145
- getConfig,
146
- get root() {
147
- return root;
148
- },
149
- updateRoot,
150
- getConfigFileList: () => configFileList
151
- };
152
- }
153
-
154
- function getPath(id) {
155
- return id.replace(/\?.*$/, "");
156
- }
157
- function isCssId(id) {
158
- return cssIdRE.test(id);
159
- }
160
- function hash(str) {
161
- let i;
162
- let l;
163
- let hval = 2166136261;
164
- for (i = 0, l = str.length; i < l; i++) {
165
- hval ^= str.charCodeAt(i);
166
- hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
167
- }
168
- return `00000${(hval >>> 0).toString(36)}`.slice(-6);
169
- }
170
- function transformSkipCode(code, map, SKIP_RULES_RE, keyFlag) {
171
- for (const item of Array.from(code.matchAll(SKIP_RULES_RE))) {
172
- if (item != null) {
173
- const matched = item[0];
174
- const withHashKey = `${keyFlag}${hash(matched)}`;
175
- map.set(withHashKey, matched);
176
- code = code.replace(matched, withHashKey);
177
- }
178
- }
179
- return code;
180
- }
181
- function restoreSkipCode(code, map) {
182
- for (const [withHashKey, matched] of map.entries())
183
- code = code.replaceAll(withHashKey, matched);
184
- return code;
185
- }
186
-
187
- async function applyTransformers(ctx, original, id, enforce = "default") {
188
- if (original.includes(IGNORE_COMMENT))
189
- return;
190
- const transformers = (ctx.uno.config.transformers || []).filter((i) => (i.enforce || "default") === enforce);
191
- if (!transformers.length)
192
- return;
193
- const skipMap = /* @__PURE__ */ new Map();
194
- let code = original;
195
- let s = new MagicString(transformSkipCode(code, skipMap, SKIP_COMMENT_RE, "@unocss-skip-placeholder-"));
196
- const maps = [];
197
- for (const t of transformers) {
198
- if (t.idFilter) {
199
- if (!t.idFilter(id))
200
- continue;
201
- } else if (!ctx.filter(code, id)) {
202
- continue;
203
- }
204
- await t.transform(s, id, ctx);
205
- if (s.hasChanged()) {
206
- code = restoreSkipCode(s.toString(), skipMap);
207
- maps.push(s.generateMap({ hires: true, source: id }));
208
- s = new MagicString(code);
209
- }
210
- }
211
- if (code !== original) {
212
- return {
213
- code,
214
- map: remapping(maps, (_, ctx2) => {
215
- ctx2.content = code;
216
- return null;
217
- })
218
- };
219
- }
220
- }
221
-
222
- async function setupContentExtractor(ctx, shouldWatch = false) {
223
- const { content } = await ctx.getConfig();
224
- const { extract, tasks, root, filter } = ctx;
225
- if (content?.inline) {
226
- await Promise.all(
227
- content.inline.map(async (c, idx) => {
228
- if (typeof c === "function")
229
- c = await c();
230
- if (typeof c === "string")
231
- c = { code: c };
232
- return extract(c.code, c.id ?? `__plain_content_${idx}__`);
233
- })
234
- );
235
- }
236
- if (content?.filesystem) {
237
- const files = await glob(content.filesystem, { cwd: root, expandDirectories: false });
238
- async function extractFile(file) {
239
- file = isAbsolute(file) ? file : resolve(root, file);
240
- const code = await fs.readFile(file, "utf-8");
241
- if (!filter(code, file))
242
- return;
243
- const preTransform = await applyTransformers(ctx, code, file, "pre");
244
- const defaultTransform = await applyTransformers(ctx, preTransform?.code || code, file);
245
- await applyTransformers(ctx, defaultTransform?.code || preTransform?.code || code, file, "post");
246
- return await extract(preTransform?.code || code, file);
247
- }
248
- if (shouldWatch) {
249
- const { watch } = await import('chokidar');
250
- const ignored = ["**/{.git,node_modules}/**"];
251
- const watcher = watch(files, {
252
- ignorePermissionErrors: true,
253
- ignored,
254
- cwd: root,
255
- ignoreInitial: true
256
- });
257
- watcher.on("all", (type, file) => {
258
- if (type === "add" || type === "change") {
259
- const absolutePath = resolve(root, file);
260
- tasks.push(extractFile(absolutePath));
261
- }
262
- });
263
- }
264
- await Promise.all(files.map(extractFile));
265
- }
266
- }
267
-
268
- function getHash(input, length = 8) {
269
- return createHash("sha256").update(input).digest("hex").slice(0, length);
270
- }
271
-
272
- const VIRTUAL_ENTRY_ALIAS = [
273
- /^(?:virtual:)?uno(?::(.+))?\.css(\?.*)?$/
274
- ];
275
- const LAYER_MARK_ALL = "__ALL__";
276
- const RESOLVED_ID_WITH_QUERY_RE = /[/\\]__uno(_.*?)?\.css(\?.*)?$/;
277
- const RESOLVED_ID_RE = /[/\\]__uno(?:_(.*?))?\.css$/;
278
- function resolveId(id) {
279
- if (id.match(RESOLVED_ID_WITH_QUERY_RE))
280
- return id;
281
- for (const alias of VIRTUAL_ENTRY_ALIAS) {
282
- const match = id.match(alias);
283
- if (match) {
284
- return match[1] ? `/__uno_${match[1]}.css` : "/__uno.css";
285
- }
286
- }
287
- }
288
- function resolveLayer(id) {
289
- const match = id.match(RESOLVED_ID_RE);
290
- if (match)
291
- return match[1] || LAYER_MARK_ALL;
292
- }
293
- const LAYER_PLACEHOLDER_RE = /#--unocss--\s*\{\s*layer\s*:\s*(.+?)\s*(?:;\s*escape-view\s*:\s*(.+?)\s*)?;?\s*\}/g;
294
- function getLayerPlaceholder(layer) {
295
- return `#--unocss--{layer:${layer};escape-view:\\"\\'\\\`\\\\}`;
296
- }
297
- function getCssEscaperForJsContent(view) {
298
- if (!view)
299
- return (css) => css;
300
- const prefix = {};
301
- const escapeViewRe = /(\\*)\\(["'`\\])/g;
302
- view.trim().replace(escapeViewRe, (_, bs, char) => {
303
- prefix[char] = bs.replace(/\\\\/g, "\\");
304
- return "";
305
- });
306
- return (css) => css.replace(/["'`\\]/g, (v) => {
307
- return (prefix[v] || "") + v;
308
- });
309
- }
310
- const HASH_PLACEHOLDER_RE = /#--unocss-hash--\s*\{\s*content\s*:\s*\\*"([^\\"]+)\\*";?\s*\}/g;
311
- function getHashPlaceholder(hash) {
312
- return `#--unocss-hash--{content:"${hash}"}`;
313
- }
314
-
315
- const PLUGIN_NAME = "unocss:webpack";
316
- const UPDATE_DEBOUNCE = 10;
317
- function defineConfig(config) {
318
- return config;
319
- }
320
15
  function WebpackPlugin(configOrPath, defaults) {
321
- return createUnplugin(() => {
322
- const ctx = createContext(configOrPath, {
323
- envMode: process$1.env.NODE_ENV === "development" ? "dev" : "build",
324
- ...defaults
325
- });
326
- const { uno, tokens, filter, extract, onInvalidate, tasks, flushTasks } = ctx;
327
- let timer;
328
- onInvalidate(() => {
329
- clearTimeout(timer);
330
- timer = setTimeout(updateModules, UPDATE_DEBOUNCE);
331
- });
332
- const nonPreTransformers = ctx.uno.config.transformers?.filter((i) => i.enforce !== "pre");
333
- if (nonPreTransformers?.length) {
334
- console.warn(
335
- // eslint-disable-next-line prefer-template
336
- '[unocss] webpack integration only supports "pre" enforce transformers currently.the following transformers will be ignored\n' + nonPreTransformers.map((i) => ` - ${i.name}`).join("\n")
337
- );
338
- }
339
- tasks.push(setupContentExtractor(ctx, typeof configOrPath === "object" && configOrPath?.watch));
340
- const entries = /* @__PURE__ */ new Set();
341
- const hashes = /* @__PURE__ */ new Map();
342
- const plugin = {
343
- name: "unocss:webpack",
344
- enforce: "pre",
345
- transformInclude(id) {
346
- return filter("", id) && !id.endsWith(".html") && !RESOLVED_ID_RE.test(id);
347
- },
348
- async transform(code, id) {
349
- const result = await applyTransformers(ctx, code, id, "pre");
350
- if (isCssId(id))
351
- return result;
352
- if (result == null)
353
- tasks.push(extract(code, id));
354
- else
355
- tasks.push(extract(result.code, id));
356
- return result;
357
- },
358
- resolveId(id) {
359
- const entry = resolveId(id);
360
- if (entry === id)
361
- return;
362
- if (entry) {
363
- let query = "";
364
- const queryIndex = id.indexOf("?");
365
- if (queryIndex >= 0)
366
- query = id.slice(queryIndex);
367
- entries.add(entry);
368
- return entry + query;
369
- }
370
- },
371
- loadInclude(id) {
372
- const layer = getLayer(id);
373
- return !!layer;
374
- },
375
- // serve the placeholders in virtual module
376
- load(id) {
377
- const layer = getLayer(id);
378
- const hash = hashes.get(id);
379
- if (layer)
380
- return (hash ? getHashPlaceholder(hash) : "") + getLayerPlaceholder(layer);
381
- },
382
- webpack(compiler) {
383
- compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
384
- const optimizeAssetsHook = (
385
- /* webpack 5 & 6 */
386
- compilation.hooks.processAssets || /* webpack 4 */
387
- compilation.hooks.optimizeAssets
388
- );
389
- optimizeAssetsHook.tapPromise(PLUGIN_NAME, async () => {
390
- const files = Object.keys(compilation.assets);
391
- await flushTasks();
392
- const result = await uno.generate(tokens, { minify: true });
393
- for (const file of files) {
394
- if (file === "*")
395
- return;
396
- let code = compilation.assets[file].source().toString();
397
- let escapeCss;
398
- let replaced = false;
399
- code = code.replace(HASH_PLACEHOLDER_RE, "");
400
- code = code.replace(LAYER_PLACEHOLDER_RE, (_, layer, escapeView) => {
401
- replaced = true;
402
- const css = layer.trim() === LAYER_MARK_ALL ? result.getLayers(void 0, Array.from(entries).map((i) => resolveLayer(i)).filter((i) => !!i)) : result.getLayer(layer) || "";
403
- escapeCss = escapeCss ?? getCssEscaperForJsContent(escapeView.trim());
404
- return escapeCss(css);
405
- });
406
- if (replaced)
407
- compilation.assets[file] = new WebpackSources.SourceMapSource(code, file, compilation.assets[file].map());
408
- }
409
- });
410
- });
411
- }
412
- };
413
- let lastTokenSize = tokens.size;
414
- async function updateModules() {
415
- if (!plugin.__vfsModules)
416
- return;
417
- await flushTasks();
418
- const result = await uno.generate(tokens);
419
- if (lastTokenSize === tokens.size)
420
- return;
421
- lastTokenSize = tokens.size;
422
- Array.from(plugin.__vfsModules).forEach((id) => {
423
- let path = decodeURIComponent(id.slice(plugin.__virtualModulePrefix.length));
424
- path = normalizeAbsolutePath(path);
425
- const layer = resolveLayer(path);
426
- if (!layer)
427
- return;
428
- const code = layer === LAYER_MARK_ALL ? result.getLayers(void 0, Array.from(entries).map((i) => resolveLayer(i)).filter((i) => !!i)) : result.getLayer(layer) || "";
429
- const hash = getHash(code);
430
- hashes.set(path, hash);
431
- plugin.__vfs.writeModule(id, code);
432
- });
433
- }
434
- return plugin;
435
- }).webpack();
436
- }
437
- function getLayer(id) {
438
- let layer = resolveLayer(getPath(id));
439
- if (!layer) {
440
- const entry = resolveId(id);
441
- if (entry)
442
- layer = resolveLayer(entry);
443
- }
444
- return layer;
445
- }
446
- function normalizeAbsolutePath(path) {
447
- if (isAbsolute(path))
448
- return normalize(path);
449
- else
450
- return path;
16
+ return unplugin(configOrPath, defaults).webpack();
451
17
  }
452
18
 
453
- export { WebpackPlugin as default, defineConfig };
19
+ export { WebpackPlugin as default };
@@ -0,0 +1,21 @@
1
+ 'use strict';
2
+
3
+ const unplugin = require('./shared/webpack.DDjG3x9e.cjs');
4
+ require('node:path');
5
+ require('node:process');
6
+ require('unplugin');
7
+ require('webpack-sources');
8
+ require('node:fs/promises');
9
+ require('tinyglobby');
10
+ require('@ampproject/remapping');
11
+ require('magic-string');
12
+ require('@unocss/core');
13
+ require('@rollup/pluginutils');
14
+ require('@unocss/config');
15
+ require('node:crypto');
16
+
17
+ function UnoCSSRspackPlugin(configOrPath, defaults) {
18
+ return unplugin.unplugin(configOrPath, defaults).rspack();
19
+ }
20
+
21
+ exports.UnoCSSRspackPlugin = UnoCSSRspackPlugin;
@@ -0,0 +1,7 @@
1
+ import { UserConfigDefaults } from '@unocss/core';
2
+ import { WebpackPluginOptions } from './index.cjs';
3
+ import 'webpack';
4
+
5
+ declare function UnoCSSRspackPlugin<Theme extends object>(configOrPath?: WebpackPluginOptions<Theme> | string, defaults?: UserConfigDefaults): RspackPluginInstance;
6
+
7
+ export { UnoCSSRspackPlugin };
@@ -0,0 +1,7 @@
1
+ import { UserConfigDefaults } from '@unocss/core';
2
+ import { WebpackPluginOptions } from './index.mjs';
3
+ import 'webpack';
4
+
5
+ declare function UnoCSSRspackPlugin<Theme extends object>(configOrPath?: WebpackPluginOptions<Theme> | string, defaults?: UserConfigDefaults): RspackPluginInstance;
6
+
7
+ export { UnoCSSRspackPlugin };
@@ -0,0 +1,7 @@
1
+ import { UserConfigDefaults } from '@unocss/core';
2
+ import { WebpackPluginOptions } from './index.js';
3
+ import 'webpack';
4
+
5
+ declare function UnoCSSRspackPlugin<Theme extends object>(configOrPath?: WebpackPluginOptions<Theme> | string, defaults?: UserConfigDefaults): RspackPluginInstance;
6
+
7
+ export { UnoCSSRspackPlugin };
@@ -0,0 +1,19 @@
1
+ import { u as unplugin } from './shared/webpack.B0TbicgL.mjs';
2
+ import 'node:path';
3
+ import 'node:process';
4
+ import 'unplugin';
5
+ import 'webpack-sources';
6
+ import 'node:fs/promises';
7
+ import 'tinyglobby';
8
+ import '@ampproject/remapping';
9
+ import 'magic-string';
10
+ import '@unocss/core';
11
+ import '@rollup/pluginutils';
12
+ import '@unocss/config';
13
+ import 'node:crypto';
14
+
15
+ function UnoCSSRspackPlugin(configOrPath, defaults) {
16
+ return unplugin(configOrPath, defaults).rspack();
17
+ }
18
+
19
+ export { UnoCSSRspackPlugin };