Merge branch 'sidv/vitestEsbuildOnly' into sidv/viteVitest

* sidv/vitestEsbuildOnly:
  Merge vitest & esbuild
  Merge vitest
  Revert "fix(test): No esm exports"
  fix(test): No esm exports
  unify Jison tranformers
  Fix jest
  fix: imports in HTML
  Revert "Add diagramAPI to outfile"
  Add `type: module` to package.json
  Update mermaid version
  Fix ports
  Fix mjs resolution
  Fix import errors
  fix: conflict
  ESM test
  Add local jison linting
  chore: cleanup
  chore: Remove webpack & babel dependencies
  feat: Remove webpack
This commit is contained in:
Sidharth Vinod 2022-09-21 00:15:11 +05:30
commit d7093c4891
No known key found for this signature in database
GPG Key ID: FB5CCD378D3907CD
46 changed files with 944 additions and 3117 deletions

View File

@ -13,8 +13,8 @@ build(iifeBuild({ minify: false, watch })).catch(handler);
build(esmBuild({ minify: false, watch })).catch(handler);
// mermaid.min.js
build(esmBuild()).catch(handler);
// mermaid.esm.min.mjs
build(iifeBuild()).catch(handler);
// mermaid.esm.min.mjs
build(esmBuild()).catch(handler);
// mermaid.core.mjs (node_modules unbundled)
build(esmCoreBuild()).catch(handler);

View File

@ -0,0 +1,14 @@
const { Generator } = require('jison');
exports.transformJison = (src) => {
const parser = new Generator(src, {
moduleType: 'js',
'token-stack': true,
});
const source = parser.generate({ moduleMain: '() => {}' });
const exporter = `
parser.parser = parser;
export { parser };
export default parser;
`;
return `${source} ${exporter}`;
};

View File

