@unocss/cli 66.5.10-beta.1 → 66.5.11

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/cli.d.mts CHANGED
@@ -1,2 +1 @@
1
-
2
- export { };
1
+ export { };
package/dist/cli.mjs CHANGED
@@ -1,45 +1,35 @@
1
- import process from 'node:process';
2
- import { loadConfig } from '@unocss/config';
3
- import { toArray } from '@unocss/core';
4
- import { cac } from 'cac';
5
- import { b as build, v as version, h as handleError } from './shared/cli.CXJ6_JxU.mjs';
6
- import 'node:fs';
7
- import 'unplugin-utils';
8
- import '@jridgewell/remapping';
9
- import 'magic-string';
10
- import 'colorette';
11
- import 'consola';
12
- import 'pathe';
13
- import 'perfect-debounce';
14
- import 'tinyglobby';
15
- import '@unocss/preset-uno';
1
+ import { i as version, r as handleError, t as build } from "./src-gL19Lj2z.mjs";
2
+ import process from "node:process";
3
+ import { loadConfig } from "@unocss/config";
4
+ import { toArray } from "@unocss/core";
5
+ import { cac } from "cac";
16
6
 
7
+ //#region src/cli-start.ts
17
8
  async function startCli(cwd = process.cwd(), argv = process.argv, options = {}) {
18
- const cli = cac("unocss");
19
- cli.command("[...patterns]", "Glob patterns", {
20
- ignoreOptionDefaultValue: true
21
- }).option("-o, --out-file <file>", "Output file", {
22
- default: cwd
23
- }).option("--stdout", "Output to STDOUT", {
24
- default: false
25
- }).option("-c, --config [file]", "Config file").option("-w, --watch", "Watch for file changes").option("--write-transformed", "Update source files with transformed utilities", { default: false }).option("--preflights", "Enable preflights", { default: true }).option("-m, --minify", "Minify generated CSS", { default: false }).action(async (patterns, flags) => {
26
- Object.assign(options, {
27
- cwd,
28
- ...flags
29
- });
30
- if (patterns)
31
- options.patterns = patterns;
32
- const { config } = await loadConfig(cwd, options.config);
33
- const entries = toArray(config.cli?.entry || options);
34
- await Promise.all(entries.map((entry) => build({
35
- ...options,
36
- ...entry
37
- })));
38
- });
39
- cli.help();
40
- cli.version(version);
41
- cli.parse(argv, { run: false });
42
- await cli.runMatchedCommand();
9
+ const cli = cac("unocss");
10
+ cli.command("[...patterns]", "Glob patterns", { ignoreOptionDefaultValue: true }).option("-o, --out-file <file>", "Output file", { default: cwd }).option("--stdout", "Output to STDOUT", { default: false }).option("-c, --config [file]", "Config file").option("-w, --watch", "Watch for file changes").option("--write-transformed", "Update source files with transformed utilities", { default: false }).option("--preflights", "Enable preflights", { default: true }).option("-m, --minify", "Minify generated CSS", { default: false }).action(async (patterns, flags) => {
11
+ var _config$cli;
12
+ Object.assign(options, {
13
+ cwd,
14
+ ...flags
15
+ });
16
+ if (patterns) options.patterns = patterns;
17
+ const { config } = await loadConfig(cwd, options.config);
18
+ const entries = toArray(((_config$cli = config.cli) === null || _config$cli === void 0 ? void 0 : _config$cli.entry) || options);
19
+ await Promise.all(entries.map((entry) => build({
20
+ ...options,
21
+ ...entry
22
+ })));
23
+ });
24
+ cli.help();
25
+ cli.version(version);
26
+ cli.parse(argv, { run: false });
27
+ await cli.runMatchedCommand();
43
28
  }
44
29
 
30
+ //#endregion
31
+ //#region src/cli.ts
45
32
  startCli().catch(handleError);
33
+
34
+ //#endregion
35
+ export { };
package/dist/index.d.mts CHANGED
@@ -1,19 +1,21 @@
1
+ //#region src/types.d.ts
1
2
  /** Mark some properties as required, leaving others unchanged */
2
3
  declare type MarkRequired<T, RK extends keyof T> = Exclude<T, RK> & Required<Pick<T, RK>>;
3
4
  interface CliOptions {
4
- cwd?: string;
5
- patterns?: Array<string>;
6
- outFile?: string;
7
- watch?: boolean;
8
- config?: string;
9
- stdout?: boolean;
10
- writeTransformed?: boolean;
11
- preflights?: boolean;
12
- minify?: boolean;
5
+ cwd?: string;
6
+ patterns?: Array<string>;
7
+ outFile?: string;
8
+ watch?: boolean;
9
+ config?: string;
10
+ stdout?: boolean;
11
+ writeTransformed?: boolean;
12
+ preflights?: boolean;
13
+ minify?: boolean;
13
14
  }
14
15
  type ResolvedCliOptions = MarkRequired<CliOptions, 'patterns'>;
15
-
16
+ //#endregion
17
+ //#region src/index.d.ts
16
18
  declare function resolveOptions(options: CliOptions): Promise<ResolvedCliOptions>;
