@icebreakers/monorepo 2.2.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -1,1560 +1,64 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
- };
11
- var __commonJS = (cb, mod) => function __require() {
12
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
- };
14
- var __copyProps = (to, from, except, desc) => {
15
- if (from && typeof from === "object" || typeof from === "function") {
16
- for (let key of __getOwnPropNames(from))
17
- if (!__hasOwnProp.call(to, key) && key !== except)
18
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
- // If the importer is in node compatibility mode or this is not an ESM
24
- // file that has been converted to a CommonJS file using a Babel-
25
- // compatible transform (i.e. "__esModule" has not been set), then set
26
- // "default" to the CommonJS "module.exports" for node compatibility.
27
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
- mod
29
- ));
30
-
31
- // ../../node_modules/.pnpm/tsup@8.5.1_@microsoft+api-extractor@7.52.12_@types+node@24.10.1__jiti@2.6.1_postcss@8.5_f48fe4e18fc17d0faecb4c10461dc770/node_modules/tsup/assets/cjs_shims.js
32
- var getImportMetaUrl, importMetaUrl;
33
- var init_cjs_shims = __esm({
34
- "../../node_modules/.pnpm/tsup@8.5.1_@microsoft+api-extractor@7.52.12_@types+node@24.10.1__jiti@2.6.1_postcss@8.5_f48fe4e18fc17d0faecb4c10461dc770/node_modules/tsup/assets/cjs_shims.js"() {
35
- "use strict";
36
- getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
37
- importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
38
- }
39
- });
40
-
41
- // ../../node_modules/.pnpm/is-primitive@3.0.1/node_modules/is-primitive/index.js
42
- var require_is_primitive = __commonJS({
43
- "../../node_modules/.pnpm/is-primitive@3.0.1/node_modules/is-primitive/index.js"(exports2, module2) {
44
- "use strict";
45
- init_cjs_shims();
46
- module2.exports = function isPrimitive(val) {
47
- if (typeof val === "object") {
48
- return val === null;
49
- }
50
- return typeof val !== "function";
51
- };
52
- }
53
- });
54
-
55
- // ../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js
56
- var require_isobject = __commonJS({
57
- "../../node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js"(exports2, module2) {
58
- "use strict";
59
- init_cjs_shims();
60
- module2.exports = function isObject2(val) {
61
- return val != null && typeof val === "object" && Array.isArray(val) === false;
62
- };
63
- }
64
- });
65
-
66
- // ../../node_modules/.pnpm/is-plain-object@2.0.4/node_modules/is-plain-object/index.js
67
- var require_is_plain_object = __commonJS({
68
- "../../node_modules/.pnpm/is-plain-object@2.0.4/node_modules/is-plain-object/index.js"(exports2, module2) {
69
- "use strict";
70
- init_cjs_shims();
71
- var isObject2 = require_isobject();
72
- function isObjectObject(o) {
73
- return isObject2(o) === true && Object.prototype.toString.call(o) === "[object Object]";
74
- }
75
- module2.exports = function isPlainObject2(o) {
76
- var ctor, prot;
77
- if (isObjectObject(o) === false) return false;
78
- ctor = o.constructor;
79
- if (typeof ctor !== "function") return false;
80
- prot = ctor.prototype;
81
- if (isObjectObject(prot) === false) return false;
82
- if (prot.hasOwnProperty("isPrototypeOf") === false) {
83
- return false;
84
- }
85
- return true;
86
- };
87
- }
88
- });
89
-
90
- // ../../node_modules/.pnpm/set-value@4.1.0/node_modules/set-value/index.js
91
- var require_set_value = __commonJS({
92
- "../../node_modules/.pnpm/set-value@4.1.0/node_modules/set-value/index.js"(exports2, module2) {
93
- "use strict";
94
- init_cjs_shims();
95
- var { deleteProperty } = Reflect;
96
- var isPrimitive = require_is_primitive();
97
- var isPlainObject2 = require_is_plain_object();
98
- var isObject2 = (value) => {
99
- return typeof value === "object" && value !== null || typeof value === "function";
100
- };
101
- var isUnsafeKey = (key) => {
102
- return key === "__proto__" || key === "constructor" || key === "prototype";
103
- };
104
- var validateKey = (key) => {
105
- if (!isPrimitive(key)) {
106
- throw new TypeError("Object keys must be strings or symbols");
107
- }
108
- if (isUnsafeKey(key)) {
109
- throw new Error(`Cannot set unsafe key: "${key}"`);
110
- }
111
- };
112
- var toStringKey = (input2) => {
113
- return Array.isArray(input2) ? input2.flat().map(String).join(",") : input2;
114
- };
115
- var createMemoKey = (input2, options) => {
116
- if (typeof input2 !== "string" || !options) return input2;
117
- let key = input2 + ";";
118
- if (options.arrays !== void 0) key += `arrays=${options.arrays};`;
119
- if (options.separator !== void 0) key += `separator=${options.separator};`;
120
- if (options.split !== void 0) key += `split=${options.split};`;
121
- if (options.merge !== void 0) key += `merge=${options.merge};`;
122
- if (options.preservePaths !== void 0) key += `preservePaths=${options.preservePaths};`;
123
- return key;
124
- };
125
- var memoize = (input2, options, fn) => {
126
- const key = toStringKey(options ? createMemoKey(input2, options) : input2);
127
- validateKey(key);
128
- const value = setValue.cache.get(key) || fn();
129
- setValue.cache.set(key, value);
130
- return value;
131
- };
132
- var splitString = (input2, options = {}) => {
133
- const sep = options.separator || ".";
134
- const preserve = sep === "/" ? false : options.preservePaths;
135
- if (typeof input2 === "string" && preserve !== false && /\//.test(input2)) {
136
- return [input2];
137
- }
138
- const parts = [];
139
- let part = "";
140
- const push = (part2) => {
141
- let number;
142
- if (part2.trim() !== "" && Number.isInteger(number = Number(part2))) {
143
- parts.push(number);
144
- } else {
145
- parts.push(part2);
146
- }
147
- };
148
- for (let i = 0; i < input2.length; i++) {
149
- const value = input2[i];
150
- if (value === "\\") {
151
- part += input2[++i];
152
- continue;
153
- }
154
- if (value === sep) {
155
- push(part);
156
- part = "";
157
- continue;
158
- }
159
- part += value;
160
- }
161
- if (part) {
162
- push(part);
163
- }
164
- return parts;
165
- };
166
- var split2 = (input2, options) => {
167
- if (options && typeof options.split === "function") return options.split(input2);
168
- if (typeof input2 === "symbol") return [input2];
169
- if (Array.isArray(input2)) return input2;
170
- return memoize(input2, options, () => splitString(input2, options));
171
- };
172
- var assignProp = (obj, prop, value, options) => {
173
- validateKey(prop);
174
- if (value === void 0) {
175
- deleteProperty(obj, prop);
176
- } else if (options && options.merge) {
177
- const merge = options.merge === "function" ? options.merge : Object.assign;
178
- if (merge && isPlainObject2(obj[prop]) && isPlainObject2(value)) {
179
- obj[prop] = merge(obj[prop], value);
180
- } else {
181
- obj[prop] = value;
182
- }
183
- } else {
184
- obj[prop] = value;
185
- }
186
- return obj;
187
- };
188
- var setValue = (target, path13, value, options) => {
189
- if (!path13 || !isObject2(target)) return target;
190
- const keys = split2(path13, options);
191
- let obj = target;
192
- for (let i = 0; i < keys.length; i++) {
193
- const key = keys[i];
194
- const next = keys[i + 1];
195
- validateKey(key);
196
- if (next === void 0) {
197
- assignProp(obj, key, value, options);
198
- break;
199
- }
200
- if (typeof next === "number" && !Array.isArray(obj[key])) {
201
- obj = obj[key] = [];
202
- continue;
203
- }
204
- if (!isObject2(obj[key])) {
205
- obj[key] = {};
206
- }
207
- obj = obj[key];
208
- }
209
- return target;
210
- };
211
- setValue.split = split2;
212
- setValue.cache = /* @__PURE__ */ new Map();
213
- setValue.clear = () => {
214
- setValue.cache = /* @__PURE__ */ new Map();
215
- };
216
- module2.exports = setValue;
217
- }
218
- });
219
-
220
- // src/cli.ts
221
- init_cjs_shims();
222
-
223
- // src/cli/program.ts
224
- init_cjs_shims();
225
- var import_node_process3 = __toESM(require("process"), 1);
226
- var import_input = __toESM(require("@inquirer/input"), 1);
227
- var import_select = __toESM(require("@inquirer/select"), 1);
228
- var import_commander = require("commander");
229
-
230
- // src/commands/index.ts
231
- init_cjs_shims();
232
-
233
- // src/core/git.ts
234
- init_cjs_shims();
235
-
236
- // ../../node_modules/.pnpm/get-value@4.0.1/node_modules/get-value/dist/index.mjs
237
- init_cjs_shims();
238
- var __defProp2 = Object.defineProperty;
239
- var __name = (target, value) => __defProp2(target, "name", { value, configurable: true });
240
- var isObject = /* @__PURE__ */ __name((v) => v !== null && typeof v === "object", "isObject");
241
- var join = /* @__PURE__ */ __name((segs, joinChar, options) => {
242
- if (typeof options.join === "function") {
243
- return options.join(segs);
244
- }
245
- return segs[0] + joinChar + segs[1];
246
- }, "join");
247
- var split = /* @__PURE__ */ __name((path13, splitChar, options) => {
248
- if (typeof options.split === "function") {
249
- return options.split(path13);
250
- }
251
- return path13.split(splitChar);
252
- }, "split");
253
- var isValid = /* @__PURE__ */ __name((key, target = {}, options) => {
254
- if (typeof (options == null ? void 0 : options.isValid) === "function") {
255
- return options.isValid(key, target);
256
- }
257
- return true;
258
- }, "isValid");
259
- var isValidObject = /* @__PURE__ */ __name((v) => {
260
- return isObject(v) || typeof v === "function";
261
- }, "isValidObject");
262
- var getValue = /* @__PURE__ */ __name((target, path13, options = {}) => {
263
- if (!isObject(options)) {
264
- options = { default: options };
265
- }
266
- if (!isValidObject(target)) {
267
- return typeof options.default !== "undefined" ? options.default : target;
268
- }
269
- if (typeof path13 === "number") {
270
- path13 = String(path13);
271
- }
272
- const pathIsArray = Array.isArray(path13);
273
- const pathIsString = typeof path13 === "string";
274
- const splitChar = options.separator || ".";
275
- const joinChar = options.joinChar || (typeof splitChar === "string" ? splitChar : ".");
276
- if (!pathIsString && !pathIsArray) {
277
- return target;
278
- }
279
- if (target[path13] !== void 0) {
280
- return isValid(path13, target, options) ? target[path13] : options.default;
281
- }
282
- const segs = pathIsArray ? path13 : split(path13, splitChar, options);
283
- const len = segs.length;
284
- let idx = 0;
285
- do {
286
- let prop = segs[idx];
287
- if (typeof prop !== "string") {
288
- prop = String(prop);
289
- }
290
- while (prop && prop.slice(-1) === "\\") {
291
- prop = join([prop.slice(0, -1), segs[++idx] || ""], joinChar, options);
292
- }
293
- if (target[prop] !== void 0) {
294
- if (!isValid(prop, target, options)) {
295
- return options.default;
296
- }
297
- target = target[prop];
298
- } else {
299
- let hasProp = false;
300
- let n = idx + 1;
301
- while (n < len) {
302
- prop = join([prop, segs[n++]], joinChar, options);
303
- if (hasProp = target[prop] !== void 0) {
304
- if (!isValid(prop, target, options)) {
305
- return options.default;
306
- }
307
- target = target[prop];
308
- idx = n - 1;
309
- break;
310
- }
311
- }
312
- if (!hasProp) {
313
- return options.default;
314
- }
315
- }
316
- } while (++idx < len && isValidObject(target));
317
- if (idx === len) {
318
- return target;
319
- }
320
- return options.default;
321
- }, "getValue");
322
- var index_default = getValue;
323
-
324
- // src/core/git.ts
325
- var import_git_url_parse = __toESM(require("git-url-parse"), 1);
326
- var import_simple_git = require("simple-git");
327
- var GitClient = class {
328
- client;
329
- #config;
330
- constructor(options = {}) {
331
- this.client = (0, import_simple_git.simpleGit)(options);
332
- }
333
- /**
334
- * 读取 Git 的 config 列表,原样返回 simple-git 的结果。
335
- */
336
- listConfig() {
337
- return this.client.listConfig();
338
- }
339
- /**
340
- * 初始化配置缓存,避免多次访问 Git 产生的性能损耗。
341
- */
342
- async init() {
343
- const listConfig = await this.listConfig();
344
- this.#config = listConfig.all;
345
- return this.#config;
346
- }
347
- /**
348
- * 获取缓存的配置,若未初始化则自动触发 init。
349
- */
350
- async getConfig() {
351
- if (this.#config) {
352
- return this.#config;
353
- } else {
354
- return await this.init();
355
- }
356
- }
357
- /**
358
- * 解析 remote.origin.url,返回 git-url-parse 的结构,便于获取仓库元信息。
359
- */
360
- async getGitUrl() {
361
- const config = await this.getConfig();
362
- const x = index_default(config, "remote.origin.url");
363
- if (x) {
364
- return (0, import_git_url_parse.default)(x);
365
- }
366
- }
367
- /**
368
- * 组合 owner/name,生成常用的仓库名表达。
369
- */
370
- async getRepoName() {
371
- const url = await this.getGitUrl();
372
- if (url) {
373
- return `${url.owner}/${url.name}`;
374
- }
375
- }
376
- /**
377
- * 从 Git 配置中提取用户信息,用于填充 package.json author 字段。
378
- */
379
- async getUser() {
380
- const config = await this.getConfig();
381
- const name2 = index_default(config, "user.name");
382
- const email = index_default(config, "user.email");
383
- return {
384
- name: name2,
385
- email
386
- };
387
- }
388
- /**
389
- * 获取当前仓库的顶层目录路径。
390
- */
391
- async getRepoRoot() {
392
- try {
393
- const root = await this.client.revparse(["--show-toplevel"]);
394
- return typeof root === "string" ? root.trim() : void 0;
395
- } catch {
396
- return void 0;
397
- }
398
- }
399
- };
400
-
401
- // src/core/workspace.ts
402
- init_cjs_shims();
403
- var import_find_workspace_dir = require("@pnpm/find-workspace-dir");
404
- var import_workspace = require("@pnpm/workspace.find-packages");
405
- var import_workspace2 = require("@pnpm/workspace.read-manifest");
406
-
407
- // ../../node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.mjs
408
- init_cjs_shims();
409
- function isPlainObject(value) {
410
- if (value === null || typeof value !== "object") {
411
- return false;
412
- }
413
- const prototype = Object.getPrototypeOf(value);
414
- if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
415
- return false;
416
- }
417
- if (Symbol.iterator in value) {
418
- return false;
419
- }
420
- if (Symbol.toStringTag in value) {
421
- return Object.prototype.toString.call(value) === "[object Module]";
422
- }
423
- return true;
424
- }
425
- function _defu(baseObject, defaults, namespace = ".", merger) {
426
- if (!isPlainObject(defaults)) {
427
- return _defu(baseObject, {}, namespace, merger);
428
- }
429
- const object = Object.assign({}, defaults);
430
- for (const key in baseObject) {
431
- if (key === "__proto__" || key === "constructor") {
432
- continue;
433
- }
434
- const value = baseObject[key];
435
- if (value === null || value === void 0) {
436
- continue;
437
- }
438
- if (merger && merger(object, key, value, namespace)) {
439
- continue;
440
- }
441
- if (Array.isArray(value) && Array.isArray(object[key])) {
442
- object[key] = [...value, ...object[key]];
443
- } else if (isPlainObject(value) && isPlainObject(object[key])) {
444
- object[key] = _defu(
445
- value,
446
- object[key],
447
- (namespace ? `${namespace}.` : "") + key.toString(),
448
- merger
449
- );
450
- } else {
451
- object[key] = value;
452
- }
453
- }
454
- return object;
455
- }
456
- function createDefu(merger) {
457
- return (...arguments_) => (
458
- // eslint-disable-next-line unicorn/no-array-reduce
459
- arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
460
- );
461
- }
462
- var defu = createDefu();
463
- var defuFn = createDefu((object, key, currentValue) => {
464
- if (object[key] !== void 0 && typeof currentValue === "function") {
465
- object[key] = currentValue(object[key]);
466
- return true;
467
- }
468
- });
469
- var defuArrayFn = createDefu((object, key, currentValue) => {
470
- if (Array.isArray(object[key]) && typeof currentValue === "function") {
471
- object[key] = currentValue(object[key]);
472
- return true;
473
- }
474
- });
475
-
476
- // src/core/workspace.ts
477
- var import_pathe = __toESM(require("pathe"), 1);
478
- async function getWorkspacePackages(workspaceDir, options) {
479
- const { ignoreRootPackage, ignorePrivatePackage, patterns } = defu(options, {
480
- ignoreRootPackage: true,
481
- ignorePrivatePackage: true
482
- });
483
- const manifest = await (0, import_workspace2.readWorkspaceManifest)(workspaceDir);
484
- const packages = await (0, import_workspace.findWorkspacePackages)(workspaceDir, {
485
- patterns: patterns ?? (manifest == null ? void 0 : manifest.packages)
486
- });
487
- let pkgs = packages.filter((x) => {
488
- if (ignorePrivatePackage && x.manifest.private) {
489
- return false;
490
- }
491
- return true;
492
- }).map((project) => {
493
- const pkgJsonPath = import_pathe.default.resolve(project.rootDir, "package.json");
494
- return {
495
- ...project,
496
- pkgJsonPath
497
- };
498
- });
499
- if (ignoreRootPackage) {
500
- pkgs = pkgs.filter((x) => {
501
- return x.rootDir !== workspaceDir;
502
- });
503
- }
504
- return pkgs;
505
- }
506
- async function getWorkspaceData(cwd2, options) {
507
- const workspaceDir = await (0, import_find_workspace_dir.findWorkspaceDir)(cwd2) ?? cwd2;
508
- const packages = await getWorkspacePackages(workspaceDir, options);
509
- return {
510
- cwd: cwd2,
511
- workspaceDir,
512
- packages
513
- };
514
- }
515
-
516
- // src/commands/clean.ts
517
- init_cjs_shims();
518
- var import_checkbox = __toESM(require("@inquirer/checkbox"), 1);
519
- var import_fs_extra = __toESM(require("fs-extra"), 1);
520
- var import_pathe3 = __toESM(require("pathe"), 1);
521
- var import_set_value = __toESM(require_set_value(), 1);
522
-
523
- // src/core/config.ts
524
- init_cjs_shims();
525
- var import_c12 = require("c12");
526
- var import_pathe2 = __toESM(require("pathe"), 1);
527
- var cache = /* @__PURE__ */ new Map();
528
- async function loadConfigInternal(cwd2) {
529
- const { config, configFile } = await (0, import_c12.loadConfig)({
530
- name: "monorepo",
531
- cwd: cwd2,
532
- // configFile: ['monorepo.config'],
533
- rcFile: false,
534
- defaults: {},
535
- globalRc: false,
536
- packageJson: false
537
- });
538
- return {
539
- file: configFile ? import_pathe2.default.resolve(configFile) : null,
540
- config: config ?? {}
541
- };
542
- }
543
- async function loadMonorepoConfig(cwd2) {
544
- const key = import_pathe2.default.resolve(cwd2);
545
- if (!cache.has(key)) {
546
- cache.set(key, loadConfigInternal(key));
547
- }
548
- const { config } = await cache.get(key);
549
- return config;
550
- }
551
- async function resolveCommandConfig(name2, cwd2) {
552
- const config = await loadMonorepoConfig(cwd2);
553
- const commands = config.commands ?? {};
554
- const commandConfig = commands[name2];
555
- return commandConfig ?? {};
556
- }
557
-
558
- // src/commands/clean.ts
559
- async function cleanProjects(cwd2) {
560
- const cleanConfig = await resolveCommandConfig("clean", cwd2);
561
- const workspaceOptions = (cleanConfig == null ? void 0 : cleanConfig.includePrivate) ? { ignorePrivatePackage: false } : void 0;
562
- const { packages, workspaceDir } = await getWorkspaceData(cwd2, workspaceOptions);
563
- const filteredPackages = packages.filter((pkg) => {
564
- var _a;
565
- const name3 = pkg.manifest.name ?? "";
566
- if (!name3) {
567
- return true;
568
- }
569
- if (!((_a = cleanConfig == null ? void 0 : cleanConfig.ignorePackages) == null ? void 0 : _a.length)) {
570
- return true;
571
- }
572
- return !cleanConfig.ignorePackages.includes(name3);
573
- });
574
- let cleanDirs = [];
575
- if (cleanConfig == null ? void 0 : cleanConfig.autoConfirm) {
576
- cleanDirs = filteredPackages.map((pkg) => pkg.rootDir);
577
- } else {
578
- cleanDirs = await (0, import_checkbox.default)({
579
- message: "\u8BF7\u9009\u62E9\u9700\u8981\u6E05\u7406\u7684\u76EE\u5F55",
580
- choices: filteredPackages.map((x) => {
581
- return {
582
- name: import_pathe3.default.relative(workspaceDir, x.rootDir),
583
- value: x.rootDir,
584
- checked: true,
585
- description: x.manifest.name
586
- };
587
- })
588
- });
589
- }
590
- const candidates = Array.from(new Set(cleanDirs.filter(Boolean)));
591
- await Promise.all(candidates.map(async (dir) => {
592
- if (await import_fs_extra.default.pathExists(dir)) {
593
- await import_fs_extra.default.remove(dir);
594
- }
595
- }));
596
- const name2 = import_pathe3.default.resolve(workspaceDir, "package.json");
597
- const pkgJson = await import_fs_extra.default.readJson(name2);
598
- (0, import_set_value.default)(pkgJson, "devDependencies.@icebreakers/monorepo", (cleanConfig == null ? void 0 : cleanConfig.pinnedVersion) ?? "latest", { preservePaths: false });
599
- await import_fs_extra.default.outputJson(name2, pkgJson, {
600
- spaces: 2
601
- });
602
- }
603
-
604
- // src/commands/create.ts
605
- init_cjs_shims();
606
- var import_node_process = __toESM(require("process"), 1);
607
- var import_fs_extra2 = __toESM(require("fs-extra"), 1);
608
- var import_pathe4 = __toESM(require("pathe"), 1);
609
- var import_picocolors = __toESM(require("picocolors"), 1);
610
- var import_set_value2 = __toESM(require_set_value(), 1);
611
-
612
- // src/constants.ts
613
- init_cjs_shims();
614
- var import_node_path = __toESM(require("path"), 1);
615
- var import_node_url = require("url");
616
-
617
- // package.json
618
- var name = "@icebreakers/monorepo";
619
- var version = "2.2.0";
620
-
621
- // src/constants.ts
622
- var packageJsonPath = (0, import_node_url.fileURLToPath)(new URL("../package.json", importMetaUrl));
623
- var packageDir = import_node_path.default.dirname(packageJsonPath);
624
- var templatesDir = import_node_path.default.join(packageDir, "templates");
625
- var assetsDir = import_node_path.default.join(packageDir, "assets");
626
- var rootDir = import_node_path.default.resolve(packageDir, "..", "..");
627
-
628
- // src/core/logger.ts
629
- init_cjs_shims();
630
- var import_consola = require("consola");
631
- var logger = (0, import_consola.createConsola)();
632
-
633
- // src/utils/fs.ts
634
- init_cjs_shims();
635
- function isIgnorableFsError(error) {
636
- if (!error) {
637
- return false;
638
- }
639
- const code = error.code;
640
- return code === "ENOENT" || code === "EBUSY" || code === "EEXIST";
641
- }
642
-
643
- // src/utils/gitignore.ts
644
- init_cjs_shims();
645
- var publishBasename = "gitignore";
646
- var workspaceBasename = ".gitignore";
647
- function detectSeparator(input2) {
648
- if (input2.includes("\\") && !input2.includes("/")) {
649
- return "\\";
650
- }
651
- return "/";
652
- }
653
- function replaceBasename(input2, from, to) {
654
- if (!input2) {
655
- return input2;
656
- }
657
- const separator = detectSeparator(input2);
658
- const normalized = input2.replace(/[\\/]/g, separator);
659
- const hasTrailingSeparator = normalized.endsWith(separator);
660
- const segments = normalized.split(separator);
661
- if (hasTrailingSeparator && segments[segments.length - 1] === "") {
662
- segments.pop();
663
- }
664
- const lastIndex = segments.length - 1;
665
- if (lastIndex >= 0 && segments[lastIndex] === from) {
666
- segments[lastIndex] = to;
667
- const rebuilt = segments.join(separator);
668
- return hasTrailingSeparator ? `${rebuilt}${separator}` : rebuilt;
669
- }
670
- return input2;
671
- }
672
- function toWorkspaceGitignorePath(input2) {
673
- return replaceBasename(input2, publishBasename, workspaceBasename);
674
- }
675
-
676
- // src/utils/hash.ts
677
- init_cjs_shims();
678
- var import_node_crypto = __toESM(require("crypto"), 1);
679
- function getFileHash(data) {
680
- const hashSum = import_node_crypto.default.createHash("md5");
681
- hashSum.update(data);
682
- return hashSum.digest("hex");
683
- }
684
- function isFileChanged(src, dest) {
685
- try {
686
- const currentHash = getFileHash(src);
687
- const previousHash = getFileHash(dest);
688
- return currentHash !== previousHash;
689
- } catch (err) {
690
- logger.error("Error calculating file hash:", err);
691
- return false;
692
- }
693
- }
694
-
695
- // src/utils/regexp.ts
696
- init_cjs_shims();
697
- function escapeStringRegexp(str) {
698
- return str.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
699
- }
700
- function isMatch(str, arr) {
701
- for (const reg of arr) {
702
- if (reg.test(str)) {
703
- return true;
704
- }
705
- }
706
- return false;
707
- }
708
-
709
- // src/commands/create.ts
710
- var templateMap = {
711
- "tsup": "packages/tsup-template",
712
- "tsdown": "packages/tsdown-template",
713
- "unbuild": "packages/unbuild-template",
714
- "vue-lib": "packages/vue-lib-template",
715
- "hono-server": "apps/server",
716
- "vue-hono": "apps/client",
717
- "vitepress": "apps/website",
718
- "cli": "apps/cli"
719
- };
720
- var defaultTemplate = "unbuild";
721
- var baseChoices = [
722
- { name: "unbuild \u6253\u5305", value: "unbuild" },
723
- { name: "tsup \u6253\u5305", value: "tsup" },
724
- { name: "tsdown \u6253\u5305", value: "tsdown" },
725
- { name: "vue \u7EC4\u4EF6", value: "vue-lib" },
726
- { name: "vue hono \u5168\u6808", value: "vue-hono" },
727
- { name: "hono \u6A21\u677F", value: "hono-server" },
728
- { name: "vitepress \u6587\u6863", value: "vitepress" },
729
- { name: "cli \u6A21\u677F", value: "cli" }
730
- ];
731
- function getCreateChoices(choices) {
732
- if (choices == null ? void 0 : choices.length) {
733
- return choices;
734
- }
735
- return [...baseChoices];
736
- }
737
- function getTemplateMap(extra) {
738
- const base = { ...templateMap };
739
- if (extra && Object.keys(extra).length) {
740
- Object.assign(base, extra);
741
- }
742
- return base;
743
- }
744
- async function applyGitMetadata(pkgJson, repoDir, targetDir) {
745
- try {
746
- const git = new GitClient({ baseDir: repoDir });
747
- const repoName = await git.getRepoName();
748
- if (!repoName) {
749
- return;
750
- }
751
- (0, import_set_value2.default)(pkgJson, ["bugs", "url"], `https://github.com/${repoName}/issues`);
752
- const repository = {
753
- type: "git",
754
- url: `git+https://github.com/${repoName}.git`
755
- };
756
- const repoRoot = await git.getRepoRoot();
757
- const directoryBase = repoRoot ?? repoDir;
758
- const relative = import_pathe4.default.relative(directoryBase, targetDir);
759
- if (relative && relative !== ".") {
760
- repository.directory = relative.split(import_pathe4.default.sep).join("/");
761
- }
762
- (0, import_set_value2.default)(pkgJson, "repository", repository);
763
- const gitUser = await git.getUser();
764
- if ((gitUser == null ? void 0 : gitUser.name) && (gitUser == null ? void 0 : gitUser.email)) {
765
- (0, import_set_value2.default)(pkgJson, "author", `${gitUser.name} <${gitUser.email}>`);
766
- }
767
- } catch {
768
- }
769
- }
770
- async function createNewProject(options) {
771
- const cwd2 = (options == null ? void 0 : options.cwd) ?? import_node_process.default.cwd();
772
- const createConfig = await resolveCommandConfig("create", cwd2);
773
- const renameJson = (options == null ? void 0 : options.renameJson) ?? (createConfig == null ? void 0 : createConfig.renameJson) ?? false;
774
- const rawName = (options == null ? void 0 : options.name) ?? (createConfig == null ? void 0 : createConfig.name);
775
- const name2 = typeof rawName === "string" ? rawName.trim() : void 0;
776
- const requestedTemplate = (options == null ? void 0 : options.type) ?? (createConfig == null ? void 0 : createConfig.type) ?? (createConfig == null ? void 0 : createConfig.defaultTemplate) ?? defaultTemplate;
777
- const templateDefinitions = getTemplateMap(createConfig == null ? void 0 : createConfig.templateMap);
778
- const templatesRoot = (createConfig == null ? void 0 : createConfig.templatesDir) ? import_pathe4.default.resolve(cwd2, createConfig.templatesDir) : templatesDir;
779
- const fallbackTemplate = (createConfig == null ? void 0 : createConfig.defaultTemplate) ?? defaultTemplate;
780
- const bundlerName = typeof requestedTemplate === "string" && templateDefinitions[requestedTemplate] ? requestedTemplate : fallbackTemplate;
781
- const sourceRelative = templateDefinitions[bundlerName];
782
- if (!sourceRelative) {
783
- throw new Error(`\u672A\u627E\u5230\u540D\u4E3A ${bundlerName} \u7684\u6A21\u677F\uFF0C\u8BF7\u68C0\u67E5 monorepo.config.ts`);
784
- }
785
- const from = import_pathe4.default.join(templatesRoot, sourceRelative);
786
- const targetName = name2 && name2.length > 0 ? name2 : sourceRelative;
787
- const to = import_pathe4.default.join(cwd2, targetName);
788
- if (await import_fs_extra2.default.pathExists(to)) {
789
- throw new Error(`${import_picocolors.default.red("\u76EE\u6807\u76EE\u5F55\u5DF2\u5B58\u5728")}: ${import_pathe4.default.relative(cwd2, to)}`);
790
- }
791
- await import_fs_extra2.default.ensureDir(to);
792
- const filelist = await import_fs_extra2.default.readdir(from);
793
- const shouldSkip = (src) => import_pathe4.default.basename(src) === ".DS_Store";
794
- const copyTasks = filelist.filter((filename) => filename !== "package.json").map(async (filename) => {
795
- const sourcePath = import_pathe4.default.resolve(from, filename);
796
- const targetPath = import_pathe4.default.resolve(to, toWorkspaceGitignorePath(filename));
797
- await import_fs_extra2.default.copy(sourcePath, targetPath, {
798
- filter(src) {
799
- if (shouldSkip(src)) {
800
- return false;
801
- }
802
- return true;
803
- }
804
- });
805
- });
806
- await Promise.all(copyTasks);
807
- if (filelist.includes("package.json")) {
808
- const sourceJsonPath = import_pathe4.default.resolve(from, "package.json");
809
- const sourceJson = await import_fs_extra2.default.readJson(sourceJsonPath);
810
- (0, import_set_value2.default)(sourceJson, "version", "0.0.0");
811
- const packageName = (name2 == null ? void 0 : name2.startsWith("@")) ? name2 : import_pathe4.default.basename(targetName);
812
- (0, import_set_value2.default)(sourceJson, "name", packageName);
813
- await applyGitMetadata(sourceJson, cwd2, to);
814
- await import_fs_extra2.default.outputJson(
815
- import_pathe4.default.resolve(
816
- to,
817
- renameJson ? "package.mock.json" : "package.json"
818
- ),
819
- sourceJson,
820
- { spaces: 2 }
821
- );
822
- }
823
- logger.success(`${import_picocolors.default.bgGreenBright(import_picocolors.default.white(`[${bundlerName}]`))} ${targetName} \u9879\u76EE\u521B\u5EFA\u6210\u529F\uFF01`);
824
- }
825
-
826
- // src/commands/init/index.ts
827
- init_cjs_shims();
828
-
829
- // src/core/context.ts
830
- init_cjs_shims();
831
- var import_pathe5 = __toESM(require("pathe"), 1);
832
- var import_types = require("@pnpm/types");
833
- async function createContext(cwd2) {
834
- const { packages, workspaceDir } = await getWorkspaceData(cwd2);
835
- const git = new GitClient({
836
- baseDir: workspaceDir
837
- });
838
- const workspaceFilepath = import_pathe5.default.resolve(workspaceDir, "pnpm-workspace.yaml");
839
- const gitUrl = await git.getGitUrl();
840
- const gitUser = await git.getUser();
841
- const config = await loadMonorepoConfig(workspaceDir);
842
- return {
843
- cwd: cwd2,
844
- git,
845
- gitUrl,
846
- gitUser,
847
- workspaceDir,
848
- workspaceFilepath,
849
- packages,
850
- config
851
- };
852
- }
853
-
854
- // src/commands/init/setChangeset.ts
855
- init_cjs_shims();
856
- var import_fs_extra3 = __toESM(require("fs-extra"), 1);
857
- var import_pathe6 = __toESM(require("pathe"), 1);
858
- var import_set_value3 = __toESM(require_set_value(), 1);
859
- async function setChangeset_default(ctx) {
860
- const { gitUrl, workspaceFilepath } = ctx;
861
- if (gitUrl && await import_fs_extra3.default.exists(workspaceFilepath)) {
862
- const changesetConfigPath = import_pathe6.default.resolve(import_pathe6.default.dirname(workspaceFilepath), ".changeset/config.json");
863
- if (await import_fs_extra3.default.exists(changesetConfigPath)) {
864
- const changesetConfig = await import_fs_extra3.default.readJson(
865
- changesetConfigPath
866
- );
867
- if (gitUrl.full_name) {
868
- (0, import_set_value3.default)(changesetConfig, "changelog.1.repo", gitUrl.full_name);
869
- await import_fs_extra3.default.outputJson(changesetConfigPath, changesetConfig, { spaces: 2 });
870
- }
871
- }
872
- }
873
- }
874
-
875
- // src/commands/init/setPkgJson.ts
876
- init_cjs_shims();
877
- var import_fs_extra4 = __toESM(require("fs-extra"), 1);
878
- var import_pathe7 = __toESM(require("pathe"), 1);
879
- var import_set_value4 = __toESM(require_set_value(), 1);
880
- async function setPkgJson_default(ctx) {
881
- const { gitUrl, gitUser, packages, cwd: cwd2, workspaceFilepath } = ctx;
882
- const workspaceExists = await import_fs_extra4.default.pathExists(workspaceFilepath);
883
- if (gitUrl && workspaceExists) {
884
- await Promise.all(packages.map(async (pkg) => {
885
- if (!await import_fs_extra4.default.pathExists(pkg.pkgJsonPath)) {
886
- return;
887
- }
888
- const pkgJson = JSON.parse(JSON.stringify(pkg.manifest));
889
- const directory = import_pathe7.default.relative(cwd2, pkg.rootDir);
890
- (0, import_set_value4.default)(pkgJson, ["bugs", "url"], `https://github.com/${gitUrl.full_name}/issues`);
891
- const repository = {
892
- type: "git",
893
- url: `git+https://github.com/${gitUrl.full_name}.git`
894
- };
895
- if (directory) {
896
- repository.directory = directory;
897
- }
898
- (0, import_set_value4.default)(pkgJson, "repository", repository);
899
- if ((gitUser == null ? void 0 : gitUser.name) && (gitUser == null ? void 0 : gitUser.email)) {
900
- (0, import_set_value4.default)(pkgJson, "author", `${gitUser.name} <${gitUser.email}>`);
901
- }
902
- const nextContent = `${JSON.stringify(pkgJson, void 0, 2)}
903
- `;
904
- const prevContent = await import_fs_extra4.default.readFile(pkg.pkgJsonPath, "utf8");
905
- if (prevContent !== nextContent) {
906
- await import_fs_extra4.default.writeFile(pkg.pkgJsonPath, nextContent, "utf8");
907
- }
908
- }));
909
- }
910
- }
911
-
912
- // src/commands/init/setReadme.ts
913
- init_cjs_shims();
914
- var import_fs_extra5 = __toESM(require("fs-extra"), 1);
915
- var import_pathe8 = __toESM(require("pathe"), 1);
916
- async function getRows(ctx) {
917
- const { packages, gitUrl, gitUser, cwd: cwd2 } = ctx;
918
- const rows = [];
919
- if (gitUrl) {
920
- rows.push(`# ${gitUrl.name}
921
- `);
922
- }
923
- rows.push("## Packages\n");
924
- const sortedPackages = [...packages].sort((a, b) => {
925
- const left = a.manifest.name ?? "";
926
- const right = b.manifest.name ?? "";
927
- return left.localeCompare(right);
928
- });
929
- for (const pkg of sortedPackages) {
930
- const p = import_pathe8.default.relative(cwd2, pkg.rootDirRealPath);
931
- if (p) {
932
- const description = pkg.manifest.description ? `- ${pkg.manifest.description}` : "";
933
- rows.push(`- [${pkg.manifest.name}](${p}) ${description}`);
934
- }
935
- }
936
- if (gitUrl) {
937
- rows.push("\n## Contributing\n");
938
- rows.push("Contributions Welcome! You can contribute in the following ways.");
939
- rows.push("");
940
- rows.push("- Create an Issue - Propose a new feature. Report a bug.");
941
- rows.push("- Pull Request - Fix a bug and typo. Refactor the code.");
942
- rows.push("- Create third-party middleware - Instruct below.");
943
- rows.push("- Share - Share your thoughts on the Blog, X, and others.");
944
- rows.push(`- Make your application - Please try to use ${gitUrl.name}.`);
945
- rows.push("");
946
- rows.push("For more details, see [CONTRIBUTING.md](CONTRIBUTING.md).");
947
- rows.push("\n## Contributors\n");
948
- rows.push(`Thanks to [all contributors](https://github.com/${gitUrl.full_name}/graphs/contributors)!`);
949
- }
950
- rows.push("\n## Authors\n");
951
- if ((gitUser == null ? void 0 : gitUser.name) && (gitUser == null ? void 0 : gitUser.email)) {
952
- rows.push(`${gitUser.name} <${gitUser.email}>`);
953
- }
954
- rows.push("\n## License\n");
955
- rows.push("Distributed under the MIT License. See [LICENSE](LICENSE) for more information.");
956
- return rows;
957
- }
958
- async function setReadme_default(ctx) {
959
- const rows = await getRows(ctx);
960
- await import_fs_extra5.default.writeFile(import_pathe8.default.resolve(ctx.cwd, "README.md"), `${rows.join("\n")}
961
- `);
962
- }
963
-
964
- // src/commands/init/index.ts
965
- async function init(cwd2) {
966
- var _a;
967
- const ctx = await createContext(cwd2);
968
- const initConfig = ((_a = ctx.config.commands) == null ? void 0 : _a.init) ?? {};
969
- if (!initConfig.skipChangeset) {
970
- await setChangeset_default(ctx);
971
- }
972
- if (!initConfig.skipPkgJson) {
973
- await setPkgJson_default(ctx);
974
- }
975
- if (!initConfig.skipReadme) {
976
- await setReadme_default(ctx);
977
- }
978
- }
979
-
980
- // src/commands/mirror/binaryMirror.ts
981
- init_cjs_shims();
982
- var import_comment_json = require("comment-json");
983
- var import_fs_extra6 = __toESM(require("fs-extra"), 1);
984
- var import_pathe9 = __toESM(require("pathe"), 1);
985
-
986
- // src/commands/mirror/sources.ts
987
- init_cjs_shims();
988
- var chinaMirrorsEnvs = {
989
- COREPACK_NPM_REGISTRY: "https://registry.npmmirror.com",
990
- EDGEDRIVER_CDNURL: "https://npmmirror.com/mirrors/edgedriver",
991
- NODEJS_ORG_MIRROR: "https://cdn.npmmirror.com/binaries/node",
992
- NVM_NODEJS_ORG_MIRROR: "https://cdn.npmmirror.com/binaries/node",
993
- PHANTOMJS_CDNURL: "https://cdn.npmmirror.com/binaries/phantomjs",
994
- CHROMEDRIVER_CDNURL: "https://cdn.npmmirror.com/binaries/chromedriver",
995
- OPERADRIVER_CDNURL: "https://cdn.npmmirror.com/binaries/operadriver",
996
- CYPRESS_DOWNLOAD_PATH_TEMPLATE: "https://cdn.npmmirror.com/binaries/cypress/${version}/${platform}-${arch}/cypress.zip",
997
- ELECTRON_MIRROR: "https://cdn.npmmirror.com/binaries/electron/",
998
- ELECTRON_BUILDER_BINARIES_MIRROR: "https://cdn.npmmirror.com/binaries/electron-builder-binaries/",
999
- SASS_BINARY_SITE: "https://cdn.npmmirror.com/binaries/node-sass",
1000
- SWC_BINARY_SITE: "https://cdn.npmmirror.com/binaries/node-swc",
1001
- NWJS_URLBASE: "https://cdn.npmmirror.com/binaries/nwjs/v",
1002
- PUPPETEER_DOWNLOAD_HOST: "https://cdn.npmmirror.com/binaries/chrome-for-testing",
1003
- PUPPETEER_DOWNLOAD_BASE_URL: "https://cdn.npmmirror.com/binaries/chrome-for-testing",
1004
- PLAYWRIGHT_DOWNLOAD_HOST: "https://cdn.npmmirror.com/binaries/playwright",
1005
- SENTRYCLI_CDNURL: "https://cdn.npmmirror.com/binaries/sentry-cli",
1006
- SAUCECTL_INSTALL_BINARY_MIRROR: "https://cdn.npmmirror.com/binaries/saucectl",
1007
- RE2_DOWNLOAD_MIRROR: "https://cdn.npmmirror.com/binaries/node-re2",
1008
- RE2_DOWNLOAD_SKIP_PATH: "true",
1009
- PRISMA_ENGINES_MIRROR: "https://cdn.npmmirror.com/binaries/prisma",
1010
- npm_config_better_sqlite3_binary_host: "https://cdn.npmmirror.com/binaries/better-sqlite3",
1011
- npm_config_keytar_binary_host: "https://cdn.npmmirror.com/binaries/keytar",
1012
- npm_config_sharp_binary_host: "https://cdn.npmmirror.com/binaries/sharp",
1013
- npm_config_sharp_libvips_binary_host: "https://cdn.npmmirror.com/binaries/sharp-libvips",
1014
- npm_config_robotjs_binary_host: "https://cdn.npmmirror.com/binaries/robotjs"
1015
- };
1016
-
1017
- // src/commands/mirror/utils.ts
1018
- init_cjs_shims();
1019
- var import_set_value5 = __toESM(require_set_value(), 1);
1020
- function setMirror(obj, envs = chinaMirrorsEnvs) {
1021
- const platforms = ["linux", "windows", "osx"];
1022
- const prefix = "terminal.integrated.env";
1023
- if (typeof obj === "object" && obj) {
1024
- for (const platform of platforms) {
1025
- (0, import_set_value5.default)(obj, [prefix, platform].join(".").replaceAll(".", "\\."), envs);
1026
- }
1027
- }
1028
- }
1029
-
1030
- // src/commands/mirror/binaryMirror.ts
1031
- async function setVscodeBinaryMirror(cwd2) {
1032
- const mirrorConfig = await resolveCommandConfig("mirror", cwd2);
1033
- const targetJsonPath = import_pathe9.default.resolve(cwd2, ".vscode/settings.json");
1034
- await import_fs_extra6.default.ensureFile(targetJsonPath);
1035
- const json = (0, import_comment_json.parse)(await import_fs_extra6.default.readFile(targetJsonPath, "utf8"), void 0, false);
1036
- const env = (mirrorConfig == null ? void 0 : mirrorConfig.env) ? { ...chinaMirrorsEnvs, ...mirrorConfig.env } : chinaMirrorsEnvs;
1037
- json && typeof json === "object" && setMirror(json, env);
1038
- await import_fs_extra6.default.writeFile(targetJsonPath, `${(0, import_comment_json.stringify)(json, void 0, 2)}
1039
- `, "utf8");
1040
- }
1041
-
1042
- // src/commands/sync.ts
1043
- init_cjs_shims();
1044
- var import_node_os = __toESM(require("os"), 1);
1045
- var import_execa = require("execa");
1046
- var import_p_queue = __toESM(require("p-queue"), 1);
1047
- var import_pathe10 = __toESM(require("pathe"), 1);
1048
- var import_picocolors2 = __toESM(require("picocolors"), 1);
1049
- function renderCommand(template, pkgName) {
1050
- return template.replaceAll("{name}", pkgName);
1051
- }
1052
- async function syncNpmMirror(cwd2, options) {
1053
- const syncConfig = await resolveCommandConfig("sync", cwd2);
1054
- const {
1055
- concurrency: configConcurrency,
1056
- command: configCommand,
1057
- packages: packageFilter,
1058
- ...workspaceOverrides
1059
- } = syncConfig ?? {};
1060
- const workspaceOptions = {
1061
- ...workspaceOverrides,
1062
- ...options ?? {}
1063
- };
1064
- const { packages, workspaceDir } = await getWorkspaceData(cwd2, workspaceOptions);
1065
- logger.info(`[\u5F53\u524D\u5DE5\u4F5C\u533ARepo]:
1066
- ${packages.map((x) => `- ${import_picocolors2.default.green(x.manifest.name)} : ${import_pathe10.default.relative(workspaceDir, x.rootDir)}`).join("\n")}
1067
- `);
1068
- const set7 = new Set(packages.map((x) => x.manifest.name));
1069
- if (packageFilter == null ? void 0 : packageFilter.length) {
1070
- for (const name2 of Array.from(set7)) {
1071
- if (!name2 || !packageFilter.includes(name2)) {
1072
- set7.delete(name2);
1073
- }
1074
- }
1075
- }
1076
- logger.info(`[\u5373\u5C06\u540C\u6B65\u7684\u5305]:
1077
- ${Array.from(set7).map((x) => `- ${import_picocolors2.default.green(x ?? "")}`).join("\n")}
1078
- `);
1079
- const concurrency = configConcurrency ?? Math.max(import_node_os.default.cpus().length, 1);
1080
- const queue = new import_p_queue.default({ concurrency });
1081
- const template = configCommand ?? "cnpm sync {name}";
1082
- const tasks = [];
1083
- for (const pkgName of set7) {
1084
- if (!pkgName) {
1085
- continue;
1086
- }
1087
- tasks.push(queue.add(async () => {
1088
- const command = renderCommand(template, pkgName);
1089
- return (0, import_execa.execaCommand)(command, {
1090
- stdio: "inherit"
1091
- });
1092
- }));
1093
- }
1094
- await Promise.all(tasks);
1095
- }
1096
-
1097
- // src/commands/upgrade/index.ts
1098
- init_cjs_shims();
1099
- var import_node_process2 = __toESM(require("process"), 1);
1100
- var import_checkbox3 = __toESM(require("@inquirer/checkbox"), 1);
1101
- var import_fs_extra8 = __toESM(require("fs-extra"), 1);
1102
- var import_klaw = __toESM(require("klaw"), 1);
1103
- var import_pathe11 = __toESM(require("pathe"), 1);
1104
- var import_set_value6 = __toESM(require_set_value(), 1);
1105
-
1106
- // src/commands/upgrade/overwrite.ts
1107
- init_cjs_shims();
1108
- var import_node_buffer = require("buffer");
1109
- var import_checkbox2 = __toESM(require("@inquirer/checkbox"), 1);
1110
- var import_fs_extra7 = __toESM(require("fs-extra"), 1);
1111
- var import_picocolors3 = __toESM(require("picocolors"), 1);
1112
- function asBuffer(data) {
1113
- return typeof data === "string" ? import_node_buffer.Buffer.from(data) : data;
1114
- }
1115
- async function evaluateWriteIntent(targetPath, options) {
1116
- const { skipOverwrite, source } = options;
1117
- const exists = await import_fs_extra7.default.pathExists(targetPath);
1118
- if (!exists) {
1119
- return {
1120
- type: "write",
1121
- reason: "missing"
1122
- };
1123
- }
1124
- if (skipOverwrite) {
1125
- return {
1126
- type: "skip",
1127
- reason: "skipOverwrite"
1128
- };
1129
- }
1130
- const src = asBuffer(source);
1131
- let destSize = 0;
1132
- try {
1133
- const stat = await import_fs_extra7.default.stat(targetPath);
1134
- destSize = stat.size;
1135
- } catch {
1136
- return {
1137
- type: "write",
1138
- reason: "missing"
1139
- };
1140
- }
1141
- if (destSize !== src.length) {
1142
- return {
1143
- type: "prompt",
1144
- reason: "changed"
1145
- };
1146
- }
1147
- const dest = await import_fs_extra7.default.readFile(targetPath);
1148
- if (!isFileChanged(src, dest)) {
1149
- return {
1150
- type: "skip",
1151
- reason: "identical"
1152
- };
1153
- }
1154
- return {
1155
- type: "prompt",
1156
- reason: "changed"
1157
- };
1158
- }
1159
- async function scheduleOverwrite(intent, options) {
1160
- const { relPath, targetPath, action, pending } = options;
1161
- if (intent.type === "write") {
1162
- await action();
1163
- return;
1164
- }
1165
- if (intent.type === "prompt") {
1166
- pending.push({
1167
- relPath,
1168
- targetPath,
1169
- action
1170
- });
1171
- }
1172
- }
1173
- async function flushPendingOverwrites(pending) {
1174
- if (!pending.length) {
1175
- return;
1176
- }
1177
- const selected = await (0, import_checkbox2.default)({
1178
- message: "\u68C0\u6D4B\u5230\u4EE5\u4E0B\u6587\u4EF6\u5185\u5BB9\u4E0E\u5F53\u524D\u4ED3\u5E93\u4E0D\u540C\uFF0C\u9009\u62E9\u9700\u8981\u8986\u76D6\u7684\u6587\u4EF6",
1179
- choices: pending.map((item) => ({
1180
- name: import_picocolors3.default.greenBright(item.relPath),
1181
- value: item.targetPath,
1182
- checked: false
1183
- })),
1184
- loop: false
1185
- });
1186
- const selectedSet = new Set(selected);
1187
- for (const item of pending) {
1188
- if (selectedSet.has(item.targetPath)) {
1189
- await item.action();
1190
- }
1191
- }
1192
- }
1193
-
1194
- // src/commands/upgrade/pkg-json.ts
1195
- init_cjs_shims();
1196
- var import_semver = require("semver");
1197
-
1198
- // src/commands/upgrade/scripts.ts
1199
- init_cjs_shims();
1200
- var scripts = {
1201
- "script:init": "monorepo init",
1202
- "script:sync": "monorepo sync",
1203
- "script:clean": "monorepo clean",
1204
- "script:mirror": "monorepo mirror",
1205
- "commitlint": "commitlint --edit"
1206
- };
1207
- var scriptsEntries = Object.entries(scripts);
1208
-
1209
- // src/commands/upgrade/pkg-json.ts
1210
- var NON_OVERRIDABLE_PREFIXES = ["workspace:", "catalog:"];
1211
- function parseVersion(input2) {
1212
- if (typeof input2 !== "string" || input2.trim().length === 0) {
1213
- return null;
1214
- }
1215
- try {
1216
- return (0, import_semver.minVersion)(input2) ?? (0, import_semver.coerce)(input2);
1217
- } catch {
1218
- return null;
1219
- }
1220
- }
1221
- function hasNonOverridablePrefix(version2) {
1222
- if (typeof version2 !== "string") {
1223
- return false;
1224
- }
1225
- return NON_OVERRIDABLE_PREFIXES.some((prefix) => version2.startsWith(prefix));
1226
- }
1227
- function shouldAssignVersion(currentVersion, nextVersion) {
1228
- if (typeof currentVersion !== "string" || currentVersion.trim().length === 0) {
1229
- return true;
1230
- }
1231
- if (currentVersion === nextVersion) {
1232
- return false;
1233
- }
1234
- const current = parseVersion(currentVersion);
1235
- const next = parseVersion(nextVersion);
1236
- if (!current || !next) {
1237
- return true;
1238
- }
1239
- return !(0, import_semver.gte)(current, next);
1240
- }
1241
- function setPkgJson(sourcePkgJson, targetPkgJson, options) {
1242
- const packageManager = sourcePkgJson.packageManager ?? "";
1243
- const sourceDeps = sourcePkgJson.dependencies ?? {};
1244
- const sourceDevDeps = sourcePkgJson.devDependencies ?? {};
1245
- const targetDeps = { ...targetPkgJson.dependencies ?? {} };
1246
- const targetDevDeps = { ...targetPkgJson.devDependencies ?? {} };
1247
- if (packageManager) {
1248
- targetPkgJson.packageManager = packageManager;
1249
- }
1250
- for (const [depName, depVersion] of Object.entries(sourceDeps)) {
1251
- if (typeof depVersion !== "string") {
1252
- continue;
1253
- }
1254
- const targetVersion = targetDeps[depName];
1255
- if (hasNonOverridablePrefix(targetVersion)) {
1256
- continue;
1257
- }
1258
- if (shouldAssignVersion(targetVersion, depVersion)) {
1259
- targetDeps[depName] = depVersion;
1260
- }
1261
- }
1262
- if (Object.keys(targetDeps).length) {
1263
- targetPkgJson.dependencies = targetDeps;
1264
- }
1265
- for (const [depName, depVersion] of Object.entries(sourceDevDeps)) {
1266
- if (typeof depVersion !== "string") {
1267
- continue;
1268
- }
1269
- if (depName === name) {
1270
- const nextVersion = `^${version}`;
1271
- const targetVersion = targetDevDeps[depName];
1272
- if (!hasNonOverridablePrefix(targetVersion) && shouldAssignVersion(targetVersion, nextVersion)) {
1273
- targetDevDeps[depName] = nextVersion;
1274
- }
1275
- } else {
1276
- const targetVersion = targetDevDeps[depName];
1277
- if (hasNonOverridablePrefix(targetVersion)) {
1278
- continue;
1279
- }
1280
- if (shouldAssignVersion(targetVersion, depVersion)) {
1281
- targetDevDeps[depName] = depVersion;
1282
- }
1283
- }
1284
- }
1285
- if (Object.keys(targetDevDeps).length) {
1286
- targetPkgJson.devDependencies = targetDevDeps;
1287
- }
1288
- const scriptPairs = (options == null ? void 0 : options.scripts) ? Object.entries(options.scripts) : scriptsEntries;
1289
- if (scriptPairs.length) {
1290
- const scripts2 = { ...targetPkgJson.scripts ?? {} };
1291
- for (const [scriptName, scriptCmd] of scriptPairs) {
1292
- scripts2[scriptName] = scriptCmd;
1293
- }
1294
- targetPkgJson.scripts = scripts2;
1295
- }
1296
- }
1297
-
1298
- // src/commands/upgrade/targets.ts
1299
- init_cjs_shims();
1300
- function getAssetTargets(core) {
1301
- const list = [
1302
- ".changeset",
1303
- ".husky",
1304
- ".vscode",
1305
- ".editorconfig",
1306
- ".gitattributes",
1307
- ".gitignore",
1308
- ".npmrc",
1309
- "commitlint.config.ts",
1310
- "eslint.config.js",
1311
- "lint-staged.config.js",
1312
- "stylelint.config.js",
1313
- "monorepo.config.ts",
1314
- "package.json",
1315
- // pnpm
1316
- "pnpm-workspace.yaml",
1317
- // base tsconfig
1318
- "tsconfig.json",
1319
- // turbo
1320
- "turbo.json",
1321
- // vitest
1322
- "vitest.config.ts",
1323
- // 'vitest.workspace.ts',
1324
- // #region docker
1325
- "Dockerfile",
1326
- ".dockerignore"
1327
- // #endregion
1328
- ];
1329
- if (!core) {
1330
- list.push(".github", "LICENSE", "renovate.json", "SECURITY.md", "CODE_OF_CONDUCT.md", "CONTRIBUTING.md", "netlify.toml");
1331
- }
1332
- return list;
1333
- }
1334
-
1335
- // src/commands/upgrade/index.ts
1336
- async function upgradeMonorepo(opts) {
1337
- const cwd2 = opts.cwd ?? import_node_process2.default.cwd();
1338
- const upgradeConfig = await resolveCommandConfig("upgrade", cwd2);
1339
- const merged = {
1340
- cwd: cwd2,
1341
- outDir: "",
1342
- ...upgradeConfig ?? {},
1343
- ...opts
1344
- };
1345
- const outDir = merged.outDir ?? "";
1346
- const absOutDir = import_pathe11.default.isAbsolute(outDir) ? outDir : import_pathe11.default.join(cwd2, outDir);
1347
- const gitClient = new GitClient({
1348
- baseDir: cwd2
1349
- });
1350
- const repoName = await gitClient.getRepoName();
1351
- const useCoreAssets = merged.core ?? false;
1352
- merged.core = useCoreAssets;
1353
- const baseTargets = getAssetTargets(useCoreAssets);
1354
- const configTargets = (upgradeConfig == null ? void 0 : upgradeConfig.targets) ?? [];
1355
- const mergeTargets = upgradeConfig == null ? void 0 : upgradeConfig.mergeTargets;
1356
- let targets = configTargets.length ? mergeTargets === false ? [...configTargets] : Array.from(/* @__PURE__ */ new Set([...baseTargets, ...configTargets])) : baseTargets;
1357
- if (merged.interactive) {
1358
- targets = await (0, import_checkbox3.default)({
1359
- message: "\u9009\u62E9\u4F60\u9700\u8981\u7684\u6587\u4EF6",
1360
- choices: targets.map((x) => {
1361
- return {
1362
- value: x,
1363
- checked: true
1364
- };
1365
- })
1366
- });
1367
- }
1368
- const regexpArr = targets.map((x) => {
1369
- return new RegExp(`^${escapeStringRegexp(x)}`);
1370
- });
1371
- const skipChangesetMarkdown = (upgradeConfig == null ? void 0 : upgradeConfig.skipChangesetMarkdown) ?? true;
1372
- const scriptOverrides = upgradeConfig == null ? void 0 : upgradeConfig.scripts;
1373
- const skipOverwrite = merged.skipOverwrite;
1374
- const pendingOverwrites = [];
1375
- for await (const file of (0, import_klaw.default)(assetsDir, {
1376
- filter(p) {
1377
- const rel = toWorkspaceGitignorePath(import_pathe11.default.relative(assetsDir, p));
1378
- return isMatch(rel, regexpArr);
1379
- }
1380
- })) {
1381
- if (!file.stats.isFile()) {
1382
- continue;
1383
- }
1384
- const relPath = toWorkspaceGitignorePath(import_pathe11.default.relative(assetsDir, file.path));
1385
- if (skipChangesetMarkdown && relPath.startsWith(".changeset/") && relPath.endsWith(".md")) {
1386
- continue;
1387
- }
1388
- const targetPath = import_pathe11.default.resolve(absOutDir, relPath);
1389
- try {
1390
- if (relPath === "package.json") {
1391
- if (!await import_fs_extra8.default.pathExists(targetPath)) {
1392
- continue;
1393
- }
1394
- const sourcePkgJson = await import_fs_extra8.default.readJson(file.path);
1395
- const targetPkgJson = await import_fs_extra8.default.readJson(targetPath);
1396
- setPkgJson(sourcePkgJson, targetPkgJson, { scripts: scriptOverrides });
1397
- const data = `${JSON.stringify(targetPkgJson, void 0, 2)}
1398
- `;
1399
- const intent2 = await evaluateWriteIntent(targetPath, { skipOverwrite, source: data });
1400
- const action2 = async () => {
1401
- await import_fs_extra8.default.outputFile(targetPath, data, "utf8");
1402
- logger.success(targetPath);
1403
- };
1404
- await scheduleOverwrite(intent2, {
1405
- relPath,
1406
- targetPath,
1407
- action: action2,
1408
- pending: pendingOverwrites
1409
- });
1410
- continue;
1411
- }
1412
- if (relPath === ".changeset/config.json" && repoName) {
1413
- const changesetJson = await import_fs_extra8.default.readJson(file.path);
1414
- (0, import_set_value6.default)(changesetJson, "changelog.1.repo", repoName);
1415
- const data = `${JSON.stringify(changesetJson, void 0, 2)}
1416
- `;
1417
- const intent2 = await evaluateWriteIntent(targetPath, { skipOverwrite, source: data });
1418
- const action2 = async () => {
1419
- await import_fs_extra8.default.outputFile(targetPath, data, "utf8");
1420
- logger.success(targetPath);
1421
- };
1422
- await scheduleOverwrite(intent2, {
1423
- relPath,
1424
- targetPath,
1425
- action: action2,
1426
- pending: pendingOverwrites
1427
- });
1428
- continue;
1429
- }
1430
- if (relPath === "LICENSE") {
1431
- const source2 = await import_fs_extra8.default.readFile(file.path);
1432
- const intent2 = await evaluateWriteIntent(targetPath, { skipOverwrite: true, source: source2 });
1433
- const action2 = async () => {
1434
- await import_fs_extra8.default.outputFile(targetPath, source2);
1435
- logger.success(targetPath);
1436
- };
1437
- await scheduleOverwrite(intent2, {
1438
- relPath,
1439
- targetPath,
1440
- action: action2,
1441
- pending: pendingOverwrites
1442
- });
1443
- continue;
1444
- }
1445
- const source = await import_fs_extra8.default.readFile(file.path);
1446
- const intent = await evaluateWriteIntent(targetPath, { skipOverwrite, source });
1447
- const action = async () => {
1448
- await import_fs_extra8.default.outputFile(targetPath, source);
1449
- logger.success(targetPath);
1450
- };
1451
- await scheduleOverwrite(intent, {
1452
- relPath,
1453
- targetPath,
1454
- action,
1455
- pending: pendingOverwrites
1456
- });
1457
- } catch (error) {
1458
- if (isIgnorableFsError(error)) {
1459
- continue;
1460
- }
1461
- throw error;
1462
- }
1463
- }
1464
- await flushPendingOverwrites(pendingOverwrites);
1465
- }
1466
-
1467
- // src/cli/program.ts
1468
- var cwd = import_node_process3.default.cwd();
1469
- import_commander.program.name(name).version(version);
1470
- import_commander.program.command("upgrade").description("\u5347\u7EA7/\u540C\u6B65 monorepo \u76F8\u5173\u5305").alias("up").option("-i,--interactive").option("-c,--core", "\u4EC5\u540C\u6B65\u6838\u5FC3\u914D\u7F6E\uFF0C\u8DF3\u8FC7 GitHub \u76F8\u5173\u8D44\u4EA7").option("--outDir <dir>", "Output directory").option("-s,--skip-overwrite", "skip overwrite").action(async (opts) => {
1471
- const normalized = {
1472
- ...opts,
1473
- core: opts.core ?? false,
1474
- cwd
1475
- };
1476
- await upgradeMonorepo(normalized);
1477
- logger.success("upgrade @icebreakers/monorepo ok!");
1
+ const require_upgrade = require('./upgrade-BpSxJA9Y.cjs');
2
+ let node_process = require("node:process");
3
+ node_process = require_upgrade.__toESM(node_process);
4
+ let __inquirer_input = require("@inquirer/input");
5
+ __inquirer_input = require_upgrade.__toESM(__inquirer_input);
6
+ let __inquirer_select = require("@inquirer/select");
7
+ __inquirer_select = require_upgrade.__toESM(__inquirer_select);
8
+ let commander = require("commander");
9
+
10
+ //#region src/cli/program.ts
11
+ const cwd = node_process.default.cwd();
12
+ commander.program.name(require_upgrade.name).version(require_upgrade.version);
13
+ /**
14
+ * 升级子命令:同步 assets 模板到当前仓库。
15
+ */
16
+ commander.program.command("upgrade").description("升级/同步 monorepo 相关包").alias("up").option("-i,--interactive").option("-c,--core", "仅同步核心配置,跳过 GitHub 相关资产").option("--outDir <dir>", "Output directory").option("-s,--skip-overwrite", "skip overwrite").action(async (opts) => {
17
+ await require_upgrade.upgradeMonorepo({
18
+ ...opts,
19
+ core: opts.core ?? false,
20
+ cwd
21
+ });
22
+ require_upgrade.logger.success("upgrade @icebreakers/monorepo ok!");
1478
23
  });
1479
- import_commander.program.command("init").description("\u521D\u59CB\u5316 package.json \u548C README.md").action(async () => {
1480
- await init(cwd);
1481
- logger.success("init finished!");
24
+ commander.program.command("init").description("初始化 package.json README.md").action(async () => {
25
+ await require_upgrade.init(cwd);
26
+ require_upgrade.logger.success("init finished!");
1482
27
  });
1483
- import_commander.program.command("sync").description("\u5411 npmmirror \u540C\u6B65\u6240\u6709\u5B50\u5305").action(async () => {
1484
- await syncNpmMirror(cwd);
1485
- logger.success("sync npm mirror finished!");
28
+ commander.program.command("sync").description(" npmmirror 同步所有子包").action(async () => {
29
+ await require_upgrade.syncNpmMirror(cwd);
30
+ require_upgrade.logger.success("sync npm mirror finished!");
1486
31
  });
1487
- import_commander.program.command("clean").description("\u6E05\u9664\u9009\u4E2D\u7684\u5305").action(async () => {
1488
- await cleanProjects(cwd);
1489
- logger.success("clean projects finished!");
32
+ commander.program.command("clean").description("清除选中的包").action(async () => {
33
+ await require_upgrade.cleanProjects(cwd);
34
+ require_upgrade.logger.success("clean projects finished!");
1490
35
  });
1491
- import_commander.program.command("mirror").description("\u8BBE\u7F6E VscodeBinaryMirror").action(async () => {
1492
- await setVscodeBinaryMirror(cwd);
1493
- logger.success("set vscode binary mirror finished!");
36
+ commander.program.command("mirror").description("设置 VscodeBinaryMirror").action(async () => {
37
+ await require_upgrade.setVscodeBinaryMirror(cwd);
38
+ require_upgrade.logger.success("set vscode binary mirror finished!");
1494
39
  });
1495
- import_commander.program.command("new").description("\u521B\u5EFA\u4E00\u4E2A\u65B0\u7684\u5B50\u5305").alias("create").argument("[name]").action(async (name2) => {
1496
- const createConfig = await resolveCommandConfig("create", cwd);
1497
- if (!name2) {
1498
- name2 = await (0, import_input.default)({
1499
- message: "\u8BF7\u8F93\u5165\u5305\u540D",
1500
- default: (createConfig == null ? void 0 : createConfig.name) ?? "my-package"
1501
- });
1502
- }
1503
- const type = await (0, import_select.default)({
1504
- message: "\u8BF7\u9009\u62E9\u6A21\u677F\u7C7B\u578B",
1505
- choices: getCreateChoices(createConfig == null ? void 0 : createConfig.choices),
1506
- default: (createConfig == null ? void 0 : createConfig.type) ?? (createConfig == null ? void 0 : createConfig.defaultTemplate) ?? defaultTemplate
1507
- });
1508
- await createNewProject({
1509
- name: name2,
1510
- cwd,
1511
- type
1512
- });
1513
- logger.success("create a package");
40
+ commander.program.command("new").description("创建一个新的子包").alias("create").argument("[name]").action(async (name$1) => {
41
+ const createConfig = await require_upgrade.resolveCommandConfig("create", cwd);
42
+ if (!name$1) name$1 = await (0, __inquirer_input.default)({
43
+ message: "请输入包名",
44
+ default: createConfig?.name ?? "my-package"
45
+ });
46
+ const type = await (0, __inquirer_select.default)({
47
+ message: "请选择模板类型",
48
+ choices: require_upgrade.getCreateChoices(createConfig?.choices),
49
+ default: createConfig?.type ?? createConfig?.defaultTemplate ?? require_upgrade.defaultTemplate
50
+ });
51
+ await require_upgrade.createNewProject({
52
+ name: name$1,
53
+ cwd,
54
+ type
55
+ });
56
+ require_upgrade.logger.success("create a package");
1514
57
  });
1515
- var program_default = import_commander.program;
58
+ var program_default = commander.program;
1516
59
 
1517
- // src/cli.ts
60
+ //#endregion
61
+ //#region src/cli.ts
1518
62
  program_default.parse();
1519
- /*! Bundled license information:
1520
-
1521
- is-primitive/index.js:
1522
- (*!
1523
- * is-primitive <https://github.com/jonschlinkert/is-primitive>
1524
- *
1525
- * Copyright (c) 2014-present, Jon Schlinkert.
1526
- * Released under the MIT License.
1527
- *)
1528
-
1529
- isobject/index.js:
1530
- (*!
1531
- * isobject <https://github.com/jonschlinkert/isobject>
1532
- *
1533
- * Copyright (c) 2014-2017, Jon Schlinkert.
1534
- * Released under the MIT License.
1535
- *)
1536
63
 
1537
- is-plain-object/index.js:
1538
- (*!
1539
- * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
1540
- *
1541
- * Copyright (c) 2014-2017, Jon Schlinkert.
1542
- * Released under the MIT License.
1543
- *)
1544
-
1545
- set-value/index.js:
1546
- (*!
1547
- * set-value <https://github.com/jonschlinkert/set-value>
1548
- *
1549
- * Copyright (c) Jon Schlinkert (https://github.com/jonschlinkert).
1550
- * Released under the MIT License.
1551
- *)
1552
-
1553
- get-value/dist/index.mjs:
1554
- (*!
1555
- * get-value <https://github.com/jonschlinkert/get-value>
1556
- *
1557
- * Copyright (c) 2014-present, Jon Schlinkert.
1558
- * Released under the MIT License.
1559
- *)
1560
- */
64
+ //#endregion