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