Skip to content

Commit

Permalink
Merge pull request #9 from jannis-baum/issue/8-linting
Browse files Browse the repository at this point in the history
Linting
  • Loading branch information
jannis-baum authored Jul 25, 2023
2 parents a81a075 + ae6380a commit 633b950
Show file tree
Hide file tree
Showing 11 changed files with 974 additions and 67 deletions.
8 changes: 8 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
parser: '@typescript-eslint/parser',
extends: [
'plugin:@typescript-eslint/recommended',
'prettier',
'plugin:prettier/recommended',
],
};
21 changes: 21 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: CI

on: push

jobs:
lint:
name: Lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: yarn
- run: yarn lint

build:
name: Build
needs: [lint]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: yarn
- run: yarn build
10 changes: 10 additions & 0 deletions .prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = {
semi: true,
endOfLine: 'lf',
bracketSpacing: true,
trailingComma: 'all',
arrowParens: 'always',
singleQuote: true,
tabWidth: 4,
printWidth: 100,
};
9 changes: 8 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"scripts": {
"dev-prog": "VIV_CMD='./node_modules/.bin/ts-node ./src/app.ts' ./viv",
"dev": "VIV_TIMEOUT=0 nodemon --exec ts-node ./src/app.ts",
"build": "tsc --project . && pkg ."
"build": "tsc --project . && pkg .",
"lint": "eslint src static"
},
"bin": "dist/app.js",
"pkg": {
Expand Down Expand Up @@ -35,8 +36,14 @@
"@types/node": "^20.4.2",
"@types/uuid": "^9.0.2",
"@types/ws": "^8.5.5",
"@typescript-eslint/eslint-plugin": "^6.2.0",
"@typescript-eslint/parser": "^6.2.0",
"eslint": "^8.45.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-prettier": "^5.0.0",
"nodemon": "^3.0.1",
"pkg": "^5.8.1",
"prettier": "^3.0.0",
"ts-node": "^10.9.1",
"typescript": "^5.1.6"
}
Expand Down
25 changes: 14 additions & 11 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import { router as healthRouter } from './routes/health';
import { router as viewerRouter } from './routes/viewer';
import { setupSockets } from './sockets';

process.env['VIV_PORT'] = process.env['VIV_PORT'] ?? '31622'
process.env['VIV_PORT'] = process.env['VIV_PORT'] ?? '31622';

const app = express()
const app = express();
app.use(express.json());
app.use((req, res, next) => {
res.locals.filepath = req.path
Expand All @@ -26,18 +26,21 @@ app.use('/viewer', viewerRouter);
const server = createServer(app);

server.listen(process.env['VIV_PORT'], () => {
console.log(`App is listening on port ${process.env['VIV_PORT']}!`)
})
console.log(`App is listening on port ${process.env['VIV_PORT']}!`);
});

let shutdownTimer: NodeJS.Timer | null = null
let shutdownTimer: NodeJS.Timer | null = null;
export const { clientsAt, messageClientsAt } = setupSockets(
server,
() => {
const timeout = parseInt(process.env['VIV_TIMEOUT'] ?? '10000')
if (timeout > 0) shutdownTimer = setInterval(() => {
console.log(`No clients for ${timeout}ms, shutting down.`)
process.exit(0)
}, timeout);
const timeout = parseInt(process.env['VIV_TIMEOUT'] ?? '10000');
if (timeout > 0)
shutdownTimer = setInterval(() => {
console.log(`No clients for ${timeout}ms, shutting down.`);
process.exit(0);
}, timeout);
},
() => {
if (shutdownTimer) clearInterval(shutdownTimer);
},
() => { if (shutdownTimer) clearInterval(shutdownTimer); }
);
36 changes: 21 additions & 15 deletions src/parser.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,45 @@
import { homedir } from "os";
import { homedir } from 'os';

import MarkdownIt from "markdown-it";
import hljs from "highlight.js";
import anchor from "markdown-it-anchor";
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import anchor from 'markdown-it-anchor';

const mdit = new MarkdownIt({
html: true,
highlight: (str, lang) => {
let content = str;
if (lang && hljs.getLanguage(lang)) {
try {
content = hljs.highlight(content, { language: lang, ignoreIllegals: true }).value;
content = hljs.highlight(content, {
language: lang,
ignoreIllegals: true,
}).value;
} catch (_) {}
}
return `<pre class="language-${lang}"><code>${content}</code></pre>`;
},
});

mdit.use(anchor, { permalink: anchor.permalink.ariaHidden({
placement: 'before'
}) });
mdit.use(require("markdown-it-emoji"));
mdit.use(require("markdown-it-task-lists"));
mdit.use(require("markdown-it-inject-linenumbers"));
mdit.use(require("markdown-it-katex"));
mdit.use(anchor, {
permalink: anchor.permalink.ariaHidden({
placement: 'before',
}),
});
/* eslint-disable @typescript-eslint/no-var-requires */
mdit.use(require('markdown-it-emoji'));
mdit.use(require('markdown-it-task-lists'));
mdit.use(require('markdown-it-inject-linenumbers'));
mdit.use(require('markdown-it-katex'));
/* eslint-enable @typescript-eslint/no-var-requires */

