pkgbld 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Konstantin Shutkin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,78 @@
1
+ # pkgbld
2
+
3
+ Rollup based build tool for building libraries based on package.json config and simple CLI options.
4
+
5
+ It is simple building tool that supports building to different targets like: `es`, `cjs`, `umd` without additional trasformation other than minification using `terser` or preprocess using `rollup-plugin-preprocess`.
6
+
7
+ ## Why
8
+
9
+ It is created to easily build libraries that contains mutliple subpackages (exports, entry points) because it is not that easy to do at the moment with `microbundle`, `tsdx` or `ng-packagr`.
10
+
11
+ ## Installation
12
+
13
+ Using npm:
14
+ ```
15
+ npm install --save-dev pkgbld
16
+ ```
17
+
18
+ ## package.json
19
+
20
+ `pkgbld` expects name field to be filled in package.json file. `exports` field defined what entries/outputs should be build for this package.
21
+
22
+ ## CLI options
23
+
24
+ ### umd
25
+
26
+ ```
27
+ pkgbld --umd=index,core
28
+ ```
29
+
30
+ Where `index,core` should be replaced by entry points that should be comiled in umd format, index is top level `'.'` entry point.
31
+
32
+ If `package.json` defined umd field option will be defaulted to `index`.
33
+
34
+ ### compress
35
+
36
+ ```
37
+ pkgbld --compress=index,core
38
+ ```
39
+
40
+ Where `index,core` should be replaced by entry points that should be compressed using terser.
41
+
42
+ ### sourcemaps
43
+
44
+ ```
45
+ pkgbld --sourcemaps=es,cjs
46
+ ```
47
+
48
+ Where `es,cjs` should be replaced by targets for which sourcemaps should be generated. Default `umd`.
49
+
50
+ Supported targets for this option: `es`, `cjs` and `umd`.
51
+
52
+ ### formats
53
+
54
+ ```
55
+ pkgbld --formats=es
56
+ ```
57
+
58
+ Defines what formats to build, only supports `es` and `cjs` at the moment. Use `umd` flag to build umd target.
59
+
60
+ ### preprocess
61
+
62
+ ```
63
+ pkgbld --preprocess=index
64
+ ```
65
+
66
+ Defines what entry points/files should be preprocessed using `rollup-plugin-preprocess`.
67
+
68
+ ### dir
69
+
70
+ ```
71
+ pkgbld --dir=dist
72
+ ```
73
+
74
+ Directory to use for build.
75
+
76
+ # License
77
+
78
+ [MIT](./LICENSE)
@@ -0,0 +1 @@
1
+ export declare function cleanupDir(dir: string): Promise<void>;
@@ -0,0 +1,2 @@
1
+ import { getCliOptions } from './get-cli-options';
2
+ export declare function createSubpackages(inputs: string[], config: ReturnType<typeof getCliOptions>): Promise<void>;
@@ -0,0 +1,8 @@
1
+ export declare function getCliOptions(): {
2
+ umdTargets: string[];
3
+ compressTargets: string[];
4
+ sourcemapTargets: string[];
5
+ formats: string[];
6
+ preprocess: string[];
7
+ dir: string;
8
+ };
@@ -0,0 +1 @@
1
+ export declare function getPackage(): Promise<any[]>;
@@ -0,0 +1,4 @@
1
+ import { InternalModuleFormat, Plugin } from 'rollup';
2
+ import { getCliOptions } from './get-cli-options';
3
+ export declare function getBuildPlugins(format: InternalModuleFormat, config: ReturnType<typeof getCliOptions>): Plugin[];
4
+ export declare function getOutputPlugins(format: InternalModuleFormat, config: ReturnType<typeof getCliOptions>): Plugin[];
@@ -0,0 +1,4 @@
1
+ import { RollupOptions } from 'rollup';
2
+ import { getCliOptions } from './get-cli-options';
3
+ import { getHelpers } from './helpers';
4
+ export declare function getRollupConfigs(inputs: string[], config: ReturnType<typeof getCliOptions>, helpers: ReturnType<typeof getHelpers>): RollupOptions[];
@@ -0,0 +1,13 @@
1
+ import { getCliOptions } from './get-cli-options';
2
+ export declare function getHelpers(pkg: any): {
3
+ external: (id: string | string[]) => any;
4
+ getGlobalName: (anInput: string) => string;
5
+ getExternalGlobalName: (id: string) => string;
6
+ umdFilter: typeof umdFilter;
7
+ };
8
+ export declare function umdFilter(config: ReturnType<typeof getCliOptions>, filename: string): boolean;
9
+ export declare function toArray<T>(object: T): (T & any[]) | T[];
10
+ export declare function isExternalInput(id: string, inputs: string | string[], currentInput: string): boolean;
11
+ export declare function formatInput(input: string[] | string | undefined): string | undefined;
12
+ export declare function formatOutput(output: any, field: string): string | undefined;
13
+ export declare function getTimeDiff(starting: number): string;
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,319 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var logger = require('@niceties/logger');
5
+ var rollup = require('rollup');
6
+ var fs = require('fs/promises');
7
+ var path = require('path');
8
+ var minimist = require('minimist');
9
+ var typescript = require('rollup-plugin-typescript2');
10
+ var commonjs = require('@rollup/plugin-commonjs');
11
+ var resolve = require('@rollup/plugin-node-resolve');
12
+ var preprocess = require('rollup-plugin-preprocess');
13
+ var rollupPluginTerser = require('rollup-plugin-terser');
14
+ var isBuiltinModule = require('is-builtin-module');
15
+ var camelCase = require('lodash/camelCase');
16
+
17
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
18
+
19
+ var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
20
+ var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
21
+ var minimist__default = /*#__PURE__*/_interopDefaultLegacy(minimist);
22
+ var typescript__default = /*#__PURE__*/_interopDefaultLegacy(typescript);
23
+ var commonjs__default = /*#__PURE__*/_interopDefaultLegacy(commonjs);
24
+ var resolve__default = /*#__PURE__*/_interopDefaultLegacy(resolve);
25
+ var preprocess__default = /*#__PURE__*/_interopDefaultLegacy(preprocess);
26
+ var isBuiltinModule__default = /*#__PURE__*/_interopDefaultLegacy(isBuiltinModule);
27
+ var camelCase__default = /*#__PURE__*/_interopDefaultLegacy(camelCase);
28
+
29
+ async function createSubpackages(inputs, config) {
30
+ for (const input of inputs) {
31
+ const basename = path__default["default"].basename(input, '.ts');
32
+ if (basename !== 'index') {
33
+ const pkg = {
34
+ types: `../${config.dir}/${basename}.d.ts`
35
+ };
36
+ await fs__default["default"].mkdir(basename, { recursive: true });
37
+ await fs__default["default"].writeFile(`${basename}/package.json`, JSON.stringify(pkg, null, 2));
38
+ }
39
+ }
40
+ }
41
+
42
+ const defaults = {
43
+ formats: ['es', 'cjs'],
44
+ umdTargets: [],
45
+ compressTargets: ['umd'],
46
+ sourcemapTargets: ['umd'],
47
+ preprocess: [],
48
+ dir: 'dist'
49
+ };
50
+ function getCliOptions() {
51
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
52
+ const parsedArgs = minimist__default["default"](process.argv.slice(2));
53
+ const umdTargets = (_b = (_a = parsedArgs.umd) === null || _a === void 0 ? void 0 : _a.split(',').map((arg) => arg.trim())) !== null && _b !== void 0 ? _b : defaults.umdTargets;
54
+ const compressTargets = (_d = (_c = parsedArgs.compress) === null || _c === void 0 ? void 0 : _c.split(',').map((arg) => arg.trim())) !== null && _d !== void 0 ? _d : defaults.compressTargets;
55
+ const sourcemapTargets = (_f = (_e = parsedArgs.sourcemaps) === null || _e === void 0 ? void 0 : _e.split(',').map((arg) => arg.trim())) !== null && _f !== void 0 ? _f : defaults.sourcemapTargets;
56
+ const formats = (_h = (_g = parsedArgs.formats) === null || _g === void 0 ? void 0 : _g.split(',').map((arg) => arg.trim())) !== null && _h !== void 0 ? _h : defaults.formats;
57
+ const preprocess = (_k = (_j = parsedArgs.preprocess) === null || _j === void 0 ? void 0 : _j.split(',').map((arg) => arg.trim())) !== null && _k !== void 0 ? _k : defaults.preprocess;
58
+ const dir = (_l = parsedArgs.dir) !== null && _l !== void 0 ? _l : defaults.dir;
59
+ return {
60
+ umdTargets,
61
+ compressTargets,
62
+ sourcemapTargets,
63
+ formats,
64
+ preprocess,
65
+ dir
66
+ };
67
+ }
68
+
69
+ async function getPackage() {
70
+ const pkgPath = path__default["default"].resolve('package.json');
71
+ const buffer = await fs__default["default"].readFile(pkgPath);
72
+ return [pkgPath, JSON.parse(buffer.toString())];
73
+ }
74
+
75
+ function getBuildPlugins(format, config) {
76
+ const result = [
77
+ resolve__default["default"](),
78
+ commonjs__default["default"](),
79
+ typescript__default["default"]()
80
+ ];
81
+ if (config.preprocess.length) {
82
+ result.unshift(preprocess__default["default"]({ include: config.preprocess.map(name => `src/${name}.ts`), context: getPreprocessContext(format) }));
83
+ }
84
+ return result;
85
+ }
86
+ function getPreprocessContext(format) {
87
+ if (format == 'es') {
88
+ return { esm: true };
89
+ }
90
+ else {
91
+ return { cjs: true };
92
+ }
93
+ }
94
+ function getOutputPlugins(format, config) {
95
+ return config.compressTargets.includes(format) ? [rollupPluginTerser.terser({
96
+ mangle: {
97
+ properties: {
98
+ regex: /_$/
99
+ }
100
+ }
101
+ })] : [];
102
+ }
103
+
104
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
105
+ function getHelpers(pkg) {
106
+ const scopeTest = /(@.+)\/.+$/g.exec(pkg.name);
107
+ let scope = undefined;
108
+ if (scopeTest && scopeTest[0]) {
109
+ scope = scopeTest[0];
110
+ }
111
+ const external = scope != null
112
+ ? (id) => id.indexOf('node_modules') >= 0 || id.indexOf(scope) >= 0 || isBuiltinModule__default["default"](id)
113
+ : (id) => id.indexOf('node_modules') >= 0 || isBuiltinModule__default["default"](id);
114
+ function getGlobalName(anInput) {
115
+ return camelCase__default["default"](path__default["default"].join(pkg.name, path__default["default"].basename(anInput, '.ts') !== 'index' ? path__default["default"].basename(anInput, '.ts') : ''));
116
+ }
117
+ function getExternalGlobalName(id) {
118
+ if (path__default["default"].isAbsolute(id)) {
119
+ return getGlobalName(path__default["default"].relative(__dirname, id));
120
+ }
121
+ return camelCase__default["default"](id);
122
+ }
123
+ return {
124
+ external,
125
+ getGlobalName,
126
+ getExternalGlobalName,
127
+ umdFilter
128
+ };
129
+ }
130
+ function umdFilter(config, filename) {
131
+ const id = path__default["default"].basename(filename, '.ts');
132
+ return config.umdTargets.includes(id);
133
+ }
134
+ function toArray(object) {
135
+ if (Array.isArray(object)) {
136
+ return object;
137
+ }
138
+ return [object];
139
+ }
140
+ function isExternalInput(id, inputs, currentInput) {
141
+ let normalizedPath;
142
+ if (path__default["default"].isAbsolute(id)) {
143
+ normalizedPath = './' + path__default["default"].relative(process.cwd(), id);
144
+ }
145
+ else {
146
+ normalizedPath = './' + path__default["default"].join('src', id + '.ts');
147
+ }
148
+ return normalizedPath !== currentInput && inputs.includes(normalizedPath);
149
+ }
150
+ function formatInput(input) {
151
+ return Array.isArray(input) ? input.join(', ') : input;
152
+ }
153
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
154
+ function formatOutput(output, field) {
155
+ return Array.isArray(output) ? output.map(item => item[field]).join(', ') : output[field];
156
+ }
157
+ function getTimeDiff(starting) {
158
+ const now = Date.now();
159
+ if (now - starting > 1000) {
160
+ return `${((now - starting) / 1000).toFixed(1)}s`;
161
+ }
162
+ return `${now - starting}ms`;
163
+ }
164
+
165
+ function getRollupConfigs(inputs, config, helpers) {
166
+ const configs = [];
167
+ if (config.formats.includes('es')) {
168
+ configs.push({
169
+ input: inputs,
170
+ output: {
171
+ format: 'es',
172
+ dir: config.dir,
173
+ entryFileNames: '[name].mjs',
174
+ chunkFileNames: '[name].mjs',
175
+ plugins: getOutputPlugins('es', config),
176
+ sourcemap: config.sourcemapTargets.includes('es')
177
+ },
178
+ plugins: getBuildPlugins('es', config),
179
+ external: helpers.external
180
+ });
181
+ }
182
+ if (config.formats.includes('cjs')) {
183
+ configs.push({
184
+ input: inputs,
185
+ output: {
186
+ format: 'cjs',
187
+ dir: config.dir,
188
+ entryFileNames: '[name].cjs',
189
+ chunkFileNames: '[name].cjs',
190
+ exports: 'auto',
191
+ plugins: getOutputPlugins('cjs', config),
192
+ sourcemap: config.sourcemapTargets.includes('cjs')
193
+ },
194
+ plugins: getBuildPlugins('cjs', config),
195
+ external: helpers.external
196
+ });
197
+ }
198
+ const umdConfigs = inputs.filter((input) => umdFilter(config, input)).map(currentInput => ({
199
+ input: currentInput,
200
+ output: {
201
+ format: 'umd',
202
+ dir: config.dir,
203
+ entryFileNames: '[name].umd.js',
204
+ name: helpers.getGlobalName(currentInput),
205
+ globals: helpers.getExternalGlobalName,
206
+ plugins: getOutputPlugins('umd', config),
207
+ sourcemap: config.sourcemapTargets.includes('umd')
208
+ },
209
+ plugins: getBuildPlugins('umd', config),
210
+ external: (id) => helpers.external(id) || isExternalInput(id, inputs, currentInput)
211
+ }));
212
+ if (umdConfigs && umdConfigs.length) {
213
+ configs.push(...umdConfigs);
214
+ }
215
+ return configs;
216
+ }
217
+
218
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
219
+ function processPackage(pkg, config) {
220
+ var _a;
221
+ const input = [];
222
+ const logger$1 = logger.createLogger();
223
+ if (typeof pkg.name !== 'string') {
224
+ logger$1.finish('expecting name to be a string in package.json', 3 /* error */);
225
+ process.exit(-1);
226
+ }
227
+ if (!Array.isArray(pkg.files)) {
228
+ pkg.files = [];
229
+ }
230
+ if (!pkg.files.includes(config.dir)) {
231
+ pkg.files.push(config.dir);
232
+ }
233
+ if (typeof pkg.exports !== 'object') {
234
+ pkg.exports = {};
235
+ }
236
+ if (pkg.exports['.'] == null) {
237
+ pkg.exports['.'] = {};
238
+ }
239
+ if (typeof pkg.umd === 'string') {
240
+ pkg.umd = `./${config.dir}/index.umd.js`;
241
+ if (!config.umdTargets.includes('index')) {
242
+ config.umdTargets.push('index');
243
+ }
244
+ }
245
+ if (typeof pkg.main !== 'string') {
246
+ pkg.main = `./${config.dir}/index.cjs`;
247
+ }
248
+ if (pkg.main !== pkg.exports['.'].require) {
249
+ pkg.exports['.'].require = pkg.main;
250
+ }
251
+ if (typeof pkg.module !== 'string') {
252
+ pkg.module = `./${config.dir}/index.mjs`;
253
+ }
254
+ if (pkg.module !== ((_a = pkg.exports['.']) === null || _a === void 0 ? void 0 : _a.default)) {
255
+ pkg.exports['.'].default = pkg.module;
256
+ }
257
+ if (umdFilter(config, 'index')) {
258
+ pkg.unpkg = `./${config.dir}/index.umd.js`;
259
+ }
260
+ for (const id in pkg.exports) {
261
+ const basename = id == '.' ? 'index' : path__default["default"].basename(id);
262
+ if (typeof pkg.exports[id] !== 'object') {
263
+ pkg.exports[id] = {};
264
+ }
265
+ pkg.exports[id].require = `./${config.dir}/${basename}.cjs`;
266
+ pkg.exports[id].default = `./${config.dir}/${basename}.mjs`;
267
+ if (basename !== 'index') {
268
+ if (!pkg.files.includes(basename)) {
269
+ pkg.files.push(basename);
270
+ }
271
+ }
272
+ input.push(`./src/${basename}.ts`);
273
+ }
274
+ return input;
275
+ }
276
+
277
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
278
+ async function writePackage(pkgPath, pkg) {
279
+ await fs__default["default"].writeFile(pkgPath, JSON.stringify(pkg, null, 2));
280
+ }
281
+
282
+ async function cleanupDir(dir) {
283
+ try {
284
+ await fs__default["default"].rm(dir, { recursive: true });
285
+ }
286
+ catch (e) {
287
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
288
+ if (e['code'] !== 'ENOENT') {
289
+ throw e;
290
+ }
291
+ }
292
+ }
293
+
294
+ async function execute() {
295
+ try {
296
+ const [pkgPath, pkg] = await getPackage();
297
+ const config = getCliOptions();
298
+ const inputs = processPackage(pkg, config);
299
+ const helpers = getHelpers(pkg);
300
+ const rollupConfigs = getRollupConfigs(inputs, config, helpers);
301
+ await cleanupDir(config.dir);
302
+ for (const config of rollupConfigs) {
303
+ const logger$1 = logger.createLogger();
304
+ const time = Date.now();
305
+ logger$1.start(`building ${formatInput(config.input)} → ${formatOutput(config.output, 'dir')}, ${formatOutput(config.output, 'format')}`, 1 /* info */);
306
+ const bundle = await rollup.rollup(config);
307
+ await Promise.all(toArray(config.output).map(config => bundle.write(config)));
308
+ await bundle.close();
309
+ logger$1.finish(`finished ${formatInput(config.input)} → ${formatOutput(config.output, 'dir')}, ${formatOutput(config.output, 'format')} in ${getTimeDiff(time)}`, 1 /* info */);
310
+ }
311
+ await writePackage(pkgPath, pkg);
312
+ await createSubpackages(inputs, config);
313
+ }
314
+ catch (e) {
315
+ logger.createLogger().finish(`${e}}`, 3 /* error */);
316
+ process.exit(-1);
317
+ }
318
+ }
319
+ execute();
@@ -0,0 +1,2 @@
1
+ import { getCliOptions } from './get-cli-options';
2
+ export declare function processPackage(pkg: any, config: ReturnType<typeof getCliOptions>): string[];
File without changes
@@ -0,0 +1 @@
1
+ export declare function writePackage(pkgPath: string, pkg: any): Promise<void>;
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "version": "1.1.0",
3
+ "license": "MIT",
4
+ "name": "pkgbld",
5
+ "author": {
6
+ "name": "Konstantin Shutkin"
7
+ },
8
+ "funding": "https://www.donationalerts.com/r/excitingcode",
9
+ "bin": "./dist/index.js",
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "engines": {
14
+ "node": ">=15"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/kshutkin/package-build.git"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/kshutkin/rollup-extras/issues"
22
+ },
23
+ "homepage": "https://github.com/kshutkin/package-build/README.md",
24
+ "keywords": [
25
+ "pkgbld",
26
+ "build",
27
+ "exports",
28
+ "rollup"
29
+ ],
30
+ "scripts": {
31
+ "build": "rimraf dist && rollup -c && node binify.js",
32
+ "lint": "eslint ./src",
33
+ "semantic-release": "npx semantic-release"
34
+ },
35
+ "devDependencies": {
36
+ "@semantic-release/changelog": "6.0.1",
37
+ "@semantic-release/commit-analyzer": "9.0.1",
38
+ "@semantic-release/git": "10.0.1",
39
+ "@semantic-release/npm": "8.0.2",
40
+ "@semantic-release/release-notes-generator": "10.0.2",
41
+ "@types/lodash": "4.14.178",
42
+ "@typescript-eslint/eslint-plugin": "5.8.0",
43
+ "@typescript-eslint/parser": "5.8.0",
44
+ "conventional-changelog-angular": "5.0.13",
45
+ "eslint": "8.5.0",
46
+ "semantic-release": "18.0.0",
47
+ "rimfar": "3.0.2-omega"
48
+ },
49
+ "dependencies": {
50
+ "@niceties/logger": "1.0.4",
51
+ "is-builtin-module": "3.1.0",
52
+ "lodash": "4.17.21",
53
+ "rollup": "2.60.1",
54
+ "rollup-plugin-terser": "7.0.2",
55
+ "rollup-plugin-typescript2": "0.31.1",
56
+ "rollup-plugin-preprocess": "0.0.4",
57
+ "@rollup/plugin-commonjs": "21.0.1",
58
+ "@rollup/plugin-node-resolve": "13.0.6",
59
+ "typescript": "4.5.x",
60
+ "minimist": "1.2.5"
61
+ }
62
+ }