@weapp-tailwindcss/cli 4.0.0-alpha.9 → 5.3.1

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 DELETED
@@ -1,1086 +0,0 @@
1
- import path from 'node:path';
2
- import createDebug from 'debug';
3
- import fs, { ensureDir } from 'fs-extra';
4
- import gulp from 'gulp';
5
- import less from 'gulp-less';
6
- import postcssrc from 'gulp-postcss';
7
- import rename from 'gulp-rename';
8
- import createSass from 'gulp-sass';
9
- import { isPackageExists, getPackageInfo } from 'local-pkg';
10
- import postcssScssParser from 'postcss-scss';
11
- import { createPlugins } from 'weapp-tailwindcss/gulp';
12
- import pc from 'picocolors';
13
- import loadPostcssConfig from 'postcss-load-config';
14
- import process from 'node:process';
15
- import { cosmiconfigSync } from 'cosmiconfig';
16
- import { Command } from 'commander';
17
-
18
- const debug = createDebug("weapp-tw-cli");
19
-
20
- const defaultJavascriptExtensions = ["js"];
21
- const defaultTypescriptExtensions = ["ts"];
22
- const defaultWxsExtensions = ["wxs"];
23
- const defaultNodeModulesDirs = [
24
- "**/node_modules/**",
25
- "**/miniprogram_npm/**",
26
- "**/project.config.json/**",
27
- "**/project.private.config.json/**",
28
- "**/package.json/**",
29
- "postcss.config.js",
30
- "tailwind.config.js",
31
- "weapp-tw.config.js"
32
- ];
33
- function noop() {
34
- }
35
- function getDefaultOptions(options, postcssOptionsFromConfig) {
36
- return {
37
- outDir: "dist",
38
- weappTailwindcssOptions: {},
39
- clean: true,
40
- src: "",
41
- exclude: [...defaultNodeModulesDirs],
42
- include: ["**/*.{png,jpg,jpeg,gif,svg,webp}"],
43
- extensions: {
44
- javascript: [...defaultJavascriptExtensions, ...defaultTypescriptExtensions, ...defaultWxsExtensions],
45
- html: ["wxml"],
46
- css: ["wxss", "less", "sass", "scss"],
47
- json: ["json"]
48
- },
49
- watchOptions: {
50
- cwd: options?.root,
51
- events: ["add", "change", "unlink", "ready"]
52
- },
53
- postcssOptions: postcssOptionsFromConfig,
54
- gulpChain: noop
55
- };
56
- }
57
-
58
- var AssetType = /* @__PURE__ */ ((AssetType2) => {
59
- AssetType2["JavaScript"] = "javascript";
60
- AssetType2["Json"] = "json";
61
- AssetType2["Css"] = "css";
62
- AssetType2["Html"] = "html";
63
- return AssetType2;
64
- })(AssetType || {});
65
-
66
- function getDefaultExportFromCjs (x) {
67
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
68
- }
69
-
70
- /*!
71
- * isobject <https://github.com/jonschlinkert/isobject>
72
- *
73
- * Copyright (c) 2014-2017, Jon Schlinkert.
74
- * Released under the MIT License.
75
- */
76
-
77
- var isobject;
78
- var hasRequiredIsobject;
79
-
80
- function requireIsobject () {
81
- if (hasRequiredIsobject) return isobject;
82
- hasRequiredIsobject = 1;
83
-
84
- isobject = function isObject(val) {
85
- return val != null && typeof val === 'object' && Array.isArray(val) === false;
86
- };
87
- return isobject;
88
- }
89
-
90
- /*!
91
- * get-value <https://github.com/jonschlinkert/get-value>
92
- *
93
- * Copyright (c) 2014-2018, Jon Schlinkert.
94
- * Released under the MIT License.
95
- */
96
-
97
- var getValue;
98
- var hasRequiredGetValue;
99
-
100
- function requireGetValue () {
101
- if (hasRequiredGetValue) return getValue;
102
- hasRequiredGetValue = 1;
103
- const isObject = requireIsobject();
104
-
105
- getValue = function(target, path, options) {
106
- if (!isObject(options)) {
107
- options = { default: options };
108
- }
109
-
110
- if (!isValidObject(target)) {
111
- return typeof options.default !== 'undefined' ? options.default : target;
112
- }
113
-
114
- if (typeof path === 'number') {
115
- path = String(path);
116
- }
117
-
118
- const isArray = Array.isArray(path);
119
- const isString = typeof path === 'string';
120
- const splitChar = options.separator || '.';
121
- const joinChar = options.joinChar || (typeof splitChar === 'string' ? splitChar : '.');
122
-
123
- if (!isString && !isArray) {
124
- return target;
125
- }
126
-
127
- if (isString && path in target) {
128
- return isValid(path, target, options) ? target[path] : options.default;
129
- }
130
-
131
- let segs = isArray ? path : split(path, splitChar, options);
132
- let len = segs.length;
133
- let idx = 0;
134
-
135
- do {
136
- let prop = segs[idx];
137
- if (typeof prop === 'number') {
138
- prop = String(prop);
139
- }
140
-
141
- while (prop && prop.slice(-1) === '\\') {
142
- prop = join([prop.slice(0, -1), segs[++idx] || ''], joinChar, options);
143
- }
144
-
145
- if (prop in target) {
146
- if (!isValid(prop, target, options)) {
147
- return options.default;
148
- }
149
-
150
- target = target[prop];
151
- } else {
152
- let hasProp = false;
153
- let n = idx + 1;
154
-
155
- while (n < len) {
156
- prop = join([prop, segs[n++]], joinChar, options);
157
-
158
- if ((hasProp = prop in target)) {
159
- if (!isValid(prop, target, options)) {
160
- return options.default;
161
- }
162
-
163
- target = target[prop];
164
- idx = n - 1;
165
- break;
166
- }
167
- }
168
-
169
- if (!hasProp) {
170
- return options.default;
171
- }
172
- }
173
- } while (++idx < len && isValidObject(target));
174
-
175
- if (idx === len) {
176
- return target;
177
- }
178
-
179
- return options.default;
180
- };
181
-
182
- function join(segs, joinChar, options) {
183
- if (typeof options.join === 'function') {
184
- return options.join(segs);
185
- }
186
- return segs[0] + joinChar + segs[1];
187
- }
188
-
189
- function split(path, splitChar, options) {
190
- if (typeof options.split === 'function') {
191
- return options.split(path);
192
- }
193
- return path.split(splitChar);
194
- }
195
-
196
- function isValid(key, target, options) {
197
- if (typeof options.isValid === 'function') {
198
- return options.isValid(key, target);
199
- }
200
- return true;
201
- }
202
-
203
- function isValidObject(val) {
204
- return isObject(val) || Array.isArray(val) || typeof val === 'function';
205
- }
206
- return getValue;
207
- }
208
-
209
- var getValueExports = requireGetValue();
210
- const get = /*@__PURE__*/getDefaultExportFromCjs(getValueExports);
211
-
212
- /*!
213
- * is-primitive <https://github.com/jonschlinkert/is-primitive>
214
- *
215
- * Copyright (c) 2014-present, Jon Schlinkert.
216
- * Released under the MIT License.
217
- */
218
-
219
- var isPrimitive;
220
- var hasRequiredIsPrimitive;
221
-
222
- function requireIsPrimitive () {
223
- if (hasRequiredIsPrimitive) return isPrimitive;
224
- hasRequiredIsPrimitive = 1;
225
-
226
- isPrimitive = function isPrimitive(val) {
227
- if (typeof val === 'object') {
228
- return val === null;
229
- }
230
- return typeof val !== 'function';
231
- };
232
- return isPrimitive;
233
- }
234
-
235
- /*!
236
- * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
237
- *
238
- * Copyright (c) 2014-2017, Jon Schlinkert.
239
- * Released under the MIT License.
240
- */
241
-
242
- var isPlainObject$1;
243
- var hasRequiredIsPlainObject;
244
-
245
- function requireIsPlainObject () {
246
- if (hasRequiredIsPlainObject) return isPlainObject$1;
247
- hasRequiredIsPlainObject = 1;
248
-
249
- var isObject = requireIsobject();
250
-
251
- function isObjectObject(o) {
252
- return isObject(o) === true
253
- && Object.prototype.toString.call(o) === '[object Object]';
254
- }
255
-
256
- isPlainObject$1 = function isPlainObject(o) {
257
- var ctor,prot;
258
-
259
- if (isObjectObject(o) === false) return false;
260
-
261
- // If has modified constructor
262
- ctor = o.constructor;
263
- if (typeof ctor !== 'function') return false;
264
-
265
- // If has modified prototype
266
- prot = ctor.prototype;
267
- if (isObjectObject(prot) === false) return false;
268
-
269
- // If constructor does not have an Object-specific method
270
- if (prot.hasOwnProperty('isPrototypeOf') === false) {
271
- return false;
272
- }
273
-
274
- // Most likely a plain Object
275
- return true;
276
- };
277
- return isPlainObject$1;
278
- }
279
-
280
- /*!
281
- * set-value <https://github.com/jonschlinkert/set-value>
282
- *
283
- * Copyright (c) Jon Schlinkert (https://github.com/jonschlinkert).
284
- * Released under the MIT License.
285
- */
286
-
287
- var setValue_1;
288
- var hasRequiredSetValue;
289
-
290
- function requireSetValue () {
291
- if (hasRequiredSetValue) return setValue_1;
292
- hasRequiredSetValue = 1;
293
-
294
- const { deleteProperty } = Reflect;
295
- const isPrimitive = requireIsPrimitive();
296
- const isPlainObject = requireIsPlainObject();
297
-
298
- const isObject = value => {
299
- return (typeof value === 'object' && value !== null) || typeof value === 'function';
300
- };
301
-
302
- const isUnsafeKey = key => {
303
- return key === '__proto__' || key === 'constructor' || key === 'prototype';
304
- };
305
-
306
- const validateKey = key => {
307
- if (!isPrimitive(key)) {
308
- throw new TypeError('Object keys must be strings or symbols');
309
- }
310
-
311
- if (isUnsafeKey(key)) {
312
- throw new Error(`Cannot set unsafe key: "${key}"`);
313
- }
314
- };
315
-
316
- const toStringKey = input => {
317
- return Array.isArray(input) ? input.flat().map(String).join(',') : input;
318
- };
319
-
320
- const createMemoKey = (input, options) => {
321
- if (typeof input !== 'string' || !options) return input;
322
- let key = input + ';';
323
- if (options.arrays !== undefined) key += `arrays=${options.arrays};`;
324
- if (options.separator !== undefined) key += `separator=${options.separator};`;
325
- if (options.split !== undefined) key += `split=${options.split};`;
326
- if (options.merge !== undefined) key += `merge=${options.merge};`;
327
- if (options.preservePaths !== undefined) key += `preservePaths=${options.preservePaths};`;
328
- return key;
329
- };
330
-
331
- const memoize = (input, options, fn) => {
332
- const key = toStringKey(options ? createMemoKey(input, options) : input);
333
- validateKey(key);
334
-
335
- const value = setValue.cache.get(key) || fn();
336
- setValue.cache.set(key, value);
337
- return value;
338
- };
339
-
340
- const splitString = (input, options = {}) => {
341
- const sep = options.separator || '.';
342
- const preserve = sep === '/' ? false : options.preservePaths;
343
-
344
- if (typeof input === 'string' && preserve !== false && /\//.test(input)) {
345
- return [input];
346
- }
347
-
348
- const parts = [];
349
- let part = '';
350
-
351
- const push = part => {
352
- let number;
353
- if (part.trim() !== '' && Number.isInteger((number = Number(part)))) {
354
- parts.push(number);
355
- } else {
356
- parts.push(part);
357
- }
358
- };
359
-
360
- for (let i = 0; i < input.length; i++) {
361
- const value = input[i];
362
-
363
- if (value === '\\') {
364
- part += input[++i];
365
- continue;
366
- }
367
-
368
- if (value === sep) {
369
- push(part);
370
- part = '';
371
- continue;
372
- }
373
-
374
- part += value;
375
- }
376
-
377
- if (part) {
378
- push(part);
379
- }
380
-
381
- return parts;
382
- };
383
-
384
- const split = (input, options) => {
385
- if (options && typeof options.split === 'function') return options.split(input);
386
- if (typeof input === 'symbol') return [input];
387
- if (Array.isArray(input)) return input;
388
- return memoize(input, options, () => splitString(input, options));
389
- };
390
-
391
- const assignProp = (obj, prop, value, options) => {
392
- validateKey(prop);
393
-
394
- // Delete property when "value" is undefined
395
- if (value === undefined) {
396
- deleteProperty(obj, prop);
397
-
398
- } else if (options && options.merge) {
399
- const merge = options.merge === 'function' ? options.merge : Object.assign;
400
-
401
- // Only merge plain objects
402
- if (merge && isPlainObject(obj[prop]) && isPlainObject(value)) {
403
- obj[prop] = merge(obj[prop], value);
404
- } else {
405
- obj[prop] = value;
406
- }
407
-
408
- } else {
409
- obj[prop] = value;
410
- }
411
-
412
- return obj;
413
- };
414
-
415
- const setValue = (target, path, value, options) => {
416
- if (!path || !isObject(target)) return target;
417
-
418
- const keys = split(path, options);
419
- let obj = target;
420
-
421
- for (let i = 0; i < keys.length; i++) {
422
- const key = keys[i];
423
- const next = keys[i + 1];
424
-
425
- validateKey(key);
426
-
427
- if (next === undefined) {
428
- assignProp(obj, key, value, options);
429
- break;
430
- }
431
-
432
- if (typeof next === 'number' && !Array.isArray(obj[key])) {
433
- obj = obj[key] = [];
434
- continue;
435
- }
436
-
437
- if (!isObject(obj[key])) {
438
- obj[key] = {};
439
- }
440
-
441
- obj = obj[key];
442
- }
443
-
444
- return target;
445
- };
446
-
447
- setValue.split = split;
448
- setValue.cache = new Map();
449
- setValue.clear = () => {
450
- setValue.cache = new Map();
451
- };
452
-
453
- setValue_1 = setValue;
454
- return setValue_1;
455
- }
456
-
457
- var setValueExports = requireSetValue();
458
- const set = /*@__PURE__*/getDefaultExportFromCjs(setValueExports);
459
-
460
- function isObject(x) {
461
- return typeof x === "object" && x !== null;
462
- }
463
- function promisify(task) {
464
- return new Promise((resolve, reject) => {
465
- if (Array.isArray(task)) {
466
- return Promise.all(task.map((x) => promisify(x))).then(resolve).catch(reject);
467
- } else {
468
- if (task.destroyed) {
469
- resolve(undefined);
470
- return;
471
- }
472
- task.on("finish", () => {
473
- resolve(undefined);
474
- }).on("error", (err) => {
475
- reject(err);
476
- });
477
- }
478
- });
479
- }
480
- function isSassLang(lang) {
481
- return lang === "scss" || lang === "sass";
482
- }
483
- function isLessLang(lang) {
484
- return lang === "less";
485
- }
486
- function isTsLang(lang) {
487
- return lang === "ts";
488
- }
489
-
490
- class GlobsSet {
491
- includeSet;
492
- excludeSet;
493
- constructor() {
494
- this.includeSet = /* @__PURE__ */ new Set();
495
- this.excludeSet = /* @__PURE__ */ new Set();
496
- }
497
- isExcludeGlob(value) {
498
- return value[0] === "!";
499
- }
500
- addSingle(value) {
501
- return this.isExcludeGlob(value) ? this.excludeSet.add(value) : this.includeSet.add(value);
502
- }
503
- add(...value) {
504
- for (const v of value) {
505
- if (Array.isArray(v)) {
506
- for (const vv of v) {
507
- this.addSingle(vv);
508
- }
509
- } else {
510
- this.addSingle(v);
511
- }
512
- }
513
- }
514
- dump() {
515
- return [...this.includeSet, ...this.excludeSet];
516
- }
517
- dumpIgnored() {
518
- return [...this.excludeSet].map((x) => x.slice(1));
519
- }
520
- }
521
-
522
- function isStream(stream, { checkOpen = true } = {}) {
523
- return stream !== null && typeof stream === "object" && (stream.writable || stream.readable || !checkOpen || stream.writable === undefined && stream.readable === undefined) && typeof stream.pipe === "function";
524
- }
525
-
526
- function normalizePlugin(plugin) {
527
- if (isStream(plugin)) {
528
- return plugin;
529
- } else if (typeof plugin === "function") {
530
- return plugin.apply(plugin);
531
- } else if (Array.isArray(plugin)) {
532
- const [fn, ...args] = plugin;
533
- return fn.apply(fn, args);
534
- }
535
- }
536
- function resolveTask({ pipes, globs, since, cwd }) {
537
- let chain = gulp.src(globs, { cwd, since: gulp.lastRun(since) });
538
- for (const p of pipes) {
539
- chain = chain.pipe(p);
540
- }
541
- return promisify(chain);
542
- }
543
- async function getTasks(options) {
544
- let { typescriptOptions } = options;
545
- const {
546
- root: cwd,
547
- weappTailwindcssOptions,
548
- outDir,
549
- src: srcBase,
550
- extensions,
551
- exclude,
552
- include,
553
- postcssOptions,
554
- preprocessorOptions,
555
- gulpChain
556
- } = options;
557
- const globsSet = new GlobsSet();
558
- const base = srcBase ? `${srcBase}/` : "";
559
- const enableSass = Boolean(preprocessorOptions?.sass);
560
- const enableLess = Boolean(preprocessorOptions?.less);
561
- function resolvePipes(plugins, type) {
562
- const newPlugins = gulpChain(plugins, type);
563
- if (newPlugins === undefined) {
564
- return plugins;
565
- }
566
- return newPlugins.map((x) => normalizePlugin(x)).filter((x) => x);
567
- }
568
- if (typescriptOptions === true) {
569
- typescriptOptions = {
570
- tsConfigFileName: "tsconfig.json"
571
- };
572
- } else if (isObject(typescriptOptions) && typescriptOptions.tsConfigFileName === undefined) {
573
- typescriptOptions.tsConfigFileName = "tsconfig.json";
574
- }
575
- const enableTs = Boolean(typescriptOptions);
576
- let sass;
577
- if (enableSass) {
578
- if (!isPackageExists("sass")) {
579
- throw new Error("\u8BF7\u5148\u6267\u884C npm / yarn / pnpm \u547D\u4EE4\u5B89\u88C5 `sass` \u540E\u91CD\u8BD5!");
580
- }
581
- const sassLib = await import('sass');
582
- sass = createSass(sassLib);
583
- }
584
- let ts;
585
- let gulpTs;
586
- if (enableTs) {
587
- if (!isPackageExists("typescript")) {
588
- throw new Error("\u8BF7\u5148\u6267\u884C npm / yarn / pnpm \u547D\u4EE4\u5B89\u88C5 `typescript` \u540E\u91CD\u8BD5!");
589
- }
590
- ts = (await import('gulp-typescript')).default;
591
- if (typeof typescriptOptions !== "boolean") {
592
- gulpTs = ts.createProject(
593
- typescriptOptions.tsConfigFileName ?? "tsconfig.json",
594
- typescriptOptions.settings
595
- );
596
- }
597
- }
598
- const { transformJs, transformWxml, transformWxss } = createPlugins(weappTailwindcssOptions);
599
- const outDirGlobs = [`!${outDir}/**/*`, `!./${outDir}/**/*`];
600
- function getGlobs(type) {
601
- const globs = [];
602
- if (typeof include === "function") {
603
- globs.push(...include(type).map((x) => x));
604
- }
605
- if (typeof exclude === "function") {
606
- globs.push(...exclude(type).map((x) => `!${x}`));
607
- } else if (Array.isArray(exclude)) {
608
- globs.push(...exclude.map((x) => `!${x}`));
609
- }
610
- globs.push(...outDirGlobs);
611
- return globs;
612
- }
613
- function getJsTasks() {
614
- const assetType = AssetType.JavaScript;
615
- const globs = getGlobs(assetType);
616
- globsSet.add(globs);
617
- return extensions[assetType]?.map((x) => {
618
- const src = `${base}**/*.${x}`;
619
- globsSet.add(src);
620
- const isTs = isTsLang(x);
621
- const loadTs = enableTs && isTs;
622
- return function JsTask() {
623
- const pipes = [];
624
- if (loadTs && gulpTs) {
625
- pipes.push(gulpTs().on("error", () => {
626
- }));
627
- }
628
- pipes.push(transformJs({
629
- babelParserOptions: !enableTs && isTs ? {
630
- plugins: ["typescript"]
631
- } : undefined
632
- }));
633
- if (loadTs) {
634
- pipes.push(rename({
635
- extname: ".js"
636
- }));
637
- }
638
- pipes.push(gulp.dest(outDir, {
639
- cwd
640
- }));
641
- return resolveTask({
642
- pipes: resolvePipes(pipes, assetType),
643
- cwd,
644
- globs: [src, ...globs],
645
- since: JsTask
646
- });
647
- };
648
- });
649
- }
650
- function getJsonTasks() {
651
- const assetType = AssetType.Json;
652
- const globs = getGlobs(assetType);
653
- globsSet.add(globs);
654
- return extensions[assetType]?.map((x) => {
655
- const src = `${base}**/*.${x}`;
656
- globsSet.add(src);
657
- return function JsonTask() {
658
- const pipes = [gulp.dest(outDir, {
659
- cwd
660
- })];
661
- return resolveTask({
662
- cwd,
663
- globs: [src, ...globs],
664
- pipes: resolvePipes(pipes, assetType),
665
- since: JsonTask
666
- });
667
- };
668
- });
669
- }
670
- function getCssTasks() {
671
- const assetType = AssetType.Css;
672
- const globs = getGlobs(assetType);
673
- globsSet.add(globs);
674
- return extensions[assetType]?.map((x) => {
675
- const src = `${base}**/*.${x}`;
676
- globsSet.add(src);
677
- const loadSass = enableSass && isSassLang(x);
678
- const loadLess = enableLess && isLessLang(x);
679
- return function CssTask() {
680
- const pipes = [];
681
- if (loadSass) {
682
- pipes.push(sass.sync(
683
- // @ts-ignore
684
- typeof preprocessorOptions?.sass === "boolean" ? undefined : preprocessorOptions?.sass
685
- ).on("error", sass.logError));
686
- }
687
- if (loadLess) {
688
- pipes.push(less(typeof preprocessorOptions?.less === "boolean" ? undefined : preprocessorOptions?.less));
689
- }
690
- if (postcssOptions) {
691
- pipes.push(postcssrc(postcssOptions?.plugins, postcssOptions?.options));
692
- }
693
- if (x === "scss" && !enableSass) {
694
- pipes.push(transformWxss({
695
- postcssOptions: {
696
- options: {
697
- parser: postcssScssParser
698
- }
699
- }
700
- }));
701
- } else {
702
- pipes.push(transformWxss());
703
- }
704
- if (loadSass || loadLess) {
705
- pipes.push(rename({
706
- extname: ".wxss"
707
- }));
708
- }
709
- pipes.push(gulp.dest(outDir, {
710
- cwd
711
- }));
712
- return resolveTask({
713
- cwd,
714
- globs: [src, ...globs],
715
- pipes: resolvePipes(pipes, assetType),
716
- since: CssTask
717
- });
718
- };
719
- });
720
- }
721
- function getHtmlTasks() {
722
- const assetType = AssetType.Html;
723
- const globs = getGlobs(assetType);
724
- globsSet.add(globs);
725
- return extensions[assetType]?.map((x) => {
726
- const src = `${base}**/*.${x}`;
727
- globsSet.add(src);
728
- return function HtmlTask() {
729
- const pipes = [transformWxml(), gulp.dest(outDir, {
730
- cwd
731
- })];
732
- return resolveTask({
733
- cwd,
734
- globs: [src, ...globs],
735
- pipes: resolvePipes(pipes, assetType),
736
- since: HtmlTask
737
- });
738
- };
739
- });
740
- }
741
- function copyOthers() {
742
- if (Array.isArray(include)) {
743
- const globs = include.map((x) => {
744
- return `${base}${x}`;
745
- });
746
- globsSet.add(globs);
747
- const pipes = [gulp.dest(outDir, {
748
- cwd
749
- })];
750
- return resolveTask({
751
- cwd,
752
- globs: [...globs, ...outDirGlobs, ...defaultNodeModulesDirs.map((x) => `!${x}`)],
753
- pipes,
754
- since: copyOthers
755
- });
756
- }
757
- }
758
- return {
759
- getGlobs,
760
- getJsTasks,
761
- getJsonTasks,
762
- getCssTasks,
763
- getHtmlTasks,
764
- copyOthers,
765
- globsSet
766
- };
767
- }
768
-
769
- function isPlainObject(value) {
770
- if (value === null || typeof value !== "object") {
771
- return false;
772
- }
773
- const prototype = Object.getPrototypeOf(value);
774
- if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
775
- return false;
776
- }
777
- if (Symbol.iterator in value) {
778
- return false;
779
- }
780
- if (Symbol.toStringTag in value) {
781
- return Object.prototype.toString.call(value) === "[object Module]";
782
- }
783
- return true;
784
- }
785
-
786
- function _defu(baseObject, defaults, namespace = ".", merger) {
787
- if (!isPlainObject(defaults)) {
788
- return _defu(baseObject, {}, namespace, merger);
789
- }
790
- const object = Object.assign({}, defaults);
791
- for (const key in baseObject) {
792
- if (key === "__proto__" || key === "constructor") {
793
- continue;
794
- }
795
- const value = baseObject[key];
796
- if (value === null || value === undefined) {
797
- continue;
798
- }
799
- if (merger && merger(object, key, value, namespace)) {
800
- continue;
801
- }
802
- if (Array.isArray(value) && Array.isArray(object[key])) {
803
- object[key] = [...value, ...object[key]];
804
- } else if (isPlainObject(value) && isPlainObject(object[key])) {
805
- object[key] = _defu(
806
- value,
807
- object[key],
808
- (namespace ? `${namespace}.` : "") + key.toString(),
809
- merger
810
- );
811
- } else {
812
- object[key] = value;
813
- }
814
- }
815
- return object;
816
- }
817
- function createDefu(merger) {
818
- return (...arguments_) => (
819
- // eslint-disable-next-line unicorn/no-array-reduce
820
- arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
821
- );
822
- }
823
- const defu = createDefu();
824
-
825
- const version = "4.0.0-alpha.9";
826
-
827
- async function createBuilder(options) {
828
- let postcssOptionsFromConfig;
829
- try {
830
- postcssOptionsFromConfig = await loadPostcssConfig({ cwd: options?.root });
831
- } catch {
832
- }
833
- const opt = defu(options, getDefaultOptions(options, postcssOptionsFromConfig));
834
- const { copyOthers, getCssTasks, getHtmlTasks, getJsTasks, getJsonTasks, globsSet } = await getTasks(opt);
835
- const tasks = {
836
- css: getCssTasks(),
837
- html: getHtmlTasks(),
838
- json: getJsonTasks(),
839
- js: getJsTasks(),
840
- extra: [copyOthers]
841
- };
842
- async function runTasks() {
843
- debug("run tasks start");
844
- for (const [key, value] of Object.entries(tasks)) {
845
- if (value) {
846
- debug(`run task ${pc.bold(pc.green(key))} start`);
847
- for (const task of value) {
848
- await task();
849
- }
850
- debug(`run task ${pc.bold(pc.green(key))} end`);
851
- }
852
- }
853
- debug("run tasks end");
854
- }
855
- const { clean: clean2, outDir, root: cwd, watchOptions } = opt;
856
- async function doClean() {
857
- debug("del start");
858
- const { deleteAsync } = await import('del');
859
- const patterns = [`${outDir}/**`];
860
- await deleteAsync(patterns, { cwd, ignore: defaultNodeModulesDirs });
861
- debug("del end");
862
- }
863
- return {
864
- watcher: undefined,
865
- async build() {
866
- if (clean2) {
867
- await doClean();
868
- }
869
- await ensureDir(path.resolve(cwd, outDir));
870
- await runTasks();
871
- return this;
872
- },
873
- async watch() {
874
- if (clean2) {
875
- await doClean();
876
- }
877
- await ensureDir(path.resolve(cwd, outDir));
878
- const dumps = globsSet.dump();
879
- const arr = (Array.isArray(watchOptions.ignored) ? watchOptions.ignored : [watchOptions.ignored]).filter(
880
- Boolean
881
- );
882
- watchOptions.ignored = [...globsSet.dumpIgnored(), ...arr];
883
- const watcher = gulp.watch(dumps, watchOptions, async (cb) => {
884
- try {
885
- await runTasks();
886
- cb();
887
- } catch (error) {
888
- cb(error);
889
- }
890
- });
891
- watcher.on("change", (path2) => {
892
- console.log(`${pc.green("changed")} ${path2}`);
893
- });
894
- watcher.on("add", (path2) => {
895
- console.log(`${pc.green("add")} ${path2}`);
896
- });
897
- watcher.on("unlink", (path2) => {
898
- console.log(`${pc.green("remove")} ${path2}`);
899
- });
900
- watcher.on("ready", async () => {
901
- const meta = await getPackageInfo("weapp-tailwindcss");
902
- let weappTwVersionStr = "";
903
- if (meta) {
904
- weappTwVersionStr = `(${pc.blue(pc.underline(meta.version))})`;
905
- }
906
- console.log(
907
- `${pc.bold(`${pc.green("weapp")}-${pc.blue("tailwindcss")}`)}${weappTwVersionStr} ${pc.cyan("cli")}(${pc.blue(pc.underline(version))}) is ready!`
908
- );
909
- });
910
- this.watcher = watcher;
911
- return this;
912
- },
913
- globsSet,
914
- clean: doClean
915
- };
916
- }
917
- async function build(options) {
918
- const builder = await createBuilder(options);
919
- return await builder.build();
920
- }
921
- async function watch(options) {
922
- const builder = await createBuilder(options);
923
- return await builder.watch();
924
- }
925
- async function clean(options) {
926
- const builder = await createBuilder(options);
927
- return await builder.clean();
928
- }
929
-
930
- function createConfigLoader(root) {
931
- const explorer = cosmiconfigSync("weapp-tw");
932
- function search(searchFrom = root) {
933
- const searchFor = explorer.search(searchFrom);
934
- if (searchFor) {
935
- searchFor.config = defu(searchFor.config, getDefaultConfig(root));
936
- return searchFor;
937
- }
938
- }
939
- function load(filepath) {
940
- return explorer.load(filepath);
941
- }
942
- return {
943
- search,
944
- load
945
- };
946
- }
947
- function getDefaultConfig(root) {
948
- return {
949
- outDir: "dist",
950
- root,
951
- src: "."
952
- };
953
- }
954
- function defineConfig(options) {
955
- return options;
956
- }
957
- function updateProjectConfig(options) {
958
- const { root, dest } = options;
959
- const projectConfigFilename = "project.config.json";
960
- const projectConfigPath = path.resolve(root, projectConfigFilename);
961
- if (fs.existsSync(projectConfigPath)) {
962
- try {
963
- const projectConfig = fs.readJSONSync(projectConfigPath);
964
- set(projectConfig, "miniprogramRoot", "dist/");
965
- set(projectConfig, "srcMiniprogramRoot", "dist/");
966
- set(projectConfig, "setting.packNpmManually", true);
967
- if (Array.isArray(get(projectConfig, "setting.packNpmRelationList"))) {
968
- const x = projectConfig.setting.packNpmRelationList.find(
969
- (x2) => x2.packageJsonPath === "./package.json" && x2.miniprogramNpmDistDir === "./dist"
970
- );
971
- if (!x) {
972
- projectConfig.setting.packNpmRelationList.push({
973
- packageJsonPath: "./package.json",
974
- miniprogramNpmDistDir: "./dist"
975
- });
976
- }
977
- } else {
978
- set(projectConfig, "setting.packNpmRelationList", [
979
- {
980
- packageJsonPath: "./package.json",
981
- miniprogramNpmDistDir: "./dist"
982
- }
983
- ]);
984
- }
985
- fs.outputJSONSync(dest ?? projectConfigPath, projectConfig, {
986
- spaces: 2
987
- });
988
- console.log(`\u2728 \u8BBE\u7F6E ${projectConfigFilename} \u914D\u7F6E\u6587\u4EF6\u6210\u529F!`);
989
- } catch {
990
- console.warn(`\u2728 \u8BBE\u7F6E ${projectConfigFilename} \u914D\u7F6E\u6587\u4EF6\u5931\u8D25!`);
991
- }
992
- } else {
993
- console.warn(`\u2728 \u6CA1\u6709\u627E\u5230 ${projectConfigFilename} \u6587\u4EF6!`);
994
- }
995
- }
996
- function updatePackageJson(options) {
997
- const { root, dest } = options;
998
- const packageJsonFilename = "package.json";
999
- const packageJsonPath = path.resolve(root, packageJsonFilename);
1000
- if (fs.existsSync(packageJsonPath)) {
1001
- try {
1002
- const packageJson = fs.readJSONSync(packageJsonPath);
1003
- set(packageJson, "scripts.dev", "weapp-tw dev");
1004
- set(packageJson, "scripts.build", "weapp-tw build");
1005
- set(packageJson, "scripts.postinstall", "weapp-tw patch");
1006
- fs.outputJSONSync(dest ?? packageJsonPath, packageJson, {
1007
- spaces: 2
1008
- });
1009
- } catch {
1010
- }
1011
- }
1012
- }
1013
- function initConfig(options) {
1014
- const { lang, root } = defu(options, {
1015
- lang: "js",
1016
- root: process.cwd()
1017
- });
1018
- const configFilename = `weapp-tw.config.${lang ?? "js"}`;
1019
- const configPath = path.resolve(root, configFilename);
1020
- const tsconfigPath = path.resolve(root, "tsconfig.json");
1021
- const isTsconfigExisted = fs.existsSync(tsconfigPath);
1022
- fs.ensureDirSync(root);
1023
- const configOptionsStr = isTsconfigExisted ? `{
1024
- src: './miniprogram'
1025
- }` : "{}";
1026
- if (lang === "ts") {
1027
- fs.writeFileSync(
1028
- configPath,
1029
- `import { defineConfig } from '@weapp-tailwindcss/cli'
1030
-
1031
- export default defineConfig(${configOptionsStr})
1032
- `,
1033
- "utf8"
1034
- );
1035
- } else {
1036
- fs.writeFileSync(
1037
- configPath,
1038
- `/** @type {import('@weapp-tailwindcss/cli').UserConfig} */
1039
- const config = ${configOptionsStr}
1040
-
1041
- module.exports = config
1042
- `,
1043
- "utf8"
1044
- );
1045
- }
1046
- console.log(`\u2728 ${configFilename} \u914D\u7F6E\u6587\u4EF6\uFF0C\u521D\u59CB\u5316\u6210\u529F!`);
1047
- updateProjectConfig({ root });
1048
- updatePackageJson({ root });
1049
- return configPath;
1050
- }
1051
-
1052
- function createCli() {
1053
- const cwd = process.cwd();
1054
- const program = new Command();
1055
- const configLoader = createConfigLoader(cwd);
1056
- const userDefinedConfig = configLoader.search(cwd);
1057
- program.command("dev").alias("serve").action(async () => {
1058
- await watch(
1059
- defu(userDefinedConfig?.config, {
1060
- root: cwd
1061
- })
1062
- );
1063
- });
1064
- program.command("build").action(async () => {
1065
- await build(
1066
- defu(userDefinedConfig?.config, {
1067
- root: cwd
1068
- })
1069
- );
1070
- });
1071
- program.command("init").action(() => {
1072
- initConfig({
1073
- root: cwd
1074
- });
1075
- });
1076
- program.command("clean").action(async () => {
1077
- await clean(
1078
- defu(userDefinedConfig?.config, {
1079
- root: cwd
1080
- })
1081
- );
1082
- });
1083
- return program;
1084
- }
1085
-
1086
- export { build, createBuilder, createCli, createConfigLoader, defineConfig, watch };