jiek 2.0.1 → 2.0.2-alpha.2

Sign up to get free protection for your applications and to get access to all the features.
package/dist/cli.js CHANGED
@@ -1,20 +1,121 @@
1
+ import * as childProcess from 'node:child_process';
1
2
  import fs from 'node:fs';
2
3
  import path, { isAbsolute, relative, resolve as resolve$1 } from 'node:path';
4
+ import { bump, TAGS } from '@jiek/utils/bumper';
3
5
  import { program } from 'commander';
4
6
  import detectIndent from 'detect-indent';
5
- import inquirer from 'inquirer';
6
7
  import { applyEdits, modify } from 'jsonc-parser';
7
- import require$$0 from 'util';
8
- import require$$0$1 from 'path';
9
- import { isWorkspaceDir, getWorkspaceDir } from '@jiek/utils/getWorkspaceDir';
10
8
  import { createRequire } from 'node:module';
11
9
  import { filterPackagesFromDir } from '@pnpm/filter-workspace-packages';
12
10
  import { load } from 'js-yaml';
13
- import * as childProcess from 'node:child_process';
14
- import { bump, TAGS } from '@jiek/utils/bumper';
11
+ import { isWorkspaceDir, getWorkspaceDir } from '@jiek/utils/getWorkspaceDir';
15
12
  import { resolveEntrypoints, filterLeafs, DEFAULT_SKIP_VALUES, entrypoints2Exports } from '@jiek/pkger/entrypoints';
13
+ import require$$0 from 'util';
14
+ import require$$0$1 from 'path';
16
15
  import 'jiek/cli-only-build';
17
16
 
17
+ let resolve;
18
+ function actionDone() {
19
+ resolve();
20
+ }
21
+ function actionRestore() {
22
+ new Promise((r) => resolve = r);
23
+ }
24
+
25
+ let root;
26
+ function getRoot() {
27
+ if (root)
28
+ return root;
29
+ const rootOption = program.getOptionValue("root");
30
+ root = rootOption ? path.isAbsolute(rootOption) ? rootOption : path.resolve(process.cwd(), rootOption) : void 0;
31
+ return root;
32
+ }
33
+
34
+ let wd;
35
+ let notWorkspace = false;
36
+ function getWD() {
37
+ if (wd)
38
+ return { wd, notWorkspace };
39
+ const root = getRoot();
40
+ if (root !== void 0) {
41
+ const isWorkspace = isWorkspaceDir(root, type);
42
+ notWorkspace = !isWorkspace;
43
+ wd = root;
44
+ return { wd, notWorkspace };
45
+ }
46
+ try {
47
+ wd = getWorkspaceDir(type);
48
+ } catch (e) {
49
+ if ("message" in e && e.message === "workspace root not found") {
50
+ wd = root;
51
+ notWorkspace = true;
52
+ } else {
53
+ throw e;
54
+ }
55
+ }
56
+ return { wd, notWorkspace };
57
+ }
58
+
59
+ let type = "";
60
+ try {
61
+ const require = createRequire(import.meta.url);
62
+ require.resolve("@pnpm/filter-workspace-packages");
63
+ type = "pnpm";
64
+ } catch {
65
+ }
66
+ async function getSelectedProjectsGraph(filter = program.getOptionValue("filter")) {
67
+ let root = getRoot();
68
+ const { wd, notWorkspace } = getWD();
69
+ if (notWorkspace) {
70
+ return {
71
+ wd,
72
+ root,
73
+ value: {
74
+ [wd]: JSON.parse(fs.readFileSync(path.resolve(wd, "package.json"), "utf-8"))
75
+ }
76
+ };
77
+ }
78
+ if (type === "pnpm") {
79
+ const pnpmWorkspaceFilePath = path.resolve(wd, "pnpm-workspace.yaml");
80
+ const pnpmWorkspaceFileContent = fs.readFileSync(pnpmWorkspaceFilePath, "utf-8");
81
+ const pnpmWorkspace = load(pnpmWorkspaceFileContent);
82
+ if (root === wd && !filter) {
83
+ throw new Error("root path is workspace root, please provide a filter");
84
+ }
85
+ if (root === void 0) {
86
+ root = process.cwd();
87
+ }
88
+ if (root !== wd && !filter) {
89
+ const packageJSONIsExist = fs.existsSync(path.resolve(root, "package.json"));
90
+ if (!packageJSONIsExist) {
91
+ throw new Error("root path is not workspace root, please provide a filter");
92
+ }
93
+ const packageJSON = JSON.parse(fs.readFileSync(path.resolve(root, "package.json"), "utf-8"));
94
+ if (!packageJSON.name) {
95
+ throw new Error("root path is not workspace root, please provide a filter");
96
+ }
97
+ filter = packageJSON.name;
98
+ }
99
+ const { selectedProjectsGraph } = await filterPackagesFromDir(wd, [{
100
+ filter: filter ?? "",
101
+ followProdDepsOnly: true
102
+ }], {
103
+ prefix: root,
104
+ workspaceDir: wd,
105
+ patterns: pnpmWorkspace.packages
106
+ });
107
+ return {
108
+ wd,
109
+ root,
110
+ value: Object.entries(selectedProjectsGraph).reduce((acc, [key, value]) => {
111
+ acc[key] = value.package.manifest;
112
+ return acc;
113
+ }, {})
114
+ };
115
+ }
116
+ throw new Error(`not supported package manager ${type}`);
117
+ }
118
+
18
119
  var utils$1 = {};