@ -1,53 +1,79 @@
const esbuild = require('esbuild');
const http = require('http');
const path = require('path');
const { iifeBuild } = require('./util.cjs');
const { iifeBuild, esmBuild } = require('./util.cjs');
const express = require('express');
// Start esbuild's server on a random local port
esbuild
.serve(
{
servedir: path.join(__dirname, '..'),
// Start 2 esbuild servers. One for IIFE and one for ESM
// Serve 2 static directories: demo & cypress/platform
// Have 3 entry points:
// mermaid: './src/mermaid',
// e2e: './cypress/platform/viewer.js',
// 'bundle-test': './cypress/platform/bundle-test.js',
const getEntryPointsAndExtensions = (format) => {
return {
entryPoints: {
mermaid: './src/mermaid',
e2e: 'cypress/platform/viewer.js',
'bundle-test': 'cypress/platform/bundle-test.js',
},
iifeBuild({ minify: false })
)
.then((result) => {
// The result tells us where esbuild's local server is
const { host, port } = result;
outExtension: { '.js': format === 'iife' ? '.js' : '.esm.mjs' },
};
};
// Then start a proxy server on port 3000
http
.createServer((req, res) => {
if (req.url.includes('mermaid.js')) {
req.url = '/dist/mermaid.js';
const generateHandler = (server) => {
return (req, res) => {
const options = {
hostname: server.host,
port: server.port,
path: req.url,
method: req.method,
headers: req.headers,
};
// Forward each incoming request to esbuild
const proxyReq = http.request(options, (proxyRes) => {
// If esbuild returns "not found", send a custom 404 page
if (proxyRes.statusCode === 404) {
if (!req.url.endsWith('.html')) {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>A custom 404 page</h1>');
return;
}
const options = {
hostname: host,
port: port,
path: req.url,
method: req.method,
headers: req.headers,
};
}
// Otherwise, forward the response from esbuild to the client
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});
// Forward the body of the request to esbuild
req.pipe(proxyReq, { end: true });
};
};
// Forward each incoming request to esbuild
const proxyReq = http.request(options, (proxyRes) => {
// If esbuild returns "not found", send a custom 404 page
console.error('pp', req.url);
if (proxyRes.statusCode === 404) {
if (!req.url.endsWith('.html')) {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>A custom 404 page</h1>');
return;
}
}
(async () => {
const iifeServer = await esbuild.serve(
{},
{
...iifeBuild({ minify: false, outfile: undefined, outdir: 'dist' }),
...getEntryPointsAndExtensions('iife'),
}
);
const esmServer = await esbuild.serve(
{},
{
...esmBuild({ minify: false, outfile: undefined, outdir: 'dist' }),
...getEntryPointsAndExtensions('esm'),
}
);
const app = express();
// Otherwise, forward the response from esbuild to the client
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});
app.use(express.static('demos'));
app.use(express.static('cypress/platform'));
app.all('/mermaid.js', generateHandler(iifeServer));
app.all('/mermaid.esm.mjs', generateHandler(esmServer));
// Forward the body of the request to esbuild
req.pipe(proxyReq, { end: true });
})
.listen(3000);
app.all('/e2e.esm.mjs', generateHandler(esmServer));
app.all('/bundle-test.esm.mjs', generateHandler(esmServer));
app.listen(9000, () => {
console.log(`Listening on http://localhost:9000`);
});
})();

View File

@ -1,4 +1,4 @@
const { transformJison } = require('./jisonTransformer');
const { transformJison } = require('./jisonTransformer.cjs');
const fs = require('fs');
const { dependencies } = require('../package.json');
@ -17,21 +17,16 @@ const buildOptions = (override = {}) => {
globalName: 'mermaid',
platform: 'browser',
tsconfig: 'tsconfig.json',
resolveExtensions: ['.ts', '.js', '.json', '.jison'],
resolveExtensions: ['.ts', '.js', '.mjs', '.json', '.jison'],
external: ['require', 'fs', 'path'],
outdir: 'dist',
entryPoints: ['src/mermaid.ts'],
outfile: 'dist/mermaid.min.js',
plugins: [jisonPlugin],
sourcemap: 'external',
...override,
};
};
const getOutFiles = (extension) => {
return {
[`mermaid${extension}`]: 'src/mermaid.ts',
[`diagramAPI${extension}`]: 'src/diagram-api/diagramAPI.ts',
};
};
/**
* Build options for mermaid.esm.* build.
*
@ -43,8 +38,7 @@ const getOutFiles = (extension) => {
exports.esmBuild = (override = { minify: true }) => {
return buildOptions({
format: 'esm',
entryPoints: getOutFiles(`.esm${override.minify ? '.min' : ''}`),
outExtension: { '.js': '.mjs' },
outfile: `dist/mermaid.esm${override.minify ? '.min' : ''}.mjs`,
...override,
});
};
@ -61,8 +55,7 @@ exports.esmBuild = (override = { minify: true }) => {
exports.esmCoreBuild = (override) => {
return buildOptions({
format: 'esm',
entryPoints: getOutFiles(`.core`),
outExtension: { '.js': '.mjs' },
outfile: `dist/mermaid.core.mjs`,
external: ['require', 'fs', 'path', ...Object.keys(dependencies)],
platform: 'neutral',
...override,
@ -79,8 +72,11 @@ exports.esmCoreBuild = (override) => {
*/
exports.iifeBuild = (override = { minify: true }) => {
return buildOptions({
entryPoints: getOutFiles(override.minify ? '.min' : ''),
outfile: `dist/mermaid${override.minify ? '.min' : ''}.js`,
format: 'iife',
footer: {
js: 'mermaid = mermaid.default;',
},
...override,
});
};

View File

@ -3,3 +3,4 @@ dist/**
docs/Setup.md
cypress.config.js
cypress/plugins/index.js
coverage

View File

@ -40,18 +40,3 @@ jobs:
- name: Verify Docs
run: yarn docs:verify
- name: Check no `console.log()` in .jison files
# ESLint can't parse .jison files directly
# In the future, it might be worth making a `eslint-plugin-jison`, so
# that this will be built into the `yarn lint` command.
run: |
shopt -s globstar
mkdir -p tmp/
for jison_file in src/**/*.jison; do
outfile="tmp/$(basename -- "$jison_file" .jison)-jison.js"
echo "Converting $jison_file to $outfile"
# default module-type (CJS) always adds a console.log()
yarn jison "$jison_file" --outfile "$outfile" --module-type "amd"
done
yarn eslint --no-eslintrc --rule no-console:error --parser "@babel/eslint-parser" "./tmp/*-jison.js"

View File

@ -1,5 +1,6 @@
{
"src/docs/**": ["yarn docs:build --git"],
"src/docs.mts": ["yarn docs:build --git"],
"*.{ts,js,json,html,md,mts}": ["eslint --fix", "prettier --write"]
"*.{ts,js,json,html,md,mts}": ["eslint --fix", "prettier --write"],
"*.jison": ["yarn lint:jison"]
}

View File

@ -1,3 +1,4 @@
dist
cypress/platform/xss3.html
.cache
.cache
coverage

View File

@ -1,25 +0,0 @@
const { Generator } = require('jison');
const validate = require('schema-utils');
const schema = {
title: 'Jison Parser options',
type: 'object',
properties: {
'token-stack': {
type: 'boolean',
},
debug: {
type: 'boolean',
},
},
additionalProperties: false,
};
module.exports = function jisonLoader(source) {
const options = this.getOptions();
(validate.validate || validate)(schema, options, {
name: 'Jison Loader',
baseDataPath: 'options',
});
return new Generator(source, options).generate();
};

View File

@ -1,46 +0,0 @@
import { merge, mergeWithCustomize, customizeObject } from 'webpack-merge';
import nodeExternals from 'webpack-node-externals';
import baseConfig from './webpack.config.base';
export default (_env, args) => {
return [
// non-minified
merge(baseConfig, {
optimization: {
minimize: false,
},
}),
// core [To be used by webpack/esbuild/vite etc to bundle mermaid]
merge(baseConfig, {
externals: [nodeExternals()],
output: {
filename: '[name].core.js',
},
optimization: {
minimize: false,
},
}),
// umd
merge(baseConfig, {
output: {
filename: '[name].min.js',
},
}),
// esm
mergeWithCustomize({
customizeObject: customizeObject({
'output.library': 'replace',
}),
})(baseConfig, {
experiments: {
outputModule: true,
},
output: {
library: {
type: 'module',
},
filename: '[name].esm.min.mjs',
},
}),
];
};

View File

@ -1,71 +0,0 @@
import path from 'path';
const esbuild = require('esbuild');
const { ESBuildMinifyPlugin } = require('esbuild-loader');
export const resolveRoot = (...relativePath) => path.resolve(__dirname, '..', ...relativePath);
export default {
amd: false, // https://github.com/lodash/lodash/issues/3052
target: 'web',
entry: {
mermaid: './src/mermaid',
},
resolve: {
extensions: ['.wasm', '.mjs', '.js', '.ts', '.json', '.jison'],
fallback: {
fs: false, // jison generated code requires 'fs'
path: require.resolve('path-browserify'),
},
},
output: {
path: resolveRoot('./dist'),
filename: '[name].js',
library: {
name: 'mermaid',
type: 'umd',
export: 'default',
},
globalObject: 'typeof self !== "undefined" ? self : this',
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.js$/,
include: [resolveRoot('./src'), resolveRoot('./node_modules/dagre-d3-renderer/lib')],
use: {
loader: 'esbuild-loader',
options: {
implementation: esbuild,
target: 'es2015',
},
},
},
{
// load scss to string
test: /\.scss$/,
use: ['css-to-string-loader', 'css-loader', 'sass-loader'],
},
{
test: /\.jison$/,
use: {
loader: path.resolve(__dirname, './loaders/jison.js'),
options: {
'token-stack': true,
},
},
},
],
},
devtool: 'source-map',
optimization: {
minimizer: [
new ESBuildMinifyPlugin({
target: 'es2015',
}),
],
},
};

View File

@ -1,26 +0,0 @@
import baseConfig, { resolveRoot } from './webpack.config.base';
import { merge } from 'webpack-merge';
export default merge(baseConfig, {
mode: 'development',
entry: {
mermaid: './src/mermaid',
e2e: './cypress/platform/viewer.js',
'bundle-test': './cypress/platform/bundle-test.js',
},
output: {
globalObject: 'window',
},
devServer: {
compress: true,
port: 9000,
static: [
{ directory: resolveRoot('cypress', 'platform') },
{ directory: resolveRoot('dist') },
{ directory: resolveRoot('demos') },
],
},
externals: {
mermaid: 'mermaid',
},
});

View File

@ -1,3 +0,0 @@
export const curveBasis = 'basis';
export const curveLinear = 'linear';
export const curveCardinal = 'cardinal';

View File

@ -1,4 +1,7 @@
let NewD3 = function () {
// @ts-nocheck TODO: Fix TS
import { vi } from 'vitest';
const NewD3 = function () {
/**
*
*/
@ -56,9 +59,9 @@ export const MockD3 = (name, parent) => {
children.push(mockElem);
return mockElem;
};
elem.lower = jest.fn(() => elem);
elem.attr = jest.fn(() => elem);
elem.text = jest.fn(() => elem);
elem.style = jest.fn(() => elem);
elem.lower = vi.fn(() => elem);
elem.attr = vi.fn(() => elem);
elem.text = vi.fn(() => elem);
elem.style = vi.fn(() => elem);
return elem;
};

3
__mocks__/dagre-d3.ts Normal file
View File

@ -0,0 +1,3 @@
import { vi } from 'vitest';
// export const render = vi.fn();

View File

@ -0,0 +1,3 @@
module.exports = function (txt: string) {
return txt;
};

View File

@ -1,10 +0,0 @@
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: 'defaults, ie >= 11, current node',
},
],
],
};

