Merge remote-tracking branch 'MERMAID/develop' into develop

This commit is contained in:
Ashley Engelund (weedySeaDragon @ github) 2022-09-24 16:16:29 -07:00
commit 908f5afe0f
22 changed files with 1132 additions and 1594 deletions

View File

@ -1,20 +0,0 @@
const { esmBuild, esmCoreBuild, iifeBuild } = require('./util.cjs');
const { build } = require('esbuild');
const handler = (e) => {
console.error(e);
process.exit(1);
};
const watch = process.argv.includes('--watch');
// mermaid.js
build(iifeBuild({ minify: false, watch })).catch(handler);
// mermaid.esm.mjs
build(esmBuild({ minify: false, watch })).catch(handler);
// mermaid.min.js
build(iifeBuild()).catch(handler);
// mermaid.esm.min.mjs
build(esmBuild()).catch(handler);
// mermaid.core.mjs (node_modules unbundled)
build(esmCoreBuild()).catch(handler);

View File

@ -1,79 +0,0 @@
const esbuild = require('esbuild');
const http = require('http');
const { iifeBuild, esmBuild } = require('./util.cjs');
const express = require('express');
// 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',
},
outExtension: { '.js': format === 'iife' ? '.js' : '.esm.mjs' },
};
};
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;
}
}
// 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 });
};
};
(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();
app.use(express.static('demos'));
app.use(express.static('cypress/platform'));
app.all('/mermaid.js', generateHandler(iifeServer));
app.all('/mermaid.esm.mjs', generateHandler(esmServer));
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,94 +0,0 @@
const { transformJison } = require('./jisonTransformer.cjs');
const fs = require('fs');
const { dependencies } = require('../package.json');
/** @typedef {import('esbuild').BuildOptions} Options */
/**
* @param {Options} override
* @returns {Options}
*/
const buildOptions = (override = {}) => {
return {
bundle: true,
minify: true,
keepNames: true,
banner: { js: '"use strict";' },
globalName: 'mermaid',
platform: 'browser',
tsconfig: 'tsconfig.json',
resolveExtensions: ['.ts', '.js', '.mjs', '.json', '.jison'],
external: ['require', 'fs', 'path'],
entryPoints: ['src/mermaid.ts'],
outfile: 'dist/mermaid.min.js',
plugins: [jisonPlugin],
sourcemap: 'external',
...override,
};
};
/**
* Build options for mermaid.esm.* build.
*
* For ESM browser use.
*
* @param {Options} override - Override options.
* @returns {Options} ESBuild build options.
*/
exports.esmBuild = (override = { minify: true }) => {
return buildOptions({
format: 'esm',
outfile: `dist/mermaid.esm${override.minify ? '.min' : ''}.mjs`,
...override,
});
};
/**
* Build options for mermaid.core.* build.
*
* This build does not bundle `./node_modules/`, as it is designed to be used with
* Webpack/ESBuild/Vite to use mermaid inside an app/website.
*
* @param {Options} override - Override options.
* @returns {Options} ESBuild build options.
*/
exports.esmCoreBuild = (override) => {
return buildOptions({
format: 'esm',
outfile: `dist/mermaid.core.mjs`,
external: ['require', 'fs', 'path', ...Object.keys(dependencies)],
platform: 'neutral',
...override,
});
};
/**
* Build options for mermaid.js build.
*
* For IIFE browser use (where ESM is not yet supported).
*
* @param {Options} override - Override options.
* @returns {Options} ESBuild build options.
*/
exports.iifeBuild = (override = { minify: true }) => {
return buildOptions({
outfile: `dist/mermaid${override.minify ? '.min' : ''}.js`,
format: 'iife',
footer: {
js: 'mermaid = mermaid.default;',
},
...override,
});
};
const jisonPlugin = {
name: 'jison',
setup(build) {
build.onLoad({ filter: /\.jison$/ }, async (args) => {
// Load the file from the file system
const source = await fs.promises.readFile(args.path, 'utf8');
const contents = transformJison(source);
return { contents, warnings: [] };
});
},
};

89
.vite/build.ts Normal file
View File

@ -0,0 +1,89 @@
import { build, InlineConfig } from 'vite';
import { resolve } from 'path';
import { fileURLToPath } from 'url';
import jisonPlugin from './jisonPlugin.js';
import pkg from '../package.json' assert { type: 'json' };
type OutputOptions = Exclude<
Exclude<InlineConfig['build'], undefined>['rollupOptions'],
undefined
>['output'];
const { dependencies } = pkg;
const watch = process.argv.includes('--watch');
const __dirname = fileURLToPath(new URL('.', import.meta.url));
interface BuildOptions {
minify: boolean | 'esbuild';
core?: boolean;
watch?: boolean;
}
export const getBuildConfig = ({ minify, core, watch }: BuildOptions): InlineConfig => {
const external = ['require', 'fs', 'path'];
let output: OutputOptions = [
{
name: 'mermaid',
format: 'esm',
sourcemap: true,
entryFileNames: `[name].esm${minify ? '.min' : ''}.mjs`,
},
{
name: 'mermaid',
format: 'umd',
sourcemap: true,
entryFileNames: `[name]${minify ? '.min' : ''}.js`,
},
];
if (core) {
// Core build is used to generate file without bundled dependencies.
// This is used by downstream projects to bundle dependencies themselves.
external.push(...Object.keys(dependencies));
// This needs to be an array. Otherwise vite will build esm & umd with same name and overwrite esm with umd.
output = [
{
format: 'esm',
sourcemap: true,
entryFileNames: `[name].core.mjs`,
},
];
}
const config: InlineConfig = {
configFile: false,
build: {
emptyOutDir: false,
lib: {
entry: resolve(__dirname, '../src/mermaid.ts'),
name: 'mermaid',
// the proper extensions will be added
fileName: 'mermaid',
},
minify,
rollupOptions: {
external,
output,
},
},
resolve: {
extensions: ['.jison', '.js', '.ts', '.json'],
},
plugins: [jisonPlugin()],
};
if (watch && config.build) {
config.build.watch = {
include: 'src/**',
};
}
return config;
};
if (watch) {
build(getBuildConfig({ minify: false, watch }));
} else {
build(getBuildConfig({ minify: false }));
build(getBuildConfig({ minify: 'esbuild' }));
build(getBuildConfig({ minify: false, core: true }));
}

17
.vite/jisonPlugin.ts Normal file
View File

@ -0,0 +1,17 @@
import { transformJison } from './jisonTransformer.js';
const fileRegex = /\.(jison)$/;
export default function jison() {
return {
name: 'jison',
transform(src: string, id: string) {
if (fileRegex.test(id)) {
return {
code: transformJison(src),
map: null, // provide source map if available
};
}
},
};
}

View File

@ -1,6 +1,9 @@
const { Generator } = require('jison');
exports.transformJison = (src) => {
const parser = new Generator(src, {
// @ts-ignore No typings for jison
import jison from 'jison';
export const transformJison = (src: string): string => {
// @ts-ignore No typings for jison
const parser = new jison.Generator(src, {
moduleType: 'js',
'token-stack': true,
});

26
.vite/server.ts Normal file
View File

@ -0,0 +1,26 @@
import express from 'express';
import { createServer as createViteServer } from 'vite';
// import { getBuildConfig } from './build';
async function createServer() {
const app = express();
// Create Vite server in middleware mode
const vite = await createViteServer({
configFile: './vite.config.ts',
server: { middlewareMode: true },
appType: 'custom', // don't include Vite's default HTML handling middlewares
});
app.use(vite.middlewares);
app.use(express.static('dist'));
app.use(express.static('demos'));
app.use(express.static('cypress/platform'));
app.listen(9000, () => {
console.log(`Listening on http://localhost:9000`);
});
}
// build(getBuildConfig({ minify: false, watch: true }));
createServer();

6
.vite/tsconfig.json Normal file
View File

@ -0,0 +1,6 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"module": "ES2022"
}
}

View File

@ -1,4 +1,6 @@
import { Base64 } from 'js-base64';
const utf8ToB64 = (str) => {
return window.btoa(unescape(encodeURIComponent(str)));
};
export const mermaidUrl = (graphStr, options, api) => {
const obj = {
@ -6,7 +8,7 @@ export const mermaidUrl = (graphStr, options, api) => {
mermaid: options,
};
const objStr = JSON.stringify(obj);
let url = 'http://localhost:9000/e2e.html?graph=' + Base64.encodeURI(objStr);
let url = 'http://localhost:9000/e2e.html?graph=' + utf8ToB64(objStr);
if (api) {
url = 'http://localhost:9000/xss.html?graph=' + graphStr;
}

View File

@ -15,7 +15,7 @@ describe('XSS', () => {
it('should not allow tags in the css', () => {
const str =
'eyJjb2RlIjoiJSV7aW5pdDogeyAnZm9udEZhbWlseSc6ICdcXFwiPjwvc3R5bGU-PGltZyBzcmM9eCBvbmVycm9yPXhzc0F0dGFjaygpPid9IH0lJVxuZ3JhcGggTFJcbiAgICAgQSAtLT4gQiIsIm1lcm1haWQiOnsidGhlbWUiOiJkZWZhdWx0IiwiZmxvd2NoYXJ0Ijp7Imh0bWxMYWJlbHMiOmZhbHNlfX0sInVwZGF0ZUVkaXRvciI6ZmFsc2V9';
'eyJjb2RlIjoiJSV7aW5pdDogeyAnZm9udEZhbWlseSc6ICdcXFwiPjwvc3R5bGU+PGltZyBzcmM9eCBvbmVycm9yPXhzc0F0dGFjaygpPid9IH0lJVxuZ3JhcGggTFJcbiAgICAgQSAtLT4gQiIsIm1lcm1haWQiOnsidGhlbWUiOiJkZWZhdWx0IiwiZmxvd2NoYXJ0Ijp7Imh0bWxMYWJlbHMiOmZhbHNlfX0sInVwZGF0ZUVkaXRvciI6ZmFsc2V9';
const url = mermaidUrl(
str,

View File

@ -1,4 +1,4 @@
import mermaid from '../../dist/mermaid.core';
import mermaid from '../../src/mermaid';
let code = `flowchart LR
Power_Supply --> Transmitter_A

View File

@ -2,7 +2,7 @@
<head>
<meta charset="utf-8" />
<!-- <meta charset="iso-8859-15"/> -->
<script src="/e2e.esm.mjs" type="module"></script>
<script src="./viewer.js" type="module" />
<!-- <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"

View File

@ -1,6 +1,9 @@
import { Base64 } from 'js-base64';
import mermaid2 from '../../src/mermaid';
function b64ToUtf8(str) {
return decodeURIComponent(escape(window.atob(str)));
}
/**
* ##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
@ -11,7 +14,7 @@ const contentLoaded = function () {
if (pos > 0) {
pos = pos + 7;
const graphBase64 = document.location.href.substr(pos);
const graphObj = JSON.parse(Base64.decode(graphBase64));
const graphObj = JSON.parse(b64ToUtf8(graphBase64));
if (graphObj.mermaid && graphObj.mermaid.theme === 'dark') {
document.body.style.background = '#3f3f3f';
}
@ -67,7 +70,7 @@ const contentLoadedApi = function () {
if (pos > 0) {
pos = pos + 7;
const graphBase64 = document.location.href.substr(pos);
const graphObj = JSON.parse(Base64.decode(graphBase64));
const graphObj = JSON.parse(b64ToUtf8(graphBase64));
// const graph = 'hello'
if (Array.isArray(graphObj.code)) {
const numCodes = graphObj.code.length;

View File

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

View File

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

View File

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

View File

@ -25,19 +25,18 @@
],
"scripts": {
"clean": "rimraf dist",
"build:code": "node .esbuild/esbuild.cjs",
"build:vite": "ts-node-esm --transpileOnly --project=.vite/tsconfig.json .vite/build.ts",
"build:types": "tsc -p ./tsconfig.json --emitDeclarationOnly",
"build:watch": "yarn build:code --watch",
"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",
"build": "yarn clean; concurrently \"yarn build:vite\" \"yarn build:types\"",
"dev": "concurrently \"yarn build:vite --watch\" \"ts-node-esm .vite/server\"",
"docs:build": "ts-node-esm --transpileOnly src/docs.mts",
"docs:verify": "yarn docs:build --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",
"release": "yarn build",
"lint": "eslint --cache --ignore-path .gitignore . && yarn lint:jison && prettier --check .",
"lint:fix": "eslint --fix --ignore-path .gitignore . && prettier --write .",
"lint:jison": "ts-node-esm src/jison/lint.mts",
"lint:jison": "ts-node-esm --transpileOnly src/jison/lint.mts",
"cypress": "cypress run",
"cypress:open": "cypress open",
"e2e": "start-server-and-test dev http://localhost:9000/ cypress",
@ -99,7 +98,6 @@
"cypress": "^10.0.0",
"cypress-image-snapshot": "^4.0.1",
"documentation": "13.2.0",
"esbuild": "^0.15.8",
"eslint": "^8.23.1",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-cypress": "^2.12.1",
@ -113,7 +111,6 @@
"husky": "^8.0.0",
"identity-obj-proxy": "^3.0.0",
"jison": "^0.4.18",
"js-base64": "3.7.2",
"jsdom": "^20.0.0",
"lint-staged": "^13.0.0",
"moment": "^2.23.0",
@ -122,10 +119,12 @@
"prettier-plugin-jsdoc": "^0.4.2",
"remark": "^14.0.2",
"rimraf": "^3.0.2",
"rollup": "^2.79.1",
"start-server-and-test": "^1.12.6",
"ts-node": "^10.9.1",
"typescript": "^4.8.3",
"unist-util-flatmap": "^1.0.0",
"vite": "^3.0.9",
"vitest": "^0.23.1"
},
"resolutions": {

View File

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

View File

@ -1,4 +1,3 @@
'use strict';
/**
* Web page integration module for the mermaid framework. It uses the mermaidAPI for mermaid
* functionality and to render the diagrams to svg code.

View File

@ -1,38 +0,0 @@
import { Generator } from 'jison';
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: new Generator(src, { 'token-stack': true }).generate(),
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'],
coverage: {
reporter: ['text', 'json', 'html', 'lcov'],
},
},
});

17
vite.config.ts Normal file
View File

@ -0,0 +1,17 @@
import jison from './.vite/jisonPlugin';
import { defineConfig } from 'vitest/config';
export default defineConfig({
resolve: {
extensions: ['.jison', '.js', '.ts', '.json'],
},
plugins: [jison()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: ['src/tests/setup.ts'],
coverage: {
reporter: ['text', 'json', 'html', 'lcov'],
},
},
});

2278
yarn.lock

File diff suppressed because it is too large Load Diff