19
120
 
20
121
  var hasRequiredUtils$1;
@@ -4121,98 +4222,94 @@ function requireMicromatch () {
4121
4222
 
4122
4223
  var micromatchExports = requireMicromatch();
4123
4224
 
4124
- let root;
4125
- function getRoot() {
4126
- if (root)
4127
- return root;
4128
- const rootOption = program.getOptionValue("root");
4129
- root = rootOption ? path.isAbsolute(rootOption) ? rootOption : path.resolve(process.cwd(), rootOption) : void 0;
4130
- return root;
4131
- }
4132
-
4133
- let type = "";
4134
- try {
4135
- const require = createRequire(import.meta.url);
4136
- require.resolve("@pnpm/filter-workspace-packages");
4137
- type = "pnpm";
4138
- } catch {
4139
- }
4140
- async function getSelectedProjectsGraph(filter = program.getOptionValue("filter")) {
4141
- let root = getRoot();
4142
- const { wd, notWorkspace } = getWD();
4143
- if (notWorkspace) {
4144
- return {
4145
- wd,
4146
- root,
4147
- value: {
4148
- [wd]: JSON.parse(fs.readFileSync(path.resolve(wd, "package.json"), "utf-8"))
4149
- }
4150
- };
4225
+ const intersection = (a, b) => new Set([...a].filter((i) => b.has(i)));
4226
+ const {
4227
+ JIEK_OUT_DIR
4228
+ } = process.env;
4229
+ const OUTDIR = JIEK_OUT_DIR ?? "dist";
4230
+ function getOutDirs({
4231
+ cwd = process.cwd(),
4232
+ defaultOutdir = OUTDIR,
4233
+ config,
4234
+ pkgName
4235
+ }) {
4236
+ const { build = {} } = config ?? {};
4237
+ const outdir = build?.output?.dir;
4238
+ function resolveOutdir(type) {
4239
+ const dir = (typeof outdir === "object" ? outdir[type] ?? outdir[{
4240
+ js: "dts",
4241
+ dts: "js"
4242
+ }[type]] : outdir) ?? defaultOutdir;
4243
+ return (isAbsolute(dir) ? dir : `./${relative(cwd, resolve$1(cwd, dir))}`).replace("{{PKG_NAME}}", pkgName);
4151
4244
  }
4152
- if (type === "pnpm") {
4153
- const pnpmWorkspaceFilePath = path.resolve(wd, "pnpm-workspace.yaml");
4154
- const pnpmWorkspaceFileContent = fs.readFileSync(pnpmWorkspaceFilePath, "utf-8");
4155
- const pnpmWorkspace = load(pnpmWorkspaceFileContent);
4156
- if (root === wd && !filter) {
4157
- throw new Error("root path is workspace root, please provide a filter");
4158
- }
4159
- if (root === void 0) {
4160
- root = process.cwd();
4161
- }
4162
- if (root !== wd && !filter) {
4163
- const packageJSONIsExist = fs.existsSync(path.resolve(root, "package.json"));
4164
- if (!packageJSONIsExist) {
4165
- throw new Error("root path is not workspace root, please provide a filter");
4166
- }
4167
- const packageJSON = JSON.parse(fs.readFileSync(path.resolve(root, "package.json"), "utf-8"));
4168
- if (!packageJSON.name) {
4169
- throw new Error("root path is not workspace root, please provide a filter");
4245
+ return {
4246
+ js: resolveOutdir("js"),
4247
+ dts: resolveOutdir("dts")
4248
+ };
4249
+ }
4250
+ function getExports({
4251
+ entrypoints,
4252
+ pkgName,
4253
+ pkgIsModule,
4254
+ entries,
4255
+ config,
4256
+ dir,
4257
+ defaultOutdir = OUTDIR,
4258
+ // FIXME dts support
4259
+ outdir = getOutDirs({ pkgName, defaultOutdir, config, cwd: dir }).js,
4260
+ noFilter,
4261
+ isPublish
4262
+ }) {
4263
+ const {
4264
+ build = {},
4265
+ publish: {
4266
+ withSuffix = false,
4267
+ withSource = true
4268
+ } = {}
4269
+ } = config ?? {};
4270
+ const {
4271
+ crossModuleConvertor = true
4272
+ } = build;
4273
+ const [, resolvedEntrypoints] = resolveEntrypoints(entrypoints);
4274
+ if (entries) {
4275
+ Object.entries(resolvedEntrypoints).forEach(([key]) => {
4276
+ if (!entries.some((e) => micromatchExports.isMatch(key, e, { matchBase: true }))) {
4277
+ delete resolvedEntrypoints[key];
4170
4278
  }
4171
- filter = packageJSON.name;
4172
- }
4173
- const { selectedProjectsGraph } = await filterPackagesFromDir(wd, [{
4174
- filter: filter ?? "",
4175
- followProdDepsOnly: true
4176
- }], {
4177
- prefix: root,
4178
- workspaceDir: wd,
4179
- patterns: pnpmWorkspace.packages
4180
4279
  });
4181
- return {
4182
- wd,
4183
- root,
4184
- value: Object.entries(selectedProjectsGraph).reduce((acc, [key, value]) => {
4185
- acc[key] = value.package.manifest;
4186
- return acc;
4187
- }, {})
4188
- };
4189
4280
  }
4190
- throw new Error(`not supported package manager ${type}`);
4191
- }
4192
-
4193
- let wd;
4194
- let notWorkspace = false;
4195
- function getWD() {
4196
- if (wd)
4197
- return { wd, notWorkspace };
4198
- const root = getRoot();
4199
- if (root !== void 0) {
4200
- const isWorkspace = isWorkspaceDir(root, type);
4201
- notWorkspace = !isWorkspace;
4202
- wd = root;
4203
- return { wd, notWorkspace };
4204
- }
4205
- try {
4206
- wd = getWorkspaceDir(type);
4207
- } catch (e) {
4208
- if ("message" in e && e.message === "workspace root not found") {
4209
- wd = root;
4210
- notWorkspace = true;
4211
- } else {
4212
- throw e;
4281
+ const filteredResolvedEntrypoints = noFilter ? resolvedEntrypoints : filterLeafs(
4282
+ resolvedEntrypoints,
4283
+ {
4284
+ skipValue: [
4285
+ // ignore values that filename starts with `.jk-noentry`
4286
+ /(^|\/)\.jk-noentry/,
4287
+ ...DEFAULT_SKIP_VALUES
4288
+ ]
4213
4289
  }
4214
- }
4215
- return { wd, notWorkspace };
4290
+ );
4291
+ const crossModuleWithConditional = crossModuleConvertor ? {
4292
+ import: (opts) => !pkgIsModule && intersection(
4293
+ new Set(opts.conditionals),
4294
+ /* @__PURE__ */ new Set(["import", "module"])
4295
+ ).size === 0 ? opts.dist.replace(/\.js$/, ".mjs") : false,
4296
+ require: (opts) => pkgIsModule && intersection(
4297
+ new Set(opts.conditionals),
4298
+ /* @__PURE__ */ new Set(["require", "node"])
4299
+ ).size === 0 ? opts.dist.replace(/\.js$/, ".cjs") : false
4300
+ } : {};
4301
+ return [
4302
+ filteredResolvedEntrypoints,
4303
+ entrypoints2Exports(filteredResolvedEntrypoints, {
4304
+ outdir,
4305
+ withSuffix: isPublish ? withSuffix : void 0,
4306
+ withSource: isPublish ? withSource : void 0,
4307
+ withConditional: {
4308
+ ...crossModuleWithConditional
4309
+ }
4310
+ }),
4311
+ outdir
4312
+ ];
4216
4313
  }
4217
4314
 
4218
4315
  const require$1 = createRequire(import.meta.url);
@@ -4321,387 +4418,30 @@ function loadConfig(dirOrOptions) {
4321
4418
  return module.default ?? module;
4322
4419
  }
4323
4420
 
4324
- const PACKAGE_JSON_TEMPLATE = `{
4325
- "name": "",
4326
- "version": "0.0.1",
4327
- "description": "",
4328
- "license": "",
4329
- "author": "",
4330
- "files": ["dist"],
4331
- "exports": {
4332
- ".": "./src/index.ts"
4333
- },
4334
- "scripts": {
4335
- },
4336
- "homepage": "",
4337
- "repository": "",
4338
- "bugs": ""
4339
- }`.trimStart();
4340
- const README_TEMPLATE = `# $name
4341
-
4342
- ## Installation
4343
-
4344
- \`\`\`bash
4345
- npm install $name
4346
- # or
4347
- pnpm install $name
4348
- # or
4349
- yarn add $name
4350
- \`\`\`
4351
-
4352
- ## Usage
4353
-
4354
-
4355
- ## License
4356
-
4357
- $license
4358
- `.trimStart();
4359
- function getTemplateStr(wd, template) {
4360
- let templateString = template ?? PACKAGE_JSON_TEMPLATE;
4361
- let isTemplateFile = false;
4362
- try {
4363
- if (template)
4364
- JSON.parse(template);
4365
- } catch (e) {
4366
- isTemplateFile = true;
4367
- }
4368
- if (isTemplateFile) {
4369
- const templatePath = path.resolve(wd, template);
4370
- templateString = fs.readFileSync(templatePath, "utf-8");
4371
- }
4372
- return templateString;
4373
- }
4374
- const wdCache = /* @__PURE__ */ new Map();
4375
- function getWDPackageJSONFiled(wd, field) {
4376
- if (wdCache.has(wd)) {
4377
- return wdCache.get(wd)[field];
4378
- }
4379
- const packageJSONPath = path.resolve(wd, "package.json");
4380
- const packageJSON = JSON.parse(fs.readFileSync(packageJSONPath, "utf-8"));
4381
- wdCache.set(wd, packageJSON);
4382
- return packageJSON[field];
4383
- }
4384
- async function getName(named, name, {
4385
- wd,
4386
- cwd,
4387
- workspaceName
4388
- }) {
4389
- const relativePath = cwd.replace(`${wd}/`, "");
4390
- let basename = path.basename(cwd);
4391
- if (typeof named === "function") {
4392
- return named(name, {
4393
- full: wd,
4394
- relative: cwd
4395
- });
4396
- }
4397
- let isParentMatched = false;
4398
- let matchedKey;
4399
- let matchedRule;
4400
- if (typeof named === "object") {
4401
- const isWD = cwd === wd;
4402
- if (isWD) {
4403
- const { rule } = await inquirer.prompt({
4404
- type: "list",
4405
- name: "rule",
4406
- message: "choose a rule",
4407
- default: "default",
4408
- choices: ["default"].concat(Object.keys(named))
4409
- });
4410
- if (rule !== "default") {
4411
- matchedKey = rule;
4412
- matchedRule = named[rule];
4413
- }
4414
- } else {
4415
- for (const [key, value] of Object.entries(named)) {
4416
- if (micromatchExports.isMatch(relativePath, key)) {
4417
- matchedKey = key;
4418
- matchedRule = value;
4419
- break;
4420
- }
4421
- if (micromatchExports.isMatch(`${relativePath}/jiek_ignore_dont_use_same_file_name`, key)) {
4422
- isParentMatched = true;
4423
- matchedKey = key;
4424
- matchedRule = value;
4425
- break;
4426
- }
4427
- }
4428
- }
4429
- }
4430
- if (!matchedRule) {
4431
- matchedKey = "packages/*";
4432
- matchedRule = `@${workspaceName}/$basename`;
4433
- }
4434
- if (!matchedRule) {
4435
- throw new Error("no matched rule");
4436
- }
4437
- if (!name && isParentMatched) {
4438
- basename = await inquirer.prompt({
4439
- type: "input",
4440
- name: "name",
4441
- message: `the matched rule is \`${String(matchedRule)}\`, please input the basename
4442
- `
4443
- }).then(({ name: name2 }) => name2);
4444
- }
4445
- if (typeof matchedRule === "function") {
4446
- return matchedRule(name, {
4447
- full: wd,
4448
- relative: cwd,
4449
- basename
4450
- });
4451
- }
4452
- if (typeof matchedRule === "string") {
4453
- const dirName = name ?? basename;
4454
- return [
4455
- matchedRule.replace(/\$basename/g, dirName),
4456
- matchedKey?.replace(/\/\*$/g, `/${dirName}`)
4457
- ];
4458
- }
4459
- throw new Error("no matched rule");
4460
- }
4461
- program.command("init [name]").option("-t, --template <template>", "the package.json template file path or file content").action(async () => {
4462
- const [, name] = program.args;
4463
- const cwd = process.cwd();
4464
- const { init = {} } = loadConfig() ?? {};
4465
- const { wd } = getWD();
4466
- const workspaceName = path.basename(wd);
4467
- const {
4468
- named,
4469
- template,
4470
- bug = {},
4471
- readme: _readme = README_TEMPLATE,
4472
- readmeTemplate
4473
- } = init;
4474
- const resolvedBug = {
4475
- template: "bug_report.yml",
4476
- labels: ["bug"],
4477
- ...bug
4478
- };
4479
- let readme = _readme;
4480
- if (readmeTemplate) {
4481
- const readmeTemplatePath = path.resolve(wd, readmeTemplate);
4482
- readme = fs.readFileSync(readmeTemplatePath, "utf-8");
4483
- }
4484
- const templateString = getTemplateStr(wd, template);
4485
- const { indent = " " } = detectIndent(templateString);
4486
- const formattingOptions = {
4487
- tabSize: indent.length,
4488
- insertSpaces: true
4489
- };
4490
- const passFields = [
4491
- "license",
4492
- "author"
4493
- ];
4494
- let newJSONString = templateString;
4495
- for (const field of passFields) {
4496
- newJSONString = applyEdits(
4497
- newJSONString,
4498
- modify(
4499
- newJSONString,
4500
- [field],
4501
- getWDPackageJSONFiled(wd, field),
4502
- { formattingOptions }
4503
- )
4504
- );
4505
- }
4506
- let [pkgName, pkgDir] = await getName(named, name, {
4507
- wd,
4508
- cwd,
4509
- workspaceName
4510
- });
4511
- if (!pkgDir) {
4512
- const { dir } = await inquirer.prompt({
4513
- type: "input",
4514
- name: "dir",
4515
- message: "package directory",
4516
- default: name
4517
- });
4518
- pkgDir = dir;
4519
- }
4520
- if (!pkgName) {
4521
- const { name: inputName } = await inquirer.prompt({
4522
- type: "input",
4523
- name: "name",
4524
- message: "package name",
4525
- default: name
4526
- });
4527
- pkgName = inputName;
4528
- }
4529
- newJSONString = applyEdits(newJSONString, modify(newJSONString, ["name"], pkgName, { formattingOptions }));
4530
- let pkgRepo = getWDPackageJSONFiled(wd, "repository");
4531
- if (typeof pkgRepo === "string") {
4532
- pkgRepo = {
4533
- type: "git",
4534
- url: pkgRepo,
4535
- directory: pkgDir
4536
- };
4537
- }
4538
- newJSONString = applyEdits(
4539
- newJSONString,
4540
- modify(
4541
- newJSONString,
4542
- ["repository"],
4543
- pkgRepo,
4544
- { formattingOptions }
4545
- )
4546
- );
4547
- const homepage = `${pkgRepo?.url}/blob/master/${pkgDir}/README.md`;
4548
- newJSONString = applyEdits(
4549
- newJSONString,
4550
- modify(
4551
- newJSONString,
4552
- ["homepage"],
4553
- homepage,
4554
- { formattingOptions }
4555
- )
4556
- );
4557
- let labels = resolvedBug.labels;
4558
- if (typeof labels === "function") {
4559
- labels = labels({
4560
- name: pkgName,
4561
- dir: pkgDir
4562
- });
4563
- }
4564
- labels.push(`scope:${pkgName}`);
4565
- const bugs = `${pkgRepo?.url}/issues/new?template=${resolvedBug.template}&labels=${labels.join(",")}`;
4566
- newJSONString = applyEdits(
4567
- newJSONString,
4568
- modify(
4569
- newJSONString,
4570
- ["bugs"],
4571
- bugs,
4572
- { formattingOptions }
4573
- )
4574
- );
4575
- function pkgDirTo(to) {
4576
- if (!pkgDir)
4577
- throw new Error("pkgDir is not defined");
4578
- return path.resolve(pkgDir, to);
4579
- }
4580
- if (!fs.existsSync(pkgDir))
4581
- fs.mkdirSync(pkgDir);
4582
- const pkgJSONFilePath = pkgDirTo("package.json");
4583
- if (fs.existsSync(pkgJSONFilePath)) {
4584
- throw new Error("package.json already exists");
4585
- }
4586
- fs.writeFileSync(pkgJSONFilePath, newJSONString);
4587
- console.log(newJSONString, "written to", pkgJSONFilePath);
4588
- const license = getWDPackageJSONFiled(wd, "license");
4589
- const readmeFilePath = pkgDirTo("README.md");
4590
- if (typeof readme === "function") {
4591
- readme = readme({
4592
- dir: pkgDir,
4593
- packageJson: JSON.parse(newJSONString)
4594
- });
4595
- }
4596
- const readmeContent = readme.replace(/\$name/g, pkgName).replace(/\$license/g, license);
4597
- fs.writeFileSync(readmeFilePath, readmeContent);
4598
- });
4599
-
4600
- let resolve;
4601
- function actionDone() {
4602
- resolve();
4603
- }
4604
- function actionRestore() {
4605
- new Promise((r) => resolve = r);
4606
- }
4607
-
4608
- const intersection = (a, b) => new Set([...a].filter((i) => b.has(i)));
4609
- const {
4610
- JIEK_OUT_DIR
4611
- } = process.env;
4612
- const OUTDIR = JIEK_OUT_DIR ?? "dist";
4613
- function getOutDirs({
4614
- cwd = process.cwd(),
4615
- defaultOutdir = OUTDIR,
4616
- config,
4617
- pkgName
4618
- }) {
4619
- const { build = {} } = config ?? {};
4620
- const outdir = build?.output?.dir;
4621
- function resolveOutdir(type) {
4622
- const dir = (typeof outdir === "object" ? outdir[type] ?? outdir[{
4623
- js: "dts",
4624
- dts: "js"
4625
- }[type]] : outdir) ?? defaultOutdir;
4626
- return (isAbsolute(dir) ? dir : `./${relative(cwd, resolve$1(cwd, dir))}`).replace("{{PKG_NAME}}", pkgName);
4627
- }
4628
- return {
4629
- js: resolveOutdir("js"),
4630
- dts: resolveOutdir("dts")
4631
- };
4632
- }
4633
- function getExports({
4634
- entrypoints,
4635
- pkgName,
4636
- pkgIsModule,
4637
- entries,
4638
- config,
4639
- dir,
4640
- defaultOutdir = OUTDIR,
4641
- // FIXME dts support
4642
- outdir = getOutDirs({ pkgName, defaultOutdir, config, cwd: dir }).js,
4643
- noFilter,
4644
- isPublish
4645
- }) {
4646
- const {
4647
- build = {},
4648
- publish: {
4649
- withSuffix = false,
4650
- withSource = true
4651
- } = {}
4652
- } = config ?? {};
4653
- const {
4654
- crossModuleConvertor = true
4655
- } = build;
4656
- const [, resolvedEntrypoints] = resolveEntrypoints(entrypoints);
4657
- if (entries) {
4658
- Object.entries(resolvedEntrypoints).forEach(([key]) => {
4659
- if (!entries.some((e) => micromatchExports.isMatch(key, e, { matchBase: true }))) {
4660
- delete resolvedEntrypoints[key];
4661
- }
4662
- });
4663
- }
4664
- const filteredResolvedEntrypoints = noFilter ? resolvedEntrypoints : filterLeafs(
4665
- resolvedEntrypoints,
4666
- {
4667
- skipValue: [
4668
- // ignore values that filename starts with `.jk-noentry`
4669
- /(^|\/)\.jk-noentry/,
4670
- ...DEFAULT_SKIP_VALUES
4671
- ]
4672
- }
4673
- );
4674
- const crossModuleWithConditional = crossModuleConvertor ? {
4675
- import: (opts) => !pkgIsModule && intersection(
4676
- new Set(opts.conditionals),
4677
- /* @__PURE__ */ new Set(["import", "module"])
4678
- ).size === 0 ? opts.dist.replace(/\.js$/, ".mjs") : false,
4679
- require: (opts) => pkgIsModule && intersection(
4680
- new Set(opts.conditionals),
4681
- /* @__PURE__ */ new Set(["require", "node"])
4682
- ).size === 0 ? opts.dist.replace(/\.js$/, ".cjs") : false
4683
- } : {};
4684
- return [
4685
- filteredResolvedEntrypoints,
4686
- entrypoints2Exports(filteredResolvedEntrypoints, {
4687
- outdir,
4688
- withSuffix: isPublish ? withSuffix : void 0,
4689
- withSource: isPublish ? withSource : void 0,
4690
- withConditional: {
4691
- ...crossModuleWithConditional
4692
- }
4693
- }),
4694
- outdir
4695
- ];
4696
- }
4697
-
4698
4421
  const outdirDescription = `
4699
4422
  The output directory of the build, which relative to the target subpackage root directory.
4700
4423
  Support with variables: 'PKG_NAME',
4701
4424
  .e.g. 'dist/{{PKG_NAME}}'.
4702
4425
  `.trim();
4703
4426
 
4704
- program.command("publish").aliases(["pub", "p"]).option("-b, --bumper <bumper>", "bump version", "patch").option("-no-b, --no-bumper", "no bump version").option("-o, --outdir <OUTDIR>", outdirDescription, String, "dist").option("-s, --silent", "no output").option("-p, --preview", "preview publish").action(async ({ outdir, preview, silent, bumper, ...options }) => {
4427
+ const description = `
4428
+ Publish package to npm registry, and auto generate exports field and other fields in published package.json.
4429
+ If you want to through the options to the \`pnpm publish\` command, you can pass the options after '--'.
4430
+ `.trim();
4431
+ program.command("publish").description(description).aliases(["pub", "p"]).option("-b, --bumper <bumper>", "bump version", "patch").option("-no-b, --no-bumper", "no bump version").option("-o, --outdir <OUTDIR>", outdirDescription, String, "dist").option("-s, --silent", "no output").option("-p, --preview", "preview publish").action(async ({ outdir, preview, silent, bumper, ...options }) => {
4432
+ let shouldPassThrough = false;
4433
+ const passThroughOptions = process.argv.reduce(
4434
+ (acc, value2) => {
4435
+ if (shouldPassThrough) {
4436
+ acc.push(value2);
4437
+ }
4438
+ if (value2 === "--") {
4439
+ shouldPassThrough = true;
4440
+ }
4441
+ return acc;
4442
+ },
4443
+ []
4444
+ );
4705
4445
  actionRestore();
4706
4446
  const { value = {} } = await getSelectedProjectsGraph() ?? {};
4707
4447
  const selectedProjectsGraphEntries = Object.entries(value);
@@ -4738,7 +4478,8 @@ program.command("publish").aliases(["pub", "p"]).option("-b, --bumper <bumper>",
4738
4478
  return acc;
4739
4479
  }, []);
4740
4480
  for (const [dir, manifest, resolvedOutdir] of manifests) {
4741
- const oldJSONString = fs.readFileSync(path.join(dir, "package.json"), "utf-8");
4481
+ const resolveByDir = (...paths) => path.resolve(dir, ...paths);
4482
+ const oldJSONString = fs.readFileSync(resolveByDir("package.json"), "utf-8");
4742
4483
  const oldJSON = JSON.parse(oldJSONString) ?? "0.0.0";
4743
4484
  const newVersion = bumper ? bump(oldJSON.version, bumper) : oldJSON.version;
4744
4485
  const { indent = " " } = detectIndent(oldJSONString);
@@ -4831,26 +4572,36 @@ program.command("publish").aliases(["pub", "p"]).option("-b, --bumper <bumper>",
4831
4572
  { formattingOptions }
4832
4573
  )
4833
4574
  );
4575
+ newJSONString = applyEdits(
4576
+ newJSONString,
4577
+ modify(newJSONString, ["publishConfig", "directory"], resolvedOutdir, { formattingOptions })
4578
+ );
4579
+ !silent && console.log(newJSONString);
4580
+ if (preview) {
4581
+ continue;
4582
+ }
4583
+ const effects = [];
4834
4584
  try {
4835
- fs.renameSync(path.join(dir, "package.json"), path.join(dir, "package.json.bak"));
4836
- fs.writeFileSync(path.join(dir, "package.json"), newJSONString);
4837
- !silent && console.log(newJSONString);
4838
- if (preview) {
4839
- continue;
4585
+ if (!fs.existsSync(resolveByDir(resolvedOutdir))) {
4586
+ fs.mkdirSync(resolveByDir(resolvedOutdir));
4587
+ effects.push(() => fs.rmdirSync(resolveByDir(resolvedOutdir), { recursive: true }));
4840
4588
  }
4589
+ fs.writeFileSync(resolveByDir(resolvedOutdir, "package.json"), newJSONString);
4590
+ effects.push(() => fs.unlinkSync(resolveByDir(resolvedOutdir, "package.json")));
4591
+ const modifyVersionPackageJSON = applyEdits(oldJSONString, modify(oldJSONString, ["version"], newVersion, {}));
4592
+ fs.writeFileSync(resolveByDir("package.json"), modifyVersionPackageJSON);
4593
+ effects.push(() => fs.writeFileSync(resolveByDir("package.json"), oldJSONString));
4841
4594
  const args = ["pnpm", "publish", "--access", "public", "--no-git-checks", ...passArgs];
4842
4595
  if (bumper && TAGS.includes(bumper)) {
4843
4596
  args.push("--tag", bumper);
4844
4597
  }
4598
+ args.push(...passThroughOptions);
4845
4599
  childProcess.execSync(args.join(" "), {
4846
4600
  cwd: dir,
4847
4601
  stdio: "inherit"
4848
4602
  });
4849
- const modifyVersionPackageJSON = applyEdits(oldJSONString, modify(oldJSONString, ["version"], newVersion, {}));
4850
- fs.writeFileSync(path.join(dir, "package.json.bak"), modifyVersionPackageJSON);
4851
4603
  } finally {
4852
- fs.unlinkSync(path.join(dir, "package.json"));
4853
- fs.renameSync(path.join(dir, "package.json.bak"), path.join(dir, "package.json"));
4604
+ effects.forEach((effect) => effect());
4854
4605
  }
4855
4606
  }
4856
4607
  actionDone();