17
19
  declare function build(_options: CliOptions): Promise<void>;
18
-
19
- export { build, resolveOptions };
20
+ //#endregion
21
+ export { build, resolveOptions };
package/dist/index.mjs CHANGED
@@ -1,14 +1,3 @@
1
- import 'node:fs';
2
- import 'node:process';
3
- export { b as build, r as resolveOptions } from './shared/cli.CXJ6_JxU.mjs';
4
- import '@unocss/core';
5
- import 'colorette';
6
- import 'consola';
7
- import 'pathe';
8
- import 'perfect-debounce';
9
- import 'tinyglobby';
10
- import '@unocss/config';
11
- import 'unplugin-utils';
12
- import '@jridgewell/remapping';
13
- import 'magic-string';
14
- import '@unocss/preset-uno';
1
+ import { n as resolveOptions, t as build } from "./src-gL19Lj2z.mjs";
2
+
3
+ export { build, resolveOptions };
@@ -0,0 +1,364 @@
1
+ import { existsSync, promises } from "node:fs";
2
+ import process from "node:process";
3
+ import { createRecoveryConfigLoader } from "@unocss/config";
4
+ import { BetterMap, createGenerator, cssIdRE, toArray } from "@unocss/core";
5
+ import { createFilter } from "unplugin-utils";
6
+ import remapping from "@jridgewell/remapping";
7
+ import MagicString from "magic-string";
8
+ import { cyan, dim, green } from "colorette";
9
+ import { consola } from "consola";
10
+ import { basename, dirname, normalize, relative, resolve } from "pathe";
11
+ import { debounce } from "perfect-debounce";
12
+ import { glob } from "tinyglobby";
13
+ import presetUno from "@unocss/preset-uno";
14
+
15
+ //#region ../../virtual-shared/integration/src/constants.ts
16
+ const INCLUDE_COMMENT = "@unocss-include";
17
+ const IGNORE_COMMENT = "@unocss-ignore";
18
+ const CSS_PLACEHOLDER = "@unocss-placeholder";
19
+ const SKIP_START_COMMENT = "@unocss-skip-start";
20
+ const SKIP_END_COMMENT = "@unocss-skip-end";
21
+ 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");
22
+
23
+ //#endregion
24
+ //#region ../../virtual-shared/integration/src/defaults.ts
25
+ const defaultPipelineExclude = [cssIdRE];
26
+ const defaultPipelineInclude = [/\.(vue|svelte|[jt]sx|vine.ts|mdx?|astro|elm|php|phtml|marko|html)($|\?)/];
27
+
28
+ //#endregion
29
+ //#region ../../virtual-shared/integration/src/deprecation.ts
30
+ function deprecationCheck(config) {}
31
+
32
+ //#endregion
33
+ //#region ../../virtual-shared/integration/src/context.ts
34
+ function createContext(configOrPath, defaults = {}, extraConfigSources = [], resolveConfigResult = () => {}) {
35
+ let root = process.cwd();
36
+ let rawConfig = {};
37
+ let configFileList = [];
38
+ let uno;
39
+ const _uno = createGenerator(rawConfig, defaults).then((r) => {
40
+ uno = r;
41
+ return r;
42
+ });
43
+ let rollupFilter = createFilter(defaultPipelineInclude, defaultPipelineExclude, { resolve: typeof configOrPath === "string" ? configOrPath : root });
44
+ const invalidations = [];
45
+ const reloadListeners = [];
46
+ const modules = new BetterMap();
47
+ const tokens = /* @__PURE__ */ new Set();
48
+ const tasks = [];
49
+ const affectedModules = /* @__PURE__ */ new Set();
50
+ const loadConfig$1 = createRecoveryConfigLoader();
51
+ let ready = reloadConfig();
52
+ async function reloadConfig() {
53
+ var _rawConfig$content, _rawConfig$content2, _rawConfig$content3;
54
+ await _uno;
55
+ const result = await loadConfig$1(root, configOrPath, extraConfigSources, defaults);
56
+ resolveConfigResult(result);
57
+ /* @__PURE__ */ deprecationCheck(result.config);
58
+ rawConfig = result.config;
59
+ configFileList = result.sources;
60
+ await uno.setConfig(rawConfig);
61
+ uno.config.envMode = "dev";
62
+ rollupFilter = ((_rawConfig$content = rawConfig.content) === null || _rawConfig$content === void 0 ? void 0 : _rawConfig$content.pipeline) === false ? () => false : createFilter(((_rawConfig$content2 = rawConfig.content) === null || _rawConfig$content2 === void 0 || (_rawConfig$content2 = _rawConfig$content2.pipeline) === null || _rawConfig$content2 === void 0 ? void 0 : _rawConfig$content2.include) || defaultPipelineInclude, ((_rawConfig$content3 = rawConfig.content) === null || _rawConfig$content3 === void 0 || (_rawConfig$content3 = _rawConfig$content3.pipeline) === null || _rawConfig$content3 === void 0 ? void 0 : _rawConfig$content3.exclude) || defaultPipelineExclude, { resolve: typeof configOrPath === "string" ? configOrPath : root });
63
+ tokens.clear();
64
+ await Promise.all(modules.map((code, id) => uno.applyExtractors(code.replace(SKIP_COMMENT_RE, ""), id, tokens)));
65
+ invalidate();
66
+ dispatchReload();
67
+ return result;
68
+ }
69
+ async function updateRoot(newRoot) {
70
+ if (newRoot !== root) {
71
+ root = newRoot;
72
+ ready = reloadConfig();
73
+ }
74
+ return await ready;
75
+ }
76
+ function invalidate() {
77
+ invalidations.forEach((cb) => cb());
78
+ }
79
+ function dispatchReload() {
80
+ reloadListeners.forEach((cb) => cb());
81
+ }
82
+ async function extract(code, id) {
83
+ const uno$1 = await _uno;
84
+ if (id) modules.set(id, code);
85
+ const len = tokens.size;
86
+ await uno$1.applyExtractors(code.replace(SKIP_COMMENT_RE, ""), id, tokens);
87
+ if (tokens.size > len) invalidate();
88
+ }
89
+ function filter(code, id) {
90
+ if (code.includes(IGNORE_COMMENT)) return false;
91
+ return code.includes(INCLUDE_COMMENT) || code.includes(CSS_PLACEHOLDER) || rollupFilter(id.replace(/\?v=\w+$/, ""));
92
+ }
93
+ async function getConfig() {
94
+ await ready;
95
+ return rawConfig;
96
+ }
97
+ async function flushTasks() {
98
+ const _tasks = [...tasks];
99
+ await Promise.all(_tasks);
100
+ if (tasks[0] === _tasks[0]) tasks.splice(0, _tasks.length);
101
+ }
102
+ /**
103
+ * Get regexes to match virtual module ids
104
+ */
105
+ const vmpCache = /* @__PURE__ */ new Map();
106
+ async function getVMPRegexes() {
107
+ const prefix = (await getConfig()).virtualModulePrefix || "__uno";
108
+ if (vmpCache.has(prefix)) return vmpCache.get(prefix);
109
+ const regexes = {
110
+ prefix,
111
+ RESOLVED_ID_WITH_QUERY_RE: /* @__PURE__ */ new RegExp(`[/\\\\]${prefix}(_.*?)?\\.css(\\?.*)?$`),
112
+ RESOLVED_ID_RE: /* @__PURE__ */ new RegExp(`[/\\\\]${prefix}(?:_(.*?))?\.css$`)
113
+ };
114
+ vmpCache.set(prefix, regexes);
115
+ return regexes;
116
+ }
117
+ return {
118
+ get ready() {
119
+ return ready;
120
+ },
121
+ tokens,
122
+ modules,
123
+ affectedModules,
124
+ tasks,
125
+ flushTasks,
126
+ invalidate,
127
+ onInvalidate(fn) {
128
+ invalidations.push(fn);
129
+ },
130
+ filter,
131
+ reloadConfig,
132
+ onReload(fn) {
133
+ reloadListeners.push(fn);
134
+ },
135
+ get uno() {
136
+ if (!uno) throw new Error("Run `await context.ready` before accessing `context.uno`");
137
+ return uno;
138
+ },
139
+ extract,
140
+ getConfig,
141
+ get root() {
142
+ return root;
143
+ },
144
+ updateRoot,
145
+ getConfigFileList: () => configFileList,
146
+ getVMPRegexes
147
+ };
148
+ }
149
+
150
+ //#endregion
151
+ //#region ../../virtual-shared/integration/src/utils.ts
152
+ function hash(str) {
153
+ let i;
154
+ let l;
155
+ let hval = 2166136261;
156
+ for (i = 0, l = str.length; i < l; i++) {
157
+ hval ^= str.charCodeAt(i);
158
+ hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
159
+ }
160
+ return `00000${(hval >>> 0).toString(36)}`.slice(-6);
161
+ }
162
+ function transformSkipCode(code, map, SKIP_RULES_RE, keyFlag) {
163
+ for (const item of Array.from(code.matchAll(SKIP_RULES_RE))) if (item != null) {
164
+ const matched = item[0];
165
+ const withHashKey = `${keyFlag}${hash(matched)}`;
166
+ map.set(withHashKey, matched);
167
+ code = code.replace(matched, withHashKey);
168
+ }
169
+ return code;
170
+ }
171
+ function restoreSkipCode(code, map) {
172
+ for (const [withHashKey, matched] of map.entries()) code = code.replaceAll(withHashKey, matched);
173
+ return code;
174
+ }
175
+
176
+ //#endregion
177
+ //#region ../../virtual-shared/integration/src/transformers.ts
178
+ async function applyTransformers(ctx, original, id, enforce = "default") {
179
+ if (original.includes(IGNORE_COMMENT)) return;
180
+ const transformers = (ctx.uno.config.transformers || []).filter((i) => (i.enforce || "default") === enforce);
181
+ if (!transformers.length) return;
182
+ const skipMap = /* @__PURE__ */ new Map();
183
+ let code = original;
184
+ let s = new MagicString(transformSkipCode(code, skipMap, SKIP_COMMENT_RE, "@unocss-skip-placeholder-"));
185
+ const maps = [];
186
+ for (const t of transformers) {
187
+ if (t.idFilter) {
188
+ if (!t.idFilter(id)) continue;
189
+ } else if (!ctx.filter(code, id)) continue;
190
+ await t.transform(s, id, ctx);
191
+ if (s.hasChanged()) {
192
+ code = restoreSkipCode(s.toString(), skipMap);
193
+ maps.push(s.generateMap({
194
+ hires: true,
195
+ source: id
196
+ }));
197
+ s = new MagicString(code);
198
+ }
199
+ }
200
+ if (code !== original) return {
201
+ code,
202
+ map: remapping(maps, (_, ctx$1) => {
203
+ ctx$1.content = code;
204
+ return null;
205
+ })
206
+ };
207
+ }
208
+
209
+ //#endregion
210
+ //#region package.json
211
+ var version = "66.5.11";
212
+
213
+ //#endregion
214
+ //#region src/config.ts
215
+ const defaultConfig = {
216
+ envMode: "build",
217
+ presets: [presetUno()]
218
+ };
219
+
220
+ //#endregion
221
+ //#region src/errors.ts
222
+ var PrettyError = class extends Error {
223
+ constructor(message) {
224
+ super(message);
225
+ this.name = this.constructor.name;
226
+ if (typeof Error.captureStackTrace === "function") Error.captureStackTrace(this, this.constructor);
227
+ else this.stack = new Error(message).stack;
228
+ }
229
+ };
230
+ function handleError(error) {
231
+ if (error instanceof PrettyError) consola.error(error.message);
232
+ process.exitCode = 1;
233
+ }
234
+
235
+ //#endregion
236
+ //#region src/watcher.ts
237
+ let watcher;
238
+ async function getWatcher(options) {
239
+ if (watcher && !options) return watcher;
240
+ const { watch } = await import("chokidar");
241
+ const ignored = ["**/{.git,node_modules}/**"];
242
+ const cwd = (options === null || options === void 0 ? void 0 : options.cwd) || process.cwd();
243
+ const newWatcher = watch((options === null || options === void 0 ? void 0 : options.patterns).map((p) => {
244
+ const abs = resolve(cwd, p);
245
+ if (abs.endsWith("/**/*")) return abs.slice(0, -5);
246
+ return abs;
247
+ }), {
248
+ ignoreInitial: false,
249
+ ignorePermissionErrors: true,
250
+ ignored,
251
+ usePolling: true,
252
+ interval: 100
253
+ });
254
+ watcher = newWatcher;
255
+ return newWatcher;
256
+ }
257
+
258
+ //#endregion
259
+ //#region src/index.ts
260
+ const name = "unocss";
261
+ async function resolveOptions(options) {
262
+ var _options$patterns;
263
+ if (!((_options$patterns = options.patterns) === null || _options$patterns === void 0 ? void 0 : _options$patterns.length)) throw new PrettyError(`No glob patterns, try ${cyan(`${name} <path/to/**/*>`)}`);
264
+ return options;
265
+ }
266
+ async function build(_options) {
267
+ const fileCache = /* @__PURE__ */ new Map();
268
+ const cwd = _options.cwd || process.cwd();
269
+ const options = await resolveOptions(_options);
270
+ async function loadConfig$1() {
271
+ const ctx$1 = createContext(options.config, defaultConfig);
272
+ return {
273
+ ctx: ctx$1,
274
+ configSources: (await ctx$1.updateRoot(cwd)).sources.map((i) => normalize(i))
275
+ };
276
+ }
277
+ const { ctx, configSources } = await loadConfig$1();
278
+ const files = await glob(options.patterns, {
279
+ cwd,
280
+ absolute: true,
281
+ expandDirectories: false
282
+ });
283
+ await Promise.all(files.map(async (file) => {
284
+ fileCache.set(file, await promises.readFile(file, "utf8"));
285
+ }));
286
+ if (options.stdout && options.outFile) {
287
+ consola.fatal(`Cannot use --stdout and --out-file at the same time`);
288
+ return;
289
+ }
290
+ consola.log(green(`${name} v${version}`));
291
+ if (options.watch) consola.start("UnoCSS in watch mode...");
292
+ else consola.start("UnoCSS for production...");
293
+ const debouncedBuild = debounce(async () => {
294
+ generate(options).catch(handleError);
295
+ }, 100);
296
+ const startWatcher = async () => {
297
+ if (!options.watch) return;
298
+ const { patterns } = options;
299
+ const watcher$1 = await getWatcher(options);
300
+ if (configSources.length) watcher$1.add(configSources);
301
+ watcher$1.on("all", async (type, file) => {
302
+ const absolutePath = resolve(cwd, file);
303
+ if (type === "addDir" || type === "unlinkDir") return;
304
+ if (configSources.includes(absolutePath)) {
305
+ await ctx.reloadConfig();
306
+ if (configSources.length) watcher$1.add(configSources);
307
+ consola.info(`${cyan(basename(file))} changed, setting new config`);
308
+ } else {
309
+ consola.log(`${green(type)} ${dim(file)}`);
310
+ if (type.startsWith("unlink")) fileCache.delete(absolutePath);
311
+ else fileCache.set(absolutePath, await promises.readFile(absolutePath, "utf8"));
312
+ }
313
+ debouncedBuild();
314
+ });
315
+ consola.info(`Watching for changes in ${toArray(patterns).map((i) => cyan(i)).join(", ")}`);
316
+ };
317
+ await generate(options);
318
+ await startWatcher().catch(handleError);
319
+ function transformFiles(sources, enforce = "default") {
320
+ return Promise.all(sources.map(({ id, code, transformedCode }) => new Promise((resolve$1) => {
321
+ applyTransformers(ctx, code, id, enforce).then((transformsRes) => {
322
+ resolve$1({
323
+ id,
324
+ code,
325
+ transformedCode: (transformsRes === null || transformsRes === void 0 ? void 0 : transformsRes.code) || transformedCode
326
+ });
327
+ });
328
+ })));
329
+ }
330
+ async function generate(options$1) {
331
+ const afterPostTrans = await transformFiles(await transformFiles(await transformFiles(Array.from(fileCache).map(([id, code]) => ({
332
+ id,
333
+ code
334
+ })), "pre")), "post");
335
+ if (options$1.writeTransformed) await Promise.all(afterPostTrans.filter(({ transformedCode }) => !!transformedCode).map(async ({ transformedCode, id }) => {
336
+ if (existsSync(id)) await promises.writeFile(id, transformedCode, "utf-8");
337
+ }));
338
+ const tokens = /* @__PURE__ */ new Set();
339
+ for (const file of afterPostTrans) {
340
+ const { matched: matched$1 } = await ctx.uno.generate((file.transformedCode || file.code).replace(SKIP_COMMENT_RE, ""), {
341
+ preflights: false,
342
+ minify: true,
343
+ id: file.id
344
+ });
345
+ matched$1.forEach((i) => tokens.add(i));
346
+ }
347
+ const { css, matched } = await ctx.uno.generate(tokens, {
348
+ preflights: options$1.preflights,
349
+ minify: options$1.minify
350
+ });
351
+ if (options$1.stdout) {
352
+ process.stdout.write(css);
353
+ return;
354
+ }
355
+ const outFile = resolve(options$1.cwd || process.cwd(), options$1.outFile ?? "uno.css");
356
+ const dir = dirname(outFile);
357
+ if (!existsSync(dir)) await promises.mkdir(dir, { recursive: true });
358
+ await promises.writeFile(outFile, css, "utf-8");
359
+ if (!options$1.watch) consola.success(`${[...matched].length} utilities generated to ${cyan(relative(process.cwd(), outFile))}\n`);
360
+ }
361
+ }
362
+
363
+ //#endregion
364
+ export { version as i, resolveOptions as n, handleError as r, build as t };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unocss/cli",
3
3
  "type": "module",
