jiek 0.4.7-alpha.3 → 0.4.7-alpha.4
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/bin/jiek.js +9 -6
- package/dist/{cli.mjs → cli.cjs} +92 -65
- package/dist/cli.js +71 -86
- package/dist/cli.min.cjs +1 -0
- package/dist/cli.min.js +1 -1
- package/dist/index.cjs +5 -0
- package/dist/index.js +1 -3
- package/dist/index.min.cjs +1 -0
- package/dist/index.min.js +1 -1
- package/dist/rollup/{index.mjs → index.cjs} +69 -63
- package/dist/rollup/index.js +67 -65
- package/dist/rollup/index.min.cjs +1 -0
- package/dist/rollup/index.min.js +1 -1
- package/package.json +11 -10
- package/dist/cli.d.mts.map +0 -1
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/cli.min.js.map +0 -1
- package/dist/cli.min.mjs +0 -1
- package/dist/cli.min.mjs.map +0 -1
- package/dist/cli.mjs.map +0 -1
- package/dist/index.d.mts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/index.min.js.map +0 -1
- package/dist/index.min.mjs +0 -1
- package/dist/index.min.mjs.map +0 -1
- package/dist/index.mjs +0 -3
- package/dist/index.mjs.map +0 -1
- package/dist/rollup/index.d.mts.map +0 -1
- package/dist/rollup/index.d.ts.map +0 -1
- package/dist/rollup/index.js.map +0 -1
- package/dist/rollup/index.min.js.map +0 -1
- package/dist/rollup/index.min.mjs +0 -1
- package/dist/rollup/index.min.mjs.map +0 -1
- package/dist/rollup/index.mjs.map +0 -1
- /package/dist/{cli.d.mts → cli.d.cts} +0 -0
- /package/dist/{index.d.mts → index.d.cts} +0 -0
- /package/dist/rollup/{index.d.mts → index.d.cts} +0 -0
package/dist/cli.js
CHANGED
@@ -1,45 +1,24 @@
|
|
1
|
-
|
2
|
-
|
3
|
-
|
4
|
-
|
5
|
-
|
6
|
-
|
7
|
-
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
var bumper = require('@jiek/utils/bumper');
|
17
|
-
var entrypoints = require('@jiek/pkger/entrypoints');
|
18
|
-
|
19
|
-
function _interopNamespaceDefault(e) {
|
20
|
-
var n = Object.create(null);
|
21
|
-
if (e) {
|
22
|
-
Object.keys(e).forEach(function (k) {
|
23
|
-
if (k !== 'default') {
|
24
|
-
var d = Object.getOwnPropertyDescriptor(e, k);
|
25
|
-
Object.defineProperty(n, k, d.get ? d : {
|
26
|
-
enumerable: true,
|
27
|
-
get: function () { return e[k]; }
|
28
|
-
});
|
29
|
-
}
|
30
|
-
});
|
31
|
-
}
|
32
|
-
n.default = e;
|
33
|
-
return Object.freeze(n);
|
34
|
-
}
|
35
|
-
|
36
|
-
var childProcess__namespace = /*#__PURE__*/_interopNamespaceDefault(childProcess);
|
1
|
+
import fs from 'node:fs';
|
2
|
+
import path, { resolve as resolve$1, relative } from 'node:path';
|
3
|
+
import { filterPackagesFromDir } from '@pnpm/filter-workspace-packages';
|
4
|
+
import { program } from 'commander';
|
5
|
+
import { load } from 'js-yaml';
|
6
|
+
import { isWorkspaceDir, getWorkspaceDir } from '@jiek/utils/getWorkspaceDir';
|
7
|
+
import { MultiBar, Presets } from 'cli-progress';
|
8
|
+
import { execaCommand } from 'execa';
|
9
|
+
import detectIndent from 'detect-indent';
|
10
|
+
import inquirer from 'inquirer';
|
11
|
+
import { applyEdits, modify } from 'jsonc-parser';
|
12
|
+
import { isMatch } from 'micromatch';
|
13
|
+
import * as childProcess from 'node:child_process';
|
14
|
+
import { bump } from '@jiek/utils/bumper';
|
15
|
+
import { resolveEntrypoints, filterLeafs, DEFAULT_SKIP_VALUES, entrypoints2Exports } from '@jiek/pkger/entrypoints';
|
37
16
|
|
38
17
|
let root;
|
39
18
|
function getRoot() {
|
40
19
|
if (root)
|
41
20
|
return root;
|
42
|
-
const rootOption =
|
21
|
+
const rootOption = program.getOptionValue("root");
|
43
22
|
root = rootOption ? path.isAbsolute(rootOption) ? rootOption : path.resolve(process.cwd(), rootOption) : void 0;
|
44
23
|
return root;
|
45
24
|
}
|
@@ -51,13 +30,13 @@ function getWD() {
|
|
51
30
|
return { wd, notWorkspace };
|
52
31
|
const root = getRoot();
|
53
32
|
if (root !== void 0) {
|
54
|
-
const isWorkspace =
|
33
|
+
const isWorkspace = isWorkspaceDir(root, type);
|
55
34
|
notWorkspace = !isWorkspace;
|
56
35
|
wd = root;
|
57
36
|
return { wd, notWorkspace };
|
58
37
|
}
|
59
38
|
try {
|
60
|
-
wd = getWorkspaceDir
|
39
|
+
wd = getWorkspaceDir(type);
|
61
40
|
} catch (e) {
|
62
41
|
if ("message" in e && e.message === "workspace root not found") {
|
63
42
|
wd = root;
|
@@ -76,16 +55,16 @@ try {
|
|
76
55
|
} catch {
|
77
56
|
}
|
78
57
|
if (type !== "") {
|
79
|
-
|
58
|
+
program.option("-f, --filter <filter>", "filter packages");
|
80
59
|
}
|
81
60
|
async function getSelectedProjectsGraph() {
|
82
|
-
let filter =
|
61
|
+
let filter = program.getOptionValue("filter");
|
83
62
|
const root = getRoot();
|
84
63
|
const { wd, notWorkspace } = getWD();
|
85
64
|
if (!notWorkspace && type === "pnpm") {
|
86
65
|
const pnpmWorkspaceFilePath = path.resolve(wd, "pnpm-workspace.yaml");
|
87
66
|
const pnpmWorkspaceFileContent = fs.readFileSync(pnpmWorkspaceFilePath, "utf-8");
|
88
|
-
const pnpmWorkspace =
|
67
|
+
const pnpmWorkspace = load(pnpmWorkspaceFileContent);
|
89
68
|
if (root === wd && !filter) {
|
90
69
|
throw new Error("root path is workspace root, please provide a filter");
|
91
70
|
}
|
@@ -100,7 +79,7 @@ async function getSelectedProjectsGraph() {
|
|
100
79
|
}
|
101
80
|
filter = packageJSON.name;
|
102
81
|
}
|
103
|
-
const { selectedProjectsGraph } = await
|
82
|
+
const { selectedProjectsGraph } = await filterPackagesFromDir(wd, [{
|
104
83
|
filter: filter ?? "",
|
105
84
|
followProdDepsOnly: true
|
106
85
|
}], {
|
@@ -128,7 +107,7 @@ async function getSelectedProjectsGraph() {
|
|
128
107
|
|
129
108
|
var pkg = require("../package.json");
|
130
109
|
|
131
|
-
|
110
|
+
program.version(pkg.version).description(pkg.description).option("--root <root>", "root path").option("-c, --config-path <configPath>", "config path");
|
132
111
|
|
133
112
|
let resolve;
|
134
113
|
function actionDone() {
|
@@ -193,7 +172,7 @@ function getConfigPath(root, dir) {
|
|
193
172
|
}
|
194
173
|
function loadConfig(dir) {
|
195
174
|
const { wd: root } = getWD();
|
196
|
-
let configPath =
|
175
|
+
let configPath = program.getOptionValue("configPath");
|
197
176
|
if (!configPath) {
|
198
177
|
configPath = getConfigPath(root, dir);
|
199
178
|
} else {
|
@@ -213,7 +192,7 @@ function loadConfig(dir) {
|
|
213
192
|
case ".json":
|
214
193
|
return require(configPath);
|
215
194
|
case ".yaml":
|
216
|
-
return
|
195
|
+
return load(fs.readFileSync(configPath, "utf-8"));
|
217
196
|
case ".ts":
|
218
197
|
if (tsRegisterName) {
|
219
198
|
require(tsRegisterName);
|
@@ -238,7 +217,7 @@ const FILE_TEMPLATE = (manifest) => `
|
|
238
217
|
const manifest = ${JSON.stringify(manifest, null, 2)}
|
239
218
|
module.exports = require('jiek/rollup').template(manifest)
|
240
219
|
`.trimStart();
|
241
|
-
|
220
|
+
program.command("build").option("-s, --silent", "Don't display logs.").option("-e, --entries <ENTRIES>", "Specify the entries of the package.json's 'exports' field.(support glob)").action(async ({
|
242
221
|
silent,
|
243
222
|
entries
|
244
223
|
}) => {
|
@@ -261,11 +240,11 @@ commander.program.command("build").option("-s, --silent", "Don't display logs.")
|
|
261
240
|
fs.mkdirSync(jiekTempDir());
|
262
241
|
}
|
263
242
|
const rollupBinaryPath = require.resolve("rollup").replace(/dist\/rollup.js$/, "dist/bin/rollup");
|
264
|
-
const multiBars = new
|
243
|
+
const multiBars = new MultiBar({
|
265
244
|
clearOnComplete: false,
|
266
245
|
hideCursor: true,
|
267
246
|
format: "- {bar} | {status} | {input} | {message}"
|
268
|
-
},
|
247
|
+
}, Presets.shades_classic);
|
269
248
|
let i = 0;
|
270
249
|
await Promise.all(
|
271
250
|
Object.entries(value).map(async ([dir, manifest]) => {
|
@@ -279,7 +258,7 @@ commander.program.command("build").option("-s, --silent", "Don't display logs.")
|
|
279
258
|
prefix = `node -r ${tsRegisterName} `;
|
280
259
|
}
|
281
260
|
const command = `${prefix}${rollupBinaryPath} --silent -c ${configFile}`;
|
282
|
-
const child =
|
261
|
+
const child = execaCommand(command, {
|
283
262
|
ipc: true,
|
284
263
|
cwd: dir,
|
285
264
|
env: {
|
@@ -453,12 +432,12 @@ async function getName(named, name, {
|
|
453
432
|
}
|
454
433
|
} else {
|
455
434
|
for (const [key, value] of Object.entries(named)) {
|
456
|
-
if (
|
435
|
+
if (isMatch(relativePath, key)) {
|
457
436
|
matchedKey = key;
|
458
437
|
matchedRule = value;
|
459
438
|
break;
|
460
439
|
}
|
461
|
-
if (
|
440
|
+
if (isMatch(`${relativePath}/jiek_ignore_dont_use_same_file_name`, key)) {
|
462
441
|
isParentMatched = true;
|
463
442
|
matchedKey = key;
|
464
443
|
matchedRule = value;
|
@@ -498,8 +477,8 @@ async function getName(named, name, {
|
|
498
477
|
}
|
499
478
|
throw new Error("no matched rule");
|
500
479
|
}
|
501
|
-
|
502
|
-
const [, name] =
|
480
|
+
program.command("init [name]").option("-t, --template <template>", "the package.json template file path or file content").action(async () => {
|
481
|
+
const [, name] = program.args;
|
503
482
|
const cwd = process.cwd();
|
504
483
|
const { init = {} } = loadConfig() ?? {};
|
505
484
|
const { wd } = getWD();
|
@@ -533,9 +512,9 @@ commander.program.command("init [name]").option("-t, --template <template>", "th
|
|
533
512
|
];
|
534
513
|
let newJSONString = templateString;
|
535
514
|
for (const field of passFields) {
|
536
|
-
newJSONString =
|
515
|
+
newJSONString = applyEdits(
|
537
516
|
newJSONString,
|
538
|
-
|
517
|
+
modify(
|
539
518
|
newJSONString,
|
540
519
|
[field],
|
541
520
|
getWDPackageJSONFiled(wd, field),
|
@@ -566,7 +545,7 @@ commander.program.command("init [name]").option("-t, --template <template>", "th
|
|
566
545
|
});
|
567
546
|
pkgName = inputName;
|
568
547
|
}
|
569
|
-
newJSONString =
|
548
|
+
newJSONString = applyEdits(newJSONString, modify(newJSONString, ["name"], pkgName, { formattingOptions }));
|
570
549
|
let pkgRepo = getWDPackageJSONFiled(wd, "repository");
|
571
550
|
if (typeof pkgRepo === "string") {
|
572
551
|
pkgRepo = {
|
@@ -575,9 +554,9 @@ commander.program.command("init [name]").option("-t, --template <template>", "th
|
|
575
554
|
directory: pkgDir
|
576
555
|
};
|
577
556
|
}
|
578
|
-
newJSONString =
|
557
|
+
newJSONString = applyEdits(
|
579
558
|
newJSONString,
|
580
|
-
|
559
|
+
modify(
|
581
560
|
newJSONString,
|
582
561
|
["repository"],
|
583
562
|
pkgRepo,
|
@@ -585,9 +564,9 @@ commander.program.command("init [name]").option("-t, --template <template>", "th
|
|
585
564
|
)
|
586
565
|
);
|
587
566
|
const homepage = `${pkgRepo?.url}/blob/master/${pkgDir}/README.md`;
|
588
|
-
newJSONString =
|
567
|
+
newJSONString = applyEdits(
|
589
568
|
newJSONString,
|
590
|
-
|
569
|
+
modify(
|
591
570
|
newJSONString,
|
592
571
|
["homepage"],
|
593
572
|
homepage,
|
@@ -603,9 +582,9 @@ commander.program.command("init [name]").option("-t, --template <template>", "th
|
|
603
582
|
}
|
604
583
|
labels.push(`scope:${pkgName}`);
|
605
584
|
const bugs = `${pkgRepo?.url}/issues/new?template=${resolvedBug.template}&labels=${labels.join(",")}`;
|
606
|
-
newJSONString =
|
585
|
+
newJSONString = applyEdits(
|
607
586
|
newJSONString,
|
608
|
-
|
587
|
+
modify(
|
609
588
|
newJSONString,
|
610
589
|
["bugs"],
|
611
590
|
bugs,
|
@@ -639,15 +618,17 @@ commander.program.command("init [name]").option("-t, --template <template>", "th
|
|
639
618
|
|
640
619
|
const intersection = (a, b) => new Set([...a].filter((i) => b.has(i)));
|
641
620
|
function getExports({
|
642
|
-
entrypoints
|
621
|
+
entrypoints,
|
643
622
|
pkgIsModule,
|
644
623
|
entries,
|
645
624
|
config,
|
646
625
|
dir,
|
647
|
-
noFilter
|
626
|
+
noFilter,
|
627
|
+
withSource,
|
628
|
+
withSuffix
|
648
629
|
}) {
|
649
|
-
const dirResolve = (...paths) =>
|
650
|
-
const dirRelative = (path
|
630
|
+
const dirResolve = (...paths) => resolve$1(dir ?? process.cwd(), ...paths);
|
631
|
+
const dirRelative = (path) => relative(dir ?? process.cwd(), path);
|
651
632
|
const { build = {} } = config ?? {};
|
652
633
|
const {
|
653
634
|
crossModuleConvertor = true
|
@@ -655,21 +636,21 @@ function getExports({
|
|
655
636
|
const jsOutdir = `./${dirRelative(dirResolve(
|
656
637
|
(typeof build?.output?.dir === "object" ? build.output.dir.js : build?.output?.dir) ?? "dist"
|
657
638
|
))}`;
|
658
|
-
const [, resolvedEntrypoints] =
|
639
|
+
const [, resolvedEntrypoints] = resolveEntrypoints(entrypoints);
|
659
640
|
if (entries) {
|
660
641
|
Object.entries(resolvedEntrypoints).forEach(([key]) => {
|
661
|
-
if (!entries.some((e) =>
|
642
|
+
if (!entries.some((e) => isMatch(key, e, { matchBase: true }))) {
|
662
643
|
delete resolvedEntrypoints[key];
|
663
644
|
}
|
664
645
|
});
|
665
646
|
}
|
666
|
-
const filteredResolvedEntrypoints = noFilter ? resolvedEntrypoints :
|
647
|
+
const filteredResolvedEntrypoints = noFilter ? resolvedEntrypoints : filterLeafs(
|
667
648
|
resolvedEntrypoints,
|
668
649
|
{
|
669
650
|
skipValue: [
|
670
651
|
// ignore values that filename starts with `.jk-noentry`
|
671
652
|
/(^|\/)\.jk-noentry/,
|
672
|
-
...
|
653
|
+
...DEFAULT_SKIP_VALUES
|
673
654
|
]
|
674
655
|
}
|
675
656
|
);
|
@@ -685,8 +666,10 @@ function getExports({
|
|
685
666
|
} : {};
|
686
667
|
return [
|
687
668
|
filteredResolvedEntrypoints,
|
688
|
-
|
669
|
+
entrypoints2Exports(filteredResolvedEntrypoints, {
|
689
670
|
outdir: jsOutdir,
|
671
|
+
withSource,
|
672
|
+
withSuffix,
|
690
673
|
withConditional: {
|
691
674
|
...crossModuleWithConditional
|
692
675
|
}
|
@@ -694,7 +677,7 @@ function getExports({
|
|
694
677
|
];
|
695
678
|
}
|
696
679
|
|
697
|
-
|
680
|
+
program.command("publish").aliases(["pub", "p"]).option("-b, --bumper <bumper>", "bump version", "patch").option("-p, --preview", "preview publish").action(async ({ preview, bumper, ...options }) => {
|
698
681
|
actionRestore();
|
699
682
|
const { value = {} } = await getSelectedProjectsGraph() ?? {};
|
700
683
|
const selectedProjectsGraphEntries = Object.entries(value);
|
@@ -710,7 +693,9 @@ commander.program.command("publish").aliases(["pub", "p"]).option("-b, --bumper
|
|
710
693
|
pkgIsModule,
|
711
694
|
config: loadConfig(dir),
|
712
695
|
dir,
|
713
|
-
noFilter: true
|
696
|
+
noFilter: true,
|
697
|
+
withSource: true,
|
698
|
+
withSuffix: true
|
714
699
|
});
|
715
700
|
newManifest.exports = {
|
716
701
|
...resolvedEntrypoints,
|
@@ -727,16 +712,16 @@ commander.program.command("publish").aliases(["pub", "p"]).option("-b, --bumper
|
|
727
712
|
for (const [dir, manifest] of manifests) {
|
728
713
|
const oldJSONString = fs.readFileSync(path.join(dir, "package.json"), "utf-8");
|
729
714
|
const oldJSON = JSON.parse(oldJSONString) ?? "0.0.0";
|
730
|
-
const newVersion =
|
715
|
+
const newVersion = bump(oldJSON.version, bumper);
|
731
716
|
const { indent = " " } = detectIndent(oldJSONString);
|
732
717
|
const formattingOptions = {
|
733
718
|
tabSize: indent.length,
|
734
719
|
insertSpaces: true
|
735
720
|
};
|
736
721
|
let newJSONString = oldJSONString;
|
737
|
-
newJSONString =
|
722
|
+
newJSONString = applyEdits(
|
738
723
|
newJSONString,
|
739
|
-
|
724
|
+
modify(
|
740
725
|
newJSONString,
|
741
726
|
["version"],
|
742
727
|
newVersion,
|
@@ -747,9 +732,9 @@ commander.program.command("publish").aliases(["pub", "p"]).option("-b, --bumper
|
|
747
732
|
if (JSON.stringify(value2) === JSON.stringify(oldJSON[key]))
|
748
733
|
continue;
|
749
734
|
if (key !== "exports") {
|
750
|
-
newJSONString =
|
735
|
+
newJSONString = applyEdits(
|
751
736
|
newJSONString,
|
752
|
-
|
737
|
+
modify(
|
753
738
|
newJSONString,
|
754
739
|
["publishConfig", key],
|
755
740
|
value2,
|
@@ -759,9 +744,9 @@ commander.program.command("publish").aliases(["pub", "p"]).option("-b, --bumper
|
|
759
744
|
} else {
|
760
745
|
const exports = value2;
|
761
746
|
for (const [k, v] of Object.entries(exports)) {
|
762
|
-
newJSONString =
|
747
|
+
newJSONString = applyEdits(
|
763
748
|
newJSONString,
|
764
|
-
|
749
|
+
modify(
|
765
750
|
newJSONString,
|
766
751
|
["publishConfig", "exports", k],
|
767
752
|
v,
|
@@ -786,9 +771,9 @@ commander.program.command("publish").aliases(["pub", "p"]).option("-b, --bumper
|
|
786
771
|
for (const [k, v] of Object.entries(indexPublishConfig)) {
|
787
772
|
if (v === void 0)
|
788
773
|
continue;
|
789
|
-
newJSONString =
|
774
|
+
newJSONString = applyEdits(
|
790
775
|
newJSONString,
|
791
|
-
|
776
|
+
modify(
|
792
777
|
newJSONString,
|
793
778
|
["publishConfig", k],
|
794
779
|
v,
|
@@ -807,11 +792,11 @@ commander.program.command("publish").aliases(["pub", "p"]).option("-b, --bumper
|
|
807
792
|
console.warn("preview mode");
|
808
793
|
continue;
|
809
794
|
}
|
810
|
-
|
795
|
+
childProcess.execSync(["pnpm", "publish", "--access", "public", "--no-git-checks", ...passArgs].join(" "), {
|
811
796
|
cwd: dir,
|
812
797
|
stdio: "inherit"
|
813
798
|
});
|
814
|
-
const modifyVersionPackageJSON =
|
799
|
+
const modifyVersionPackageJSON = applyEdits(oldJSONString, modify(oldJSONString, ["version"], newVersion, {}));
|
815
800
|
fs.writeFileSync(path.join(dir, "package.json.bak"), modifyVersionPackageJSON);
|
816
801
|
} finally {
|
817
802
|
fs.unlinkSync(path.join(dir, "package.json"));
|
@@ -821,4 +806,4 @@ commander.program.command("publish").aliases(["pub", "p"]).option("-b, --bumper
|
|
821
806
|
actionDone();
|
822
807
|
});
|
823
808
|
|
824
|
-
|
809
|
+
program.parse(process.argv);
|
package/dist/cli.min.cjs
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
"use strict";var e=require("node:fs"),t=require("node:path"),r=require("@pnpm/filter-workspace-packages"),n=require("commander"),o=require("js-yaml"),i=require("@jiek/utils/getWorkspaceDir"),s=require("cli-progress"),a=require("execa"),c=require("detect-indent"),p=require("inquirer"),l=require("jsonc-parser"),u=require("micromatch"),f=require("node:child_process"),d=require("@jiek/utils/bumper"),m=require("@jiek/pkger/entrypoints");function g(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var y=g(f);let w,h;function b(){if(w)return w;const e=n.program.getOptionValue("root");return w=e?t.isAbsolute(e)?e:t.resolve(process.cwd(),e):void 0,w}let k=!1;function j(){if(h)return{wd:h,notWorkspace:k};const e=b();if(void 0!==e){const t=i.isWorkspaceDir(e,S);return k=!t,h=e,{wd:h,notWorkspace:k}}try{h=i.getWorkspaceDir(S)}catch(t){if(!("message"in t)||"workspace root not found"!==t.message)throw t;h=e,k=!0}return{wd:h,notWorkspace:k}}let S="";try{require.resolve("@pnpm/filter-workspace-packages"),S="pnpm"}catch{}async function v(){let i=n.program.getOptionValue("filter");const s=b(),{wd:a,notWorkspace:c}=j();if(!c&&"pnpm"===S){const n=t.resolve(a,"pnpm-workspace.yaml"),c=e.readFileSync(n,"utf-8"),p=o.load(c);if(s===a&&!i)throw new Error("root path is workspace root, please provide a filter");if(s!==a&&!i){if(!e.existsSync(t.resolve(s,"package.json")))throw new Error("root path is not workspace root, please provide a filter");const r=JSON.parse(e.readFileSync(t.resolve(s,"package.json"),"utf-8"));if(!r.name)throw new Error("root path is not workspace root, please provide a filter");i=r.name}const{selectedProjectsGraph:l}=await r.filterPackagesFromDir(a,[{filter:i??"",followProdDepsOnly:!0}],{prefix:s,workspaceDir:a,patterns:p.packages});return{wd:a,root:s,value:Object.entries(l).reduce(((e,[t,r])=>(e[t]=r.package.manifest,e)),{})}}return{wd:a,root:s,value:{[a]:JSON.parse(e.readFileSync(t.resolve(a,"package.json"),"utf-8"))}}}""!==S&&n.program.option("-f, --filter <filter>","filter packages");var $=require("../package.json");let E,O;function q(){E()}function x(){new Promise((e=>E=e))}function F(e){try{return require.resolve(e),!0}catch(e){return!1}}n.program.version($.version).description($.description).option("--root <root>","root path").option("-c, --config-path <configPath>","config path");const _=[process.env.JIEK_TS_REGISTER,"esbuild-register","@swc-node/register","ts-node/register"].filter(Boolean);for(const e of _)if(F(e)){O=e;break}let J="jiek.config";function M(r){const{wd:i}=j();let s=n.program.getOptionValue("configPath");if(s){if(!e.existsSync(s))throw new Error(`config file not found: ${s}`);t.isAbsolute(s)||(s=t.resolve(i,s))}else s=function(r,n){const o=!!O;function i(o){const i=[t.resolve(process.cwd(),`${J}.${o}`),t.resolve(process.cwd(),`.${J}.${o}`),t.resolve(r,`${J}.${o}`),t.resolve(r,`.${J}.${o}`)];n&&i.unshift(t.resolve(n,`${J}.${o}`),t.resolve(n,`.${J}.${o}`));for(const t of i)if(e.existsSync(t)&&e.lstatSync(t).isFile())return t}return J=i("js")??J,J=i("json")??J,J=i("yaml")??J,o&&(J=i("ts")??J),t.resolve(r,J)}(i,r);const a=t.extname(s);let c;switch(a){case".js":c=require(s);break;case".json":return require(s);case".yaml":return o.load(e.readFileSync(s,"utf-8"));case".ts":if(O){require(O),c=require(s);break}throw new Error("ts config file is not supported without ts register, please install esbuild-register or set JIEK_TS_REGISTER env for custom ts register");case".config":c={};break;default:throw new Error(`unsupported config file type: ${a}`)}if(!c)throw new Error("config file is empty");return c.default??c}n.program.command("build").option("-s, --silent","Don't display logs.").option("-e, --entries <ENTRIES>","Specify the entries of the package.json's 'exports' field.(support glob)").action((async({silent:r,entries:n})=>{x();const{build:o}=M();r=r??o?.silent??!1;const{wd:i,value:c={}}=await v()??{};if(0===Object.keys(c).length)throw new Error("no package found");const p=t.resolve(i,"node_modules");e.existsSync(p)||e.mkdirSync(p);const l=(...e)=>t.resolve(p,".jiek",...e);e.existsSync(l())||e.mkdirSync(l());const u=require.resolve("rollup").replace(/dist\/rollup.js$/,"dist/bin/rollup"),f=new s.MultiBar({clearOnComplete:!1,hideCursor:!0,format:"- {bar} | {status} | {input} | {message}"},s.Presets.shades_classic);let d=0;await Promise.all(Object.entries(c).map((async([t,o])=>{const s=o.name?.replace(/^@/g,"").replace(/\//g,"+"),c=l(`${s??"anonymous-"+d++}.rollup.config.js`);e.writeFileSync(c,(e=>`\nconst manifest = ${JSON.stringify(e,null,2)}\nmodule.exports = require('jiek/rollup').template(manifest)\n`.trimStart())(o));let p="";O&&(p=`node -r ${O} `);const m=`${p}${u} --silent -c ${c}`,g=a.execaCommand(m,{ipc:!0,cwd:t,env:{...process.env,JIEK_ROOT:i,JIEK_ENTRIES:n}}),y={};let w=10;g.on("message",(e=>{"debug"===e.type&&console.log(...Array.isArray(e.data)?e.data:[e.data])})),!r&&g.on("message",(e=>{if("init"===e.type){const{leafMap:t,targetsLength:r}=e.data,n=Array.from(t.entries()).flatMap((([e,t])=>t.map((([t,...r])=>({input:e,path:t,conditions:r})))));console.log(`Package '${o.name}' has ${r} targets to build`),n.forEach((({input:e})=>{w=Math.max(w,e.length)})),n.forEach((({input:e,path:t})=>{const r=`${e}:${t}`;y[r]||(y[r]=f.create(50,0,{input:e.padEnd(w),status:"waiting".padEnd(10)},{barsize:20,linewrap:!0}))}))}if("progress"===e.type){const{path:t,tags:r,input:n,event:o,message:i}=e.data,s=y[`${n}:${t}`];if(!s)return;s.update({start:0,resolve:20,end:50}[o??"start"]??0,{input:n.padEnd(w),status:o?.padEnd(10),message:`${r?.join(", ")}: ${i}`})}})),await new Promise(((e,t)=>{let r="";g.stderr?.on("data",(e=>{r+=e})),g.once("exit",(n=>0===n?e():t(new Error(`rollup build failed:\n${r}`))))}))}))).finally((()=>{f.stop()})),q()}));const N='{\n "name": "",\n "version": "0.0.1",\n "description": "",\n "license": "",\n "author": "",\n "files": ["dist"],\n "exports": {\n ".": "./src/index.ts"\n },\n "scripts": {\n },\n "homepage": "",\n "repository": "",\n "bugs": ""\n}'.trimStart(),P="# $name\n\n## Installation\n\n```bash\nnpm install $name\n# or\npnpm install $name\n# or\nyarn add $name\n```\n\n## Usage\n\n\n## License\n\n$license\n".trimStart();const D=new Map;function I(r,n){if(D.has(r))return D.get(r)[n];const o=t.resolve(r,"package.json"),i=JSON.parse(e.readFileSync(o,"utf-8"));return D.set(r,i),i[n]}n.program.command("init [name]").option("-t, --template <template>","the package.json template file path or file content").action((async()=>{const[,r]=n.program.args,o=process.cwd(),{init:i={}}=M()??{},{wd:s}=j(),a=t.basename(s),{named:f,template:d,bug:m={},readme:g=P,readmeTemplate:y}=i,w={template:"bug_report.yml",labels:["bug"],...m};let h=g;if(y){const r=t.resolve(s,y);h=e.readFileSync(r,"utf-8")}const b=function(r,n){let o=n??N,i=!1;try{n&&JSON.parse(n)}catch(e){i=!0}if(i){const i=t.resolve(r,n);o=e.readFileSync(i,"utf-8")}return o}(s,d),{indent:k=" "}=c(b),S={tabSize:k.length,insertSpaces:!0},v=["license","author"];let $=b;for(const e of v)$=l.applyEdits($,l.modify($,[e],I(s,e),{formattingOptions:S}));let[E,O]=await async function(e,r,{wd:n,cwd:o,workspaceName:i}){const s=o.replace(`${n}/`,"");let a=t.basename(o);if("function"==typeof e)return e(r,{full:n,relative:o});let c,l,f=!1;if("object"==typeof e)if(o===n){const{rule:t}=await p.prompt({type:"list",name:"rule",message:"choose a rule",default:"default",choices:["default"].concat(Object.keys(e))});"default"!==t&&(c=t,l=e[t])}else for(const[t,r]of Object.entries(e)){if(u.isMatch(s,t)){c=t,l=r;break}if(u.isMatch(`${s}/jiek_ignore_dont_use_same_file_name`,t)){f=!0,c=t,l=r;break}}if(l||(c="packages/*",l=`@${i}/$basename`),!l)throw new Error("no matched rule");if(!r&&f&&(a=await p.prompt({type:"input",name:"name",message:`the matched rule is \`${String(l)}\`, please input the basename\n`}).then((({name:e})=>e))),"function"==typeof l)return l(r,{full:n,relative:o,basename:a});if("string"==typeof l){const e=r??a;return[l.replace(/\$basename/g,e),c?.replace(/\/\*$/g,`/${e}`)]}throw new Error("no matched rule")}(f,r,{wd:s,cwd:o,workspaceName:a});if(!O){const{dir:e}=await p.prompt({type:"input",name:"dir",message:"package directory",default:r});O=e}if(!E){const{name:e}=await p.prompt({type:"input",name:"name",message:"package name",default:r});E=e}$=l.applyEdits($,l.modify($,["name"],E,{formattingOptions:S}));let q=I(s,"repository");"string"==typeof q&&(q={type:"git",url:q,directory:O}),$=l.applyEdits($,l.modify($,["repository"],q,{formattingOptions:S}));const x=`${q?.url}/blob/master/${O}/README.md`;$=l.applyEdits($,l.modify($,["homepage"],x,{formattingOptions:S}));let F=w.labels;"function"==typeof F&&(F=F({name:E,dir:O})),F.push(`scope:${E}`);const _=`${q?.url}/issues/new?template=${w.template}&labels=${F.join(",")}`;function J(e){if(!O)throw new Error("pkgDir is not defined");return t.resolve(O,e)}$=l.applyEdits($,l.modify($,["bugs"],_,{formattingOptions:S})),e.existsSync(O)||e.mkdirSync(O);const D=J("package.json");if(e.existsSync(D))throw new Error("package.json already exists");e.writeFileSync(D,$),console.log($,"written to",D);const A=I(s,"license"),R=J("README.md");"function"==typeof h&&(h=h({dir:O,packageJson:JSON.parse($)}));const T=h.replace(/\$name/g,E).replace(/\$license/g,A);e.writeFileSync(R,T)}));const A=(e,t)=>new Set([...e].filter((e=>t.has(e))));function R({entrypoints:e,pkgIsModule:r,entries:n,config:o,dir:i,noFilter:s,withSource:a,withSuffix:c}){const{build:p={}}=o??{},{crossModuleConvertor:l=!0}=p,f=`./${d=((...e)=>t.resolve(i??process.cwd(),...e))(("object"==typeof p?.output?.dir?p.output.dir.js:p?.output?.dir)??"dist"),t.relative(i??process.cwd(),d)}`;var d;const[,g]=m.resolveEntrypoints(e);n&&Object.entries(g).forEach((([e])=>{n.some((t=>u.isMatch(e,t,{matchBase:!0})))||delete g[e]}));const y=s?g:m.filterLeafs(g,{skipValue:[/(^|\/)\.jk-noentry/,...m.DEFAULT_SKIP_VALUES]}),w=l?{import:e=>!r&&0===A(new Set(e.conditionals),new Set(["import","module"])).size&&e.dist.replace(/\.js$/,".mjs"),require:e=>!(!r||0!==A(new Set(e.conditionals),new Set(["require","node"])).size)&&e.dist.replace(/\.js$/,".cjs")}:{};return[y,m.entrypoints2Exports(y,{outdir:f,withSource:a,withSuffix:c,withConditional:{...w}})]}n.program.command("publish").aliases(["pub","p"]).option("-b, --bumper <bumper>","bump version","patch").option("-p, --preview","preview publish").action((async({preview:r,bumper:n,...o})=>{x();const{value:i={}}=await v()??{},s=Object.entries(i);if(0===s.length)throw new Error("no packages selected");const a=s.map((([e,t])=>{const{type:r,exports:n={}}=t,o="module"===r,i={...t},[s,a]=R({entrypoints:n,pkgIsModule:o,config:M(e),dir:e,noFilter:!0,withSource:!0,withSuffix:!0});return i.exports={...s,...a},[e,i]})),p=Object.entries(o).reduce(((e,[t,r])=>(r&&e.push(`--${t}`,r),e)),[]);for(const[o,i]of a){const s=e.readFileSync(t.join(o,"package.json"),"utf-8"),a=JSON.parse(s)??"0.0.0",u=d.bump(a.version,n),{indent:f=" "}=c(s),m={tabSize:f.length,insertSpaces:!0};let g=s;g=l.applyEdits(g,l.modify(g,["version"],u,{formattingOptions:m}));for(const[e,t]of Object.entries(i))if(JSON.stringify(t)!==JSON.stringify(a[e]))if("exports"!==e)g=l.applyEdits(g,l.modify(g,["publishConfig",e],t,{formattingOptions:m}));else{const e=t;for(const[t,r]of Object.entries(e))g=l.applyEdits(g,l.modify(g,["publishConfig","exports",t],r,{formattingOptions:m}));const r=e?.["."],n={};if(r){switch(typeof r){case"string":n["module"===i?.type?"module":"main"]=r;break;case"object":{const e=r;n.main=e.require??e.default,n.module=e.import??e.module??e.default;break}}for(const[e,t]of Object.entries(n))void 0!==t&&(g=l.applyEdits(g,l.modify(g,["publishConfig",e],t,{formattingOptions:m})))}}try{if(e.renameSync(t.join(o,"package.json"),t.join(o,"package.json.bak")),e.writeFileSync(t.join(o,"package.json"),g),console.log(g),r){console.warn("preview mode");continue}y.execSync(["pnpm","publish","--access","public","--no-git-checks",...p].join(" "),{cwd:o,stdio:"inherit"});const n=l.applyEdits(s,l.modify(s,["version"],u,{}));e.writeFileSync(t.join(o,"package.json.bak"),n)}finally{e.unlinkSync(t.join(o,"package.json")),e.renameSync(t.join(o,"package.json.bak"),t.join(o,"package.json"))}}q()})),n.program.parse(process.argv);
|
package/dist/cli.min.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
"use strict";var e=require("node:fs"),t=require("node:path"),r=require("@pnpm/filter-workspace-packages"),n=require("commander"),o=require("js-yaml"),s=require("@jiek/utils/getWorkspaceDir"),i=require("cli-progress"),a=require("execa"),c=require("detect-indent"),p=require("inquirer"),l=require("jsonc-parser"),u=require("micromatch"),f=require("node:child_process"),d=require("@jiek/utils/bumper"),m=require("@jiek/pkger/entrypoints");function g(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var y=g(f);let w,h;function b(){if(w)return w;const e=n.program.getOptionValue("root");return w=e?t.isAbsolute(e)?e:t.resolve(process.cwd(),e):void 0,w}let k=!1;function j(){if(h)return{wd:h,notWorkspace:k};const e=b();if(void 0!==e){const t=s.isWorkspaceDir(e,v);return k=!t,h=e,{wd:h,notWorkspace:k}}try{h=s.getWorkspaceDir(v)}catch(t){if(!("message"in t)||"workspace root not found"!==t.message)throw t;h=e,k=!0}return{wd:h,notWorkspace:k}}let v="";try{require.resolve("@pnpm/filter-workspace-packages"),v="pnpm"}catch{}async function S(){let s=n.program.getOptionValue("filter");const i=b(),{wd:a,notWorkspace:c}=j();if(!c&&"pnpm"===v){const n=t.resolve(a,"pnpm-workspace.yaml"),c=e.readFileSync(n,"utf-8"),p=o.load(c);if(i===a&&!s)throw new Error("root path is workspace root, please provide a filter");if(i!==a&&!s){if(!e.existsSync(t.resolve(i,"package.json")))throw new Error("root path is not workspace root, please provide a filter");const r=JSON.parse(e.readFileSync(t.resolve(i,"package.json"),"utf-8"));if(!r.name)throw new Error("root path is not workspace root, please provide a filter");s=r.name}const{selectedProjectsGraph:l}=await r.filterPackagesFromDir(a,[{filter:s??"",followProdDepsOnly:!0}],{prefix:i,workspaceDir:a,patterns:p.packages});return{wd:a,root:i,value:Object.entries(l).reduce(((e,[t,r])=>(e[t]=r.package.manifest,e)),{})}}return{wd:a,root:i,value:{[a]:JSON.parse(e.readFileSync(t.resolve(a,"package.json"),"utf-8"))}}}""!==v&&n.program.option("-f, --filter <filter>","filter packages");var $=require("../package.json");let E,O;function q(){E()}function x(){new Promise((e=>E=e))}function F(e){try{return require.resolve(e),!0}catch(e){return!1}}n.program.version($.version).description($.description).option("--root <root>","root path").option("-c, --config-path <configPath>","config path");const _=[process.env.JIEK_TS_REGISTER,"esbuild-register","@swc-node/register","ts-node/register"].filter(Boolean);for(const e of _)if(F(e)){O=e;break}let J="jiek.config";function M(r){const{wd:s}=j();let i=n.program.getOptionValue("configPath");if(i){if(!e.existsSync(i))throw new Error(`config file not found: ${i}`);t.isAbsolute(i)||(i=t.resolve(s,i))}else i=function(r,n){const o=!!O;function s(o){const s=[t.resolve(process.cwd(),`${J}.${o}`),t.resolve(process.cwd(),`.${J}.${o}`),t.resolve(r,`${J}.${o}`),t.resolve(r,`.${J}.${o}`)];n&&s.unshift(t.resolve(n,`${J}.${o}`),t.resolve(n,`.${J}.${o}`));for(const t of s)if(e.existsSync(t)&&e.lstatSync(t).isFile())return t}return J=s("js")??J,J=s("json")??J,J=s("yaml")??J,o&&(J=s("ts")??J),t.resolve(r,J)}(s,r);const a=t.extname(i);let c;switch(a){case".js":c=require(i);break;case".json":return require(i);case".yaml":return o.load(e.readFileSync(i,"utf-8"));case".ts":if(O){require(O),c=require(i);break}throw new Error("ts config file is not supported without ts register, please install esbuild-register or set JIEK_TS_REGISTER env for custom ts register");case".config":c={};break;default:throw new Error(`unsupported config file type: ${a}`)}if(!c)throw new Error("config file is empty");return c.default??c}n.program.command("build").option("-s, --silent","Don't display logs.").option("-e, --entries <ENTRIES>","Specify the entries of the package.json's 'exports' field.(support glob)").action((async({silent:r,entries:n})=>{x();const{build:o}=M();r=r??o?.silent??!1;const{wd:s,value:c={}}=await S()??{};if(0===Object.keys(c).length)throw new Error("no package found");const p=t.resolve(s,"node_modules");e.existsSync(p)||e.mkdirSync(p);const l=(...e)=>t.resolve(p,".jiek",...e);e.existsSync(l())||e.mkdirSync(l());const u=require.resolve("rollup").replace(/dist\/rollup.js$/,"dist/bin/rollup"),f=new i.MultiBar({clearOnComplete:!1,hideCursor:!0,format:"- {bar} | {status} | {input} | {message}"},i.Presets.shades_classic);let d=0;await Promise.all(Object.entries(c).map((async([t,o])=>{const i=o.name?.replace(/^@/g,"").replace(/\//g,"+"),c=l(`${i??"anonymous-"+d++}.rollup.config.js`);e.writeFileSync(c,(e=>`\nconst manifest = ${JSON.stringify(e,null,2)}\nmodule.exports = require('jiek/rollup').template(manifest)\n`.trimStart())(o));let p="";O&&(p=`node -r ${O} `);const m=`${p}${u} --silent -c ${c}`,g=a.execaCommand(m,{ipc:!0,cwd:t,env:{...process.env,JIEK_ROOT:s,JIEK_ENTRIES:n}}),y={};let w=10;g.on("message",(e=>{"debug"===e.type&&console.log(...Array.isArray(e.data)?e.data:[e.data])})),!r&&g.on("message",(e=>{if("init"===e.type){const{leafMap:t,targetsLength:r}=e.data,n=Array.from(t.entries()).flatMap((([e,t])=>t.map((([t,...r])=>({input:e,path:t,conditions:r})))));console.log(`Package '${o.name}' has ${r} targets to build`),n.forEach((({input:e})=>{w=Math.max(w,e.length)})),n.forEach((({input:e,path:t})=>{const r=`${e}:${t}`;y[r]||(y[r]=f.create(50,0,{input:e.padEnd(w),status:"waiting".padEnd(10)},{barsize:20,linewrap:!0}))}))}if("progress"===e.type){const{path:t,tags:r,input:n,event:o,message:s}=e.data,i=y[`${n}:${t}`];if(!i)return;i.update({start:0,resolve:20,end:50}[o??"start"]??0,{input:n.padEnd(w),status:o?.padEnd(10),message:`${r?.join(", ")}: ${s}`})}})),await new Promise(((e,t)=>{let r="";g.stderr?.on("data",(e=>{r+=e})),g.once("exit",(n=>0===n?e():t(new Error(`rollup build failed:\n${r}`))))}))}))).finally((()=>{f.stop()})),q()}));const N='{\n "name": "",\n "version": "0.0.1",\n "description": "",\n "license": "",\n "author": "",\n "files": ["dist"],\n "exports": {\n ".": "./src/index.ts"\n },\n "scripts": {\n },\n "homepage": "",\n "repository": "",\n "bugs": ""\n}'.trimStart(),P="# $name\n\n## Installation\n\n```bash\nnpm install $name\n# or\npnpm install $name\n# or\nyarn add $name\n```\n\n## Usage\n\n\n## License\n\n$license\n".trimStart();const D=new Map;function I(r,n){if(D.has(r))return D.get(r)[n];const o=t.resolve(r,"package.json"),s=JSON.parse(e.readFileSync(o,"utf-8"));return D.set(r,s),s[n]}n.program.command("init [name]").option("-t, --template <template>","the package.json template file path or file content").action((async()=>{const[,r]=n.program.args,o=process.cwd(),{init:s={}}=M()??{},{wd:i}=j(),a=t.basename(i),{named:f,template:d,bug:m={},readme:g=P,readmeTemplate:y}=s,w={template:"bug_report.yml",labels:["bug"],...m};let h=g;if(y){const r=t.resolve(i,y);h=e.readFileSync(r,"utf-8")}const b=function(r,n){let o=n??N,s=!1;try{n&&JSON.parse(n)}catch(e){s=!0}if(s){const s=t.resolve(r,n);o=e.readFileSync(s,"utf-8")}return o}(i,d),{indent:k=" "}=c(b),v={tabSize:k.length,insertSpaces:!0},S=["license","author"];let $=b;for(const e of S)$=l.applyEdits($,l.modify($,[e],I(i,e),{formattingOptions:v}));let[E,O]=await async function(e,r,{wd:n,cwd:o,workspaceName:s}){const i=o.replace(`${n}/`,"");let a=t.basename(o);if("function"==typeof e)return e(r,{full:n,relative:o});let c,l,f=!1;if("object"==typeof e)if(o===n){const{rule:t}=await p.prompt({type:"list",name:"rule",message:"choose a rule",default:"default",choices:["default"].concat(Object.keys(e))});"default"!==t&&(c=t,l=e[t])}else for(const[t,r]of Object.entries(e)){if(u.isMatch(i,t)){c=t,l=r;break}if(u.isMatch(`${i}/jiek_ignore_dont_use_same_file_name`,t)){f=!0,c=t,l=r;break}}if(l||(c="packages/*",l=`@${s}/$basename`),!l)throw new Error("no matched rule");if(!r&&f&&(a=await p.prompt({type:"input",name:"name",message:`the matched rule is \`${String(l)}\`, please input the basename\n`}).then((({name:e})=>e))),"function"==typeof l)return l(r,{full:n,relative:o,basename:a});if("string"==typeof l){const e=r??a;return[l.replace(/\$basename/g,e),c?.replace(/\/\*$/g,`/${e}`)]}throw new Error("no matched rule")}(f,r,{wd:i,cwd:o,workspaceName:a});if(!O){const{dir:e}=await p.prompt({type:"input",name:"dir",message:"package directory",default:r});O=e}if(!E){const{name:e}=await p.prompt({type:"input",name:"name",message:"package name",default:r});E=e}$=l.applyEdits($,l.modify($,["name"],E,{formattingOptions:v}));let q=I(i,"repository");"string"==typeof q&&(q={type:"git",url:q,directory:O}),$=l.applyEdits($,l.modify($,["repository"],q,{formattingOptions:v}));const x=`${q?.url}/blob/master/${O}/README.md`;$=l.applyEdits($,l.modify($,["homepage"],x,{formattingOptions:v}));let F=w.labels;"function"==typeof F&&(F=F({name:E,dir:O})),F.push(`scope:${E}`);const _=`${q?.url}/issues/new?template=${w.template}&labels=${F.join(",")}`;function J(e){if(!O)throw new Error("pkgDir is not defined");return t.resolve(O,e)}$=l.applyEdits($,l.modify($,["bugs"],_,{formattingOptions:v})),e.existsSync(O)||e.mkdirSync(O);const D=J("package.json");if(e.existsSync(D))throw new Error("package.json already exists");e.writeFileSync(D,$),console.log($,"written to",D);const A=I(i,"license"),R=J("README.md");"function"==typeof h&&(h=h({dir:O,packageJson:JSON.parse($)}));const T=h.replace(/\$name/g,E).replace(/\$license/g,A);e.writeFileSync(R,T)}));const A=(e,t)=>new Set([...e].filter((e=>t.has(e))));function R({entrypoints:e,pkgIsModule:r,entries:n,config:o,dir:s,noFilter:i}){const{build:a={}}=o??{},{crossModuleConvertor:c=!0}=a,p=`./${l=((...e)=>t.resolve(s??process.cwd(),...e))(("object"==typeof a?.output?.dir?a.output.dir.js:a?.output?.dir)??"dist"),t.relative(s??process.cwd(),l)}`;var l;const[,f]=m.resolveEntrypoints(e);n&&Object.entries(f).forEach((([e])=>{n.some((t=>u.isMatch(e,t,{matchBase:!0})))||delete f[e]}));const d=i?f:m.filterLeafs(f,{skipValue:[/(^|\/)\.jk-noentry/,...m.DEFAULT_SKIP_VALUES]}),g=c?{import:e=>!r&&0===A(new Set(e.conditionals),new Set(["import","module"])).size&&e.dist.replace(/\.js$/,".mjs"),require:e=>!(!r||0!==A(new Set(e.conditionals),new Set(["require","node"])).size)&&e.dist.replace(/\.js$/,".cjs")}:{};return[d,m.entrypoints2Exports(d,{outdir:p,withConditional:{...g}})]}n.program.command("publish").aliases(["pub","p"]).option("-b, --bumper <bumper>","bump version","patch").option("-p, --preview","preview publish").action((async({preview:r,bumper:n,...o})=>{x();const{value:s={}}=await S()??{},i=Object.entries(s);if(0===i.length)throw new Error("no packages selected");const a=i.map((([e,t])=>{const{type:r,exports:n={}}=t,o="module"===r,s={...t},[i,a]=R({entrypoints:n,pkgIsModule:o,config:M(e),dir:e,noFilter:!0});return s.exports={...i,...a},[e,s]})),p=Object.entries(o).reduce(((e,[t,r])=>(r&&e.push(`--${t}`,r),e)),[]);for(const[o,s]of a){const i=e.readFileSync(t.join(o,"package.json"),"utf-8"),a=JSON.parse(i)??"0.0.0",u=d.bump(a.version,n),{indent:f=" "}=c(i),m={tabSize:f.length,insertSpaces:!0};let g=i;g=l.applyEdits(g,l.modify(g,["version"],u,{formattingOptions:m}));for(const[e,t]of Object.entries(s))if(JSON.stringify(t)!==JSON.stringify(a[e]))if("exports"!==e)g=l.applyEdits(g,l.modify(g,["publishConfig",e],t,{formattingOptions:m}));else{const e=t;for(const[t,r]of Object.entries(e))g=l.applyEdits(g,l.modify(g,["publishConfig","exports",t],r,{formattingOptions:m}));const r=e?.["."],n={};if(r){switch(typeof r){case"string":n["module"===s?.type?"module":"main"]=r;break;case"object":{const e=r;n.main=e.require??e.default,n.module=e.import??e.module??e.default;break}}for(const[e,t]of Object.entries(n))void 0!==t&&(g=l.applyEdits(g,l.modify(g,["publishConfig",e],t,{formattingOptions:m})))}}try{if(e.renameSync(t.join(o,"package.json"),t.join(o,"package.json.bak")),e.writeFileSync(t.join(o,"package.json"),g),console.log(g),r){console.warn("preview mode");continue}y.execSync(["pnpm","publish","--access","public","--no-git-checks",...p].join(" "),{cwd:o,stdio:"inherit"});const n=l.applyEdits(i,l.modify(i,["version"],u,{}));e.writeFileSync(t.join(o,"package.json.bak"),n)}finally{e.unlinkSync(t.join(o,"package.json")),e.renameSync(t.join(o,"package.json.bak"),t.join(o,"package.json"))}}q()})),n.program.parse(process.argv);
|
1
|
+
import e from"node:fs";import t,{resolve as n,relative as o}from"node:path";import{filterPackagesFromDir as r}from"@pnpm/filter-workspace-packages";import{program as s}from"commander";import{load as i}from"js-yaml";import{isWorkspaceDir as a,getWorkspaceDir as c}from"@jiek/utils/getWorkspaceDir";import{MultiBar as p,Presets as l}from"cli-progress";import{execaCommand as f}from"execa";import u from"detect-indent";import m from"inquirer";import{applyEdits as d,modify as g}from"jsonc-parser";import{isMatch as w}from"micromatch";import*as y from"node:child_process";import{bump as h}from"@jiek/utils/bumper";import{resolveEntrypoints as k,filterLeafs as b,DEFAULT_SKIP_VALUES as j,entrypoints2Exports as S}from"@jiek/pkger/entrypoints";let v,$;function E(){if(v)return v;const e=s.getOptionValue("root");return v=e?t.isAbsolute(e)?e:t.resolve(process.cwd(),e):void 0,v}let O=!1;function x(){if($)return{wd:$,notWorkspace:O};const e=E();if(void 0!==e){const t=a(e,F);return O=!t,$=e,{wd:$,notWorkspace:O}}try{$=c(F)}catch(t){if(!("message"in t)||"workspace root not found"!==t.message)throw t;$=e,O=!0}return{wd:$,notWorkspace:O}}let F="";try{require.resolve("@pnpm/filter-workspace-packages"),F="pnpm"}catch{}async function _(){let n=s.getOptionValue("filter");const o=E(),{wd:a,notWorkspace:c}=x();if(!c&&"pnpm"===F){const s=t.resolve(a,"pnpm-workspace.yaml"),c=e.readFileSync(s,"utf-8"),p=i(c);if(o===a&&!n)throw new Error("root path is workspace root, please provide a filter");if(o!==a&&!n){if(!e.existsSync(t.resolve(o,"package.json")))throw new Error("root path is not workspace root, please provide a filter");const r=JSON.parse(e.readFileSync(t.resolve(o,"package.json"),"utf-8"));if(!r.name)throw new Error("root path is not workspace root, please provide a filter");n=r.name}const{selectedProjectsGraph:l}=await r(a,[{filter:n??"",followProdDepsOnly:!0}],{prefix:o,workspaceDir:a,patterns:p.packages});return{wd:a,root:o,value:Object.entries(l).reduce(((e,[t,n])=>(e[t]=n.package.manifest,e)),{})}}return{wd:a,root:o,value:{[a]:JSON.parse(e.readFileSync(t.resolve(a,"package.json"),"utf-8"))}}}""!==F&&s.option("-f, --filter <filter>","filter packages");var J=require("../package.json");let q,N;function I(){q()}function M(){new Promise((e=>q=e))}function R(e){try{return require.resolve(e),!0}catch(e){return!1}}s.version(J.version).description(J.description).option("--root <root>","root path").option("-c, --config-path <configPath>","config path");const P=[process.env.JIEK_TS_REGISTER,"esbuild-register","@swc-node/register","ts-node/register"].filter(Boolean);for(const e of P)if(R(e)){N=e;break}let T="jiek.config";function A(n){const{wd:o}=x();let r=s.getOptionValue("configPath");if(r){if(!e.existsSync(r))throw new Error(`config file not found: ${r}`);t.isAbsolute(r)||(r=t.resolve(o,r))}else r=function(n,o){const r=!!N;function s(r){const s=[t.resolve(process.cwd(),`${T}.${r}`),t.resolve(process.cwd(),`.${T}.${r}`),t.resolve(n,`${T}.${r}`),t.resolve(n,`.${T}.${r}`)];o&&s.unshift(t.resolve(o,`${T}.${r}`),t.resolve(o,`.${T}.${r}`));for(const t of s)if(e.existsSync(t)&&e.lstatSync(t).isFile())return t}return T=s("js")??T,T=s("json")??T,T=s("yaml")??T,r&&(T=s("ts")??T),t.resolve(n,T)}(o,n);const a=t.extname(r);let c;switch(a){case".js":c=require(r);break;case".json":return require(r);case".yaml":return i(e.readFileSync(r,"utf-8"));case".ts":if(N){require(N),c=require(r);break}throw new Error("ts config file is not supported without ts register, please install esbuild-register or set JIEK_TS_REGISTER env for custom ts register");case".config":c={};break;default:throw new Error(`unsupported config file type: ${a}`)}if(!c)throw new Error("config file is empty");return c.default??c}s.command("build").option("-s, --silent","Don't display logs.").option("-e, --entries <ENTRIES>","Specify the entries of the package.json's 'exports' field.(support glob)").action((async({silent:n,entries:o})=>{M();const{build:r}=A();n=n??r?.silent??!1;const{wd:s,value:i={}}=await _()??{};if(0===Object.keys(i).length)throw new Error("no package found");const a=t.resolve(s,"node_modules");e.existsSync(a)||e.mkdirSync(a);const c=(...e)=>t.resolve(a,".jiek",...e);e.existsSync(c())||e.mkdirSync(c());const u=require.resolve("rollup").replace(/dist\/rollup.js$/,"dist/bin/rollup"),m=new p({clearOnComplete:!1,hideCursor:!0,format:"- {bar} | {status} | {input} | {message}"},l.shades_classic);let d=0;await Promise.all(Object.entries(i).map((async([t,r])=>{const i=r.name?.replace(/^@/g,"").replace(/\//g,"+"),a=c(`${i??"anonymous-"+d++}.rollup.config.js`);e.writeFileSync(a,(e=>`\nconst manifest = ${JSON.stringify(e,null,2)}\nmodule.exports = require('jiek/rollup').template(manifest)\n`.trimStart())(r));let p="";N&&(p=`node -r ${N} `);const l=f(`${p}${u} --silent -c ${a}`,{ipc:!0,cwd:t,env:{...process.env,JIEK_ROOT:s,JIEK_ENTRIES:o}}),g={};let w=10;l.on("message",(e=>{"debug"===e.type&&console.log(...Array.isArray(e.data)?e.data:[e.data])})),!n&&l.on("message",(e=>{if("init"===e.type){const{leafMap:t,targetsLength:n}=e.data,o=Array.from(t.entries()).flatMap((([e,t])=>t.map((([t,...n])=>({input:e,path:t,conditions:n})))));console.log(`Package '${r.name}' has ${n} targets to build`),o.forEach((({input:e})=>{w=Math.max(w,e.length)})),o.forEach((({input:e,path:t})=>{const n=`${e}:${t}`;g[n]||(g[n]=m.create(50,0,{input:e.padEnd(w),status:"waiting".padEnd(10)},{barsize:20,linewrap:!0}))}))}if("progress"===e.type){const{path:t,tags:n,input:o,event:r,message:s}=e.data,i=g[`${o}:${t}`];if(!i)return;i.update({start:0,resolve:20,end:50}[r??"start"]??0,{input:o.padEnd(w),status:r?.padEnd(10),message:`${n?.join(", ")}: ${s}`})}})),await new Promise(((e,t)=>{let n="";l.stderr?.on("data",(e=>{n+=e})),l.once("exit",(o=>0===o?e():t(new Error(`rollup build failed:\n${n}`))))}))}))).finally((()=>{m.stop()})),I()}));const C='{\n "name": "",\n "version": "0.0.1",\n "description": "",\n "license": "",\n "author": "",\n "files": ["dist"],\n "exports": {\n ".": "./src/index.ts"\n },\n "scripts": {\n },\n "homepage": "",\n "repository": "",\n "bugs": ""\n}'.trimStart(),D="# $name\n\n## Installation\n\n```bash\nnpm install $name\n# or\npnpm install $name\n# or\nyarn add $name\n```\n\n## Usage\n\n\n## License\n\n$license\n".trimStart();const z=new Map;function W(n,o){if(z.has(n))return z.get(n)[o];const r=t.resolve(n,"package.json"),s=JSON.parse(e.readFileSync(r,"utf-8"));return z.set(n,s),s[o]}s.command("init [name]").option("-t, --template <template>","the package.json template file path or file content").action((async()=>{const[,n]=s.args,o=process.cwd(),{init:r={}}=A()??{},{wd:i}=x(),a=t.basename(i),{named:c,template:p,bug:l={},readme:f=D,readmeTemplate:y}=r,h={template:"bug_report.yml",labels:["bug"],...l};let k=f;if(y){const n=t.resolve(i,y);k=e.readFileSync(n,"utf-8")}const b=function(n,o){let r=o??C,s=!1;try{o&&JSON.parse(o)}catch(e){s=!0}if(s){const s=t.resolve(n,o);r=e.readFileSync(s,"utf-8")}return r}(i,p),{indent:j=" "}=u(b),S={tabSize:j.length,insertSpaces:!0},v=["license","author"];let $=b;for(const e of v)$=d($,g($,[e],W(i,e),{formattingOptions:S}));let[E,O]=await async function(e,n,{wd:o,cwd:r,workspaceName:s}){const i=r.replace(`${o}/`,"");let a=t.basename(r);if("function"==typeof e)return e(n,{full:o,relative:r});let c,p,l=!1;if("object"==typeof e)if(r===o){const{rule:t}=await m.prompt({type:"list",name:"rule",message:"choose a rule",default:"default",choices:["default"].concat(Object.keys(e))});"default"!==t&&(c=t,p=e[t])}else for(const[t,n]of Object.entries(e)){if(w(i,t)){c=t,p=n;break}if(w(`${i}/jiek_ignore_dont_use_same_file_name`,t)){l=!0,c=t,p=n;break}}if(p||(c="packages/*",p=`@${s}/$basename`),!p)throw new Error("no matched rule");if(!n&&l&&(a=await m.prompt({type:"input",name:"name",message:`the matched rule is \`${String(p)}\`, please input the basename\n`}).then((({name:e})=>e))),"function"==typeof p)return p(n,{full:o,relative:r,basename:a});if("string"==typeof p){const e=n??a;return[p.replace(/\$basename/g,e),c?.replace(/\/\*$/g,`/${e}`)]}throw new Error("no matched rule")}(c,n,{wd:i,cwd:o,workspaceName:a});if(!O){const{dir:e}=await m.prompt({type:"input",name:"dir",message:"package directory",default:n});O=e}if(!E){const{name:e}=await m.prompt({type:"input",name:"name",message:"package name",default:n});E=e}$=d($,g($,["name"],E,{formattingOptions:S}));let F=W(i,"repository");"string"==typeof F&&(F={type:"git",url:F,directory:O}),$=d($,g($,["repository"],F,{formattingOptions:S}));$=d($,g($,["homepage"],`${F?.url}/blob/master/${O}/README.md`,{formattingOptions:S}));let _=h.labels;"function"==typeof _&&(_=_({name:E,dir:O})),_.push(`scope:${E}`);const J=`${F?.url}/issues/new?template=${h.template}&labels=${_.join(",")}`;function q(e){if(!O)throw new Error("pkgDir is not defined");return t.resolve(O,e)}$=d($,g($,["bugs"],J,{formattingOptions:S})),e.existsSync(O)||e.mkdirSync(O);const N=q("package.json");if(e.existsSync(N))throw new Error("package.json already exists");e.writeFileSync(N,$),console.log($,"written to",N);const I=W(i,"license"),M=q("README.md");"function"==typeof k&&(k=k({dir:O,packageJson:JSON.parse($)}));const R=k.replace(/\$name/g,E).replace(/\$license/g,I);e.writeFileSync(M,R)}));const K=(e,t)=>new Set([...e].filter((e=>t.has(e))));s.command("publish").aliases(["pub","p"]).option("-b, --bumper <bumper>","bump version","patch").option("-p, --preview","preview publish").action((async({preview:r,bumper:s,...i})=>{M();const{value:a={}}=await _()??{},c=Object.entries(a);if(0===c.length)throw new Error("no packages selected");const p=c.map((([e,t])=>{const{type:r,exports:s={}}=t,i="module"===r,a={...t},[c,p]=function({entrypoints:e,pkgIsModule:t,entries:r,config:s,dir:i,noFilter:a,withSource:c,withSuffix:p}){const{build:l={}}=s??{},{crossModuleConvertor:f=!0}=l,u=`./${(e=>o(i??process.cwd(),e))(((...e)=>n(i??process.cwd(),...e))(("object"==typeof l?.output?.dir?l.output.dir.js:l?.output?.dir)??"dist"))}`,[,m]=k(e);r&&Object.entries(m).forEach((([e])=>{r.some((t=>w(e,t,{matchBase:!0})))||delete m[e]}));const d=a?m:b(m,{skipValue:[/(^|\/)\.jk-noentry/,...j]});return[d,S(d,{outdir:u,withSource:c,withSuffix:p,withConditional:{...f?{import:e=>!t&&0===K(new Set(e.conditionals),new Set(["import","module"])).size&&e.dist.replace(/\.js$/,".mjs"),require:e=>!(!t||0!==K(new Set(e.conditionals),new Set(["require","node"])).size)&&e.dist.replace(/\.js$/,".cjs")}:{}}})]}({entrypoints:s,pkgIsModule:i,config:A(e),dir:e,noFilter:!0,withSource:!0,withSuffix:!0});return a.exports={...c,...p},[e,a]})),l=Object.entries(i).reduce(((e,[t,n])=>(n&&e.push(`--${t}`,n),e)),[]);for(const[n,o]of p){const i=e.readFileSync(t.join(n,"package.json"),"utf-8"),a=JSON.parse(i)??"0.0.0",c=h(a.version,s),{indent:p=" "}=u(i),f={tabSize:p.length,insertSpaces:!0};let m=i;m=d(m,g(m,["version"],c,{formattingOptions:f}));for(const[e,t]of Object.entries(o))if(JSON.stringify(t)!==JSON.stringify(a[e]))if("exports"!==e)m=d(m,g(m,["publishConfig",e],t,{formattingOptions:f}));else{const e=t;for(const[t,n]of Object.entries(e))m=d(m,g(m,["publishConfig","exports",t],n,{formattingOptions:f}));const n=e?.["."],r={};if(n){switch(typeof n){case"string":r["module"===o?.type?"module":"main"]=n;break;case"object":{const e=n;r.main=e.require??e.default,r.module=e.import??e.module??e.default;break}}for(const[e,t]of Object.entries(r))void 0!==t&&(m=d(m,g(m,["publishConfig",e],t,{formattingOptions:f})))}}try{if(e.renameSync(t.join(n,"package.json"),t.join(n,"package.json.bak")),e.writeFileSync(t.join(n,"package.json"),m),console.log(m),r){console.warn("preview mode");continue}y.execSync(["pnpm","publish","--access","public","--no-git-checks",...l].join(" "),{cwd:n,stdio:"inherit"});const o=d(i,g(i,["version"],c,{}));e.writeFileSync(t.join(n,"package.json.bak"),o)}finally{e.unlinkSync(t.join(n,"package.json")),e.renameSync(t.join(n,"package.json.bak"),t.join(n,"package.json"))}}I()})),s.parse(process.argv);
|
package/dist/index.cjs
ADDED
package/dist/index.js
CHANGED
@@ -0,0 +1 @@
|
|
1
|
+
"use strict";exports.defineConfig=e=>e;
|
package/dist/index.min.js
CHANGED
@@ -1 +1 @@
|
|
1
|
-
|
1
|
+
const o=o=>o;export{o as defineConfig};
|