@cmmn/tools 1.1.0 → 1.2.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/bin.js CHANGED
@@ -2,11 +2,12 @@
2
2
 
3
3
  import {bundle} from "./bundle/bundle.js";
4
4
  import {compile} from "./compile/compile.js";
5
+ import {gen} from "./gen/gen.js";
5
6
 
6
7
  const [action, ...args] = process.argv.slice(2);
7
8
 
8
9
  const actions = {
9
- bundle, compile
10
+ bundle, compile, gen
10
11
  }
11
12
 
12
- actions[action](...args);
13
+ actions[action](...args);
package/bundle/bundle.js CHANGED
@@ -1,22 +1,33 @@
1
- import {getConfig} from "./rollup.config.js";
1
+ import {ConfigCreator} from "./rollup.config.js";
2
2
  import {rollup, watch} from "rollup";
3
3
  import fs from "fs";
4
4
  import path from "path";
5
5
  import fg from "fast-glob";
6
6
 
7
- function getPackageConfigs(rootDir, options) {
7
+ function getProjectConfig(rootDir, cmmn, options) {
8
+ const configCreator = new ConfigCreator({
9
+ ...options,
10
+ ...cmmn,
11
+ });
12
+ configCreator.setRootDir(rootDir);
13
+ return configCreator.getConfig();
14
+ }
15
+
16
+ function getPackageConfigs(rootDir, options, name = null) {
8
17
  const results = [];
9
18
  const pkg = JSON.parse(fs.readFileSync(path.join(rootDir, 'package.json')));
10
- for (let name in pkg.cmmn) {
11
- results.push(...getConfig({
12
- name,
13
- outDir: path.join(rootDir, pkg.cmmn[name].output ?? 'dist'),
14
- input: path.join(rootDir, pkg.cmmn[name].input ?? 'index.ts'),
15
- minify: options.includes('--prod'),
16
- devServer: options.includes('--run'),
17
- stats: options.includes('--stats'),
18
- module: pkg.cmmn[name].module ?? 'es'
19
- }))
19
+ if (name) {
20
+ results.push(...getProjectConfig(rootDir, pkg.cmmn[name], {
21
+ ...options,
22
+ name
23
+ }));
24
+ } else {
25
+ for (let name in pkg.cmmn) {
26
+ results.push(...getProjectConfig(rootDir, pkg.cmmn[name], {
27
+ ...options,
28
+ name
29
+ }));
30
+ }
20
31
  }
21
32
  return results;
22
33
  }
@@ -34,25 +45,29 @@ function getLernaSubPackages(lernaFile, options) {
34
45
  }
35
46
 
36
47
  function getConfigs(options) {
37
- if (options.includes('-b')) {
48
+ if (!options.input || options.project) {
38
49
  const rootDir = process.cwd();
39
50
  const lernaPath = path.join(rootDir, 'lerna.json');
40
51
  if (fs.existsSync(lernaPath)) {
41
52
  return getLernaSubPackages(lernaPath, options);
42
53
  }
54
+ return getPackageConfigs(process.cwd(), options);
55
+ }
56
+ if (options.input && !fs.existsSync(options.input)) {
57
+ return getPackageConfigs(process.cwd(), options, options.input);
43
58
  }
44
- const input = options.filter(x => !x.startsWith('-'))[0];
45
- return getConfig({
46
- input,
59
+ const creator = new ConfigCreator(options);
60
+ return creator.getConfig();
61
+ }
62
+
63
+ export async function bundle(...options) {
64
+ const configs = getConfigs({
65
+ input: options.filter(x => !x.startsWith('-'))[0],
66
+ project: options.includes('-b'),
47
67
  minify: options.includes('--prod'),
48
68
  devServer: options.includes('--run'),
49
69
  stats: options.includes('--stats'),
50
- module: 'es'
51
70
  });
52
- }
53
-
54
- export async function bundle(...options) {
55
- const configs = getConfigs(options);
56
71
  if (!options.includes('--watch')) {
57
72
  for (let config of configs) {
58
73
  console.log(`1. ${config.input} -> ${config.output.file}`);
@@ -3,59 +3,181 @@ import nodeResolve from '@rollup/plugin-node-resolve';
3
3
  import {terser} from "rollup-plugin-terser"
4
4
  import {visualizer} from 'rollup-plugin-visualizer';
5
5
  import styles from "rollup-plugin-styles";
6
+ import builtins from "rollup-plugin-node-builtins";
6
7
  import {string} from "rollup-plugin-string";
7
8
  import serve from 'rollup-plugin-serve'
8
9
  import livereload from 'rollup-plugin-livereload'
10
+ import fs from "fs";
11
+ import path from "path";
12
+ import html from '@open-wc/rollup-plugin-html';
13
+ /**
14
+ * @typedef {import(rollup).RollupOptions} RollupOptions
15
+ * @typedef {import(rollup).OutputOptions} OutputOptions
16
+ */
9
17
 
10
- export const getConfig = ({minify, input, devServer, module, stats, name, outDir}) => {
11
- const output = `${outDir ?? 'dist'}/${name ?? 'index'}-${module}${minify ? '.min' : ''}.js`;
12
- return [{
13
- input,
14
- output: {
15
- file: output,
16
- sourcemap: !minify,
17
- format: module,
18
- exports: 'auto',
19
- name: 'global'
20
- },
21
- onwarn: function () {
22
-
23
- },
24
- // prettier-ignore
25
- plugins: [
18
+ export class ConfigCreator {
19
+
20
+ /**
21
+ * @type {{
22
+ * minify: boolean,
23
+ * input: string,
24
+ * devServer: boolean,
25
+ * module: string,
26
+ * external: string[],
27
+ * stats: boolean,
28
+ * name: string,
29
+ * outDir: string,
30
+ * html: string,
31
+ * dedupe: string[]
32
+ * }}
33
+ */
34
+ options;
35
+
36
+ /**
37
+ * @type {string}
38
+ */
39
+ root = process.cwd();
40
+
41
+
42
+ constructor(options) {
43
+ this.options = {
44
+ ...options
45
+ };
46
+ }
47
+
48
+ setRootDir(rootDir){
49
+ this.root = rootDir;
50
+ }
51
+
52
+ get outDir(){
53
+ return path.join(this.root, this.options.outDir);
54
+ }
55
+
56
+ /**
57
+ *
58
+ * @returns {OutputOptions}
59
+ */
60
+ get output() {
61
+ // const output = `${this.options.name ?? 'index'}-${this.options.module}${this.options.minify ? '.min' : ''}.js`;
62
+ return {
63
+ entryFileNames: `[name]-${this.options.module}${this.options.minify ? '.min' : ''}.js`,
64
+ // file: output,
65
+ dir: this.outDir,
66
+ sourcemap: !this.options.minify,
67
+ format: this.options.module,
68
+ name: 'global',
69
+ };
70
+ }
71
+
72
+ get html(){
73
+ return html({
74
+ publicPath: '/',
75
+ dir: this.outDir,
76
+ template: () => fs.readFileSync(path.join(this.root, this.options.html), 'utf8')
77
+ });
78
+ }
79
+ get devServer(){
80
+ return serve({
81
+ open: false,
82
+ contentBase: [this.outDir, path.join(this.root, 'assets')],
83
+ port: 3001,
84
+ historyApiFallback: true
85
+ });
86
+ }
87
+
88
+ get livereload(){
89
+ return livereload({
90
+ watch: [this.outDir, path.join(this.root, 'assets')],
91
+ verbose: false, // Disable console output
92
+ // other livereload options
93
+ port: 12345,
94
+ delay: 300,
95
+ })
96
+ }
97
+
98
+ get visualizer(){
99
+ return visualizer({
100
+ open: true,
101
+ sourcemap: true,
102
+ template: 'treemap',
103
+ brotliSize: true,
104
+ filename: path.join(this.outDir, '/stats.html')
105
+ })
106
+ }
107
+
108
+ get plugins() {
109
+ const result = [
110
+ builtins(),
26
111
  nodeResolve({
27
112
  browser: true,
28
- dedupe: ['lib0']
113
+ dedupe: this.options.dedupe || []
114
+ }),
115
+ commonjs({
116
+ requireReturnsDefault: "namespace",
117
+ }),
118
+ styles({
119
+ mode: "emit",
29
120
  }),
30
- commonjs({}),
31
- styles({mode: "emit"}),
32
121
  string({
33
122
  include: /\.(html|svg|less|css)$/,
34
123
  }),
35
- ...(minify ? [terser({})] : []),
36
- ...(devServer ? [
37
- serve({
38
- open: false,
39
- contentBase: ['dist', 'assets'],
40
- port: 3001,
41
- historyApiFallback: true
42
- }), livereload({
43
- watch: ['dist', 'assets'],
44
- verbose: false, // Disable console output
45
-
46
- // other livereload options
47
- port: 12345,
48
- delay: 300,
49
- })] : []),
50
- ...(stats ? [
51
- visualizer({
52
- open: true,
53
- sourcemap: true,
54
- template: 'treemap',
55
- brotliSize: true,
56
- filename: 'dist/stats.html'
57
- }),
58
- ] : [])
59
- ]
60
- }];
61
- };
124
+ ];
125
+ if (this.options.html || this.options.input.endsWith('.html')){
126
+ result.push(this.html);
127
+ }
128
+ if (this.options.minify) {
129
+ result.push(terser({
130
+ module: true,
131
+ ecma: 2020,
132
+ compress: true,
133
+ keep_classnames: false,
134
+ keep_fnames: false,
135
+ mangle: true,
136
+ output: {
137
+ comments: false
138
+ }
139
+ }));
140
+ }
141
+ if (this.options.devServer) {
142
+ result.push(this.devServer, this.livereload);
143
+ }
144
+ if (this.options.stats){
145
+ result.push(this.visualizer);
146
+ }
147
+ return result;
148
+ }
149
+
150
+ /**
151
+ * @returns {RollupOptions[]}
152
+ */
153
+ getConfig() {
154
+ Object.assign(this.options,{
155
+ module: this.options.module || 'es',
156
+ external: this.options.external || [],
157
+ name: this.options.name || 'index',
158
+ outDir: this.options.outDir || 'dist'
159
+ });
160
+ if (this.options.external && typeof this.options.external === "string")
161
+ this.options.external = [this.options.external]
162
+ console.log(this.options);
163
+ return [{
164
+ input: {
165
+ [this.options.name]: path.join(this.root,this.options.input)
166
+ },
167
+ output: this.output,
168
+ external: (this.options.external || []).map(s => new RegExp(s)),
169
+ onwarn(warning) {
170
+ // Silence circular dependency warning for moment package
171
+ if (
172
+ warning.code === 'CIRCULAR_DEPENDENCY'
173
+ ) {
174
+ return
175
+ }
176
+
177
+ console.warn(`(!) ${warning.message}`)
178
+ },
179
+ plugins: this.plugins,
180
+ treeshake: this.options.minify ? "smallest" : "recommended"
181
+ }]
182
+ }
183
+ }
@@ -0,0 +1,38 @@
1
+ import ts from "ttypescript";
2
+ import {resolve} from 'path';
3
+
4
+ const rootDir = process.cwd();
5
+
6
+ export function compile(...flags) {
7
+
8
+ const host = ts.createSolutionBuilderWithWatchHost(ts.sys, createProgram);
9
+ host.useCaseSensitiveFileNames();
10
+
11
+ const builderFactory = flags.includes('--watch') ?
12
+ ts.createSolutionBuilderWithWatch :
13
+ ts.createSolutionBuilder;
14
+
15
+ const builder = builderFactory(host, [rootDir], {
16
+ incremental: true,
17
+ dry: false
18
+ }, {
19
+ excludeDirectories: ["node_modules", "dist"]
20
+ });
21
+ if (flags.includes('-b')) {
22
+ builder.cleanReferences(rootDir);
23
+ builder.buildReferences(rootDir);
24
+ } else {
25
+ builder.clean(rootDir);
26
+ builder.build(rootDir);
27
+ }
28
+ }
29
+
30
+ function createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) {
31
+ options.outDir = resolve(options.configFilePath, '../dist/esm');
32
+ options.declarationDir = resolve(options.configFilePath, '../dist/typings');
33
+ options.baseUrl = resolve(options.configFilePath, '../');
34
+ console.log('build', options.configFilePath);
35
+ return ts.createEmitAndSemanticDiagnosticsBuilderProgram(
36
+ rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences
37
+ )
38
+ }
@@ -0,0 +1,47 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "ES6",
4
+ "moduleResolution": "Node",
5
+ "target": "ES2019",
6
+ "composite": true,
7
+ "sourceMap": true,
8
+ "baseUrl": "./",
9
+ "experimentalDecorators": true,
10
+ "checkJs": false,
11
+ "outDir": "./dist/esm",
12
+ "skipLibCheck": true,
13
+ "skipDefaultLibCheck": true,
14
+ "allowJs": true,
15
+ "allowSyntheticDefaultImports": true,
16
+ "emitDecoratorMetadata": true ,
17
+ "noEmitHelpers": true,
18
+ "declarationDir": "./dist/typings",
19
+ "declaration": true,
20
+ "types": [
21
+ ],
22
+ "lib": [
23
+ "ES2020.BigInt",
24
+ "ESNext",
25
+ "DOM"
26
+ ],
27
+ "plugins": [
28
+ {
29
+ "transform": "@cmmn/tools/plugins/absolute-plugin.cjs",
30
+ "after": true
31
+ },
32
+ // Transform paths in output .js files
33
+ {
34
+ "transform": "typescript-transform-paths"
35
+ },
36
+ // Transform paths in output .d.ts files (Include this line if you output declarations files)
37
+ {
38
+ "transform": "typescript-transform-paths",
39
+ "afterDeclarations": true
40
+ }
41
+ ]
42
+ },
43
+ "exclude": [
44
+ "node_modules",
45
+ "dist"
46
+ ]
47
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cmmn/tools",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "di, base extensions, useful functions",
5
5
  "main": "dist/rollup.config.js",
6
6
  "type": "module",
@@ -13,7 +13,9 @@
13
13
  },
14
14
  "files": [
15
15
  "bin.js",
16
- "bundle/*"
16
+ "compile/*",
17
+ "bundle/*",
18
+ "plugins/*"
17
19
  ],
18
20
  "dependencies": {
19
21
  "less": "^4",
@@ -22,6 +24,7 @@
22
24
  "typescript-transform-paths": "^3.3.1"
23
25
  },
24
26
  "devDependencies": {
27
+ "@open-wc/rollup-plugin-html": "^1.2.5",
25
28
  "@rollup/plugin-commonjs": "^21",
26
29
  "@rollup/plugin-node-resolve": "^13",
27
30
  "@rollup/plugin-typescript": "^8",
@@ -29,6 +32,8 @@
29
32
  "fast-glob": "^3.2.11",
30
33
  "rollup": "^2",
31
34
  "rollup-plugin-livereload": "^2.0.5",
35
+ "rollup-plugin-node-builtins": "^2.1.2",
36
+ "rollup-plugin-node-globals": "^1.4.0",
32
37
  "rollup-plugin-serve": "^1.1.0",
33
38
  "rollup-plugin-string": "^3.0.0",
34
39
  "rollup-plugin-styles": "^4",
@@ -0,0 +1,50 @@
1
+ const ts = require("typescript");
2
+ const path = require("path");
3
+
4
+ function visitImportNode(importNode, sourceFile) {
5
+ const file = importNode.moduleSpecifier?.text;
6
+ if (!/\.(less|css|scss|sass|svg|png|html)/.test(file))
7
+ return;
8
+ const sourceFileDir = path.dirname(sourceFile.path);
9
+ const real = path.join(sourceFileDir, file);
10
+ return ts.updateImportDeclaration(importNode, importNode.decorators, importNode.modifiers, importNode.importClause, ts.createStringLiteral(real));
11
+ }
12
+
13
+ function visitRequireNode(importNode, sourceFile) {
14
+ if (!(importNode.expression.kind == ts.SyntaxKind.Identifier &&
15
+ importNode.expression.escapedText == "require")) {
16
+ return;
17
+ }
18
+ const file = importNode.arguments[0].text;
19
+ if (/\.(less|css|scss|sass|svg|png|html)/.test(file)) {
20
+ const sourceFileDir = path.dirname(sourceFile.path);
21
+ const real = path.join(sourceFileDir, file);
22
+ return ts.updateCall(importNode, importNode.expression, undefined, [ts.createStringLiteral(real)]);
23
+ }
24
+ }
25
+
26
+ const lessToStringTransformer = function (context) {
27
+ return (sourceFile) => {
28
+ function visitor(node) {
29
+ // if (node && node.kind == ts.SyntaxKind.ImportDeclaration) {
30
+ // return visitImportNode(node as ts.ImportDeclaration);
31
+ // }
32
+ if (node && ts.isCallExpression(node)) {
33
+ const result = visitRequireNode(node, sourceFile);
34
+ if (result)
35
+ return result;
36
+ }
37
+ if (node && ts.isImportDeclaration(node)) {
38
+ const result = visitImportNode(node, sourceFile);
39
+ if (result)
40
+ return result;
41
+ }
42
+ return ts.visitEachChild(node, visitor, context);
43
+ }
44
+
45
+ return ts.visitEachChild(sourceFile, visitor, context);
46
+ };
47
+ };
48
+ exports.default = function (program, pluginOptions) {
49
+ return lessToStringTransformer;
50
+ }
package/readme.md ADDED
@@ -0,0 +1,11 @@
1
+ ## Builder and bundler for your projects
2
+
3
+ ### Use cases:
4
+ `cmmn compile [target] [-b] [--watch]`
5
+ > Runs typescript compiler
6
+
7
+ `cmmn bundle [target] [-b] [--watch] [--run] [--prod]`
8
+ > Runs rollup bundler
9
+
10
+ `cmmn gen name directory [-n]`
11
+ > Generates component with template at directory