4
- "version": "66.5.10-beta.1",
4
+ "version": "66.5.11",
5
5
  "description": "CLI for UnoCSS",
6
6
  "author": {
7
7
  "name": "Johann Schopplich",
@@ -42,20 +42,20 @@
42
42
  "dependencies": {
43
43
  "@jridgewell/remapping": "^2.3.5",
44
44
  "cac": "^6.7.14",
45
- "chokidar": "^3.6.0",
45
+ "chokidar": "^5.0.0",
46
46
  "colorette": "^2.0.20",
47
47
  "consola": "^3.4.2",
48
48
  "magic-string": "^0.30.21",
49
49
  "pathe": "^2.0.3",
50
- "perfect-debounce": "^1.0.0",
50
+ "perfect-debounce": "^2.0.0",
51
51
  "tinyglobby": "^0.2.15",
52
52
  "unplugin-utils": "^0.3.1",
53
- "@unocss/core": "66.5.10-beta.1",
54
- "@unocss/preset-uno": "66.5.10-beta.1",
55
- "@unocss/config": "66.5.10-beta.1"
53
+ "@unocss/config": "66.5.11",
54
+ "@unocss/core": "66.5.11",
55
+ "@unocss/preset-uno": "66.5.11"
56
56
  },
57
57
  "scripts": {
58
- "build": "unbuild",
59
- "stub": "unbuild --stub"
58
+ "build": "tsdown --config-loader unrun",
59
+ "dev": "tsdown --config-loader unrun --watch"
60
60
  }
61
61
  }
