jiek 0.4.0 → 0.4.2

Sign up to get free protection for your applications and to get access to all the features.
package/dist/cli.cjs CHANGED
@@ -1,2 +1,683 @@
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"),a=require("@jiek/utils/getWorkspaceDir"),i=require("node:child_process"),s=require("@jiek/pkger"),l=require("detect-indent"),c=require("inquirer"),p=require("jsonc-parser"),u=require("micromatch"),f=require("@jiek/utils/bumper");function d(e){return e&&e.__esModule?e:{default:e}}function m(e){if(e&&e.__esModule)return 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 g=d(e),y=d(t),w=m(i),k=d(l),h=d(c);let b,j;function v(){if(b)return b;const e=n.program.getOptionValue("root");return b=e?y.default.isAbsolute(e)?e:y.default.resolve(process.cwd(),e):void 0,b}let S=!1;function $(){if(j)return{wd:j,notWorkspace:S};const e=v();if(void 0!==e){const t=a.isWorkspaceDir(e,E);return S=!t,j=e,{wd:j,notWorkspace:S}}try{j=a.getWorkspaceDir(E)}catch(t){if(!("message"in t)||"workspace root not found"!==t.message)throw t;j=e,S=!0}return{wd:j,notWorkspace:S}}let E="";try{require.resolve("@pnpm/filter-workspace-packages"),E="pnpm"}catch{}async function O(){let e=n.program.getOptionValue("filter");const t=v(),{wd:a,notWorkspace:i}=$();if(!i&&"pnpm"===E){const n=y.default.resolve(a,"pnpm-workspace.yaml"),i=g.default.readFileSync(n,"utf-8"),s=o.load(i);if(t===a&&!e)throw new Error("root path is workspace root, please provide a filter");if(t!==a&&!e){if(!g.default.existsSync(y.default.resolve(t,"package.json")))throw new Error("root path is not workspace root, please provide a filter");const r=JSON.parse(g.default.readFileSync(y.default.resolve(t,"package.json"),"utf-8"));if(!r.name)throw new Error("root path is not workspace root, please provide a filter");e=r.name}const{selectedProjectsGraph:l}=await r.filterPackagesFromDir(a,[{filter:e??"",followProdDepsOnly:!0}],{prefix:t,workspaceDir:a,patterns:s.packages});return{wd:a,root:t,value:Object.entries(l).reduce(((e,[t,r])=>(e[t]=r.package.manifest,e)),{})}}return{wd:a,root:t,value:{[a]:JSON.parse(g.default.readFileSync(y.default.resolve(a,"package.json"),"utf-8"))}}}""!==E&&n.program.option("-f, --filter <filter>","filter packages");const q=require("../package.json");let x,F;function _(){x()}function A(){new Promise((e=>x=e))}function D(e,t,r={}){const{excludeDistInExports:n=!1}=r,{jiek:{cwd:o,...a}={}}=e,{outdir:i="dist"}=a;let{exports:l}=e,c=!1;"string"==typeof l&&(c=!0,l={".":l}),void 0===l&&(l={".":"./src/index.ts"}),"object"==typeof l&&(c=!!(Array.isArray(l)&&l.length>0)||!!l["."]);let p=Array.isArray(l)?l:Object.entries(l).reduce(((e,[t,r])=>{if("string"==typeof r)return"."===t?[r,...e]:e.concat(r);if(Array.isArray(r))return e.concat(r);throw new TypeError(`Unexpected value type for key "${t}" in exports, expected string, got ${typeof r}`)}),[]);if(n&&(p=p.filter((e=>!e.startsWith(`./${i}`)&&!e.startsWith(i)))),0===p.length)throw new Error("No inputs found");const u=p.map((e=>y.default.isAbsolute(e)?e:y.default.resolve(t,e)));let f=y.default.dirname(u[0]);u.length>1&&(f=function(e,t=process.cwd()){const r=e.map((e=>y.default.isAbsolute(e)?e:y.default.resolve(t,e))),[n=""]=r,o=n.split("/");let a="";for(let e=0;e<o.length;e++){const t=o[e];if(!r.every((e=>e.startsWith(a+t))))break;a+=t+"/"}return a}(u,t));const d=u.map((e=>y.default.relative(f,e)));return{...e,...s.pkger({cwd:t,noIndex:!c,source:y.default.relative(t,f),inputs:d,...a})}}function J(e){try{return require.resolve(e),!0}catch(e){return!1}}n.program.version(q.version).description(q.description).option("--root <root>","root path").option("-c, --config-path <configPath>","config path");const N=[process.env.JIEK_TS_REGISTER,"esbuild-register","@swc-node/register","ts-node/register"].filter(Boolean);for(const e of N)if(J(e)){F=e;break}const W=e=>`\nconst pkg = ${JSON.stringify(e,null,2)}\nconst { jiek = {} } = pkg\nconst templateArg = jiek.templateArgFilePath\n ? require.resolve(jiek.templateArgFilePath)\n : {\n styled: jiek.styled\n }\nmodule.exports = require('jiek/rollup').template(templateArg, pkg)\n`.trimStart();n.program.command("build").action((async()=>{A();const{wd:e,value:t={}}=await O()??{};if(0===Object.keys(t).length)throw new Error("no package found");const r=(...t)=>y.default.resolve(e,"node_modules/.jiek",...t);g.default.existsSync(r())||g.default.mkdirSync(r());const n=require.resolve("rollup").replace(/dist\/rollup.js$/,"dist/bin/rollup");let o=0;for(const[e,a]of Object.entries(t)){const t=D(a,e,{excludeDistInExports:!0}),i=a.name?.replace(/^@/g,"").replace(/\//g,"+"),s=r(`${i??"anonymous-"+o++}.rollup.config.js`);g.default.writeFileSync(s,W(t));let l="";F&&(l=`node -r ${F} `),w.execSync(`${l}${n} --silent -c ${s}`,{cwd:e,stdio:"inherit"})}_()}));let P="jiek.config";function I(){const{wd:e,notWorkspace:t}=$();if(t)throw new Error("not in workspace");let r=n.program.getOptionValue("configPath");if(r){if(!g.default.existsSync(r))throw new Error(`config file not found: ${r}`);y.default.isAbsolute(r)||(r=y.default.resolve(e,r))}else r=function(e){const t=!!F;function r(t){const r=[y.default.resolve(e,`${P}.${t}`),y.default.resolve(e,`.${P}.${t}`)];for(const e of r)if(g.default.existsSync(e)&&g.default.lstatSync(e).isFile())return e}return P=r("js")??P,P=r("json")??P,P=r("yaml")??P,t&&(P=r("ts")??P),y.default.resolve(e,P)}(e);const a=y.default.extname(r);let i;switch(a){case".js":i=require(r);break;case".json":return require(r);case".yaml":return o.load(g.default.readFileSync(r,"utf-8"));case".ts":if(F){require(F),i=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":i={};break;default:throw new Error(`unsupported config file type: ${a}`)}if(!i)throw new Error("config file is empty");return i.default??i}const M='{\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(),R="# $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 T=new Map;function z(e,t){if(T.has(e))return T.get(e)[t];const r=y.default.resolve(e,"package.json"),n=JSON.parse(g.default.readFileSync(r,"utf-8"));return T.set(e,n),n[t]}n.program.command("init [name]").option("-t, --template <template>","the package.json template file path or file content").action((async()=>{const[,e]=n.program.args,t=process.cwd(),{init:r={}}=I()??{},{wd:o}=$(),a=y.default.basename(o),{named:i,template:s,bug:l={},readme:c=R,readmeTemplate:f}=r,d={template:"bug_report.yml",labels:["bug"],...l};let m=c;if(f){const e=y.default.resolve(o,f);m=g.default.readFileSync(e,"utf-8")}const w=function(e,t){let r=t??M,n=!1;try{t&&JSON.parse(t)}catch(e){n=!0}if(n){const n=y.default.resolve(e,t);r=g.default.readFileSync(n,"utf-8")}return r}(o,s),{indent:b=" "}=k.default(w),j={tabSize:b.length,insertSpaces:!0},v=["license","author"];let S=w;for(const e of v)S=p.applyEdits(S,p.modify(S,[e],z(o,e),{formattingOptions:j}));let[E,O]=await async function(e,t,{wd:r,cwd:n,workspaceName:o}){const a=n.replace(`${r}/`,"");let i=y.default.basename(n);if("function"==typeof e)return e(t,{full:r,relative:n});let s,l,c=!1;if("object"==typeof e)if(n===r){const{rule:t}=await h.default.prompt({type:"list",name:"rule",message:"choose a rule",default:"default",choices:["default"].concat(Object.keys(e))});"default"!==t&&(s=t,l=e[t])}else for(const[t,r]of Object.entries(e)){if(u.isMatch(a,t)){s=t,l=r;break}if(u.isMatch(`${a}/jiek_ignore_dont_use_same_file_name`,t)){c=!0,s=t,l=r;break}}if(l||(s="packages/*",l=`@${o}/$basename`),!l)throw new Error("no matched rule");if(!t&&c&&(i=await h.default.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(t,{full:r,relative:n,basename:i});if("string"==typeof l){const e=t??i;return[l.replace(/\$basename/g,e),s?.replace(/\/\*$/g,`/${e}`)]}throw new Error("no matched rule")}(i,e,{wd:o,cwd:t,workspaceName:a});if(!O){const{dir:t}=await h.default.prompt({type:"input",name:"dir",message:"package directory",default:e});O=t}if(!E){const{name:t}=await h.default.prompt({type:"input",name:"name",message:"package name",default:e});E=t}S=p.applyEdits(S,p.modify(S,["name"],E,{formattingOptions:j}));let q=z(o,"repository");"string"==typeof q&&(q={type:"git",url:q,directory:O}),S=p.applyEdits(S,p.modify(S,["repository"],q,{formattingOptions:j}));const x=`${q?.url}/blob/master/${O}/README.md`;S=p.applyEdits(S,p.modify(S,["homepage"],x,{formattingOptions:j}));let F=d.labels;"function"==typeof F&&(F=F({name:E,dir:O})),F.push(`scope:${E}`);const _=`${q?.url}/issues/new?template=${d.template}&labels=${F.join(",")}`;function A(e){if(!O)throw new Error("pkgDir is not defined");return y.default.resolve(O,e)}S=p.applyEdits(S,p.modify(S,["bugs"],_,{formattingOptions:j})),g.default.existsSync(O)||g.default.mkdirSync(O);const D=A("package.json");if(g.default.existsSync(D))throw new Error("package.json already exists");g.default.writeFileSync(D,S),console.log(S,"written to",D);const J=z(o,"license"),N=A("README.md");"function"==typeof m&&(m=m({dir:O,packageJson:JSON.parse(S)}));const W=m.replace(/\$name/g,E).replace(/\$license/g,J);g.default.writeFileSync(N,W)})),n.program.command("publish").aliases(["pub","p"]).option("-b, --bumper <bumper>","bump version","patch").option("-p, --preview","preview publish").action((async({preview:e,bumper:t,...r})=>{A();const{value:n={}}=await O()??{},o=Object.entries(n);if(0===o.length)throw new Error("no packages selected");const a=o.map((([e,t])=>[e,D(t,e)])),i=Object.entries(r).reduce(((e,[t,r])=>(r&&e.push(`--${t}`,r),e)),[]);for(const[r,n]of a){const o=g.default.readFileSync(y.default.join(r,"package.json"),"utf-8"),a=JSON.parse(o)??"0.0.0",s=f.bump(a.version,t),{indent:l=" "}=k.default(o),c={tabSize:l.length,insertSpaces:!0};let u=o;u=p.applyEdits(u,p.modify(u,["version"],s,{formattingOptions:c}));for(const[e,t]of Object.entries(n))JSON.stringify(t)!==JSON.stringify(a[e])&&(u=p.applyEdits(u,p.modify(u,["publishConfig",e],t,{formattingOptions:c})));try{if(g.default.renameSync(y.default.join(r,"package.json"),y.default.join(r,"package.json.bak")),g.default.writeFileSync(y.default.join(r,"package.json"),u),console.log(u),e){console.warn("preview mode");continue}w.execSync(["pnpm","publish","--access","public","--no-git-checks",...i].join(" "),{cwd:r,stdio:"inherit"});const t=p.applyEdits(o,p.modify(o,["version"],s,{}));g.default.writeFileSync(y.default.join(r,"package.json.bak"),t)}finally{g.default.unlinkSync(y.default.join(r,"package.json")),g.default.renameSync(y.default.join(r,"package.json.bak"),y.default.join(r,"package.json"))}}_()})),n.program.parse(process.argv);
1
+ 'use strict';
2
+
3
+ var fs = require('node:fs');
4
+ var path = require('node:path');
5
+ var filterWorkspacePackages = require('@pnpm/filter-workspace-packages');
6
+ var commander = require('commander');
7
+ var jsYaml = require('js-yaml');
8
+ var getWorkspaceDir = require('@jiek/utils/getWorkspaceDir');
9
+ var childProcess = require('node:child_process');
10
+ var pkger = require('@jiek/pkger');
11
+ var detectIndent = require('detect-indent');
12
+ var inquirer = require('inquirer');
13
+ var jsoncParser = require('jsonc-parser');
14
+ var micromatch = require('micromatch');
15
+ var bumper = require('@jiek/utils/bumper');
16
+
17
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
18
+
19
+ function _interopNamespace(e) {
20
+ if (e && e.__esModule) return e;
21
+ var n = Object.create(null);
22
+ if (e) {
23
+ Object.keys(e).forEach(function (k) {
24
+ if (k !== 'default') {
25
+ var d = Object.getOwnPropertyDescriptor(e, k);
26
+ Object.defineProperty(n, k, d.get ? d : {
27
+ enumerable: true,
28
+ get: function () { return e[k]; }
29
+ });
30
+ }
31
+ });
32
+ }
33
+ n.default = e;
34
+ return Object.freeze(n);
35
+ }
36
+
37
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
38
+ var path__default = /*#__PURE__*/_interopDefault(path);
39
+ var childProcess__namespace = /*#__PURE__*/_interopNamespace(childProcess);
40
+ var detectIndent__default = /*#__PURE__*/_interopDefault(detectIndent);
41
+ var inquirer__default = /*#__PURE__*/_interopDefault(inquirer);
42
+
43
+ let root;
44
+ function getRoot() {
45
+ if (root)
46
+ return root;
47
+ const rootOption = commander.program.getOptionValue("root");
48
+ root = rootOption ? path__default.default.isAbsolute(rootOption) ? rootOption : path__default.default.resolve(process.cwd(), rootOption) : void 0;
49
+ return root;
50
+ }
51
+
52
+ let wd;
53
+ let notWorkspace = false;
54
+ function getWD() {
55
+ if (wd)
56
+ return { wd, notWorkspace };
57
+ const root = getRoot();
58
+ if (root !== void 0) {
59
+ const isWorkspace = getWorkspaceDir.isWorkspaceDir(root, type);
60
+ notWorkspace = !isWorkspace;
61
+ wd = root;
62
+ return { wd, notWorkspace };
63
+ }
64
+ try {
65
+ wd = getWorkspaceDir.getWorkspaceDir(type);
66
+ } catch (e) {
67
+ if ("message" in e && e.message === "workspace root not found") {
68
+ wd = root;
69
+ notWorkspace = true;
70
+ } else {
71
+ throw e;
72
+ }
73
+ }
74
+ return { wd, notWorkspace };
75
+ }
76
+
77
+ let type = "";
78
+ try {
79
+ require.resolve("@pnpm/filter-workspace-packages");
80
+ type = "pnpm";
81
+ } catch {
82
+ }
83
+ if (type !== "") {
84
+ commander.program.option("-f, --filter <filter>", "filter packages");
85
+ }
86
+ async function getSelectedProjectsGraph() {
87
+ let filter = commander.program.getOptionValue("filter");
88
+ const root = getRoot();
89
+ const { wd, notWorkspace } = getWD();
90
+ if (!notWorkspace && type === "pnpm") {
91
+ const pnpmWorkspaceFilePath = path__default.default.resolve(wd, "pnpm-workspace.yaml");
92
+ const pnpmWorkspaceFileContent = fs__default.default.readFileSync(pnpmWorkspaceFilePath, "utf-8");
93
+ const pnpmWorkspace = jsYaml.load(pnpmWorkspaceFileContent);
94
+ if (root === wd && !filter) {
95
+ throw new Error("root path is workspace root, please provide a filter");
96
+ }
97
+ if (root !== wd && !filter) {
98
+ const packageJSONIsExist = fs__default.default.existsSync(path__default.default.resolve(root, "package.json"));
99
+ if (!packageJSONIsExist) {
100
+ throw new Error("root path is not workspace root, please provide a filter");
101
+ }
102
+ const packageJSON = JSON.parse(fs__default.default.readFileSync(path__default.default.resolve(root, "package.json"), "utf-8"));
103
+ if (!packageJSON.name) {
104
+ throw new Error("root path is not workspace root, please provide a filter");
105
+ }
106
+ filter = packageJSON.name;
107
+ }
108
+ const { selectedProjectsGraph } = await filterWorkspacePackages.filterPackagesFromDir(wd, [{
109
+ filter: filter ?? "",
110
+ followProdDepsOnly: true
111
+ }], {
112
+ prefix: root,
113
+ workspaceDir: wd,
114
+ patterns: pnpmWorkspace.packages
115
+ });
116
+ return {
117
+ wd,
118
+ root,
119
+ value: Object.entries(selectedProjectsGraph).reduce((acc, [key, value]) => {
120
+ acc[key] = value.package.manifest;
121
+ return acc;
122
+ }, {})
123
+ };
124
+ }
125
+ return {
126
+ wd,
127
+ root,
128
+ value: {
129
+ [wd]: JSON.parse(fs__default.default.readFileSync(path__default.default.resolve(wd, "package.json"), "utf-8"))
130
+ }
131
+ };
132
+ }
133
+
134
+ var pkg = require("../package.json");
135
+
136
+ commander.program.version(pkg.version).description(pkg.description).option("--root <root>", "root path").option("-c, --config-path <configPath>", "config path");
137
+
138
+ let resolve;
139
+ function actionDone() {
140
+ resolve();
141
+ }
142
+ function actionRestore() {
143
+ new Promise((r) => resolve = r);
144
+ }
145
+
146
+ function commondir(files, cwd = process.cwd()) {
147
+ const resolvedFiles = files.map((file) => {
148
+ if (path__default.default.isAbsolute(file))
149
+ return file;
150
+ return path__default.default.resolve(cwd, file);
151
+ });
152
+ const sep = "/";
153
+ const [first = ""] = resolvedFiles;
154
+ const parts = first.split(sep);
155
+ let common = "";
156
+ for (let i = 0; i < parts.length; i++) {
157
+ const segment = parts[i];
158
+ if (resolvedFiles.every((file) => file.startsWith(common + segment))) {
159
+ common += segment + sep;
160
+ } else {
161
+ break;
162
+ }
163
+ }
164
+ return common;
165
+ }
166
+
167
+ function mergePackageJson(manifest, cwd, options = {}) {
168
+ const {
169
+ excludeDistInExports = false
170
+ } = options;
171
+ const {
172
+ jiek: { cwd: _, ...jiek } = {}
173
+ } = manifest;
174
+ const { outdir = "dist" } = jiek;
175
+ let { exports } = manifest;
176
+ let includeIndex = false;
177
+ if (typeof exports === "string") {
178
+ includeIndex = true;
179
+ exports = { ".": exports };
180
+ }
181
+ if (exports === void 0) {
182
+ exports = { ".": "./src/index.ts" };
183
+ }
184
+ if (typeof exports === "object") {
185
+ if (Array.isArray(exports) && exports.length > 0) {
186
+ includeIndex = true;
187
+ } else {
188
+ includeIndex = !!exports["."];
189
+ }
190
+ }
191
+ let inputs = Array.isArray(exports) ? exports : Object.entries(exports).reduce((acc, [key, value]) => {
192
+ if (typeof value === "string")
193
+ return key === "." ? [value, ...acc] : acc.concat(value);
194
+ if (Array.isArray(value))
195
+ return acc.concat(value);
196
+ throw new TypeError(`Unexpected value type for key "${key}" in exports, expected string, got ${typeof value}`);
197
+ }, []);
198
+ if (excludeDistInExports) {
199
+ inputs = inputs.filter((input) => !input.startsWith(`./${outdir}`) && !input.startsWith(outdir));
200
+ }
201
+ if (inputs.length === 0)
202
+ throw new Error("No inputs found");
203
+ const absoluteInputs = inputs.map(
204
+ (input) => path__default.default.isAbsolute(input) ? input : path__default.default.resolve(cwd, input)
205
+ );
206
+ let cDir = path__default.default.dirname(absoluteInputs[0]);
207
+ if (absoluteInputs.length > 1) {
208
+ cDir = commondir(absoluteInputs, cwd);
209
+ }
210
+ const resolvedInputs = absoluteInputs.map((input) => {
211
+ return path__default.default.relative(cDir, input);
212
+ });
213
+ return {
214
+ ...manifest,
215
+ ...pkger.pkger({
216
+ cwd,
217
+ noIndex: !includeIndex,
218
+ source: path__default.default.relative(cwd, cDir),
219
+ inputs: resolvedInputs,
220
+ ...jiek
221
+ })
222
+ };
223
+ }
224
+
225
+ function packageIsExist(name) {
226
+ try {
227
+ require.resolve(name);
228
+ return true;
229
+ } catch (e) {
230
+ return false;
231
+ }
232
+ }
233
+ let tsRegisterName;
234
+ const registers = [
235
+ process.env.JIEK_TS_REGISTER,
236
+ "esbuild-register",
237
+ "@swc-node/register",
238
+ "ts-node/register"
239
+ ].filter(Boolean);
240
+ for (const register of registers) {
241
+ if (packageIsExist(register)) {
242
+ tsRegisterName = register;
243
+ break;
244
+ }
245
+ }
246
+
247
+ const FILE_TEMPLATE = (manifest) => `
248
+ const pkg = ${JSON.stringify(manifest, null, 2)}
249
+ const { jiek = {} } = pkg
250
+ const templateArg = jiek.templateArgFilePath
251
+ ? require.resolve(jiek.templateArgFilePath)
252
+ : {
253
+ styled: jiek.styled
254
+ }
255
+ module.exports = require('jiek/rollup').template(templateArg, pkg)
256
+ `.trimStart();
257
+ commander.program.command("build").action(async () => {
258
+ actionRestore();
259
+ const {
260
+ wd,
261
+ value = {}
262
+ } = await getSelectedProjectsGraph() ?? {};
263
+ if (Object.keys(value).length === 0) {
264
+ throw new Error("no package found");
265
+ }
266
+ const jiekTempDir = (...paths) => path__default.default.resolve(wd, "node_modules/.jiek", ...paths);
267
+ if (!fs__default.default.existsSync(jiekTempDir()))
268
+ fs__default.default.mkdirSync(jiekTempDir());
269
+ const rollupBinaryPath = require.resolve("rollup").replace(/dist\/rollup.js$/, "dist/bin/rollup");
270
+ let i = 0;
271
+ for (const [dir, manifest] of Object.entries(value)) {
272
+ const newManifest = mergePackageJson(manifest, dir, { excludeDistInExports: true });
273
+ const escapeManifestName = manifest.name?.replace(/^@/g, "").replace(/\//g, "+");
274
+ const configFile = jiekTempDir(
275
+ `${escapeManifestName ?? `anonymous-${i++}`}.rollup.config.js`
276
+ );
277
+ fs__default.default.writeFileSync(configFile, FILE_TEMPLATE(newManifest));
278
+ let prefix = "";
279
+ if (tsRegisterName) {
280
+ prefix = `node -r ${tsRegisterName} `;
281
+ }
282
+ childProcess__namespace.execSync(`${prefix}${rollupBinaryPath} --silent -c ${configFile}`, {
283
+ cwd: dir,
284
+ stdio: "inherit"
285
+ });
286
+ }
287
+ actionDone();
288
+ });
289
+
290
+ let configName = "jiek.config";
291
+ function getConfigPath(root) {
292
+ const isSupportTsLoader = !!tsRegisterName;
293
+ function configWithExtIsExist(ext) {
294
+ const filenames = [
295
+ path__default.default.resolve(root, `${configName}.${ext}`),
296
+ path__default.default.resolve(root, `.${configName}.${ext}`)
297
+ ];
298
+ for (const filename of filenames) {
299
+ if (fs__default.default.existsSync(filename) && fs__default.default.lstatSync(filename).isFile()) {
300
+ return filename;
301
+ }
302
+ }
303
+ return;
304
+ }
305
+ configName = configWithExtIsExist("js") ?? configName;
306
+ configName = configWithExtIsExist("json") ?? configName;
307
+ configName = configWithExtIsExist("yaml") ?? configName;
308
+ if (isSupportTsLoader) {
309
+ configName = configWithExtIsExist("ts") ?? configName;
310
+ }
311
+ return path__default.default.resolve(root, configName);
312
+ }
313
+ function loadConfig() {
314
+ const { wd: root, notWorkspace } = getWD();
315
+ if (notWorkspace)
316
+ throw new Error("not in workspace");
317
+ let configPath = commander.program.getOptionValue("configPath");
318
+ if (!configPath) {
319
+ configPath = getConfigPath(root);
320
+ } else {
321
+ if (!fs__default.default.existsSync(configPath))
322
+ throw new Error(`config file not found: ${configPath}`);
323
+ if (!path__default.default.isAbsolute(configPath))
324
+ configPath = path__default.default.resolve(root, configPath);
325
+ }
326
+ const ext = path__default.default.extname(configPath);
327
+ let module;
328
+ switch (ext) {
329
+ case ".js":
330
+ module = require(configPath);
331
+ break;
332
+ case ".json":
333
+ return require(configPath);
334
+ case ".yaml":
335
+ return jsYaml.load(fs__default.default.readFileSync(configPath, "utf-8"));
336
+ case ".ts":
337
+ if (tsRegisterName) {
338
+ require(tsRegisterName);
339
+ module = require(configPath);
340
+ break;
341
+ }
342
+ throw new Error(
343
+ "ts config file is not supported without ts register, please install esbuild-register or set JIEK_TS_REGISTER env for custom ts register"
344
+ );
345
+ case ".config":
346
+ module = {};
347
+ break;
348
+ default:
349
+ throw new Error(`unsupported config file type: ${ext}`);
350
+ }
351
+ if (!module)
352
+ throw new Error("config file is empty");
353
+ return module.default ?? module;
354
+ }
355
+
356
+ const PACKAGE_JSON_TEMPLATE = `{
357
+ "name": "",
358
+ "version": "0.0.1",
359
+ "description": "",
360
+ "license": "",
361
+ "author": "",
362
+ "files": ["dist"],
363
+ "exports": {
364
+ ".": "./src/index.ts"
365
+ },
366
+ "scripts": {
367
+ },
368
+ "homepage": "",
369
+ "repository": "",
370
+ "bugs": ""
371
+ }`.trimStart();
372
+ const README_TEMPLATE = `# $name
373
+
374
+ ## Installation
375
+
376
+ \`\`\`bash
377
+ npm install $name
378
+ # or
379
+ pnpm install $name
380
+ # or
381
+ yarn add $name
382
+ \`\`\`
383
+
384
+ ## Usage
385
+
386
+
387
+ ## License
388
+
389
+ $license
390
+ `.trimStart();
391
+ function getTemplateStr(wd, template) {
392
+ let templateString = template ?? PACKAGE_JSON_TEMPLATE;
393
+ let isTemplateFile = false;
394
+ try {
395
+ if (template)
396
+ JSON.parse(template);
397
+ } catch (e) {
398
+ isTemplateFile = true;
399
+ }
400
+ if (isTemplateFile) {
401
+ const templatePath = path__default.default.resolve(wd, template);
402
+ templateString = fs__default.default.readFileSync(templatePath, "utf-8");
403
+ }
404
+ return templateString;
405
+ }
406
+ const wdCache = /* @__PURE__ */ new Map();
407
+ function getWDPackageJSONFiled(wd, field) {
408
+ if (wdCache.has(wd)) {
409
+ return wdCache.get(wd)[field];
410
+ }
411
+ const packageJSONPath = path__default.default.resolve(wd, "package.json");
412
+ const packageJSON = JSON.parse(fs__default.default.readFileSync(packageJSONPath, "utf-8"));
413
+ wdCache.set(wd, packageJSON);
414
+ return packageJSON[field];
415
+ }
416
+ async function getName(named, name, {
417
+ wd,
418
+ cwd,
419
+ workspaceName
420
+ }) {
421
+ const relativePath = cwd.replace(`${wd}/`, "");
422
+ let basename = path__default.default.basename(cwd);
423
+ if (typeof named === "function") {
424
+ return named(name, {
425
+ full: wd,
426
+ relative: cwd
427
+ });
428
+ }
429
+ let isParentMatched = false;
430
+ let matchedKey;
431
+ let matchedRule;
432
+ if (typeof named === "object") {
433
+ const isWD = cwd === wd;
434
+ if (isWD) {
435
+ const { rule } = await inquirer__default.default.prompt({
436
+ type: "list",
437
+ name: "rule",
438
+ message: "choose a rule",
439
+ default: "default",
440
+ choices: ["default"].concat(Object.keys(named))
441
+ });
442
+ if (rule !== "default") {
443
+ matchedKey = rule;
444
+ matchedRule = named[rule];
445
+ }
446
+ } else
447
+ for (const [key, value] of Object.entries(named)) {
448
+ if (micromatch.isMatch(relativePath, key)) {
449
+ matchedKey = key;
450
+ matchedRule = value;
451
+ break;
452
+ }
453
+ if (micromatch.isMatch(`${relativePath}/jiek_ignore_dont_use_same_file_name`, key)) {
454
+ isParentMatched = true;
455
+ matchedKey = key;
456
+ matchedRule = value;
457
+ break;
458
+ }
459
+ }
460
+ }
461
+ if (!matchedRule) {
462
+ matchedKey = "packages/*";
463
+ matchedRule = `@${workspaceName}/$basename`;
464
+ }
465
+ if (!matchedRule)
466
+ throw new Error("no matched rule");
467
+ if (!name && isParentMatched) {
468
+ basename = await inquirer__default.default.prompt({
469
+ type: "input",
470
+ name: "name",
471
+ message: `the matched rule is \`${String(matchedRule)}\`, please input the basename
472
+ `
473
+ }).then(({ name: name2 }) => name2);
474
+ }
475
+ if (typeof matchedRule === "function") {
476
+ return matchedRule(name, {
477
+ full: wd,
478
+ relative: cwd,
479
+ basename
480
+ });
481
+ }
482
+ if (typeof matchedRule === "string") {
483
+ const dirName = name ?? basename;
484
+ return [
485
+ matchedRule.replace(/\$basename/g, dirName),
486
+ matchedKey?.replace(/\/\*$/g, `/${dirName}`)
487
+ ];
488
+ }
489
+ throw new Error("no matched rule");
490
+ }
491
+ commander.program.command("init [name]").option("-t, --template <template>", "the package.json template file path or file content").action(async () => {
492
+ const [, name] = commander.program.args;
493
+ const cwd = process.cwd();
494
+ const { init = {} } = loadConfig() ?? {};
495
+ const { wd } = getWD();
496
+ const workspaceName = path__default.default.basename(wd);
497
+ const {
498
+ named,
499
+ template,
500
+ bug = {},
501
+ readme: _readme = README_TEMPLATE,
502
+ readmeTemplate
503
+ } = init;
504
+ const resolvedBug = {
505
+ template: "bug_report.yml",
506
+ labels: ["bug"],
507
+ ...bug
508
+ };
509
+ let readme = _readme;
510
+ if (readmeTemplate) {
511
+ const readmeTemplatePath = path__default.default.resolve(wd, readmeTemplate);
512
+ readme = fs__default.default.readFileSync(readmeTemplatePath, "utf-8");
513
+ }
514
+ const templateString = getTemplateStr(wd, template);
515
+ const { indent = " " } = detectIndent__default.default(templateString);
516
+ const formattingOptions = {
517
+ tabSize: indent.length,
518
+ insertSpaces: true
519
+ };
520
+ const passFields = [
521
+ "license",
522
+ "author"
523
+ ];
524
+ let newJSONString = templateString;
525
+ for (const field of passFields) {
526
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
527
+ newJSONString,
528
+ [field],
529
+ getWDPackageJSONFiled(wd, field),
530
+ { formattingOptions }
531
+ ));
532
+ }
533
+ let [pkgName, pkgDir] = await getName(named, name, {
534
+ wd,
535
+ cwd,
536
+ workspaceName
537
+ });
538
+ if (!pkgDir) {
539
+ const { dir } = await inquirer__default.default.prompt({
540
+ type: "input",
541
+ name: "dir",
542
+ message: "package directory",
543
+ default: name
544
+ });
545
+ pkgDir = dir;
546
+ }
547
+ if (!pkgName) {
548
+ const { name: inputName } = await inquirer__default.default.prompt({
549
+ type: "input",
550
+ name: "name",
551
+ message: "package name",
552
+ default: name
553
+ });
554
+ pkgName = inputName;
555
+ }
556
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(newJSONString, ["name"], pkgName, { formattingOptions }));
557
+ let pkgRepo = getWDPackageJSONFiled(wd, "repository");
558
+ if (typeof pkgRepo === "string") {
559
+ pkgRepo = {
560
+ type: "git",
561
+ url: pkgRepo,
562
+ directory: pkgDir
563
+ };
564
+ }
565
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
566
+ newJSONString,
567
+ ["repository"],
568
+ pkgRepo,
569
+ { formattingOptions }
570
+ ));
571
+ const homepage = `${pkgRepo?.url}/blob/master/${pkgDir}/README.md`;
572
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
573
+ newJSONString,
574
+ ["homepage"],
575
+ homepage,
576
+ { formattingOptions }
577
+ ));
578
+ let labels = resolvedBug.labels;
579
+ if (typeof labels === "function")
580
+ labels = labels({
581
+ name: pkgName,
582
+ dir: pkgDir
583
+ });
584
+ labels.push(`scope:${pkgName}`);
585
+ const bugs = `${pkgRepo?.url}/issues/new?template=${resolvedBug.template}&labels=${labels.join(",")}`;
586
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
587
+ newJSONString,
588
+ ["bugs"],
589
+ bugs,
590
+ { formattingOptions }
591
+ ));
592
+ function pkgDirTo(to) {
593
+ if (!pkgDir)
594
+ throw new Error("pkgDir is not defined");
595
+ return path__default.default.resolve(pkgDir, to);
596
+ }
597
+ if (!fs__default.default.existsSync(pkgDir))
598
+ fs__default.default.mkdirSync(pkgDir);
599
+ const pkgJSONFilePath = pkgDirTo("package.json");
600
+ if (fs__default.default.existsSync(pkgJSONFilePath)) {
601
+ throw new Error("package.json already exists");
602
+ }
603
+ fs__default.default.writeFileSync(pkgJSONFilePath, newJSONString);
604
+ console.log(newJSONString, "written to", pkgJSONFilePath);
605
+ const license = getWDPackageJSONFiled(wd, "license");
606
+ const readmeFilePath = pkgDirTo("README.md");
607
+ if (typeof readme === "function") {
608
+ readme = readme({
609
+ dir: pkgDir,
610
+ packageJson: JSON.parse(newJSONString)
611
+ });
612
+ }
613
+ const readmeContent = readme.replace(/\$name/g, pkgName).replace(/\$license/g, license);
614
+ fs__default.default.writeFileSync(readmeFilePath, readmeContent);
615
+ });
616
+
617
+ commander.program.command("publish").aliases(["pub", "p"]).option("-b, --bumper <bumper>", "bump version", "patch").option("-p, --preview", "preview publish").action(async ({ preview, bumper: bumper$1, ...options }) => {
618
+ actionRestore();
619
+ const { value = {} } = await getSelectedProjectsGraph() ?? {};
620
+ const selectedProjectsGraphEntries = Object.entries(value);
621
+ if (selectedProjectsGraphEntries.length === 0) {
622
+ throw new Error("no packages selected");
623
+ }
624
+ const mainfests = selectedProjectsGraphEntries.map(([dir, manifest]) => [
625
+ dir,
626
+ mergePackageJson(manifest, dir)
627
+ ]);
628
+ const passArgs = Object.entries(options).reduce((acc, [key, value2]) => {
629
+ if (value2) {
630
+ acc.push(`--${key}`, value2);
631
+ }
632
+ return acc;
633
+ }, []);
634
+ for (const [dir, manifest] of mainfests) {
635
+ const oldJSONString = fs__default.default.readFileSync(path__default.default.join(dir, "package.json"), "utf-8");
636
+ const oldJSON = JSON.parse(oldJSONString) ?? "0.0.0";
637
+ const newVersion = bumper.bump(oldJSON.version, bumper$1);
638
+ const { indent = " " } = detectIndent__default.default(oldJSONString);
639
+ const formattingOptions = {
640
+ tabSize: indent.length,
641
+ insertSpaces: true
642
+ };
643
+ let newJSONString = oldJSONString;
644
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
645
+ newJSONString,
646
+ ["version"],
647
+ newVersion,
648
+ { formattingOptions }
649
+ ));
650
+ for (const [key, value2] of Object.entries(manifest)) {
651
+ if (JSON.stringify(value2) === JSON.stringify(oldJSON[key]))
652
+ continue;
653
+ newJSONString = jsoncParser.applyEdits(newJSONString, jsoncParser.modify(
654
+ newJSONString,
655
+ ["publishConfig", key],
656
+ value2,
657
+ { formattingOptions }
658
+ ));
659
+ }
660
+ try {
661
+ fs__default.default.renameSync(path__default.default.join(dir, "package.json"), path__default.default.join(dir, "package.json.bak"));
662
+ fs__default.default.writeFileSync(path__default.default.join(dir, "package.json"), newJSONString);
663
+ console.log(newJSONString);
664
+ if (preview) {
665
+ console.warn("preview mode");
666
+ continue;
667
+ }
668
+ childProcess__namespace.execSync(["pnpm", "publish", "--access", "public", "--no-git-checks", ...passArgs].join(" "), {
669
+ cwd: dir,
670
+ stdio: "inherit"
671
+ });
672
+ const modifyVersionPackageJSON = jsoncParser.applyEdits(oldJSONString, jsoncParser.modify(oldJSONString, ["version"], newVersion, {}));
673
+ fs__default.default.writeFileSync(path__default.default.join(dir, "package.json.bak"), modifyVersionPackageJSON);
674
+ } finally {
675
+ fs__default.default.unlinkSync(path__default.default.join(dir, "package.json"));
676
+ fs__default.default.renameSync(path__default.default.join(dir, "package.json.bak"), path__default.default.join(dir, "package.json"));
677
+ }
678
+ }
679
+ actionDone();
680
+ });
681
+
682
+ commander.program.parse(process.argv);
2
683
  //# sourceMappingURL=cli.cjs.map