export const pathHeading = (path: string) =>
`# \`${path.replace(homedir(), '~')}\``
export const pathHeading = (path: string) => `# \`${path.replace(homedir(), '~')}\``;

export default function parse(src: string, path?: string) {
let md = src;

const fileEnding = path?.split('.')?.at(-1);
if (fileEnding && fileEnding !== 'md') {
md = `${pathHeading(path!)}\n\n\`\`\`${fileEnding}\n${src}\n\`\`\``
md = `${pathHeading(path!)}\n\n\`\`\`${fileEnding}\n${src}\n\`\`\``;
}

return mdit.render(md);
Expand Down
6 changes: 3 additions & 3 deletions src/routes/health.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Request, Response, Router } from "express";
import { Request, Response, Router } from 'express';

import { clientsAt } from "../app";
import { clientsAt } from '../app';

export const router = Router()
export const router = Router();

router.get('/', async (_: Request, res: Response) => {
res.end();
Expand Down
31 changes: 15 additions & 16 deletions src/routes/viewer.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { execSync } from "child_process";
import { lstatSync, readdirSync, readFileSync } from "fs";
import { basename, dirname, join } from "path";
import { execSync } from 'child_process';
import { lstatSync, readdirSync, readFileSync } from 'fs';
import { basename, dirname, join } from 'path';

import { Request, Response, Router } from "express";
import { Request, Response, Router } from 'express';

import { messageClientsAt } from "../app";
import parse, { pathHeading } from "../parser";
import { messageClientsAt } from '../app';
import parse, { pathHeading } from '../parser';

export const router = Router()
export const router = Router();

const liveContent = new Map<string, string>()
const liveContent = new Map<string, string>();

const getMimeFromPath = (path: string) =>
execSync(`file --mime-type -b '${path}'`).toString().trim();
Expand All @@ -21,9 +21,9 @@ router.get(/.*/, async (req: Request, res: Response) => {
if (!body) {
try {
if (lstatSync(path).isDirectory()) {
const list = readdirSync(path).map((item) =>
`- [\`${item}\`](/viewer${join(path, item)})`
).join('\n');
const list = readdirSync(path)
.map((item) => `- [\`${item}\`](/viewer${join(path, item)})`)
.join('\n');
body = parse(`${pathHeading(path)}\n\n${list}`);
} else {
const data = readFileSync(path);
Expand Down Expand Up @@ -63,7 +63,7 @@ router.get(/.*/, async (req: Request, res: Response) => {
<script type="text/javascript" src="/static/client.js"></script>
</html>
`);
})
});

router.post(/.*/, async (req: Request, res: Response) => {
const path = res.locals.filepath;
Expand All @@ -77,16 +77,15 @@ router.post(/.*/, async (req: Request, res: Response) => {
if (cursor) messageClientsAt(path, `SCROLL: ${cursor}`);

res.end();
})
});

router.delete(/.*/, async (req: Request, res: Response) => {
const path = req.path;
if (path === '/') {
const paths = [...liveContent.keys()]
const paths = [...liveContent.keys()];
liveContent.clear();
paths.forEach((path) => messageClientsAt(path, 'RELOAD: 1'));
}
else {
} else {
liveContent.delete(path) && messageClientsAt(path, 'RELOAD: 1');
}
res.end();
Expand Down
14 changes: 5 additions & 9 deletions src/sockets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ export function setupSockets(server: Server, onNoClients: () => void, onFirstCli
});

socket.on('message', (message) => {
const fields = message.toString().split(': ')
const fields = message.toString().split(': ');
if (fields.length != 2) return;
const [key, value] = fields;

switch (key) {
case 'PATH':
sockets.get(id)!.path = value
break
sockets.get(id)!.path = value;
break;
}
});
});
Expand All @@ -56,13 +56,9 @@ export function setupSockets(server: Server, onNoClients: () => void, onFirstCli

wss.on('close', () => clearInterval(interval));

const clientsAt = (p: string) =>
[...sockets.values()]
.filter(({ path }) => path == p);
const clientsAt = (p: string) => [...sockets.values()].filter(({ path }) => path == p);
const messageClientsAt = (p: string, message: string) =>
clientsAt(p)
.forEach(({ socket }) => socket.send(message))
clientsAt(p).forEach(({ socket }) => socket.send(message));

return { clientsAt, messageClientsAt };
}

7 changes: 5 additions & 2 deletions static/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ ws.addEventListener('open', () => {
});

ws.addEventListener('message', (event) => {
const fields = event.data.toString().split(': ')
const fields = event.data.toString().split(': ');
if (fields.length < 2) return;
const [key, ...values] = fields;
const value = values.join(': ');
Expand All @@ -19,7 +19,10 @@ ws.addEventListener('message', (event) => {
while (line) {
const targets = document.querySelectorAll(`[data-source-line="${line - 1}"]`);
if (targets.length) {
targets[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
targets[0].scrollIntoView({
behavior: 'smooth',
block: 'nearest',
});
break;
}
line -= 1;
Expand Down
Loading

0 comments on commit 633b950

Please sign in to comment.