@weapp-core/init 6.0.1 → 6.0.3

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.
Files changed (3) hide show
  1. package/dist/index.d.ts +118 -99
  2. package/dist/index.js +926 -924
  3. package/package.json +7 -6
package/dist/index.js CHANGED
@@ -1,642 +1,683 @@
1
- // src/index.ts
2
- import process2 from "process";
3
-
4
- // src/configFiles.ts
1
+ import process$1 from "node:process";
5
2
  import logger from "@weapp-core/logger";
6
-
7
- // ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
8
- var _lazyMatch = () => {
9
- var __lib__ = (() => {
10
- var m = Object.defineProperty, V = Object.getOwnPropertyDescriptor, G = Object.getOwnPropertyNames, T = Object.prototype.hasOwnProperty, q = (r, e) => {
11
- for (var n in e) m(r, n, { get: e[n], enumerable: true });
12
- }, H = (r, e, n, a) => {
13
- if (e && typeof e == "object" || typeof e == "function") for (let t of G(e)) !T.call(r, t) && t !== n && m(r, t, { get: () => e[t], enumerable: !(a = V(e, t)) || a.enumerable });
14
- return r;
15
- }, J = (r) => H(m({}, "__esModule", { value: true }), r), w = {};
16
- q(w, { default: () => re });
17
- var A = (r) => Array.isArray(r), d = (r) => typeof r == "function", Q = (r) => r.length === 0, W = (r) => typeof r == "number", K = (r) => typeof r == "object" && r !== null, X = (r) => r instanceof RegExp, b = (r) => typeof r == "string", h = (r) => r === void 0, Y = (r) => {
18
- const e = /* @__PURE__ */ new Map();
19
- return (n) => {
20
- const a = e.get(n);
21
- if (a) return a;
22
- const t = r(n);
23
- return e.set(n, t), t;
24
- };
25
- }, rr = (r, e, n = {}) => {
26
- const a = { cache: {}, input: r, index: 0, indexMax: 0, options: n, output: [] };
27
- if (v(e)(a) && a.index === r.length) return a.output;
28
- throw new Error(`Failed to parse at index ${a.indexMax}`);
29
- }, i = (r, e) => A(r) ? er(r, e) : b(r) ? ar(r, e) : nr(r, e), er = (r, e) => {
30
- const n = {};
31
- for (const a of r) {
32
- if (a.length !== 1) throw new Error(`Invalid character: "${a}"`);
33
- const t = a.charCodeAt(0);
34
- n[t] = true;
35
- }
36
- return (a) => {
37
- const t = a.index, o = a.input;
38
- for (; a.index < o.length && o.charCodeAt(a.index) in n; ) a.index += 1;
39
- const u = a.index;
40
- if (u > t) {
41
- if (!h(e) && !a.options.silent) {
42
- const s = a.input.slice(t, u), c = d(e) ? e(s, o, String(t)) : e;
43
- h(c) || a.output.push(c);
44
- }
45
- a.indexMax = Math.max(a.indexMax, a.index);
46
- }
47
- return true;
48
- };
49
- }, nr = (r, e) => {
50
- const n = r.source, a = r.flags.replace(/y|$/, "y"), t = new RegExp(n, a);
51
- return g((o) => {
52
- t.lastIndex = o.index;
53
- const u = t.exec(o.input);
54
- if (u) {
55
- if (!h(e) && !o.options.silent) {
56
- const s = d(e) ? e(...u, o.input, String(o.index)) : e;
57
- h(s) || o.output.push(s);
58
- }
59
- return o.index += u[0].length, o.indexMax = Math.max(o.indexMax, o.index), true;
60
- } else return false;
61
- });
62
- }, ar = (r, e) => (n) => {
63
- if (n.input.startsWith(r, n.index)) {
64
- if (!h(e) && !n.options.silent) {
65
- const t = d(e) ? e(r, n.input, String(n.index)) : e;
66
- h(t) || n.output.push(t);
67
- }
68
- return n.index += r.length, n.indexMax = Math.max(n.indexMax, n.index), true;
69
- } else return false;
70
- }, C = (r, e, n, a) => {
71
- const t = v(r);
72
- return g(_(M((o) => {
73
- let u = 0;
74
- for (; u < n; ) {
75
- const s = o.index;
76
- if (!t(o) || (u += 1, o.index === s)) break;
77
- }
78
- return u >= e;
79
- })));
80
- }, tr = (r, e) => C(r, 0, 1), f = (r, e) => C(r, 0, 1 / 0), x = (r, e) => {
81
- const n = r.map(v);
82
- return g(_(M((a) => {
83
- for (let t = 0, o = n.length; t < o; t++) if (!n[t](a)) return false;
84
- return true;
85
- })));
86
- }, l = (r, e) => {
87
- const n = r.map(v);
88
- return g(_((a) => {
89
- for (let t = 0, o = n.length; t < o; t++) if (n[t](a)) return true;
90
- return false;
91
- }));
92
- }, M = (r, e = false) => {
93
- const n = v(r);
94
- return (a) => {
95
- const t = a.index, o = a.output.length, u = n(a);
96
- return (!u || e) && (a.index = t, a.output.length !== o && (a.output.length = o)), u;
97
- };
98
- }, _ = (r, e) => {
99
- const n = v(r);
100
- return n;
101
- }, g = /* @__PURE__ */ (() => {
102
- let r = 0;
103
- return (e) => {
104
- const n = v(e), a = r += 1;
105
- return (t) => {
106
- var o;
107
- if (t.options.memoization === false) return n(t);
108
- const u = t.index, s = (o = t.cache)[a] || (o[a] = /* @__PURE__ */ new Map()), c = s.get(u);
109
- if (c === false) return false;
110
- if (W(c)) return t.index = c, true;
111
- if (c) return t.index = c.index, c.output?.length && t.output.push(...c.output), true;
112
- {
113
- const Z = t.output.length;
114
- if (n(t)) {
115
- const D = t.index, U = t.output.length;
116
- if (U > Z) {
117
- const ee = t.output.slice(Z, U);
118
- s.set(u, { index: D, output: ee });
119
- } else s.set(u, D);
120
- return true;
121
- } else return s.set(u, false), false;
122
- }
123
- };
124
- };
125
- })(), E = (r) => {
126
- let e;
127
- return (n) => (e || (e = v(r())), e(n));
128
- }, v = Y((r) => {
129
- if (d(r)) return Q(r) ? E(r) : r;
130
- if (b(r) || X(r)) return i(r);
131
- if (A(r)) return x(r);
132
- if (K(r)) return l(Object.values(r));
133
- throw new Error("Invalid rule");
134
- }), P = "abcdefghijklmnopqrstuvwxyz", ir = (r) => {
135
- let e = "";
136
- for (; r > 0; ) {
137
- const n = (r - 1) % 26;
138
- e = P[n] + e, r = Math.floor((r - 1) / 26);
139
- }
140
- return e;
141
- }, O = (r) => {
142
- let e = 0;
143
- for (let n = 0, a = r.length; n < a; n++) e = e * 26 + P.indexOf(r[n]) + 1;
144
- return e;
145
- }, S = (r, e) => {
146
- if (e < r) return S(e, r);
147
- const n = [];
148
- for (; r <= e; ) n.push(r++);
149
- return n;
150
- }, or = (r, e, n) => S(r, e).map((a) => String(a).padStart(n, "0")), R = (r, e) => S(O(r), O(e)).map(ir), p = (r) => r, z = (r) => ur((e) => rr(e, r, { memoization: false }).join("")), ur = (r) => {
151
- const e = {};
152
- return (n) => e[n] ?? (e[n] = r(n));
153
- }, sr = i(/^\*\*\/\*$/, ".*"), cr = i(/^\*\*\/(\*)?([ a-zA-Z0-9._-]+)$/, (r, e, n) => `.*${e ? "" : "(?:^|/)"}${n.replaceAll(".", "\\.")}`), lr = i(/^\*\*\/(\*)?([ a-zA-Z0-9._-]*)\{([ a-zA-Z0-9._-]+(?:,[ a-zA-Z0-9._-]+)*)\}$/, (r, e, n, a) => `.*${e ? "" : "(?:^|/)"}${n.replaceAll(".", "\\.")}(?:${a.replaceAll(",", "|").replaceAll(".", "\\.")})`), y = i(/\\./, p), pr = i(/[$.*+?^(){}[\]\|]/, (r) => `\\${r}`), vr = i(/./, p), hr = i(/^(?:!!)*!(.*)$/, (r, e) => `(?!^${L(e)}$).*?`), dr = i(/^(!!)+/, ""), fr = l([hr, dr]), xr = i(/\/(\*\*\/)+/, "(?:/.+/|/)"), gr = i(/^(\*\*\/)+/, "(?:^|.*/)"), mr = i(/\/(\*\*)$/, "(?:/.*|$)"), _r = i(/\*\*/, ".*"), j = l([xr, gr, mr, _r]), Sr = i(/\*\/(?!\*\*\/)/, "[^/]*/"), yr = i(/\*/, "[^/]*"), N = l([Sr, yr]), k = i("?", "[^/]"), $r = i("[", p), wr = i("]", p), Ar = i(/[!^]/, "^/"), br = i(/[a-z]-[a-z]|[0-9]-[0-9]/i, p), Cr = i(/[$.*+?^(){}[\|]/, (r) => `\\${r}`), Mr = i(/[^\]]/, p), Er = l([y, Cr, br, Mr]), B = x([$r, tr(Ar), f(Er), wr]), Pr = i("{", "(?:"), Or = i("}", ")"), Rr = i(/(\d+)\.\.(\d+)/, (r, e, n) => or(+e, +n, Math.min(e.length, n.length)).join("|")), zr = i(/([a-z]+)\.\.([a-z]+)/, (r, e, n) => R(e, n).join("|")), jr = i(/([A-Z]+)\.\.([A-Z]+)/, (r, e, n) => R(e.toLowerCase(), n.toLowerCase()).join("|").toUpperCase()), Nr = l([Rr, zr, jr]), I = x([Pr, Nr, Or]), kr = i("{", "(?:"), Br = i("}", ")"), Ir = i(",", "|"), Fr = i(/[$.*+?^(){[\]\|]/, (r) => `\\${r}`), Lr = i(/[^}]/, p), Zr = E(() => F), Dr = l([j, N, k, B, I, Zr, y, Fr, Ir, Lr]), F = x([kr, f(Dr), Br]), Ur = f(l([sr, cr, lr, fr, j, N, k, B, I, F, y, pr, vr])), Vr = Ur, Gr = z(Vr), L = Gr, Tr = i(/\\./, p), qr = i(/./, p), Hr = i(/\*\*\*+/, "*"), Jr = i(/([^/{[(!])\*\*/, (r, e) => `${e}*`), Qr = i(/(^|.)\*\*(?=[^*/)\]}])/, (r, e) => `${e}*`), Wr = f(l([Tr, Hr, Jr, Qr, qr])), Kr = Wr, Xr = z(Kr), Yr = Xr, $ = (r, e) => {
154
- const n = Array.isArray(r) ? r : [r];
155
- if (!n.length) return false;
156
- const a = n.map($.compile), t = n.every((s) => /(\/(?:\*\*)?|\[\/\])$/.test(s)), o = e.replace(/[\\\/]+/g, "/").replace(/\/$/, t ? "/" : "");
157
- return a.some((s) => s.test(o));
158
- };
159
- $.compile = (r) => new RegExp(`^${L(Yr(r))}$`, "s");
160
- var re = $;
161
- return J(w);
162
- })();
163
- return __lib__.default || __lib__;
3
+ import fs from "fs-extra";
4
+ import { defu, get, set } from "@weapp-core/shared";
5
+ import https from "node:https";
6
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
7
+ let _lazyMatch = () => {
8
+ var __lib__ = (() => {
9
+ var m = Object.defineProperty, V = Object.getOwnPropertyDescriptor, G = Object.getOwnPropertyNames, T = Object.prototype.hasOwnProperty, q = (r, e) => {
10
+ for (var n in e) m(r, n, {
11
+ get: e[n],
12
+ enumerable: true
13
+ });
14
+ }, H = (r, e, n, a) => {
15
+ if (e && typeof e == "object" || typeof e == "function") for (let t of G(e)) !T.call(r, t) && t !== n && m(r, t, {
16
+ get: () => e[t],
17
+ enumerable: !(a = V(e, t)) || a.enumerable
18
+ });
19
+ return r;
20
+ }, J = (r) => H(m({}, "__esModule", { value: true }), r), w = {};
21
+ q(w, { default: () => re });
22
+ var A = (r) => Array.isArray(r), d = (r) => typeof r == "function", Q = (r) => r.length === 0, W = (r) => typeof r == "number", K = (r) => typeof r == "object" && r !== null, X = (r) => r instanceof RegExp, b = (r) => typeof r == "string", h = (r) => r === void 0, Y = (r) => {
23
+ const e = /* @__PURE__ */ new Map();
24
+ return (n) => {
25
+ const a = e.get(n);
26
+ if (a) return a;
27
+ const t = r(n);
28
+ return e.set(n, t), t;
29
+ };
30
+ }, rr = (r, e, n = {}) => {
31
+ const a = {
32
+ cache: {},
33
+ input: r,
34
+ index: 0,
35
+ indexMax: 0,
36
+ options: n,
37
+ output: []
38
+ };
39
+ if (v(e)(a) && a.index === r.length) return a.output;
40
+ throw new Error(`Failed to parse at index ${a.indexMax}`);
41
+ }, i = (r, e) => A(r) ? er(r, e) : b(r) ? ar(r, e) : nr(r, e), er = (r, e) => {
42
+ const n = {};
43
+ for (const a of r) {
44
+ if (a.length !== 1) throw new Error(`Invalid character: "${a}"`);
45
+ const t = a.charCodeAt(0);
46
+ n[t] = true;
47
+ }
48
+ return (a) => {
49
+ const t = a.index, o = a.input;
50
+ for (; a.index < o.length && o.charCodeAt(a.index) in n;) a.index += 1;
51
+ const u = a.index;
52
+ if (u > t) {
53
+ if (!h(e) && !a.options.silent) {
54
+ const s = a.input.slice(t, u), c = d(e) ? e(s, o, String(t)) : e;
55
+ h(c) || a.output.push(c);
56
+ }
57
+ a.indexMax = Math.max(a.indexMax, a.index);
58
+ }
59
+ return true;
60
+ };
61
+ }, nr = (r, e) => {
62
+ const n = r.source, a = r.flags.replace(/y|$/, "y"), t = new RegExp(n, a);
63
+ return g((o) => {
64
+ t.lastIndex = o.index;
65
+ const u = t.exec(o.input);
66
+ if (u) {
67
+ if (!h(e) && !o.options.silent) {
68
+ const s = d(e) ? e(...u, o.input, String(o.index)) : e;
69
+ h(s) || o.output.push(s);
70
+ }
71
+ return o.index += u[0].length, o.indexMax = Math.max(o.indexMax, o.index), true;
72
+ } else return false;
73
+ });
74
+ }, ar = (r, e) => (n) => {
75
+ if (n.input.startsWith(r, n.index)) {
76
+ if (!h(e) && !n.options.silent) {
77
+ const t = d(e) ? e(r, n.input, String(n.index)) : e;
78
+ h(t) || n.output.push(t);
79
+ }
80
+ return n.index += r.length, n.indexMax = Math.max(n.indexMax, n.index), true;
81
+ } else return false;
82
+ }, C = (r, e, n, a) => {
83
+ const t = v(r);
84
+ return g(_(M((o) => {
85
+ let u = 0;
86
+ for (; u < n;) {
87
+ const s = o.index;
88
+ if (!t(o) || (u += 1, o.index === s)) break;
89
+ }
90
+ return u >= e;
91
+ })));
92
+ }, tr = (r, e) => C(r, 0, 1), f = (r, e) => C(r, 0, Infinity), x = (r, e) => {
93
+ const n = r.map(v);
94
+ return g(_(M((a) => {
95
+ for (let t = 0, o = n.length; t < o; t++) if (!n[t](a)) return false;
96
+ return true;
97
+ })));
98
+ }, l = (r, e) => {
99
+ const n = r.map(v);
100
+ return g(_((a) => {
101
+ for (let t = 0, o = n.length; t < o; t++) if (n[t](a)) return true;
102
+ return false;
103
+ }));
104
+ }, M = (r, e = false) => {
105
+ const n = v(r);
106
+ return (a) => {
107
+ const t = a.index, o = a.output.length, u = n(a);
108
+ return (!u || e) && (a.index = t, a.output.length !== o && (a.output.length = o)), u;
109
+ };
110
+ }, _ = (r, e) => {
111
+ return v(r);
112
+ }, g = (() => {
113
+ let r = 0;
114
+ return (e) => {
115
+ const n = v(e), a = r += 1;
116
+ return (t) => {
117
+ var o;
118
+ if (t.options.memoization === false) return n(t);
119
+ const u = t.index, s = (o = t.cache)[a] || (o[a] = /* @__PURE__ */ new Map()), c = s.get(u);
120
+ if (c === false) return false;
121
+ if (W(c)) return t.index = c, true;
122
+ if (c) return t.index = c.index, c.output?.length && t.output.push(...c.output), true;
123
+ {
124
+ const Z = t.output.length;
125
+ if (n(t)) {
126
+ const D = t.index, U = t.output.length;
127
+ if (U > Z) {
128
+ const ee = t.output.slice(Z, U);
129
+ s.set(u, {
130
+ index: D,
131
+ output: ee
132
+ });
133
+ } else s.set(u, D);
134
+ return true;
135
+ } else return s.set(u, false), false;
136
+ }
137
+ };
138
+ };
139
+ })(), E = (r) => {
140
+ let e;
141
+ return (n) => (e || (e = v(r())), e(n));
142
+ }, v = Y((r) => {
143
+ if (d(r)) return Q(r) ? E(r) : r;
144
+ if (b(r) || X(r)) return i(r);
145
+ if (A(r)) return x(r);
146
+ if (K(r)) return l(Object.values(r));
147
+ throw new Error("Invalid rule");
148
+ }), P = "abcdefghijklmnopqrstuvwxyz", ir = (r) => {
149
+ let e = "";
150
+ for (; r > 0;) e = P[(r - 1) % 26] + e, r = Math.floor((r - 1) / 26);
151
+ return e;
152
+ }, O = (r) => {
153
+ let e = 0;
154
+ for (let n = 0, a = r.length; n < a; n++) e = e * 26 + P.indexOf(r[n]) + 1;
155
+ return e;
156
+ }, S = (r, e) => {
157
+ if (e < r) return S(e, r);
158
+ const n = [];
159
+ for (; r <= e;) n.push(r++);
160
+ return n;
161
+ }, or = (r, e, n) => S(r, e).map((a) => String(a).padStart(n, "0")), R = (r, e) => S(O(r), O(e)).map(ir), p = (r) => r, z = (r) => ur((e) => rr(e, r, { memoization: false }).join("")), ur = (r) => {
162
+ const e = {};
163
+ return (n) => e[n] ?? (e[n] = r(n));
164
+ }, sr = i(/^\*\*\/\*$/, ".*"), cr = i(/^\*\*\/(\*)?([ a-zA-Z0-9._-]+)$/, (r, e, n) => `.*${e ? "" : "(?:^|/)"}${n.replaceAll(".", "\\.")}`), lr = i(/^\*\*\/(\*)?([ a-zA-Z0-9._-]*)\{([ a-zA-Z0-9._-]+(?:,[ a-zA-Z0-9._-]+)*)\}$/, (r, e, n, a) => `.*${e ? "" : "(?:^|/)"}${n.replaceAll(".", "\\.")}(?:${a.replaceAll(",", "|").replaceAll(".", "\\.")})`), y = i(/\\./, p), pr = i(/[$.*+?^(){}[\]\|]/, (r) => `\\${r}`), vr = i(/./, p), fr = l([i(/^(?:!!)*!(.*)$/, (r, e) => `(?!^${L(e)}$).*?`), i(/^(!!)+/, "")]), j = l([
165
+ i(/\/(\*\*\/)+/, "(?:/.+/|/)"),
166
+ i(/^(\*\*\/)+/, "(?:^|.*/)"),
167
+ i(/\/(\*\*)$/, "(?:/.*|$)"),
168
+ i(/\*\*/, ".*")
169
+ ]), N = l([i(/\*\/(?!\*\*\/)/, "[^/]*/"), i(/\*/, "[^/]*")]), k = i("?", "[^/]"), $r = i("[", p), wr = i("]", p), Ar = i(/[!^]/, "^/"), br = i(/[a-z]-[a-z]|[0-9]-[0-9]/i, p), Er = l([
170
+ y,
171
+ i(/[$.*+?^(){}[\|]/, (r) => `\\${r}`),
172
+ br,
173
+ i(/[^\]]/, p)
174
+ ]), B = x([
175
+ $r,
176
+ tr(Ar),
177
+ f(Er),
178
+ wr
179
+ ]), Pr = i("{", "(?:"), Or = i("}", ")"), I = x([
180
+ Pr,
181
+ l([
182
+ i(/(\d+)\.\.(\d+)/, (r, e, n) => or(+e, +n, Math.min(e.length, n.length)).join("|")),
183
+ i(/([a-z]+)\.\.([a-z]+)/, (r, e, n) => R(e, n).join("|")),
184
+ i(/([A-Z]+)\.\.([A-Z]+)/, (r, e, n) => R(e.toLowerCase(), n.toLowerCase()).join("|").toUpperCase())
185
+ ]),
186
+ Or
187
+ ]), kr = i("{", "(?:"), Br = i("}", ")"), Ir = i(",", "|"), Fr = i(/[$.*+?^(){[\]\|]/, (r) => `\\${r}`), Lr = i(/[^}]/, p), F = x([
188
+ kr,
189
+ f(l([
190
+ j,
191
+ N,
192
+ k,
193
+ B,
194
+ I,
195
+ E(() => F),
196
+ y,
197
+ Fr,
198
+ Ir,
199
+ Lr
200
+ ])),
201
+ Br
202
+ ]), L = z(f(l([
203
+ sr,
204
+ cr,
205
+ lr,
206
+ fr,
207
+ j,
208
+ N,
209
+ k,
210
+ B,
211
+ I,
212
+ F,
213
+ y,
214
+ pr,
215
+ vr
216
+ ]))), Tr = i(/\\./, p), qr = i(/./, p), Yr = z(f(l([
217
+ Tr,
218
+ i(/\*\*\*+/, "*"),
219
+ i(/([^/{[(!])\*\*/, (r, e) => `${e}*`),
220
+ i(/(^|.)\*\*(?=[^*/)\]}])/, (r, e) => `${e}*`),
221
+ qr
222
+ ]))), $ = (r, e) => {
223
+ const n = Array.isArray(r) ? r : [r];
224
+ if (!n.length) return false;
225
+ const a = n.map($.compile), t = n.every((s) => /(\/(?:\*\*)?|\[\/\])$/.test(s)), o = e.replace(/[\\\/]+/g, "/").replace(/\/$/, t ? "/" : "");
226
+ return a.some((s) => s.test(o));
227
+ };
228
+ $.compile = (r) => new RegExp(`^${L(Yr(r))}$`, "s");
229
+ var re = $;
230
+ return J(w);
231
+ })();
232
+ return __lib__.default || __lib__;
164
233
  };
165
- var _match;
166
- var zeptomatch = (path, pattern) => {
167
- if (!_match) {
168
- _match = _lazyMatch();
169
- _lazyMatch = null;
170
- }
171
- return _match(path, pattern);
234
+ let _match;
235
+ const zeptomatch = (path, pattern) => {
236
+ if (!_match) {
237
+ _match = _lazyMatch();
238
+ _lazyMatch = null;
239
+ }
240
+ return _match(path, pattern);
172
241
  };
173
- var _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
242
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
174
243
  function normalizeWindowsPath(input = "") {
175
- if (!input) {
176
- return input;
177
- }
178
- return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
244
+ if (!input) return input;
245
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
179
246
  }
180
- var _UNC_REGEX = /^[/\\]{2}/;
181
- var _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
182
- var _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
183
- var _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
184
- var _EXTNAME_RE = /.(\.[^./]+|\.)$/;
185
- var _PATH_ROOT_RE = /^[/\\]|^[a-zA-Z]:[/\\]/;
186
- var sep = "/";
187
- var normalize = function(path) {
188
- if (path.length === 0) {
189
- return ".";
190
- }
191
- path = normalizeWindowsPath(path);
192
- const isUNCPath = path.match(_UNC_REGEX);
193
- const isPathAbsolute = isAbsolute(path);
194
- const trailingSeparator = path[path.length - 1] === "/";
195
- path = normalizeString(path, !isPathAbsolute);
196
- if (path.length === 0) {
197
- if (isPathAbsolute) {
198
- return "/";
199
- }
200
- return trailingSeparator ? "./" : ".";
201
- }
202
- if (trailingSeparator) {
203
- path += "/";
204
- }
205
- if (_DRIVE_LETTER_RE.test(path)) {
206
- path += "/";
207
- }
208
- if (isUNCPath) {
209
- if (!isPathAbsolute) {
210
- return `//./${path}`;
211
- }
212
- return `//${path}`;
213
- }
214
- return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
247
+ const _UNC_REGEX = /^[/\\]{2}/;
248
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
249
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
250
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
251
+ const _EXTNAME_RE = /.(\.[^./]+|\.)$/;
252
+ const _PATH_ROOT_RE = /^[/\\]|^[a-zA-Z]:[/\\]/;
253
+ const normalize = function(path) {
254
+ if (path.length === 0) return ".";
255
+ path = normalizeWindowsPath(path);
256
+ const isUNCPath = path.match(_UNC_REGEX);
257
+ const isPathAbsolute = isAbsolute(path);
258
+ const trailingSeparator = path[path.length - 1] === "/";
259
+ path = normalizeString(path, !isPathAbsolute);
260
+ if (path.length === 0) {
261
+ if (isPathAbsolute) return "/";
262
+ return trailingSeparator ? "./" : ".";
263
+ }
264
+ if (trailingSeparator) path += "/";
265
+ if (_DRIVE_LETTER_RE.test(path)) path += "/";
266
+ if (isUNCPath) {
267
+ if (!isPathAbsolute) return `//./${path}`;
268
+ return `//${path}`;
269
+ }
270
+ return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
215
271
  };
216
- var join = function(...segments) {
217
- let path = "";
218
- for (const seg of segments) {
219
- if (!seg) {
220
- continue;
221
- }
222
- if (path.length > 0) {
223
- const pathTrailing = path[path.length - 1] === "/";
224
- const segLeading = seg[0] === "/";
225
- const both = pathTrailing && segLeading;
226
- if (both) {
227
- path += seg.slice(1);
228
- } else {
229
- path += pathTrailing || segLeading ? seg : `/${seg}`;
230
- }
231
- } else {
232
- path += seg;
233
- }
234
- }
235
- return normalize(path);
272
+ const join = function(...segments) {
273
+ let path = "";
274
+ for (const seg of segments) {
275
+ if (!seg) continue;
276
+ if (path.length > 0) {
277
+ const pathTrailing = path[path.length - 1] === "/";
278
+ const segLeading = seg[0] === "/";
279
+ if (pathTrailing && segLeading) path += seg.slice(1);
280
+ else path += pathTrailing || segLeading ? seg : `/${seg}`;
281
+ } else path += seg;
282
+ }
283
+ return normalize(path);
236
284
  };
237
285
  function cwd() {
238
- if (typeof process !== "undefined" && typeof process.cwd === "function") {
239
- return process.cwd().replace(/\\/g, "/");
240
- }
241
- return "/";
286
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
287
+ return "/";
242
288
  }
243
- var resolve = function(...arguments_) {
244
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
245
- let resolvedPath = "";
246
- let resolvedAbsolute = false;
247
- for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
248
- const path = index >= 0 ? arguments_[index] : cwd();
249
- if (!path || path.length === 0) {
250
- continue;
251
- }
252
- resolvedPath = `${path}/${resolvedPath}`;
253
- resolvedAbsolute = isAbsolute(path);
254
- }
255
- resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
256
- if (resolvedAbsolute && !isAbsolute(resolvedPath)) {
257
- return `/${resolvedPath}`;
258
- }
259
- return resolvedPath.length > 0 ? resolvedPath : ".";
289
+ const resolve = function(...arguments_) {
290
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
291
+ let resolvedPath = "";
292
+ let resolvedAbsolute = false;
293
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
294
+ const path = index >= 0 ? arguments_[index] : cwd();
295
+ if (!path || path.length === 0) continue;
296
+ resolvedPath = `${path}/${resolvedPath}`;
297
+ resolvedAbsolute = isAbsolute(path);
298
+ }
299
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
300
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
301
+ return resolvedPath.length > 0 ? resolvedPath : ".";
260
302
  };
261
303
  function normalizeString(path, allowAboveRoot) {
262
- let res = "";
263
- let lastSegmentLength = 0;
264
- let lastSlash = -1;
265
- let dots = 0;
266
- let char = null;
267
- for (let index = 0; index <= path.length; ++index) {
268
- if (index < path.length) {
269
- char = path[index];
270
- } else if (char === "/") {
271
- break;
272
- } else {
273
- char = "/";
274
- }
275
- if (char === "/") {
276
- if (lastSlash === index - 1 || dots === 1) ;
277
- else if (dots === 2) {
278
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
279
- if (res.length > 2) {
280
- const lastSlashIndex = res.lastIndexOf("/");
281
- if (lastSlashIndex === -1) {
282
- res = "";
283
- lastSegmentLength = 0;
284
- } else {
285
- res = res.slice(0, lastSlashIndex);
286
- lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
287
- }
288
- lastSlash = index;
289
- dots = 0;
290
- continue;
291
- } else if (res.length > 0) {
292
- res = "";
293
- lastSegmentLength = 0;
294
- lastSlash = index;
295
- dots = 0;
296
- continue;
297
- }
298
- }
299
- if (allowAboveRoot) {
300
- res += res.length > 0 ? "/.." : "..";
301
- lastSegmentLength = 2;
302
- }
303
- } else {
304
- if (res.length > 0) {
305
- res += `/${path.slice(lastSlash + 1, index)}`;
306
- } else {
307
- res = path.slice(lastSlash + 1, index);
308
- }
309
- lastSegmentLength = index - lastSlash - 1;
310
- }
311
- lastSlash = index;
312
- dots = 0;
313
- } else if (char === "." && dots !== -1) {
314
- ++dots;
315
- } else {
316
- dots = -1;
317
- }
318
- }
319
- return res;
304
+ let res = "";
305
+ let lastSegmentLength = 0;
306
+ let lastSlash = -1;
307
+ let dots = 0;
308
+ let char = null;
309
+ for (let index = 0; index <= path.length; ++index) {
310
+ if (index < path.length) char = path[index];
311
+ else if (char === "/") break;
312
+ else char = "/";
313
+ if (char === "/") {
314
+ if (lastSlash === index - 1 || dots === 1);
315
+ else if (dots === 2) {
316
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
317
+ if (res.length > 2) {
318
+ const lastSlashIndex = res.lastIndexOf("/");
319
+ if (lastSlashIndex === -1) {
320
+ res = "";
321
+ lastSegmentLength = 0;
322
+ } else {
323
+ res = res.slice(0, lastSlashIndex);
324
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
325
+ }
326
+ lastSlash = index;
327
+ dots = 0;
328
+ continue;
329
+ } else if (res.length > 0) {
330
+ res = "";
331
+ lastSegmentLength = 0;
332
+ lastSlash = index;
333
+ dots = 0;
334
+ continue;
335
+ }
336
+ }
337
+ if (allowAboveRoot) {
338
+ res += res.length > 0 ? "/.." : "..";
339
+ lastSegmentLength = 2;
340
+ }
341
+ } else {
342
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
343
+ else res = path.slice(lastSlash + 1, index);
344
+ lastSegmentLength = index - lastSlash - 1;
345
+ }
346
+ lastSlash = index;
347
+ dots = 0;
348
+ } else if (char === "." && dots !== -1) ++dots;
349
+ else dots = -1;
350
+ }
351
+ return res;
320
352
  }
321
- var isAbsolute = function(p) {
322
- return _IS_ABSOLUTE_RE.test(p);
353
+ const isAbsolute = function(p) {
354
+ return _IS_ABSOLUTE_RE.test(p);
323
355
  };
324
- var toNamespacedPath = function(p) {
325
- return normalizeWindowsPath(p);
356
+ const toNamespacedPath = function(p) {
357
+ return normalizeWindowsPath(p);
326
358
  };
327
- var extname = function(p) {
328
- if (p === "..") return "";
329
- const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
330
- return match && match[1] || "";
359
+ const extname = function(p) {
360
+ if (p === "..") return "";
361
+ const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
362
+ return match && match[1] || "";
331
363
  };
332
- var relative = function(from, to) {
333
- const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
334
- const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
335
- if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) {
336
- return _to.join("/");
337
- }
338
- const _fromCopy = [..._from];
339
- for (const segment of _fromCopy) {
340
- if (_to[0] !== segment) {
341
- break;
342
- }
343
- _from.shift();
344
- _to.shift();
345
- }
346
- return [..._from.map(() => ".."), ..._to].join("/");
364
+ const relative = function(from, to) {
365
+ const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
366
+ const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
367
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
368
+ const _fromCopy = [..._from];
369
+ for (const segment of _fromCopy) {
370
+ if (_to[0] !== segment) break;
371
+ _from.shift();
372
+ _to.shift();
373
+ }
374
+ return [..._from.map(() => ".."), ..._to].join("/");
347
375
  };
348
- var dirname = function(p) {
349
- const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
350
- if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) {
351
- segments[0] += "/";
352
- }
353
- return segments.join("/") || (isAbsolute(p) ? "/" : ".");
376
+ const dirname = function(p) {
377
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
378
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
379
+ return segments.join("/") || (isAbsolute(p) ? "/" : ".");
354
380
  };
355
- var format = function(p) {
356
- const ext = p.ext ? p.ext.startsWith(".") ? p.ext : `.${p.ext}` : "";
357
- const segments = [p.root, p.dir, p.base ?? (p.name ?? "") + ext].filter(
358
- Boolean
359
- );
360
- return normalizeWindowsPath(
361
- p.root ? resolve(...segments) : segments.join("/")
362
- );
381
+ const format = function(p) {
382
+ const ext = p.ext ? p.ext.startsWith(".") ? p.ext : `.${p.ext}` : "";
383
+ const segments = [
384
+ p.root,
385
+ p.dir,
386
+ p.base ?? (p.name ?? "") + ext
387
+ ].filter(Boolean);
388
+ return normalizeWindowsPath(p.root ? resolve(...segments) : segments.join("/"));
363
389
  };
364
- var basename = function(p, extension) {
365
- const segments = normalizeWindowsPath(p).split("/");
366
- let lastSegment = "";
367
- for (let i = segments.length - 1; i >= 0; i--) {
368
- const val = segments[i];
369
- if (val) {
370
- lastSegment = val;
371
- break;
372
- }
373
- }
374
- return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
390
+ const basename = function(p, extension) {
391
+ const segments = normalizeWindowsPath(p).split("/");
392
+ let lastSegment = "";
393
+ for (let i = segments.length - 1; i >= 0; i--) {
394
+ const val = segments[i];
395
+ if (val) {
396
+ lastSegment = val;
397
+ break;
398
+ }
399
+ }
400
+ return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
375
401
  };
376
- var parse = function(p) {
377
- const root = _PATH_ROOT_RE.exec(p)?.[0]?.replace(/\\/g, "/") || "";
378
- const base = basename(p);
379
- const extension = extname(base);
380
- return {
381
- root,
382
- dir: dirname(p),
383
- base,
384
- ext: extension,
385
- name: base.slice(0, base.length - extension.length)
386
- };
402
+ const parse = function(p) {
403
+ const root = _PATH_ROOT_RE.exec(p)?.[0]?.replace(/\\/g, "/") || "";
404
+ const base = basename(p);
405
+ const extension = extname(base);
406
+ return {
407
+ root,
408
+ dir: dirname(p),
409
+ base,
410
+ ext: extension,
411
+ name: base.slice(0, base.length - extension.length)
412
+ };
387
413
  };
388
- var matchesGlob = (path, pattern) => {
389
- return zeptomatch(pattern, normalize(path));
414
+ const matchesGlob = (path, pattern) => {
415
+ return zeptomatch(pattern, normalize(path));
390
416
  };
391
- var _path = {
392
- __proto__: null,
393
- basename,
394
- dirname,
395
- extname,
396
- format,
397
- isAbsolute,
398
- join,
399
- matchesGlob,
400
- normalize,
401
- normalizeString,
402
- parse,
403
- relative,
404
- resolve,
405
- sep,
406
- toNamespacedPath
417
+ const _path = {
418
+ __proto__: null,
419
+ basename,
420
+ dirname,
421
+ extname,
422
+ format,
423
+ isAbsolute,
424
+ join,
425
+ matchesGlob,
426
+ normalize,
427
+ normalizeString,
428
+ parse,
429
+ relative,
430
+ resolve,
431
+ sep: "/",
432
+ toNamespacedPath
407
433
  };
408
-
409
- // ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/index.mjs
410
- var delimiter = /* @__PURE__ */ (() => globalThis.process?.platform === "win32" ? ";" : ":")();
411
- var _platforms = { posix: void 0, win32: void 0 };
412
- var mix = (del = delimiter) => {
413
- return new Proxy(_path, {
414
- get(_, prop) {
415
- if (prop === "delimiter") return del;
416
- if (prop === "posix") return posix;
417
- if (prop === "win32") return win32;
418
- return _platforms[prop] || _path[prop];
419
- }
420
- });
434
+ //#endregion
435
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/index.mjs
436
+ const delimiter = globalThis.process?.platform === "win32" ? ";" : ":";
437
+ const _platforms = {
438
+ posix: void 0,
439
+ win32: void 0
421
440
  };
422
- var posix = /* @__PURE__ */ mix(":");
423
- var win32 = /* @__PURE__ */ mix(";");
424
-
425
- // src/context.ts
441
+ const mix = (del = delimiter) => {
442
+ return new Proxy(_path, { get(_, prop) {
443
+ if (prop === "delimiter") return del;
444
+ if (prop === "posix") return posix;
445
+ if (prop === "win32") return win32;
446
+ return _platforms[prop] || _path[prop];
447
+ } });
448
+ };
449
+ const posix = /* @__PURE__ */ mix(":");
450
+ const win32 = /* @__PURE__ */ mix(";");
451
+ //#endregion
452
+ //#region src/context.ts
426
453
  function createDocument() {
427
- return {
428
- name: "",
429
- path: "",
430
- value: null
431
- };
454
+ return {
455
+ name: "",
456
+ path: "",
457
+ value: null
458
+ };
432
459
  }
460
+ /**
461
+ * @description 创建初始化上下文
462
+ */
433
463
  function createContext() {
434
- return {
435
- projectConfig: createDocument(),
436
- packageJson: createDocument(),
437
- viteConfig: createDocument(),
438
- tsconfig: createDocument(),
439
- tsconfigApp: createDocument(),
440
- tsconfigNode: createDocument(),
441
- dts: createDocument()
442
- };
464
+ return {
465
+ projectConfig: createDocument(),
466
+ packageJson: createDocument(),
467
+ viteConfig: createDocument(),
468
+ tsconfig: createDocument(),
469
+ tsconfigApp: createDocument(),
470
+ tsconfigNode: createDocument(),
471
+ dts: createDocument()
472
+ };
443
473
  }
444
-
445
- // src/state.ts
446
- var ctx = createContext();
474
+ //#endregion
475
+ //#region src/state.ts
476
+ /**
477
+ * @description 全局上下文(用于 init 过程中的状态存储)
478
+ */
479
+ const ctx = createContext();
480
+ /**
481
+ * @description 重置全局上下文
482
+ */
447
483
  function resetContext() {
448
- const next = createContext();
449
- Object.assign(ctx.projectConfig, next.projectConfig);
450
- Object.assign(ctx.packageJson, next.packageJson);
451
- Object.assign(ctx.viteConfig, next.viteConfig);
452
- Object.assign(ctx.tsconfig, next.tsconfig);
453
- Object.assign(ctx.tsconfigApp, next.tsconfigApp);
454
- Object.assign(ctx.tsconfigNode, next.tsconfigNode);
455
- Object.assign(ctx.dts, next.dts);
484
+ const next = createContext();
485
+ Object.assign(ctx.projectConfig, next.projectConfig);
486
+ Object.assign(ctx.packageJson, next.packageJson);
487
+ Object.assign(ctx.viteConfig, next.viteConfig);
488
+ Object.assign(ctx.tsconfig, next.tsconfig);
489
+ Object.assign(ctx.tsconfigApp, next.tsconfigApp);
490
+ Object.assign(ctx.tsconfigNode, next.tsconfigNode);
491
+ Object.assign(ctx.dts, next.dts);
456
492
  }
457
-
458
- // src/tsconfigJson.ts
459
- var srcIncludeGlobs = [
460
- "src/**/*.ts",
461
- "src/**/*.tsx",
462
- "src/**/*.js",
463
- "src/**/*.jsx",
464
- "src/**/*.mts",
465
- "src/**/*.cts",
466
- "src/**/*.vue",
467
- "src/**/*.json",
468
- "src/**/*.d.ts",
469
- "types/**/*.d.ts",
470
- "env.d.ts"
493
+ //#endregion
494
+ //#region src/tsconfigJson.ts
495
+ const srcIncludeGlobs = [
496
+ "src/**/*.ts",
497
+ "src/**/*.tsx",
498
+ "src/**/*.js",
499
+ "src/**/*.jsx",
500
+ "src/**/*.mts",
501
+ "src/**/*.cts",
502
+ "src/**/*.vue",
503
+ "src/**/*.json",
504
+ "src/**/*.d.ts",
505
+ "types/**/*.d.ts",
506
+ "env.d.ts"
471
507
  ];
508
+ /**
509
+ * @description 生成默认 tsconfig.json
510
+ */
472
511
  function getDefaultTsconfigJson() {
473
- return {
474
- references: [
475
- {
476
- path: "./tsconfig.app.json"
477
- },
478
- {
479
- path: "./tsconfig.node.json"
480
- }
481
- ],
482
- files: []
483
- };
512
+ return {
513
+ references: [{ path: "./tsconfig.app.json" }, { path: "./tsconfig.node.json" }],
514
+ files: []
515
+ };
484
516
  }
517
+ /**
518
+ * @description 生成默认 tsconfig.app.json
519
+ */
485
520
  function getDefaultTsconfigAppJson() {
486
- return {
487
- compilerOptions: {
488
- tsBuildInfoFile: "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
489
- target: "ES2023",
490
- lib: [
491
- "ES2023",
492
- "DOM",
493
- "DOM.Iterable"
494
- ],
495
- jsx: "preserve",
496
- module: "ESNext",
497
- moduleResolution: "bundler",
498
- moduleDetection: "force",
499
- baseUrl: ".",
500
- paths: {
501
- "@/*": [
502
- "./src/*"
503
- ]
504
- },
505
- resolveJsonModule: true,
506
- types: [
507
- "miniprogram-api-typings"
508
- ],
509
- allowImportingTsExtensions: true,
510
- allowJs: true,
511
- allowSyntheticDefaultImports: true,
512
- esModuleInterop: true,
513
- isolatedModules: true,
514
- strict: true,
515
- noFallthroughCasesInSwitch: true,
516
- noUnusedLocals: true,
517
- noUnusedParameters: true,
518
- noEmit: true,
519
- verbatimModuleSyntax: true,
520
- noUncheckedSideEffectImports: true,
521
- erasableSyntaxOnly: true,
522
- skipLibCheck: true
523
- },
524
- include: srcIncludeGlobs
525
- };
521
+ return {
522
+ compilerOptions: {
523
+ tsBuildInfoFile: "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
524
+ target: "ES2023",
525
+ lib: [
526
+ "ES2023",
527
+ "DOM",
528
+ "DOM.Iterable"
529
+ ],
530
+ jsx: "preserve",
531
+ module: "ESNext",
532
+ moduleResolution: "bundler",
533
+ moduleDetection: "force",
534
+ baseUrl: ".",
535
+ paths: { "@/*": ["./src/*"] },
536
+ resolveJsonModule: true,
537
+ types: ["miniprogram-api-typings"],
538
+ allowImportingTsExtensions: true,
539
+ allowJs: true,
540
+ allowSyntheticDefaultImports: true,
541
+ esModuleInterop: true,
542
+ isolatedModules: true,
543
+ strict: true,
544
+ noFallthroughCasesInSwitch: true,
545
+ noUnusedLocals: true,
546
+ noUnusedParameters: true,
547
+ noEmit: true,
548
+ verbatimModuleSyntax: true,
549
+ noUncheckedSideEffectImports: true,
550
+ erasableSyntaxOnly: true,
551
+ skipLibCheck: true
552
+ },
553
+ include: srcIncludeGlobs
554
+ };
526
555
  }
556
+ /**
557
+ * @description 生成默认 tsconfig.node.json
558
+ */
527
559
  function getDefaultTsconfigNodeJson(include = []) {
528
- const baseInclude = [
529
- "vite.config.ts",
530
- "vite.config.*.ts",
531
- "*.config.ts",
532
- "config/**/*.ts",
533
- "scripts/**/*.ts"
534
- ];
535
- const mergedInclude = Array.from(/* @__PURE__ */ new Set([
536
- ...baseInclude,
537
- ...include
538
- ]));
539
- return {
540
- compilerOptions: {
541
- tsBuildInfoFile: "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
542
- target: "ES2023",
543
- lib: [
544
- "ES2023"
545
- ],
546
- module: "ESNext",
547
- moduleResolution: "bundler",
548
- moduleDetection: "force",
549
- types: [
550
- "node"
551
- ],
552
- allowImportingTsExtensions: true,
553
- resolveJsonModule: true,
554
- verbatimModuleSyntax: true,
555
- strict: true,
556
- noFallthroughCasesInSwitch: true,
557
- noUnusedLocals: true,
558
- noUnusedParameters: true,
559
- noEmit: true,
560
- noUncheckedSideEffectImports: true,
561
- erasableSyntaxOnly: true,
562
- skipLibCheck: true
563
- },
564
- include: mergedInclude
565
- };
560
+ return {
561
+ compilerOptions: {
562
+ tsBuildInfoFile: "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
563
+ target: "ES2023",
564
+ lib: ["ES2023"],
565
+ module: "ESNext",
566
+ moduleResolution: "bundler",
567
+ moduleDetection: "force",
568
+ types: ["node"],
569
+ allowImportingTsExtensions: true,
570
+ resolveJsonModule: true,
571
+ verbatimModuleSyntax: true,
572
+ strict: true,
573
+ noFallthroughCasesInSwitch: true,
574
+ noUnusedLocals: true,
575
+ noUnusedParameters: true,
576
+ noEmit: true,
577
+ noUncheckedSideEffectImports: true,
578
+ erasableSyntaxOnly: true,
579
+ skipLibCheck: true
580
+ },
581
+ include: [...new Set([...[
582
+ "vite.config.ts",
583
+ "vite.config.*.ts",
584
+ "*.config.ts",
585
+ "config/**/*.ts",
586
+ "scripts/**/*.ts"
587
+ ], ...include])]
588
+ };
566
589
  }
567
-
568
- // src/tsDts.ts
590
+ //#endregion
591
+ //#region src/tsDts.ts
592
+ /**
593
+ * @description 生成默认的 env.d.ts 模板
594
+ */
569
595
  function getDefaultTsDts() {
570
- return `/// <reference types="weapp-vite/client" />
596
+ return `/// <reference types="weapp-vite/client" />
571
597
  `;
572
598
  }
573
-
574
- // src/utils/fs.ts
575
- import fs from "fs-extra";
599
+ //#endregion
600
+ //#region src/utils/fs.ts
601
+ /**
602
+ * @description 文件读取错误
603
+ */
576
604
  var FsReadError = class extends Error {
577
- constructor(filepath, cause) {
578
- super(`Failed to read ${filepath}`);
579
- this.filepath = filepath;
580
- this.cause = cause;
581
- this.name = "FsReadError";
582
- }
605
+ constructor(filepath, cause) {
606
+ super(`Failed to read ${filepath}`);
607
+ this.filepath = filepath;
608
+ this.cause = cause;
609
+ this.name = "FsReadError";
610
+ }
583
611
  };
612
+ /**
613
+ * @description 文件写入错误
614
+ */
584
615
  var FsWriteError = class extends Error {
585
- constructor(filepath, cause) {
586
- super(`Failed to write ${filepath}`);
587
- this.filepath = filepath;
588
- this.cause = cause;
589
- this.name = "FsWriteError";
590
- }
616
+ constructor(filepath, cause) {
617
+ super(`Failed to write ${filepath}`);
618
+ this.filepath = filepath;
619
+ this.cause = cause;
620
+ this.name = "FsWriteError";
621
+ }
591
622
  };
623
+ /**
624
+ * @description 读取 JSON 文件;不存在则返回 null
625
+ */
592
626
  async function readJsonIfExists(filepath) {
593
- try {
594
- return await fs.readJSON(filepath);
595
- } catch (error) {
596
- if (error?.code === "ENOENT") {
597
- return null;
598
- }
599
- throw new FsReadError(filepath, error);
600
- }
627
+ try {
628
+ return await fs.readJSON(filepath);
629
+ } catch (error) {
630
+ if (error?.code === "ENOENT") return null;
631
+ throw new FsReadError(filepath, error);
632
+ }
601
633
  }
634
+ /**
635
+ * @description 读取文本文件;不存在则返回 null
636
+ */
602
637
  async function readFileIfExists(filepath) {
603
- try {
604
- return await fs.readFile(filepath, "utf8");
605
- } catch (error) {
606
- if (error?.code === "ENOENT") {
607
- return null;
608
- }
609
- throw new FsReadError(filepath, error);
610
- }
638
+ try {
639
+ return await fs.readFile(filepath, "utf8");
640
+ } catch (error) {
641
+ if (error?.code === "ENOENT") return null;
642
+ throw new FsReadError(filepath, error);
643
+ }
611
644
  }
645
+ /**
646
+ * @description 写入 JSON 文件
647
+ */
612
648
  async function writeJsonFile(filepath, data, spaces = 2) {
613
- try {
614
- await fs.outputJSON(filepath, data, {
615
- spaces
616
- });
617
- } catch (error) {
618
- throw new FsWriteError(filepath, error);
619
- }
649
+ try {
650
+ await fs.outputJSON(filepath, data, { spaces });
651
+ } catch (error) {
652
+ throw new FsWriteError(filepath, error);
653
+ }
620
654
  }
655
+ /**
656
+ * @description 写入文本文件
657
+ */
621
658
  async function writeFile(filepath, contents) {
622
- try {
623
- await fs.outputFile(filepath, contents, "utf8");
624
- } catch (error) {
625
- throw new FsWriteError(filepath, error);
626
- }
659
+ try {
660
+ await fs.outputFile(filepath, contents, "utf8");
661
+ } catch (error) {
662
+ throw new FsWriteError(filepath, error);
663
+ }
627
664
  }
628
-
629
- // src/utils/path.ts
665
+ //#endregion
666
+ //#region src/utils/path.ts
667
+ /**
668
+ * @description 根据输出目录配置解析最终输出路径
669
+ */
630
670
  function resolveOutputPath(root, dest, fallback) {
631
- if (!dest) {
632
- return fallback;
633
- }
634
- return posix.isAbsolute(dest) ? dest : posix.resolve(root, dest);
671
+ if (!dest) return fallback;
672
+ return posix.isAbsolute(dest) ? dest : posix.resolve(root, dest);
635
673
  }
636
-
637
- // src/viteConfig.ts
674
+ //#endregion
675
+ //#region src/viteConfig.ts
676
+ /**
677
+ * @description 生成默认的 vite.config.ts 模板
678
+ */
638
679
  function getDefaultViteConfig() {
639
- return `import { defineConfig } from 'weapp-vite/config'
680
+ return `import { defineConfig } from 'weapp-vite/config'
640
681
 
641
682
  export default defineConfig({
642
683
  weapp: {
@@ -645,301 +686,273 @@ export default defineConfig({
645
686
  })
646
687
  `;
647
688
  }
648
-
649
- // src/configFiles.ts
689
+ //#endregion
690
+ //#region src/configFiles.ts
650
691
  async function initViteConfigFile(options) {
651
- const { root, dest, write = true } = options;
652
- const packageType = ctx.packageJson.value?.type ?? "module";
653
- const targetFilename = ctx.viteConfig.name = packageType === "module" ? "vite.config.ts" : "vite.config.mts";
654
- const viteConfigFilePath = ctx.viteConfig.path = posix.resolve(root, targetFilename);
655
- const outputPath = resolveOutputPath(root, dest, viteConfigFilePath);
656
- const code = getDefaultViteConfig();
657
- ctx.viteConfig.value = code;
658
- if (write) {
659
- await writeFile(outputPath, code);
660
- logger.log(`\u2728 \u5199\u5165 ${posix.relative(root, outputPath)} \u6210\u529F!`);
661
- }
662
- return code;
692
+ const { root, dest, write = true } = options;
693
+ const packageType = ctx.packageJson.value?.type ?? "module";
694
+ const targetFilename = ctx.viteConfig.name = packageType === "module" ? "vite.config.ts" : "vite.config.mts";
695
+ const outputPath = resolveOutputPath(root, dest, ctx.viteConfig.path = posix.resolve(root, targetFilename));
696
+ const code = getDefaultViteConfig();
697
+ ctx.viteConfig.value = code;
698
+ if (write) {
699
+ await writeFile(outputPath, code);
700
+ logger.log(`✨ 写入 ${posix.relative(root, outputPath)} 成功!`);
701
+ }
702
+ return code;
663
703
  }
664
704
  async function initTsDtsFile(options) {
665
- const { root, dest, write = true } = options;
666
- const targetFilename = ctx.dts.name = "vite-env.d.ts";
667
- const viteDtsFilePath = ctx.dts.path = posix.resolve(root, targetFilename);
668
- const outputPath = resolveOutputPath(root, dest, viteDtsFilePath);
669
- const code = getDefaultTsDts();
670
- ctx.dts.value = code;
671
- if (write) {
672
- await writeFile(outputPath, code);
673
- logger.log(`\u2728 \u5199\u5165 ${posix.relative(root, outputPath)} \u6210\u529F!`);
674
- }
675
- return code;
705
+ const { root, dest, write = true } = options;
706
+ const targetFilename = ctx.dts.name = "vite-env.d.ts";
707
+ const outputPath = resolveOutputPath(root, dest, ctx.dts.path = posix.resolve(root, targetFilename));
708
+ const code = getDefaultTsDts();
709
+ ctx.dts.value = code;
710
+ if (write) {
711
+ await writeFile(outputPath, code);
712
+ logger.log(`✨ 写入 ${posix.relative(root, outputPath)} 成功!`);
713
+ }
714
+ return code;
676
715
  }
677
716
  async function initTsJsonFiles(options) {
678
- const { root, dest, write = true } = options;
679
- const tsJsonFilename = ctx.tsconfig.name = "tsconfig.json";
680
- const tsJsonFilePath = ctx.tsconfig.path = posix.resolve(root, tsJsonFilename);
681
- const tsAppJsonFilename = ctx.tsconfigApp.name = "tsconfig.app.json";
682
- const tsAppJsonFilePath = ctx.tsconfigApp.path = posix.resolve(root, tsAppJsonFilename);
683
- const tsNodeJsonFilename = ctx.tsconfigNode.name = "tsconfig.node.json";
684
- const tsNodeJsonFilePath = ctx.tsconfigNode.path = posix.resolve(root, tsNodeJsonFilename);
685
- const tsconfig = getDefaultTsconfigJson();
686
- const tsconfigApp = getDefaultTsconfigAppJson();
687
- const includeFiles = ctx.viteConfig.name ? [ctx.viteConfig.name] : [];
688
- const tsconfigNode = getDefaultTsconfigNodeJson(includeFiles);
689
- ctx.tsconfig.value = tsconfig;
690
- ctx.tsconfigApp.value = tsconfigApp;
691
- ctx.tsconfigNode.value = tsconfigNode;
692
- if (write) {
693
- const tsconfigOutputPath = resolveOutputPath(root, dest, tsJsonFilePath);
694
- const tsconfigAppOutputPath = resolveOutputPath(root, dest, tsAppJsonFilePath);
695
- const tsconfigNodeOutputPath = resolveOutputPath(root, dest, tsNodeJsonFilePath);
696
- await writeJsonFile(tsconfigOutputPath, tsconfig);
697
- await writeJsonFile(tsconfigAppOutputPath, tsconfigApp);
698
- await writeJsonFile(tsconfigNodeOutputPath, tsconfigNode);
699
- logger.log(
700
- `\u2728 \u5199\u5165 ${[
701
- posix.relative(root, tsconfigOutputPath),
702
- posix.relative(root, tsconfigAppOutputPath),
703
- posix.relative(root, tsconfigNodeOutputPath)
704
- ].join(", ")} \u6210\u529F!`
705
- );
706
- }
707
- return {
708
- tsconfig,
709
- tsconfigApp,
710
- tsconfigNode
711
- };
717
+ const { root, dest, write = true } = options;
718
+ const tsJsonFilename = ctx.tsconfig.name = "tsconfig.json";
719
+ const tsJsonFilePath = ctx.tsconfig.path = posix.resolve(root, tsJsonFilename);
720
+ const tsAppJsonFilename = ctx.tsconfigApp.name = "tsconfig.app.json";
721
+ const tsAppJsonFilePath = ctx.tsconfigApp.path = posix.resolve(root, tsAppJsonFilename);
722
+ const tsNodeJsonFilename = ctx.tsconfigNode.name = "tsconfig.node.json";
723
+ const tsNodeJsonFilePath = ctx.tsconfigNode.path = posix.resolve(root, tsNodeJsonFilename);
724
+ const tsconfig = getDefaultTsconfigJson();
725
+ const tsconfigApp = getDefaultTsconfigAppJson();
726
+ const tsconfigNode = getDefaultTsconfigNodeJson(ctx.viteConfig.name ? [ctx.viteConfig.name] : []);
727
+ ctx.tsconfig.value = tsconfig;
728
+ ctx.tsconfigApp.value = tsconfigApp;
729
+ ctx.tsconfigNode.value = tsconfigNode;
730
+ if (write) {
731
+ const tsconfigOutputPath = resolveOutputPath(root, dest, tsJsonFilePath);
732
+ const tsconfigAppOutputPath = resolveOutputPath(root, dest, tsAppJsonFilePath);
733
+ const tsconfigNodeOutputPath = resolveOutputPath(root, dest, tsNodeJsonFilePath);
734
+ await writeJsonFile(tsconfigOutputPath, tsconfig);
735
+ await writeJsonFile(tsconfigAppOutputPath, tsconfigApp);
736
+ await writeJsonFile(tsconfigNodeOutputPath, tsconfigNode);
737
+ logger.log(`✨ 写入 ${[
738
+ posix.relative(root, tsconfigOutputPath),
739
+ posix.relative(root, tsconfigAppOutputPath),
740
+ posix.relative(root, tsconfigNodeOutputPath)
741
+ ].join(", ")} 成功!`);
742
+ }
743
+ return {
744
+ tsconfig,
745
+ tsconfigApp,
746
+ tsconfigNode
747
+ };
712
748
  }
713
-
714
- // src/packageJson.ts
715
- import logger2 from "@weapp-core/logger";
716
- import { defu, get, set } from "@weapp-core/shared";
717
-
718
- // ../../packages/weapp-vite/package.json
719
- var version = "6.5.1";
720
-
721
- // src/npm.ts
722
- import https from "https";
749
+ //#endregion
750
+ //#region ../../packages/weapp-vite/package.json
751
+ var version = "6.9.1";
752
+ //#endregion
753
+ //#region src/npm.ts
754
+ /**
755
+ * @description npm registry 获取包的最新版本号
756
+ */
723
757
  function getLatestVersionFromNpm(packageName) {
724
- return new Promise((resolve2, reject) => {
725
- const url = `https://registry.npmjs.org/${packageName}/latest`;
726
- https.get(url, (res) => {
727
- if (!res || res.statusCode && res.statusCode >= 400) {
728
- res?.resume();
729
- reject(new Error(`Request to ${url} failed with status ${res?.statusCode ?? "unknown"}`));
730
- return;
731
- }
732
- let data = "";
733
- res.setEncoding("utf8");
734
- res.on("data", (chunk) => data += chunk);
735
- res.on("end", () => {
736
- try {
737
- const json = JSON.parse(data);
738
- if (!json.version || typeof json.version !== "string") {
739
- reject(new Error(`Unexpected response when fetching ${packageName}: missing version`));
740
- return;
741
- }
742
- resolve2(json.version);
743
- } catch (err) {
744
- reject(err);
745
- }
746
- });
747
- res.on("error", reject);
748
- }).on("error", reject);
749
- });
758
+ return new Promise((resolve, reject) => {
759
+ const url = `https://registry.npmjs.org/${packageName}/latest`;
760
+ https.get(url, (res) => {
761
+ if (!res || res.statusCode && res.statusCode >= 400) {
762
+ res?.resume();
763
+ reject(/* @__PURE__ */ new Error(`Request to ${url} failed with status ${res?.statusCode ?? "unknown"}`));
764
+ return;
765
+ }
766
+ let data = "";
767
+ res.setEncoding("utf8");
768
+ res.on("data", (chunk) => data += chunk);
769
+ res.on("end", () => {
770
+ try {
771
+ const json = JSON.parse(data);
772
+ if (!json.version || typeof json.version !== "string") {
773
+ reject(/* @__PURE__ */ new Error(`Unexpected response when fetching ${packageName}: missing version`));
774
+ return;
775
+ }
776
+ resolve(json.version);
777
+ } catch (err) {
778
+ reject(err);
779
+ }
780
+ });
781
+ res.on("error", reject);
782
+ }).on("error", reject);
783
+ });
750
784
  }
751
785
  async function latestVersion(packageName, prefix = "^", fetch = getLatestVersionFromNpm) {
752
- try {
753
- const resolved = await fetch(packageName);
754
- if (!resolved) {
755
- return null;
756
- }
757
- return `${prefix}${resolved}`;
758
- } catch {
759
- return null;
760
- }
786
+ try {
787
+ const resolved = await fetch(packageName);
788
+ if (!resolved) return null;
789
+ return `${prefix}${resolved}`;
790
+ } catch {
791
+ return null;
792
+ }
761
793
  }
762
-
763
- // src/packageJson.ts
764
- var FALLBACK_DEP_VERSIONS = {
765
- "miniprogram-api-typings": "^4.1.0",
766
- "typescript": "^5.9.2",
767
- "weapp-tailwindcss": "^4.3.3"
794
+ //#endregion
795
+ //#region src/packageJson.ts
796
+ const FALLBACK_DEP_VERSIONS = {
797
+ "miniprogram-api-typings": "^4.1.0",
798
+ "typescript": "^5.9.2",
799
+ "weapp-tailwindcss": "^4.3.3"
768
800
  };
801
+ /**
802
+ * @description 创建默认 package.json 模板
803
+ */
769
804
  function createDefaultPackageJson() {
770
- return {
771
- name: "weapp-vite-app",
772
- homepage: "https://vite.icebreaker.top/",
773
- type: "module",
774
- scripts: {},
775
- devDependencies: {}
776
- };
805
+ return {
806
+ name: "weapp-vite-app",
807
+ homepage: "https://vite.icebreaker.top/",
808
+ type: "module",
809
+ scripts: {},
810
+ devDependencies: {}
811
+ };
777
812
  }
813
+ /**
814
+ * @description 写入/更新依赖版本
815
+ */
778
816
  async function upsertDependencyVersion(packageJson, keyPath, packageName, options = {}) {
779
- const currentValue = get(packageJson, keyPath);
780
- const resolved = options.skipNetwork ? null : await latestVersion(packageName);
781
- if (resolved) {
782
- set(packageJson, keyPath, resolved);
783
- return;
784
- }
785
- if (currentValue === void 0) {
786
- const fallback = FALLBACK_DEP_VERSIONS[packageName] ?? "latest";
787
- set(packageJson, keyPath, fallback);
788
- }
817
+ const currentValue = get(packageJson, keyPath);
818
+ const resolved = options.skipNetwork ? null : await latestVersion(packageName);
819
+ if (resolved) {
820
+ set(packageJson, keyPath, resolved);
821
+ return;
822
+ }
823
+ if (currentValue === void 0) set(packageJson, keyPath, FALLBACK_DEP_VERSIONS[packageName] ?? "latest");
789
824
  }
825
+ /**
826
+ * @description 创建或更新 package.json
827
+ */
790
828
  async function createOrUpdatePackageJson(options) {
791
- const { root, dest, command, cb, write, filename } = defu(options, {
792
- write: true,
793
- filename: "package.json",
794
- command: "weapp-vite"
795
- });
796
- const packageJsonFilename = ctx.packageJson.name = filename;
797
- const packageJsonPath = ctx.packageJson.path = posix.resolve(root, packageJsonFilename);
798
- const outputPath = resolveOutputPath(root, dest, packageJsonPath);
799
- try {
800
- let packageJson = await readJsonIfExists(packageJsonPath);
801
- if (!packageJson) {
802
- packageJson = createDefaultPackageJson();
803
- logger2.info(`\u2728 \u6CA1\u6709\u627E\u5230 ${packageJsonFilename} \u6587\u4EF6\uFF0C\u6B63\u5728\u521B\u5EFA\u9ED8\u8BA4 package.json ...`);
804
- }
805
- set(packageJson, "scripts.dev", `${command} dev`);
806
- set(packageJson, "scripts.dev:open", `${command} dev -o`);
807
- set(packageJson, "scripts.build", `${command} build`);
808
- if (command === "weapp-vite") {
809
- set(packageJson, "scripts.open", `${command} open`);
810
- set(packageJson, "scripts.g", `${command} generate`);
811
- set(packageJson, "devDependencies.weapp-vite", `^${version}`);
812
- await Promise.all([
813
- upsertDependencyVersion(packageJson, "devDependencies.miniprogram-api-typings", "miniprogram-api-typings", { skipNetwork: !write }),
814
- upsertDependencyVersion(packageJson, "devDependencies.typescript", "typescript", { skipNetwork: !write })
815
- ]);
816
- }
817
- cb?.(
818
- (...args) => {
819
- set(packageJson, ...args);
820
- }
821
- );
822
- ctx.packageJson.value = packageJson;
823
- if (write) {
824
- await writeJsonFile(outputPath, packageJson);
825
- logger2.log(`\u2728 \u5199\u5165 ${posix.relative(root, outputPath)} \u6210\u529F!`);
826
- }
827
- return packageJson;
828
- } catch (error) {
829
- logger2.error(`\u26A0\uFE0F \u8BBE\u7F6E ${packageJsonFilename} \u914D\u7F6E\u6587\u4EF6\u5931\u8D25`, error);
830
- throw error;
831
- }
829
+ const { root, dest, command, cb, write, filename } = defu(options, {
830
+ write: true,
831
+ filename: "package.json",
832
+ command: "weapp-vite"
833
+ });
834
+ const packageJsonFilename = ctx.packageJson.name = filename;
835
+ const packageJsonPath = ctx.packageJson.path = posix.resolve(root, packageJsonFilename);
836
+ const outputPath = resolveOutputPath(root, dest, packageJsonPath);
837
+ try {
838
+ let packageJson = await readJsonIfExists(packageJsonPath);
839
+ if (!packageJson) {
840
+ packageJson = createDefaultPackageJson();
841
+ logger.info(`✨ 没有找到 ${packageJsonFilename} 文件,正在创建默认 package.json ...`);
842
+ }
843
+ set(packageJson, "scripts.dev", `${command} dev`);
844
+ set(packageJson, "scripts.dev:open", `${command} dev -o`);
845
+ set(packageJson, "scripts.build", `${command} build`);
846
+ if (command === "weapp-vite") {
847
+ set(packageJson, "scripts.open", `${command} open`);
848
+ set(packageJson, "scripts.g", `${command} generate`);
849
+ set(packageJson, "devDependencies.weapp-vite", `^${version}`);
850
+ await Promise.all([upsertDependencyVersion(packageJson, "devDependencies.miniprogram-api-typings", "miniprogram-api-typings", { skipNetwork: !write }), upsertDependencyVersion(packageJson, "devDependencies.typescript", "typescript", { skipNetwork: !write })]);
851
+ }
852
+ cb?.((...args) => {
853
+ set(packageJson, ...args);
854
+ });
855
+ ctx.packageJson.value = packageJson;
856
+ if (write) {
857
+ await writeJsonFile(outputPath, packageJson);
858
+ logger.log(`✨ 写入 ${posix.relative(root, outputPath)} 成功!`);
859
+ }
860
+ return packageJson;
861
+ } catch (error) {
862
+ logger.error(`⚠️ 设置 ${packageJsonFilename} 配置文件失败`, error);
863
+ throw error;
864
+ }
832
865
  }
833
-
834
- // src/projectConfig.ts
835
- import logger3 from "@weapp-core/logger";
836
- import { defu as defu2, get as get2, set as set2 } from "@weapp-core/shared";
866
+ //#endregion
867
+ //#region src/projectConfig.ts
837
868
  function applyProjectConfigDefaults(projectConfig) {
838
- set2(projectConfig, "miniprogramRoot", "dist/");
839
- set2(projectConfig, "srcMiniprogramRoot", "dist/");
840
- set2(projectConfig, "setting.packNpmManually", true);
841
- const compileType = get2(projectConfig, "compileType");
842
- if (compileType === "plugin") {
843
- set2(projectConfig, "pluginRoot", "dist-plugin");
844
- }
869
+ set(projectConfig, "miniprogramRoot", "dist/");
870
+ set(projectConfig, "srcMiniprogramRoot", "dist/");
871
+ set(projectConfig, "setting.packNpmManually", true);
872
+ if (get(projectConfig, "compileType") === "plugin") set(projectConfig, "pluginRoot", "dist-plugin");
845
873
  }
846
874
  function ensurePackNpmRelationList(projectConfig) {
847
- const relations = get2(projectConfig, "setting.packNpmRelationList");
848
- const defaultRelation = {
849
- packageJsonPath: "./package.json",
850
- miniprogramNpmDistDir: "./dist"
851
- };
852
- if (Array.isArray(relations)) {
853
- const exists = relations.some(
854
- (relation) => relation.packageJsonPath === defaultRelation.packageJsonPath && relation.miniprogramNpmDistDir === defaultRelation.miniprogramNpmDistDir
855
- );
856
- if (!exists) {
857
- relations.push(defaultRelation);
858
- }
859
- } else {
860
- set2(projectConfig, "setting.packNpmRelationList", [defaultRelation]);
861
- }
875
+ const relations = get(projectConfig, "setting.packNpmRelationList");
876
+ const defaultRelation = {
877
+ packageJsonPath: "./package.json",
878
+ miniprogramNpmDistDir: "./dist"
879
+ };
880
+ if (Array.isArray(relations)) {
881
+ if (!relations.some((relation) => relation.packageJsonPath === defaultRelation.packageJsonPath && relation.miniprogramNpmDistDir === defaultRelation.miniprogramNpmDistDir)) relations.push(defaultRelation);
882
+ } else set(projectConfig, "setting.packNpmRelationList", [defaultRelation]);
862
883
  }
863
884
  function createDefaultProjectConfig() {
864
- return {
865
- compileType: "miniprogram",
866
- libVersion: "trial",
867
- packOptions: {
868
- ignore: [],
869
- include: []
870
- },
871
- setting: {
872
- coverView: true,
873
- es6: true,
874
- postcss: true,
875
- minified: true,
876
- enhance: true,
877
- showShadowRootInWxmlPanel: true,
878
- packNpmRelationList: [
879
- {
880
- packageJsonPath: "./package.json",
881
- miniprogramNpmDistDir: "./dist"
882
- }
883
- ],
884
- babelSetting: {
885
- ignore: [],
886
- disablePlugins: [],
887
- outputPath: ""
888
- },
889
- packNpmManually: true
890
- },
891
- condition: {},
892
- editorSetting: {
893
- tabIndent: "auto",
894
- tabSize: 2
895
- },
896
- appid: "",
897
- miniprogramRoot: "dist/",
898
- srcMiniprogramRoot: "dist/"
899
- };
885
+ return {
886
+ compileType: "miniprogram",
887
+ libVersion: "trial",
888
+ packOptions: {
889
+ ignore: [],
890
+ include: []
891
+ },
892
+ setting: {
893
+ coverView: true,
894
+ es6: true,
895
+ postcss: true,
896
+ minified: true,
897
+ enhance: true,
898
+ showShadowRootInWxmlPanel: true,
899
+ packNpmRelationList: [{
900
+ packageJsonPath: "./package.json",
901
+ miniprogramNpmDistDir: "./dist"
902
+ }],
903
+ babelSetting: {
904
+ ignore: [],
905
+ disablePlugins: [],
906
+ outputPath: ""
907
+ },
908
+ packNpmManually: true
909
+ },
910
+ condition: {},
911
+ editorSetting: {
912
+ tabIndent: "auto",
913
+ tabSize: 2
914
+ },
915
+ appid: "",
916
+ miniprogramRoot: "dist/",
917
+ srcMiniprogramRoot: "dist/"
918
+ };
900
919
  }
920
+ /**
921
+ * @description 创建或更新 project.config.json
922
+ */
901
923
  async function createOrUpdateProjectConfig(options) {
902
- const { root, dest, cb, write, filename } = defu2(
903
- options,
904
- {
905
- write: true,
906
- filename: "project.config.json"
907
- }
908
- );
909
- const projectConfigFilename = ctx.projectConfig.name = filename;
910
- const projectConfigPath = ctx.projectConfig.path = posix.resolve(root, projectConfigFilename);
911
- const outputPath = resolveOutputPath(root, dest, projectConfigPath);
912
- try {
913
- let projectConfig = await readJsonIfExists(projectConfigPath);
914
- if (projectConfig) {
915
- applyProjectConfigDefaults(projectConfig);
916
- } else {
917
- projectConfig = createDefaultProjectConfig();
918
- logger3.info(`\u2728 \u6CA1\u6709\u627E\u5230 ${projectConfigFilename} \u6587\u4EF6\uFF0C\u6B63\u5728\u4F7F\u7528\u9ED8\u8BA4\u6A21\u677F\u521B\u5EFA...`);
919
- }
920
- cb?.(
921
- (...args) => {
922
- set2(projectConfig, ...args);
923
- }
924
- );
925
- ensurePackNpmRelationList(projectConfig);
926
- ctx.projectConfig.value = projectConfig;
927
- if (write) {
928
- await writeJsonFile(outputPath, projectConfig);
929
- logger3.log(`\u2728 \u5199\u5165 ${posix.relative(root, outputPath)} \u6210\u529F!`);
930
- }
931
- return projectConfig;
932
- } catch (error) {
933
- logger3.error(`\u26A0\uFE0F \u8BBE\u7F6E ${projectConfigFilename} \u914D\u7F6E\u6587\u4EF6\u5931\u8D25`, error);
934
- throw error;
935
- }
924
+ const { root, dest, cb, write, filename } = defu(options, {
925
+ write: true,
926
+ filename: "project.config.json"
927
+ });
928
+ const projectConfigFilename = ctx.projectConfig.name = filename;
929
+ const projectConfigPath = ctx.projectConfig.path = posix.resolve(root, projectConfigFilename);
930
+ const outputPath = resolveOutputPath(root, dest, projectConfigPath);
931
+ try {
932
+ let projectConfig = await readJsonIfExists(projectConfigPath);
933
+ if (projectConfig) applyProjectConfigDefaults(projectConfig);
934
+ else {
935
+ projectConfig = createDefaultProjectConfig();
936
+ logger.info(`✨ 没有找到 ${projectConfigFilename} 文件,正在使用默认模板创建...`);
937
+ }
938
+ cb?.((...args) => {
939
+ set(projectConfig, ...args);
940
+ });
941
+ ensurePackNpmRelationList(projectConfig);
942
+ ctx.projectConfig.value = projectConfig;
943
+ if (write) {
944
+ await writeJsonFile(outputPath, projectConfig);
945
+ logger.log(`✨ 写入 ${posix.relative(root, outputPath)} 成功!`);
946
+ }
947
+ return projectConfig;
948
+ } catch (error) {
949
+ logger.error(`⚠️ 设置 ${projectConfigFilename} 配置文件失败`, error);
950
+ throw error;
951
+ }
936
952
  }
937
-
938
- // src/updateGitignore.ts
939
- import logger4 from "@weapp-core/logger";
940
-
941
- // src/gitignore.ts
942
- var DEFAULT_GITIGNORE = `# dependencies
953
+ //#endregion
954
+ //#region src/gitignore.ts
955
+ const DEFAULT_GITIGNORE = `# dependencies
943
956
  node_modules
944
957
  .pnp
945
958
  .pnp.js
@@ -976,84 +989,73 @@ dist-plugin
976
989
  dist-web
977
990
  dist/web
978
991
  vite.config.ts.timestamp-*.mjs`;
992
+ const CRLF_RE = /\r\n/g;
979
993
  function normalizeLineEndings(value) {
980
- return value.replace(/\r\n/g, "\n");
994
+ return value.replace(CRLF_RE, "\n");
981
995
  }
982
996
  function trimTrailingBlankLines(lines) {
983
- let end = lines.length;
984
- while (end > 0 && lines[end - 1] === "") {
985
- end -= 1;
986
- }
987
- return lines.slice(0, end);
997
+ let end = lines.length;
998
+ while (end > 0 && lines[end - 1] === "") end -= 1;
999
+ return lines.slice(0, end);
988
1000
  }
989
1001
  function ensureTrailingNewline(value) {
990
- return value.endsWith("\n") ? value : `${value}
991
- `;
1002
+ return value.endsWith("\n") ? value : `${value}\n`;
992
1003
  }
1004
+ /**
1005
+ * @description 合并已有 gitignore 内容(保持去重)
1006
+ */
993
1007
  function mergeGitignore(existing) {
994
- const normalizedExisting = normalizeLineEndings(existing ?? "");
995
- const existingLines = normalizedExisting.length ? normalizedExisting.split("\n") : [];
996
- const merged = [...existingLines];
997
- while (merged.length > 0 && merged[merged.length - 1] === "") {
998
- merged.pop();
999
- }
1000
- const seen = new Set(merged);
1001
- let appendedNonBlank = false;
1002
- for (const line of DEFAULT_GITIGNORE.split("\n")) {
1003
- const isBlank = line.length === 0;
1004
- if (isBlank) {
1005
- if (merged.length === 0 || merged[merged.length - 1] === "") {
1006
- continue;
1007
- }
1008
- merged.push("");
1009
- continue;
1010
- }
1011
- if (seen.has(line)) {
1012
- continue;
1013
- }
1014
- if (!appendedNonBlank && merged.length > 0 && merged[merged.length - 1] !== "") {
1015
- merged.push("");
1016
- }
1017
- merged.push(line);
1018
- seen.add(line);
1019
- appendedNonBlank = true;
1020
- }
1021
- return ensureTrailingNewline(trimTrailingBlankLines(merged).join("\n"));
1008
+ const normalizedExisting = normalizeLineEndings(existing ?? "");
1009
+ const merged = [...normalizedExisting.length ? normalizedExisting.split("\n") : []];
1010
+ while (merged.length > 0 && merged.at(-1) === "") merged.pop();
1011
+ const seen = new Set(merged);
1012
+ let appendedNonBlank = false;
1013
+ for (const line of DEFAULT_GITIGNORE.split("\n")) {
1014
+ if (line.length === 0) {
1015
+ if (merged.length === 0 || merged.at(-1) === "") continue;
1016
+ merged.push("");
1017
+ continue;
1018
+ }
1019
+ if (seen.has(line)) continue;
1020
+ if (!appendedNonBlank && merged.length > 0 && merged.at(-1) !== "") merged.push("");
1021
+ merged.push(line);
1022
+ seen.add(line);
1023
+ appendedNonBlank = true;
1024
+ }
1025
+ return ensureTrailingNewline(trimTrailingBlankLines(merged).join("\n"));
1022
1026
  }
1023
-
1024
- // src/updateGitignore.ts
1027
+ //#endregion
1028
+ //#region src/updateGitignore.ts
1025
1029
  async function updateGitIgnore(options) {
1026
- const { root, dest, write = true } = options;
1027
- const gitignorePath = posix.resolve(root, ".gitignore");
1028
- const outputPath = resolveOutputPath(root, dest, gitignorePath);
1029
- const existing = await readFileIfExists(outputPath);
1030
- const merged = mergeGitignore(existing);
1031
- if (write && merged !== (existing ?? "")) {
1032
- await writeFile(outputPath, merged);
1033
- logger4.log(`\u2728 \u66F4\u65B0 ${posix.relative(root, outputPath)} \u6210\u529F!`);
1034
- }
1035
- return merged;
1030
+ const { root, dest, write = true } = options;
1031
+ const outputPath = resolveOutputPath(root, dest, posix.resolve(root, ".gitignore"));
1032
+ const existing = await readFileIfExists(outputPath);
1033
+ const merged = mergeGitignore(existing);
1034
+ if (write && merged !== (existing ?? "")) {
1035
+ await writeFile(outputPath, merged);
1036
+ logger.log(`✨ 更新 ${posix.relative(root, outputPath)} 成功!`);
1037
+ }
1038
+ return merged;
1036
1039
  }
1037
-
1038
- // src/index.ts
1040
+ //#endregion
1041
+ //#region src/index.ts
1042
+ /**
1043
+ * @description 初始化项目配置(project.config、package.json、tsconfig、vite.config 等)
1044
+ */
1039
1045
  async function initConfig(options) {
1040
- const { root = process2.cwd(), command } = options;
1041
- await createOrUpdateProjectConfig({ root });
1042
- await createOrUpdatePackageJson({ root, command });
1043
- await updateGitIgnore({ root });
1044
- if (command === "weapp-vite") {
1045
- await initViteConfigFile({ root });
1046
- await initTsDtsFile({ root });
1047
- await initTsJsonFiles({ root });
1048
- }
1049
- return ctx;
1046
+ const { root = process$1.cwd(), command } = options;
1047
+ await createOrUpdateProjectConfig({ root });
1048
+ await createOrUpdatePackageJson({
1049
+ root,
1050
+ command
1051
+ });
1052
+ await updateGitIgnore({ root });
1053
+ if (command === "weapp-vite") {
1054
+ await initViteConfigFile({ root });
1055
+ await initTsDtsFile({ root });
1056
+ await initTsJsonFiles({ root });
1057
+ }
1058
+ return ctx;
1050
1059
  }
1051
- export {
1052
- createOrUpdatePackageJson,
1053
- createOrUpdateProjectConfig,
1054
- initConfig,
1055
- initTsDtsFile,
1056
- initTsJsonFiles,
1057
- initViteConfigFile,
1058
- resetContext
1059
- };
1060
+ //#endregion
1061
+ export { createOrUpdatePackageJson, createOrUpdateProjectConfig, initConfig, initTsDtsFile, initTsJsonFiles, initViteConfigFile, resetContext };