View File

@ -2,7 +2,7 @@
<head>
<meta charset="utf-8" />
<!-- <meta charset="iso-8859-15"/> -->
<script src="/e2e.js"></script>
<script src="/e2e.esm.mjs" type="module"></script>
<!-- <link href="https://fonts.googleapis.com/css?family=Mansalva&display=swap" rel="stylesheet" /> -->
<link
href="https://fonts.googleapis.com/css?family=Noto+Sans+SC&display=swap"
@ -37,7 +37,7 @@
</style>
</head>
<body>
<script src="./mermaid.js"></script>
<!-- <script src="./mermaid.js"></script> -->
<script>
// Notice startOnLoad=false
// This prevents default handling in mermaid from render before the e2e logic is applied

View File

@ -3,7 +3,8 @@ import mermaid2 from '../../src/mermaid';
/**
* ##contentLoaded Callback function that is called when page is loaded. This functions fetches
* configuration for mermaid rendering and calls init for rendering the mermaid diagrams on the page.
* configuration for mermaid rendering and calls init for rendering the mermaid diagrams on the
* page.
*/
const contentLoaded = function () {
let pos = document.location.href.indexOf('?graph=');
@ -32,8 +33,8 @@ const contentLoaded = function () {
document.getElementsByTagName('body')[0].appendChild(div);
}
global.mermaid.initialize(graphObj.mermaid);
global.mermaid.init();
mermaid2.initialize(graphObj.mermaid);
mermaid2.init();
}
};

View File

@ -12,6 +12,6 @@
</head>
<body>
<div id="graph-to-be"></div>
<script src="./bundle-test.js" charset="utf-8"></script>
<script src="./bundle-test.esm.mjs" type="module" charset="utf-8"></script>
</body>
</html>

View File

