@bpmn-io/lint-core 0.0.0-stage → 0.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
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018-present bpmn.io Contributors
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
13
+ all 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
21
+ THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,33 @@
1
- # Temporary Holding Version
1
+ # @bpmn-io/lint-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Shared implementation of [bpmnlint](https://github.com/bpmn-io/bpmnlint) and [dmnlint](https://github.com/bpmn-io/dmnlint).
4
+
5
+ > **This package is an implementation detail.**
6
+ > It has no stable API and may change in any release.
7
+ > Depend on [`bpmnlint`](https://github.com/bpmn-io/bpmnlint) or [`dmnlint`](https://github.com/bpmn-io/dmnlint) instead.
8
+
9
+ ## How it works
10
+
11
+ Every module is a factory that is bound to a _product_:
12
+
13
+ ```javascript
14
+ const { createLinter } = require('@bpmn-io/lint-core');
15
+
16
+ const product = {
17
+ name: 'bpmnlint',
18
+
19
+ // optional, defaults to `${ name }-plugin-`
20
+ pluginPrefix: 'bpmnlint-plugin-'
21
+ };
22
+
23
+ const Linter = createLinter(product);
24
+ ```
25
+
26
+ The product determines
27
+
28
+ * the package that rules and configurations are loaded from by default (`name`)
29
+ * how plugins are named (`pluginPrefix`)
30
+
31
+ ## License
32
+
33
+ MIT
package/lib/cli.js ADDED
@@ -0,0 +1,469 @@
1
+ const { readFile } = require('node:fs/promises');
2
+ const { writeFileSync, existsSync } = require('node:fs');
3
+ const { resolve: resolvePath } = require('node:path');
4
+ const process = require('node:process');
5
+
6
+ const mri = require('mri');
7
+ const colors = require('ansi-colors');
8
+
9
+ colors.enabled = require('color-support').hasBasic;
10
+
11
+ const tinyGlob = require('tiny-glob');
12
+
13
+ const Table = require('cli-table');
14
+
15
+ const pluralize = require('pluralize');
16
+
17
+ const { pathStringify } = require('@bpmn-io/moddle-utils');
18
+
19
+ const { normalizeProduct } = require('./product');
20
+
21
+ const { createScopedRequire } = require('./resolver/helper');
22
+
23
+ /**
24
+ * @typedef { import('./types.js').Product } Product
25
+ * @typedef { import('./types.js').ModdleElement } ModdleElement
26
+ * @typedef { Error & { element: ModdleElement } } ImportWarning
27
+ */
28
+
29
+ const {
30
+ red,
31
+ yellow,
32
+ underline,
33
+ bold,
34
+ magenta
35
+ } = colors;
36
+
37
+ const categoryMap = {
38
+ warn: 'warning'
39
+ };
40
+
41
+
42
+ /**
43
+ * Create the command line interface for the given product.
44
+ *
45
+ * @param { {
46
+ * product: Product,
47
+ * version: string,
48
+ * Linter: any,
49
+ * NodeResolver: any,
50
+ * createModdle: (extensions: Record<string, any>) => any,
51
+ * fileType: string,
52
+ * help: string,
53
+ * docsUrl: string,
54
+ * rcFile?: string,
55
+ * defaultConfig?: string
56
+ * } } options
57
+ *
58
+ * @return { { run: (argv?: string[]) => Promise<void> } }
59
+ */
60
+ function createCli(options) {
61
+
62
+ const {
63
+ product,
64
+ version,
65
+ Linter,
66
+ NodeResolver,
67
+ createModdle: createProductModdle,
68
+ fileType,
69
+ help,
70
+ docsUrl
71
+ } = options;
72
+
73
+ const {
74
+ name
75
+ } = normalizeProduct(product);
76
+
77
+ const {
78
+ rcFile = `.${ name }rc`,
79
+ defaultConfig = `${ name }:recommended`
80
+ } = options;
81
+
82
+ const defaultConfigContents = `{
83
+ "extends": "${ defaultConfig }"
84
+ }`;
85
+
86
+
87
+ /**
88
+ * Reads XML form path and return moddle object
89
+ *
90
+ * @param { string } diagramXML
91
+ * @param { any } moddle
92
+ *
93
+ * @return { Promise<{ moddleElement?: any; warnings: Error[], error?: Error }> } parseResult
94
+ */
95
+ async function parseDiagram(diagramXML, moddle) {
96
+
97
+ try {
98
+ const {
99
+ rootElement: moddleElement,
100
+ warnings = []
101
+ } = await moddle.fromXML(diagramXML);
102
+
103
+ return {
104
+ moddleElement,
105
+ warnings
106
+ };
107
+ } catch (error) {
108
+
109
+ const {
110
+
111
+ // @ts-expect-error
112
+ warnings = []
113
+ } = error;
114
+
115
+ return {
116
+
117
+ // @ts-expect-error
118
+ error,
119
+ warnings
120
+ };
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Prints lint results to the console
126
+ *
127
+ * @param {String} filePath
128
+ * @param {Object} results
129
+ */
130
+ function printReports(filePath, results) {
131
+
132
+ let errorCount = 0;
133
+ let warningCount = 0;
134
+
135
+ const table = createTable();
136
+
137
+ Object.entries(results).forEach(function([ name, reports ]) {
138
+
139
+ reports.forEach(function(report) {
140
+
141
+ const {
142
+ category,
143
+ id,
144
+ message,
145
+ name: reportName
146
+ } = report;
147
+
148
+ table.push(tableEntry({
149
+ category,
150
+ id,
151
+ message,
152
+ name: reportName || name
153
+ }));
154
+
155
+ if (category === 'error') {
156
+ errorCount++;
157
+ } else {
158
+ warningCount++;
159
+ }
160
+ });
161
+ });
162
+
163
+ const problemCount = warningCount + errorCount;
164
+
165
+ if (problemCount) {
166
+ console.log();
167
+ console.log(underline(resolvePath(filePath)));
168
+ console.log(table.toString());
169
+ }
170
+
171
+ return {
172
+ errorCount,
173
+ warningCount
174
+ };
175
+ }
176
+
177
+ async function lintDiagram(diagramPath, config, moddle) {
178
+
179
+ let diagramXML;
180
+
181
+ try {
182
+ diagramXML = await readFile(resolvePath(diagramPath), 'utf-8');
183
+ } catch (error) {
184
+ throw errorAndExit(`Error: Failed to read ${diagramPath}\n\n%s`, /** @type { Error } */ (error).message);
185
+ }
186
+
187
+
188
+ const {
189
+ error: importError,
190
+ warnings: importWarnings,
191
+ moddleElement
192
+ } = await parseDiagram(diagramXML, moddle);
193
+
194
+ if (importError) {
195
+ return printReports(diagramPath, {
196
+ '': [
197
+ {
198
+ message: 'Parse error: ' + importError.message,
199
+ category: 'error'
200
+ }
201
+ ]
202
+ });
203
+ }
204
+
205
+ const importReports = importWarnings.length ? {
206
+ '': importWarnings.map(function(warning) {
207
+
208
+ const {
209
+ element,
210
+ message
211
+ } = /** @type { ImportWarning } */ (warning);
212
+
213
+ const id = element && element.id;
214
+
215
+ return {
216
+ id,
217
+ message: 'Import warning: ' + message.split(/\n/)[0],
218
+ category: 'error'
219
+ };
220
+ })
221
+ } : {};
222
+
223
+ try {
224
+ const linter = new Linter({
225
+ config,
226
+ resolver: new NodeResolver()
227
+ });
228
+
229
+ const lintReports = await linter.lint(moddleElement);
230
+
231
+ const allResults = {
232
+ ...importReports,
233
+ ...lintReports
234
+ };
235
+
236
+ return printReports(diagramPath, allResults);
237
+ } catch (e) {
238
+ throw errorAndExit(e);
239
+ }
240
+ }
241
+
242
+ async function lint(files, config, maxWarnings) {
243
+
244
+ let errorCount = 0;
245
+ let warningCount = 0;
246
+
247
+ console.log();
248
+
249
+ const moddle = createModdle(config);
250
+
251
+ for (let i = 0; i < files.length; i++) {
252
+ let results = await lintDiagram(files[i], config, moddle);
253
+
254
+ errorCount += results.errorCount;
255
+ warningCount += results.warningCount;
256
+ }
257
+
258
+ const problemCount = errorCount + warningCount;
259
+
260
+ if (problemCount) {
261
+
262
+ const color = warningCount ? boldYellow : boldRed;
263
+
264
+ console.log();
265
+ console.log(color(
266
+ `✖ ${problemCount} ${pluralize('problem', problemCount)} (${errorCount} ${pluralize('error', errorCount)}, ${warningCount} ${pluralize('warning', warningCount)})`
267
+ ));
268
+ }
269
+
270
+ if (errorCount || (maxWarnings !== -1 && warningCount > maxWarnings)) {
271
+ process.exit(1);
272
+ }
273
+
274
+ }
275
+
276
+ /**
277
+ * Create moddle instance with extensions from the config.
278
+ *
279
+ * @param { any } config
280
+ *
281
+ * @return { any }
282
+ */
283
+ function createModdle(config) {
284
+ const scopedRequire = createScopedRequire(process.cwd());
285
+
286
+ const options = config.moddleExtensions || {};
287
+
288
+ for (const key in options) {
289
+ const extension = options[key];
290
+
291
+ try {
292
+ options[key] = scopedRequire(extension);
293
+ } catch (error) {
294
+ errorAndExit('Error: Could not load moddle extension <%s> from %s\n\n', key, extension, /** @type { Error } */ (error).message);
295
+ }
296
+ }
297
+
298
+ try {
299
+ return createProductModdle(options);
300
+ } catch (error) {
301
+ errorAndExit('Error: Could not create moddle instance\n\n%s', /** @type { Error } */ (error).message);
302
+ }
303
+ }
304
+
305
+ async function run(argv = process.argv.slice(2)) {
306
+
307
+ const {
308
+ help: showHelp,
309
+ init,
310
+ version: showVersion,
311
+ config: configOverridePath,
312
+ 'max-warnings': maxWarnings,
313
+ _: files
314
+ } = mri(argv, {
315
+ string: [ 'config' ],
316
+ alias: {
317
+ c: 'config'
318
+ },
319
+ default: {
320
+ 'max-warnings': -1
321
+ }
322
+ });
323
+
324
+ if (showVersion) {
325
+ return showVersionAndExit(version);
326
+ }
327
+
328
+ if (showHelp) {
329
+ return infoAndExit(help);
330
+ }
331
+
332
+ if (init) {
333
+ if (existsSync(rcFile)) {
334
+ throw errorAndExit(`Not overriding existing ${ rcFile }`);
335
+ }
336
+
337
+ writeFileSync(rcFile, defaultConfigContents, 'utf8');
338
+
339
+ throw infoAndExit(`Created ${magenta(rcFile)} file`);
340
+ }
341
+
342
+ if (files.length === 0) {
343
+ throw errorAndExit(`Error: ${ fileType } file path missing`);
344
+ }
345
+
346
+ const configPath = configOverridePath || rcFile;
347
+
348
+ let configString, config;
349
+
350
+ try {
351
+ configString = await readFile(configPath, 'utf-8');
352
+ } catch (error) {
353
+
354
+ const message = (
355
+ configOverridePath
356
+ ? `Error: Could not read ${ magenta(configOverridePath) }`
357
+ : `Error: Could not locate local ${ magenta(rcFile) } file. Create one via
358
+
359
+ ${magenta(`${ name } --init`)}
360
+
361
+ Learn more about configuring ${ name }: ${ docsUrl }`
362
+ );
363
+
364
+ throw errorAndExit(message);
365
+ }
366
+
367
+ try {
368
+ config = JSON.parse(configString);
369
+ } catch (error) {
370
+ throw errorAndExit('Error: Could not parse %s\n\n%s', configPath, /** @type { Error } */ (error).message);
371
+ }
372
+
373
+ const actualFiles = await glob(files);
374
+
375
+ return lint(actualFiles, config, maxWarnings);
376
+ }
377
+
378
+ return {
379
+ run: (argv) => run(argv).catch(errorAndExit)
380
+ };
381
+ }
382
+
383
+ module.exports = {
384
+ createCli
385
+ };
386
+
387
+
388
+ // helpers ///////////////////////////
389
+
390
+ function boldRed(str) {
391
+ return bold(red(str));
392
+ }
393
+
394
+ function boldYellow(str) {
395
+ return bold(yellow(str));
396
+ }
397
+
398
+ function glob(files) {
399
+ return Promise.all(
400
+ files.map(
401
+ file => tinyGlob(file, { dot: true })
402
+ )
403
+ ).then(files => [].concat(...files));
404
+ }
405
+
406
+ /**
407
+ * Logs a formatted message
408
+ */
409
+ function tableEntry(report) {
410
+ let {
411
+ category,
412
+ id = '',
413
+ message,
414
+ name = '',
415
+ path
416
+ } = report;
417
+
418
+ if (path) {
419
+ id = `${ id }#${ pathStringify(path) }`;
420
+ }
421
+
422
+ const color = category === 'error' ? red : yellow;
423
+
424
+ return [ id, color(categoryMap[ category ] || category), message, name ];
425
+ }
426
+
427
+ function createTable() {
428
+ return new Table({
429
+ chars: {
430
+ 'top': '',
431
+ 'top-mid': '',
432
+ 'top-left': '',
433
+ 'top-right': '',
434
+ 'bottom': '',
435
+ 'bottom-mid': '',
436
+ 'bottom-left': '',
437
+ 'bottom-right': '',
438
+ 'left': ' ',
439
+ 'left-mid': '',
440
+ 'mid': '',
441
+ 'mid-mid': '',
442
+ 'right': '',
443
+ 'right-mid': '',
444
+ 'middle': ' '
445
+ },
446
+ style: {
447
+ 'padding-left': 0,
448
+ 'padding-right': 0
449
+ }
450
+ });
451
+ }
452
+
453
+ function errorAndExit(...args) {
454
+ console.error(...args);
455
+
456
+ process.exit(1);
457
+ }
458
+
459
+ function showVersionAndExit(version) {
460
+ console.log(version);
461
+
462
+ process.exit(0);
463
+ }
464
+
465
+ function infoAndExit(...args) {
466
+ console.log(...args);
467
+
468
+ process.exit(0);
469
+ }
package/lib/index.js ADDED
@@ -0,0 +1,11 @@
1
+ const { createLinter } = require('./linter');
2
+ const StaticResolver = require('./resolver/static-resolver');
3
+ const traverse = require('./traverse');
4
+ const testRule = require('./test-rule');
5
+
6
+ module.exports = {
7
+ createLinter,
8
+ StaticResolver,
9
+ traverse,
10
+ testRule
11
+ };