package/dist/cli.d.ts DELETED
@@ -1,2 +0,0 @@
1
-
2
- export { };
package/dist/index.d.ts DELETED
@@ -1,19 +0,0 @@
1
- /** Mark some properties as required, leaving others unchanged */
2
- declare type MarkRequired<T, RK extends keyof T> = Exclude<T, RK> & Required<Pick<T, RK>>;
3
- interface CliOptions {
4
- cwd?: string;
5
- patterns?: Array<string>;
6
- outFile?: string;
7
- watch?: boolean;
8
- config?: string;
9
- stdout?: boolean;
10
- writeTransformed?: boolean;
11
- preflights?: boolean;
12
- minify?: boolean;
13
- }
14
- type ResolvedCliOptions = MarkRequired<CliOptions, 'patterns'>;
15
-
16
- declare function resolveOptions(options: CliOptions): Promise<ResolvedCliOptions>;
17
- declare function build(_options: CliOptions): Promise<void>;
18
-
19
- export { build, resolveOptions };
@@ -1,392 +0,0 @@
1
- import { promises, existsSync } from 'node:fs';
2
- import process from 'node:process';
3
- import { createRecoveryConfigLoader } from '@unocss/config';
4
- import { cssIdRE, createGenerator, BetterMap, toArray } from '@unocss/core';
5
- import { createFilter } from 'unplugin-utils';
6
- import remapping from '@jridgewell/remapping';
7
- import MagicString from 'magic-string';
8
- import { green, cyan, dim } from 'colorette';
9
- import { consola } from 'consola';
10
- import { resolve, dirname, relative, normalize, basename } from 'pathe';
11
- import { debounce } from 'perfect-debounce';
12
- import { glob } from 'tinyglobby';
13
- import presetUno from '@unocss/preset-uno';
14
-
15
- const INCLUDE_COMMENT = "@unocss-include";
16
- const IGNORE_COMMENT = "@unocss-ignore";
17
- const CSS_PLACEHOLDER = "@unocss-placeholder";
18
- const SKIP_START_COMMENT = "@unocss-skip-start";
19
- const SKIP_END_COMMENT = "@unocss-skip-end";
20
- 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");
21
-
22
- const defaultPipelineExclude = [cssIdRE];
23
- const defaultPipelineInclude = [/\.(vue|svelte|[jt]sx|vine.ts|mdx?|astro|elm|php|phtml|marko|html)($|\?)/];
24
-
25
- function deprecationCheck(config) {
26
- }
27
-
28
- function createContext(configOrPath, defaults = {}, extraConfigSources = [], resolveConfigResult = () => {
29
- }) {
30
- let root = process.cwd();
31
- let rawConfig = {};
32
- let configFileList = [];
33
- let uno;
34
- const _uno = createGenerator(rawConfig, defaults).then((r) => {
35
- uno = r;
36
- return r;
37
- });
38
- let rollupFilter = createFilter(
39
- defaultPipelineInclude,
40
- defaultPipelineExclude,
41
- { resolve: typeof configOrPath === "string" ? configOrPath : root }
42
- );
43
- const invalidations = [];
44
- const reloadListeners = [];
45
- const modules = new BetterMap();
46
- const tokens = /* @__PURE__ */ new Set();
47
- const tasks = [];
48
- const affectedModules = /* @__PURE__ */ new Set();
49
- const loadConfig = createRecoveryConfigLoader();
50
- let ready = reloadConfig();
51
- async function reloadConfig() {
52
- await _uno;
53
- const result = await loadConfig(root, configOrPath, extraConfigSources, defaults);
54
- resolveConfigResult(result);
55
- deprecationCheck(result.config);
56
- rawConfig = result.config;
57
- configFileList = result.sources;
58
- await uno.setConfig(rawConfig);
59
- uno.config.envMode = "dev";
60
- rollupFilter = rawConfig.content?.pipeline === false ? () => false : createFilter(
61
- rawConfig.content?.pipeline?.include || defaultPipelineInclude,
62
- rawConfig.content?.pipeline?.exclude || defaultPipelineExclude,
63
- { resolve: typeof configOrPath === "string" ? configOrPath : root }
64
- );
65
- tokens.clear();
66
- await Promise.all(modules.map((code, id) => uno.applyExtractors(code.replace(SKIP_COMMENT_RE, ""), id, tokens)));
67
- invalidate();
68
- dispatchReload();
69
- return result;
70
- }
71
- async function updateRoot(newRoot) {
72
- if (newRoot !== root) {
73
- root = newRoot;
74
- ready = reloadConfig();
75
- }
76
- return await ready;
77
- }
78
- function invalidate() {
79
- invalidations.forEach((cb) => cb());
80
- }
81
- function dispatchReload() {
82
- reloadListeners.forEach((cb) => cb());
83
- }
84
- async function extract(code, id) {
85
- const uno2 = await _uno;
86
- if (id)
87
- modules.set(id, code);
88
- const len = tokens.size;
89
- await uno2.applyExtractors(code.replace(SKIP_COMMENT_RE, ""), id, tokens);
90
- if (tokens.size > len)
91
- invalidate();
92
- }
93
- function filter(code, id) {
94
- if (code.includes(IGNORE_COMMENT))
95
- return false;
96
- return code.includes(INCLUDE_COMMENT) || code.includes(CSS_PLACEHOLDER) || rollupFilter(id.replace(/\?v=\w+$/, ""));
97
- }
98
- async function getConfig() {
99
- await ready;
100
- return rawConfig;
101
- }
102
- async function flushTasks() {
103
- const _tasks = [...tasks];
104
- await Promise.all(_tasks);
105
- if (tasks[0] === _tasks[0])
106
- tasks.splice(0, _tasks.length);
107
- }
108
- const vmpCache = /* @__PURE__ */ new Map();
109
- async function getVMPRegexes() {
110
- const config = await getConfig();
111
- const prefix = config.virtualModulePrefix || "__uno";
112
- if (vmpCache.has(prefix))
113
- return vmpCache.get(prefix);
114
- const RESOLVED_ID_WITH_QUERY_RE = new RegExp(`[/\\\\]${prefix}(_.*?)?\\.css(\\?.*)?$`);
115
- const RESOLVED_ID_RE = new RegExp(`[/\\\\]${prefix}(?:_(.*?))?.css$`);
116
- const regexes = {
117
- prefix,
118
- RESOLVED_ID_WITH_QUERY_RE,
119
- RESOLVED_ID_RE
120
- };
121
- vmpCache.set(prefix, regexes);
122
- return regexes;
123
- }
124
- return {
125
- get ready() {
126
- return ready;
127
- },
128
- tokens,
129
- modules,
130
- affectedModules,
131
- tasks,
132
- flushTasks,
133
- invalidate,
134
- onInvalidate(fn) {
135
- invalidations.push(fn);
136
- },
137
- filter,
138
- reloadConfig,
139
- onReload(fn) {
140
- reloadListeners.push(fn);
141
- },
142
- get uno() {
143
- if (!uno)
144
- throw new Error("Run `await context.ready` before accessing `context.uno`");
145
- return uno;
146
- },
147
- extract,
148
- getConfig,
149
- get root() {
150
- return root;
151
- },
152
- updateRoot,
153
- getConfigFileList: () => configFileList,
154
- getVMPRegexes
155
- };
156
- }
157
-
158
- function hash(str) {
159
- let i;
160
- let l;
161
- let hval = 2166136261;
162
- for (i = 0, l = str.length; i < l; i++) {
163
- hval ^= str.charCodeAt(i);
164
- hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
165
- }
166
- return `00000${(hval >>> 0).toString(36)}`.slice(-6);
167
- }
168
- function transformSkipCode(code, map, SKIP_RULES_RE, keyFlag) {
169
- for (const item of Array.from(code.matchAll(SKIP_RULES_RE))) {
170
- if (item != null) {
171
- const matched = item[0];
172
- const withHashKey = `${keyFlag}${hash(matched)}`;
173
- map.set(withHashKey, matched);
174
- code = code.replace(matched, withHashKey);
175
- }
176
- }
177
- return code;
178
- }
179
- function restoreSkipCode(code, map) {
180
- for (const [withHashKey, matched] of map.entries())
181
- code = code.replaceAll(withHashKey, matched);
182
- return code;
183
- }
184
-
185
- async function applyTransformers(ctx, original, id, enforce = "default") {
186
- if (original.includes(IGNORE_COMMENT))
187
- return;
188
- const transformers = (ctx.uno.config.transformers || []).filter((i) => (i.enforce || "default") === enforce);
189
- if (!transformers.length)
190
- return;
191
- const skipMap = /* @__PURE__ */ new Map();
192
- let code = original;
193
- let s = new MagicString(transformSkipCode(code, skipMap, SKIP_COMMENT_RE, "@unocss-skip-placeholder-"));
194
- const maps = [];
195
- for (const t of transformers) {
196
- if (t.idFilter) {
197
- if (!t.idFilter(id))
198
- continue;
199
- } else if (!ctx.filter(code, id)) {
200
- continue;
201
- }
202
- await t.transform(s, id, ctx);
203
- if (s.hasChanged()) {
204
- code = restoreSkipCode(s.toString(), skipMap);
205
- maps.push(s.generateMap({ hires: true, source: id }));
206
- s = new MagicString(code);
207
- }
208
- }
209
- if (code !== original) {
210
- return {
211
- code,
212
- map: remapping(maps, (_, ctx2) => {
213
- ctx2.content = code;
214
- return null;
215
- })
216
- };
217
- }
218
- }
219
-
220
- const version = "66.5.10-beta.1";
221
-
222
- const defaultConfig = {
223
- envMode: "build",
224
- presets: [
225
- // TODO: Remove the default presets to make engine more agnostic
226
- presetUno()
227
- ]
228
- };
229
-
230
- class PrettyError extends Error {
231
- constructor(message) {
232
- super(message);
233
- this.name = this.constructor.name;
234
- if (typeof Error.captureStackTrace === "function")
235
- Error.captureStackTrace(this, this.constructor);
236
- else
237
- this.stack = new Error(message).stack;
238
- }
239
- }
240
- function handleError(error) {
241
- if (error instanceof PrettyError)
242
- consola.error(error.message);
243
- process.exitCode = 1;
244
- }
245
-
246
- let watcher;
247
- async function getWatcher(options) {
248
- if (watcher && !options)
249
- return watcher;
250
- const { watch } = await import('chokidar');
251
- const ignored = ["**/{.git,node_modules}/**"];
252
- const newWatcher = watch(options?.patterns, {
253
- ignoreInitial: true,
254
- ignorePermissionErrors: true,
255
- ignored,
256
- cwd: options?.cwd || process.cwd()
257
- });
258
- watcher = newWatcher;
259
- return newWatcher;
260
- }
261
-
262
- const name = "unocss";
263
- async function resolveOptions(options) {
264
- if (!options.patterns?.length) {
265
- throw new PrettyError(
266
- `No glob patterns, try ${cyan(`${name} <path/to/**/*>`)}`
267
- );
268
- }
269
- return options;
270
- }
271
- async function build(_options) {
272
- const fileCache = /* @__PURE__ */ new Map();
273
- const cwd = _options.cwd || process.cwd();
274
- const options = await resolveOptions(_options);
275
- async function loadConfig() {
276
- const ctx2 = createContext(options.config, defaultConfig);
277
- const configSources2 = (await ctx2.updateRoot(cwd)).sources.map((i) => normalize(i));
278
- return { ctx: ctx2, configSources: configSources2 };
279
- }
280
- const { ctx, configSources } = await loadConfig();
281
- const files = await glob(options.patterns, { cwd, absolute: true, expandDirectories: false });
282
- await Promise.all(
283
- files.map(async (file) => {
284
- fileCache.set(file, await promises.readFile(file, "utf8"));
285
- })
286
- );
287
- if (options.stdout && options.outFile) {
288
- consola.fatal(`Cannot use --stdout and --out-file at the same time`);
289
- return;
290
- }
291
- consola.log(green(`${name} v${version}`));
292
- if (options.watch)
293
- consola.start("UnoCSS in watch mode...");
294
- else
295
- consola.start("UnoCSS for production...");
296
- const debouncedBuild = debounce(
297
- async () => {
298
- generate(options).catch(handleError);
299
- },
300
- 100
301
- );
302
- const startWatcher = async () => {
303
- if (!options.watch)
304
- return;
305
- const { patterns } = options;
306
- const watcher = await getWatcher(options);
307
- if (configSources.length)
308
- watcher.add(configSources);
309
- watcher.on("all", async (type, file) => {
310
- const absolutePath = resolve(cwd, file);
311
- if (configSources.includes(absolutePath)) {
312
- await ctx.reloadConfig();
313
- if (configSources.length)
314
- watcher.add(configSources);
315
- consola.info(`${cyan(basename(file))} changed, setting new config`);
316
- } else {
317
- consola.log(`${green(type)} ${dim(file)}`);
318
- if (type.startsWith("unlink"))
319
- fileCache.delete(absolutePath);
320
- else
321
- fileCache.set(absolutePath, await promises.readFile(absolutePath, "utf8"));
322
- }
323
- debouncedBuild();
324
- });
325
- consola.info(
326
- `Watching for changes in ${toArray(patterns).map((i) => cyan(i)).join(", ")}`
327
- );
328
- };
329
- await generate(options);
330
- await startWatcher().catch(handleError);
331
- function transformFiles(sources, enforce = "default") {
332
- return Promise.all(
333
- sources.map(({ id, code, transformedCode }) => new Promise((resolve2) => {
334
- applyTransformers(ctx, code, id, enforce).then((transformsRes) => {
335
- resolve2({ id, code, transformedCode: transformsRes?.code || transformedCode });
336
- });
337
- }))
338
- );
339
- }
340
- async function generate(options2) {
341
- const sourceCache = Array.from(fileCache).map(([id, code]) => ({ id, code }));
342
- const afterPreTrans = await transformFiles(sourceCache, "pre");
343
- const afterDefaultTrans = await transformFiles(afterPreTrans);
344
- const afterPostTrans = await transformFiles(afterDefaultTrans, "post");
345
- if (options2.writeTransformed) {
346
- await Promise.all(
347
- afterPostTrans.filter(({ transformedCode }) => !!transformedCode).map(async ({ transformedCode, id }) => {
348
- if (existsSync(id))
349
- await promises.writeFile(id, transformedCode, "utf-8");
350
- })
351
- );
352
- }
353
- const tokens = /* @__PURE__ */ new Set();
354
- for (const file of afterPostTrans) {
355
- const { matched: matched2 } = await ctx.uno.generate(
356
- (file.transformedCode || file.code).replace(SKIP_COMMENT_RE, ""),
357
- {
358
- preflights: false,
359
- minify: true,
360
- id: file.id
361
- }
362
- );
363
- matched2.forEach((i) => tokens.add(i));
364
- }
365
- const { css, matched } = await ctx.uno.generate(
366
- tokens,
367
- {
368
- preflights: options2.preflights,
369
- minify: options2.minify
370
- }
371
- );
372
- if (options2.stdout) {
373
- process.stdout.write(css);
374
- return;
375
- }
376
- const outFile = resolve(options2.cwd || process.cwd(), options2.outFile ?? "uno.css");
377
- const dir = dirname(outFile);
378
- if (!existsSync(dir))
379
- await promises.mkdir(dir, { recursive: true });
380
- await promises.writeFile(outFile, css, "utf-8");
381
- if (!options2.watch) {
382
- consola.success(
383
- `${[...matched].length} utilities generated to ${cyan(
384
- relative(process.cwd(), outFile)
385
- )}
386
- `
387
- );
388
- }
389
- }
390
- }
391
-
392
- export { build as b, handleError as h, resolveOptions as r, version as v };