@ -1,6 +1,6 @@
<html>
<head>
<script src="/e2e.js"></script>
<script src="/e2e.esm.mjs" type="module"></script>
<link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet" />
<style>
.malware {

View File

@ -23,8 +23,8 @@ ORDER ||--|{ LINE-ITEM : contains
CUSTOMER }|..|{ DELIVERY-ADDRESS : uses
</pre>
<script src="./mermaid.js"></script>
<script>
<script type="module">
import mermaid from './mermaid.esm.mjs';
mermaid.initialize({
theme: 'forest',
// themeCSS: '.node rect { fill: red; }',

View File

@ -1,24 +0,0 @@
// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require('path');
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
testEnvironment: 'jsdom',
preset: 'ts-jest',
transform: {
'^.+\\.[jt]sx?$': 'esbuild-jest',
'^.+\\.jison$': [
path.resolve(__dirname, './src/jison/transformer.js'),
{ 'token-stack': true },
],
},
coveragePathIgnorePatterns: [
'/node_modules/',
'^.+\\.jison$', // might be able to fix in future if .jison adds source-map support
],
transformIgnorePatterns: ['/node_modules/(?!dagre-d3-renderer/lib|khroma).*\\.js'],
testPathIgnorePatterns: ['/node_modules/', '.cache', './cypress'],
moduleNameMapper: {
'\\.(css|scss)$': 'identity-obj-proxy',
},
moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx', 'node', 'jison'],
};

View File

@ -5,6 +5,7 @@
"main": "dist/mermaid.core.mjs",
"module": "dist/mermaid.core.mjs",
"types": "dist/mermaid.d.ts",
"type": "module",
"exports": {
".": {
"require": "./dist/mermaid.min.js",
@ -27,25 +28,24 @@
"build:vite": "vite build",
"build:code": "node .esbuild/esbuild.cjs",
"build:types": "tsc -p ./tsconfig.json --emitDeclarationOnly",
"build:webpack": "webpack --mode production --progress --color",
"build:watch": "yarn build:code --watch",
"build:new": "concurrently \"yarn build:code\" \"yarn build:types\"",
"build": "yarn clean; yarn build:webpack",
"build:esbuild": "concurrently \"yarn build:code\" \"yarn build:types\"",
"build": "yarn clean; yarn build:esbuild",
"dev": "node .esbuild/serve.cjs",
"docs:build": "ts-node-esm src/docs.mts",
"docs:verify": "ts-node-esm src/docs.mts --verify",
"postbuild": "documentation build src/mermaidAPI.ts src/config.ts src/defaultConfig.ts --shallow -f md --markdown-toc false > src/docs/Setup.md && prettier --write src/docs/Setup.md && yarn docs:build",
"release": "yarn build",
"lint": "eslint --cache --ignore-path .gitignore . && prettier --check .",
"lint": "eslint --cache --ignore-path .gitignore . && yarn lint:jison && prettier --check .",
"lint:fix": "eslint --fix --ignore-path .gitignore . && prettier --write .",
"e2e:depr": "yarn lint && jest e2e --config e2e/jest.config.js",
"lint:jison": "ts-node-esm src/jison/lint.mts",
"cypress": "cypress run",
"cypress:open": "cypress open",
"e2e": "start-server-and-test dev http://localhost:9000/ cypress",
"e2e-upd": "yarn lint && jest e2e -u --config e2e/jest.config.js",
"dev": "webpack serve --config ./.webpack/webpack.config.e2e.babel.js",
"ci": "jest src/.*",
"test": "yarn lint && jest src/.*",
"test:watch": "jest --watch src",
"ci": "vitest run",
"test": "yarn lint && vitest run",
"test:watch": "vitest --coverage --watch",
"prepublishOnly": "yarn build && yarn test",
"prepare": "concurrently \"husky install\" \"yarn build\"",
"pre-commit": "lint-staged"
@ -82,29 +82,26 @@
},
"devDependencies": {
"@applitools/eyes-cypress": "^3.25.7",
"@babel/core": "^7.19.0",
"@babel/eslint-parser": "^7.14.7",
"@babel/preset-env": "^7.19.0",
"@babel/register": "^7.14.5",
"@commitlint/cli": "^17.1.2",
"@commitlint/config-conventional": "^17.0.0",
"@types/d3": "^7.4.0",
"@types/dompurify": "^2.3.4",
"@types/jest": "^28.1.7",
"@types/eslint": "^8.4.6",
"@types/express": "^4.17.13",
"@types/jsdom": "^20.0.0",
"@types/lodash": "^4.14.184",
"@types/prettier": "^2.7.0",
"@types/stylis": "^4.0.2",
"@typescript-eslint/eslint-plugin": "^5.37.0",
"@typescript-eslint/parser": "^5.37.0",
"babel-jest": "^29.0.3",
"babel-loader": "^8.2.2",
"@vitest/coverage-c8": "^0.23.2",
"@vitest/ui": "^0.23.2",
"concurrently": "^7.4.0",
"css-to-string-loader": "^0.1.3",
"coveralls": "^3.1.1",
"cypress": "^10.0.0",
"cypress-image-snapshot": "^4.0.1",
"documentation": "13.2.0",
"esbuild": "^0.15.6",
"esbuild-jest": "^0.5.0",
"esbuild-loader": "^2.19.0",
"eslint": "^8.23.1",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-cypress": "^2.12.1",
@ -113,13 +110,13 @@
"eslint-plugin-jsdoc": "^39.3.6",
"eslint-plugin-json": "^3.1.0",
"eslint-plugin-markdown": "^3.0.0",
"express": "^4.18.1",
"globby": "^13.1.2",
"husky": "^8.0.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^28.0.3",
"jest-environment-jsdom": "^29.0.3",
"jison": "^0.4.18",
"js-base64": "3.7.2",
"jsdom": "^20.0.0",
"lint-staged": "^13.0.0",
"moment": "^2.23.0",
"path-browserify": "^1.0.1",
@ -129,18 +126,11 @@
"rimraf": "^3.0.2",
"rollup-pluginutils": "^2.8.2",
"start-server-and-test": "^1.12.6",
"terser-webpack-plugin": "^5.3.6",
"ts-jest": "^28.0.8",
"ts-loader": "^9.3.1",
"ts-node": "^10.9.1",
"typescript": "^4.8.3",
"unist-util-flatmap": "^1.0.0",
"vite": "^3.0.9",
"webpack": "^5.53.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^4.11.0",
"webpack-merge": "^5.8.0",
"webpack-node-externals": "^3.0.0"
"vitest": "^0.23.1"
},
"resolutions": {
"d3": "^7.0.0"

View File

@ -1,3 +0,0 @@
module.exports = function (txt) {
return txt;
};

View File

@ -1,18 +1,15 @@
/**
* Mocks for `./mermaidAPI`.
*
* We can't easily use `jest.spyOn(mermaidAPI, "function")` since the object is frozen with `Object.freeze()`.
* We can't easily use `vi.spyOn(mermaidAPI, "function")` since the object is frozen with `Object.freeze()`.
*/
import * as configApi from '../config';
import { vi } from 'vitest';
import { addDiagrams } from '../diagram-api/diagram-orchestration';
import Diagram from '../Diagram';
// Normally, we could just do the following to get the original `parse()`
// implementation, however, requireActual isn't currently supported in Jest
// for ESM, see https://github.com/facebook/jest/issues/9430
// and https://github.com/facebook/jest/pull/10976
// const {parse} = jest.requireActual("./mermaidAPI");
// implementation, however, requireActual returns a promise and it's not documented how to use withing mock file.
let hasLoadedDiagrams = false;
/**
@ -31,10 +28,10 @@ function parse(text: string, parseError?: Function): boolean {
// original version cannot be modified since it was frozen with `Object.freeze()`
export const mermaidAPI = {
render: jest.fn(),
render: vi.fn(),
parse,
parseDirective: jest.fn(),
initialize: jest.fn(),
parseDirective: vi.fn(),
initialize: vi.fn(),
getConfig: configApi.getConfig,
setConfig: configApi.setConfig,
getSiteConfig: configApi.getSiteConfig,

View File

@ -1,7 +1,7 @@
import { parser } from './parser/classDiagram';
import classDb from './classDb';
const spyOn = jest.spyOn;
import { vi } from 'vitest';
const spyOn = vi.spyOn;
describe('class diagram, ', function () {
describe('when parsing an info graph it', function () {
@ -14,7 +14,7 @@ describe('class diagram, ', function () {
parser.parse(str);
});
xit('should handle a leading newline axa', function () {
it.skip('should handle a leading newline axa', function () {
const str = '\nclassDiagram\n' + 'class Car';
try {

View File

@ -4,9 +4,6 @@ import flowRenderer from './flowRenderer';
import Diagram from '../../Diagram';
import { addDiagrams } from '../../diagram-api/diagram-orchestration';
addDiagrams();
afterEach(() => {
jest.restoreAllMocks();
});
describe('when using mermaid and ', function () {
describe('when calling addEdges ', function () {

View File

@ -1,8 +1,8 @@
import flowDb from '../flowDb';
import flow from './flow';
import { setConfig } from '../../../config';
const spyOn = jest.spyOn;
import { vi } from 'vitest';
const spyOn = vi.spyOn;
setConfig({
securityLevel: 'strict',

View File

@ -284,7 +284,7 @@ describe('[Text] when parsing', () => {
expect(edges[0].text).toBe('text including graph space and v');
});
// xit('should handle text on open links',function(){
// it.skip('should handle text on open links',function(){
// const res = flow.parser.parse('graph TD;A-- text including graph space --B');
//
// const vert = flow.parser.yy.getVertices();
@ -324,7 +324,7 @@ describe('[Text] when parsing', () => {
expect(vert['C'].type).toBe('round');
expect(vert['C'].text).toBe('Chimpansen hoppar åäö <br> - ÅÄÖ');
});
// xit('should handle åäö, minus and space and br',function(){
// it.skip('should handle åäö, minus and space and br',function(){
// const res = flow.parser.parse('graph TD; A[Object&#40;foo,bar&#41;]-->B(Thing);');
//
// const vert = flow.parser.yy.getVertices();

View File

@ -62,7 +62,7 @@ describe('when parsing subgraphs', function () {
expect(subgraph.id).toBe('some-id');
});
xit('should handle subgraph without id and space in title', function () {
it.skip('should handle subgraph without id and space in title', function () {
const res = flow.parser.parse('graph TB\nsubgraph Some Title\n\ta1-->a2\nend');
const subgraphs = flow.parser.yy.getSubGraphs();
expect(subgraphs.length).toBe(1);

View File

@ -1,5 +1,8 @@
// @ts-nocheck TODO: Fix TS
import moment from 'moment-mini';
import ganttDb from './ganttDb';
import { it, describe } from 'vitest';
import { convert } from '../../tests/util';
describe('when using the ganttDb', function () {
beforeEach(function () {
@ -7,14 +10,23 @@ describe('when using the ganttDb', function () {
});
describe('when using duration', function () {
it.each`
it.each([{ str: '1d', expected: moment.duration(1, 'd') }])(
'should %s resulting in $o duration',
({ str, expected }) => {
expect(ganttDb.parseDuration(str)).toEqual(expected);
}
);
it.each(
convert`
str | expected
${'1d'} | ${moment.duration(1, 'd')}
${'2w'} | ${moment.duration(2, 'w')}
${'1ms'} | ${moment.duration(1, 'ms')}
${'0.1s'} | ${moment.duration(100, 'ms')}
${'1f'} | ${moment.duration.invalid()}
`('should $str resulting in $expected duration', ({ str, expected }) => {
`
)('should $str resulting in $expected duration', ({ str, expected }) => {
expect(ganttDb.parseDuration(str)).toEqual(expected);
});
});
@ -31,7 +43,7 @@ describe('when using the ganttDb', function () {
ganttDb.clear();
});
it.each`
it.each(convert`
fn | expected
${'getTasks'} | ${[]}
${'getAccTitle'} | ${''}
@ -42,12 +54,13 @@ describe('when using the ganttDb', function () {
${'getExcludes'} | ${[]}
${'getSections'} | ${[]}
${'endDatesAreInclusive'} | ${false}
`('should clear $fn', ({ fn, expected }) => {
`)('should clear $fn', ({ fn, expected }) => {
expect(ganttDb[fn]()).toEqual(expected);
});
});
it.each`
// prettier-ignore
it.each(convert`
testName | section | taskName | taskData | expStartDate | expEndDate | expId | expTask
${'should handle fixed dates'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2013-01-12'} | ${new Date(2013, 0, 1)} | ${new Date(2013, 0, 12)} | ${'id1'} | ${'test1'}
${'should handle duration (days) instead of fixed date to determine end date'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2d'} | ${new Date(2013, 0, 1)} | ${new Date(2013, 0, 3)} | ${'id1'} | ${'test1'}
@ -57,7 +70,7 @@ describe('when using the ganttDb', function () {
${'should handle duration (weeks) instead of fixed date to determine end date'} | ${'testa1'} | ${'test1'} | ${'id1,2013-01-01,2w'} | ${new Date(2013, 0, 1)} | ${new Date(2013, 0, 15)} | ${'id1'} | ${'test1'}
${'should handle fixed dates without id'} | ${'testa1'} | ${'test1'} | ${'2013-01-01,2013-01-12'} | ${new Date(2013, 0, 1)} | ${new Date(2013, 0, 12)} | ${'task1'} | ${'test1'}
${'should handle duration instead of a fixed date to determine end date without id'} | ${'testa1'} | ${'test1'} | ${'2013-01-01,4d'} | ${new Date(2013, 0, 1)} | ${new Date(2013, 0, 5)} | ${'task1'} | ${'test1'}
`('$testName', ({ section, taskName, taskData, expStartDate, expEndDate, expId, expTask }) => {
`)('$testName', ({ section, taskName, taskData, expStartDate, expEndDate, expId, expTask }) => {
ganttDb.setDateFormat('YYYY-MM-DD');
ganttDb.addSection(section);
ganttDb.addTask(taskName, taskData);
@ -68,14 +81,15 @@ describe('when using the ganttDb', function () {
expect(tasks[0].task).toEqual(expTask);
});
it.each`
// prettier-ignore
it.each(convert`
section | taskName1 | taskName2 | taskData1 | taskData2 | expStartDate2 | expEndDate2 | expId2 | expTask2
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'id2,after id1,1d'} | ${new Date(2013, 0, 15)} | ${undefined} | ${'id2'} | ${'test2'}
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'id2,after id3,1d'} | ${new Date(new Date().setHours(0, 0, 0, 0))} | ${undefined} | ${'id2'} | ${'test2'}
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'after id1,1d'} | ${new Date(2013, 0, 15)} | ${undefined} | ${'task1'} | ${'test2'}
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'2013-01-26'} | ${new Date(2013, 0, 15)} | ${new Date(2013, 0, 26)} | ${'task1'} | ${'test2'}
${'testa1'} | ${'test1'} | ${'test2'} | ${'id1,2013-01-01,2w'} | ${'2d'} | ${new Date(2013, 0, 15)} | ${new Date(2013, 0, 17)} | ${'task1'} | ${'test2'}
`(
`)(
'$testName',
({
section,
@ -381,11 +395,11 @@ describe('when using the ganttDb', function () {
});
});
it.each`
it.each(convert`
type | expected
${'hide'} | ${'off'}
${'style'} | ${'stoke:stroke-width:5px,stroke:#00f,opacity:0.5'}
`('should ${type} today marker', ({ expected }) => {
`)('should ${type} today marker', ({ expected }) => {
ganttDb.setTodayMarker(expected);
expect(ganttDb.getTodayMarker()).toEqual(expected);
});

View File

@ -1,7 +1,8 @@
import { parser } from './gantt';
import ganttDb from '../ganttDb';
const spyOn = jest.spyOn;
import { convert } from '../../../tests/util';
import { vi } from 'vitest';
const spyOn = vi.spyOn;
const parserFnConstructor = (str) => {
return () => {
parser.parse(str);
@ -92,14 +93,14 @@ describe('when parsing a gantt diagram it', function () {
expect(tasks[0].id).toEqual('des1');
expect(tasks[0].task).toEqual('Design jison grammar');
});
it.each`
it.each(convert`
tags | milestone | done | crit | active
${'milestone'} | ${true} | ${false} | ${false} | ${false}
${'done'} | ${false} | ${true} | ${false} | ${false}
${'crit'} | ${false} | ${false} | ${true} | ${false}
${'active'} | ${false} | ${false} | ${false} | ${true}
${'crit,milestone,done'} | ${true} | ${true} | ${true} | ${false}
`('should handle a task with tags $tags', ({ tags, milestone, done, crit, active }) => {
`)('should handle a task with tags $tags', ({ tags, milestone, done, crit, active }) => {
const str =
'gantt\n' +
'dateFormat YYYY-MM-DD\n' +

View File

@ -25,15 +25,15 @@ describe('more than one sequence diagram', () => {
Alice->Bob:Hello Bob, how are you?
Bob-->Alice: I am good thanks!`);
expect(diagram1.db.getMessages()).toMatchInlineSnapshot(`
Array [
Object {
[
{
"from": "Alice",
"message": "Hello Bob, how are you?",
"to": "Bob",
"type": 5,
"wrap": false,
},
Object {
{
"from": "Bob",
"message": "I am good thanks!",
"to": "Alice",
@ -48,15 +48,15 @@ describe('more than one sequence diagram', () => {
Bob-->Alice: I am good thanks!`);
expect(diagram2.db.getMessages()).toMatchInlineSnapshot(`
Array [
Object {
[
{
"from": "Alice",
"message": "Hello Bob, how are you?",
"to": "Bob",
"type": 5,
"wrap": false,
},
Object {
{
"from": "Bob",
"message": "I am good thanks!",
"to": "Alice",
@ -73,15 +73,15 @@ describe('more than one sequence diagram', () => {
John-->Alice: I am good thanks!`);
expect(diagram3.db.getMessages()).toMatchInlineSnapshot(`
Array [
Object {
[
{
"from": "Alice",
"message": "Hello John, how are you?",
"to": "John",
"type": 5,
"wrap": false,
},
Object {
{
"from": "John",
"message": "I am good thanks!",
"to": "Alice",

View File

@ -389,7 +389,7 @@ describe('state diagram, ', function () {
});
});
describe('when parsing an ignored info graph it', function () {
xit('should handle if statements', function () {
it.skip('should handle if statements', function () {
const str = `stateDiagram\n
[*] --> "Order Submitted"
if "Payment Accepted" then

View File

@ -1,4 +1,5 @@
import journeyDb from './journeyDb';
import { convert } from '../../tests/util';
describe('when using the journeyDb', function () {
beforeEach(function () {
@ -13,13 +14,13 @@ describe('when using the journeyDb', function () {
journeyDb.clear();
});
it.each`
it.each(convert`
fn | expected
${'getTasks'} | ${[]}
${'getAccTitle'} | ${''}
${'getSections'} | ${[]}
${'getActors'} | ${[]}
`('should clear $fn', ({ fn, expected }) => {
`)('should clear $fn', ({ fn, expected }) => {
expect(journeyDb[fn]()).toEqual(expected);
});
});
@ -31,18 +32,18 @@ describe('when using the journeyDb', function () {
journeyDb.addTask('test2', '1: id2');
journeyDb.clear();
});
it.each`
it.each(convert`
fn | expected
${'getTasks'} | ${[]}
${'getAccTitle'} | ${''}
${'getAccDescription'} | ${''}
${'getSections'} | ${[]}
`('should clear $fn', ({ fn, expected }) => {
`)('should clear $fn', ({ fn, expected }) => {
expect(journeyDb[fn]()).toEqual(expected);
});
});
describe('tasks and actors should be added', function () {
it('tasks and actors should be added', function () {
journeyDb.setAccTitle('Shopping');
journeyDb.setAccDescription('A user journey for family shopping');
journeyDb.addSection('Journey to the shops');

31
src/jison/lint.mts Normal file
View File

@ -0,0 +1,31 @@
/* eslint-disable no-console */
import { readFile } from 'fs/promises';
import { globby } from 'globby';
import { ESLint } from 'eslint';
// @ts-ignore no typings
import jison from 'jison';
const linter = new ESLint({
overrideConfig: { rules: { 'no-console': 'error' }, parser: '@typescript-eslint/parser' },
useEslintrc: false,
});
const lint = async (file: string): Promise<boolean> => {
const jisonCode = await readFile(file, 'utf8');
// @ts-ignore no typings
const jsCode = new jison.Generator(jisonCode, { moduleType: 'amd' }).generate();
const [result] = await linter.lintText(jsCode);
if (result.errorCount > 0) {
console.error(`Linting failed for ${file}`);
console.error(result.messages);
}
return result.errorCount === 0;
};
(async () => {
const jisonFiles = await globby(['./src/**/*.jison'], { dot: true });
const lintResults = await Promise.all(jisonFiles.map(lint));
if (lintResults.some((result) => result === false)) {
process.exit(1);
}
})();

View File

@ -1,8 +1,8 @@
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { Generator } = require('jison');
const { transformJison } = require('../../.esbuild/jisonTransformer.cjs');
module.exports = {
process(sourceText, sourcePath, options) {
return { code: new Generator(sourceText, options.transformerConfig).generate() };
return { code: transformJison(sourceText) };
},
};

View File

@ -1,19 +1,12 @@
// mocks the mermaidAPI.render function (see `./__mocks__/mermaidAPI`)
jest.mock('./mermaidAPI');
// jest.mock only works well with CJS, see https://github.com/facebook/jest/issues/9430
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { default: mermaid } = require('./mermaid');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { mermaidAPI } = require('./mermaidAPI');
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { default: flowDb } = require('./diagrams/flowchart/flowDb');
import mermaid from './mermaid';
import { mermaidAPI } from './mermaidAPI';
import { vi, describe, it, beforeEach, afterEach, expect } from 'vitest';
const spyOn = vi.spyOn;
import flowParser from './diagrams/flowchart/parser/flow';
const spyOn = jest.spyOn;
vi.mock('./mermaidAPI');
afterEach(() => {
jest.restoreAllMocks();
vi.restoreAllMocks();
});
describe('when using mermaid and ', function () {
@ -63,11 +56,6 @@ describe('when using mermaid and ', function () {
});
describe('checking validity of input ', function () {
beforeEach(function () {
flowParser.parser.yy = flowDb;
flowDb.clear();
flowDb.setGen('gen-2');
});
it('should throw for an invalid definition', function () {
expect(() => mermaid.parse('this is not a mermaid diagram definition')).toThrow();
});

3
src/tests/setup.ts Normal file
View File

@ -0,0 +1,3 @@
import { vi } from 'vitest';
vi.mock('d3');
vi.mock('dagre-d3');

44
src/tests/util.ts Normal file
View File

@ -0,0 +1,44 @@
/*
Used to convert jest's Tagged Template literals to object arrays as required by vitest.
Example:
Jest code
```ts
it.each`
str | expected
${'1d'} | ${moment.duration(1, 'd')}
${'2w'} | ${moment.duration(2, 'w')}
`('should parse $str to $expected duration', ({ str, expected }) => {
expect(yourFunction(str)).toEqual(expected);
});
```
Vitest code
```ts
it.each(convert`
str | expected
${'1d'} | ${moment.duration(1, 'd')}
${'2w'} | ${moment.duration(2, 'w')}
`)('should parse $str to $expected duration', ({ str, expected }) => {
expect(yourFunction(str)).toEqual(expected);
});
```
*/
export const convert = (template: TemplateStringsArray, ...params: any[]) => {
const header = template[0]
.trim()
.split('|')
.map((s) => s.trim());
if (header.length === 0 || params.length % header.length !== 0) {
throw new Error('Table column count mismatch');
}
const chunkSize = header.length;
const out = [];
for (let i = 0; i < params.length; i += chunkSize) {
const chunk = params.slice(i, i + chunkSize);
out.push(Object.fromEntries(chunk.map((v, i) => [header[i], v])));
}
return out;
};

View File

@ -1,3 +1,4 @@
import { vi, describe, it, expect, beforeEach } from 'vitest';
import utils from './utils';
import assignWithDepth from './assignWithDepth';
import { detectType } from './diagram-api/detectType';
@ -303,14 +304,22 @@ describe('when formatting urls', function () {
});
describe('when initializing the id generator', function () {
it('should return a random number generator based on Date', function (done) {
beforeEach(() => {
// tell vitest we use mocked time
vi.useFakeTimers();
});
afterEach(() => {
// restoring date after each test run
vi.useRealTimers();
});
it('should return a random number generator based on Date', function () {
const idGenerator = new utils.initIdGenerator(false);
expect(typeof idGenerator.next).toEqual('function');
const lastId = idGenerator.next();
setTimeout(() => {
expect(idGenerator.next() > lastId).toBe(true);
done();
}, 5);
vi.advanceTimersByTime(1000);
expect(idGenerator.next() > lastId).toBe(true);
});
it('should return a non random number generator', function () {

View File

@ -11,10 +11,10 @@
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"target": "ES6" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"lib": [
"ES2021",
"DOM"
"DOM",
"ES2021"
] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
@ -34,7 +34,10 @@
// "paths": {} /* Specify a set of entries that re-map imports to additional lookup locations. */,
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [] /* Specify multiple folders that act like `./node_modules/@types`. */,
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
"types": [
"vitest/globals"
] /* Specify type package names to be included without being referenced in a source file. */,
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
"resolveJsonModule": true /* Enable importing .json files */,
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */

35
vite.config.cts Normal file
View File

@ -0,0 +1,35 @@
import { transformJison } from './.esbuild/jisonTransformer.cjs';
import { defineConfig } from 'vitest/config';
const fileRegex = /\.jison$/;
/** Transforms jison to js. */
export function jisonPlugin() {
return {
name: 'transform-jison',
transform(src: string, id: string) {
if (fileRegex.test(id)) {
// eslint-disable-next-line no-console
console.log('Transforming', id);
return {
// @ts-ignore no typings for jison
code: transformJison(src),
map: null, // provide source map if available
};
}
},
};
}
export default defineConfig({
resolve: {
extensions: ['.jison', '.js', '.ts', '.json'],
},
plugins: [jisonPlugin()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: ['src/tests/setup.ts'],
},
});

3312
yarn.lock

File diff suppressed because it is too large Load Diff