Added Markdown support

This commit is contained in:
Magnus Åhall 2024-01-09 16:28:40 +01:00
parent 9bd4833e4b
commit 9bb203066c
29 changed files with 9771 additions and 220 deletions

4
go.sum
View File

@ -1,7 +1,7 @@
git.gibonuddevalla.se/go/dbschema v1.3.0 h1:HzFMR29tWfy/ibIjltTbIMI4inVktj/rh8bESALibgM= git.gibonuddevalla.se/go/dbschema v1.3.0 h1:HzFMR29tWfy/ibIjltTbIMI4inVktj/rh8bESALibgM=
git.gibonuddevalla.se/go/dbschema v1.3.0/go.mod h1:BNw3q/574nXbGoeWyK+tLhRfggVkw2j2aXZzrBKC3ig= git.gibonuddevalla.se/go/dbschema v1.3.0/go.mod h1:BNw3q/574nXbGoeWyK+tLhRfggVkw2j2aXZzrBKC3ig=
git.gibonuddevalla.se/go/webservice v0.1.1 h1:OTMp0OXJ26lRvBZeT5QqNOduVturFGe5+HdU7vyXXrI= git.gibonuddevalla.se/go/webservice v0.2.2 h1:pmfeLa7c9pSPbuu6TuzcJ6yuVwdMLJ8SSPm1IkusThk=
git.gibonuddevalla.se/go/webservice v0.1.1/go.mod h1:3uBS6nLbK9qbuGzDls8MZD5Xr9ORY1Srbj6v06BIhws= git.gibonuddevalla.se/go/webservice v0.2.2/go.mod h1:3uBS6nLbK9qbuGzDls8MZD5Xr9ORY1Srbj6v06BIhws=
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU= github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=

View File

@ -222,13 +222,14 @@ func nodeUpdate(w http.ResponseWriter, r *http.Request, sess *session.T) { // {{
NodeID int NodeID int
Content string Content string
CryptoKeyID int CryptoKeyID int
Markdown bool
}{} }{}
if err = parseRequest(r, &req); err != nil { if err = parseRequest(r, &req); err != nil {
responseError(w, err) responseError(w, err)
return return
} }
err = UpdateNode(sess.UserID, req.NodeID, req.Content, req.CryptoKeyID) err = UpdateNode(sess.UserID, req.NodeID, req.Content, req.CryptoKeyID, req.Markdown)
if err != nil { if err != nil {
responseError(w, err) responseError(w, err)
return return

58
node.go
View File

@ -23,9 +23,10 @@ type Node struct {
Level int Level int
ContentEncrypted string `db:"content_encrypted" json:"-"` ContentEncrypted string `db:"content_encrypted" json:"-"`
Markdown bool
} }
func NodeTree(userID, startNodeID int) (nodes []Node, err error) {// {{{ func NodeTree(userID, startNodeID int) (nodes []Node, err error) { // {{{
var rows *sqlx.Rows var rows *sqlx.Rows
rows, err = service.Db.Conn.Queryx(` rows, err = service.Db.Conn.Queryx(`
WITH RECURSIVE nodetree AS ( WITH RECURSIVE nodetree AS (
@ -89,8 +90,8 @@ func NodeTree(userID, startNodeID int) (nodes []Node, err error) {// {{{
} }
return return
}// }}} } // }}}
func RootNode(userID int) (node Node, err error) {// {{{ func RootNode(userID int) (node Node, err error) { // {{{
var rows *sqlx.Rows var rows *sqlx.Rows
rows, err = service.Db.Conn.Queryx(` rows, err = service.Db.Conn.Queryx(`
SELECT SELECT
@ -114,8 +115,8 @@ func RootNode(userID int) (node Node, err error) {// {{{
node.UserID = userID node.UserID = userID
node.Complete = true node.Complete = true
node.Children = []Node{} node.Children = []Node{}
node.Crumbs = []Node{} node.Crumbs = []Node{}
node.Files = []File{} node.Files = []File{}
for rows.Next() { for rows.Next() {
row := Node{} row := Node{}
if err = rows.StructScan(&row); err != nil { if err = rows.StructScan(&row); err != nil {
@ -131,8 +132,8 @@ func RootNode(userID int) (node Node, err error) {// {{{
} }
return return
}// }}} } // }}}
func RetrieveNode(userID, nodeID int) (node Node, err error) {// {{{ func RetrieveNode(userID, nodeID int) (node Node, err error) { // {{{
if nodeID == 0 { if nodeID == 0 {
return RootNode(userID) return RootNode(userID)
} }
@ -148,6 +149,7 @@ func RetrieveNode(userID, nodeID int) (node Node, err error) {// {{{
name, name,
content, content,
content_encrypted, content_encrypted,
markdown,
0 AS level 0 AS level
FROM node FROM node
WHERE WHERE
@ -164,6 +166,7 @@ func RetrieveNode(userID, nodeID int) (node Node, err error) {// {{{
n.name, n.name,
'' AS content, '' AS content,
'' AS content_encrypted, '' AS content_encrypted,
false AS markdown,
r.level + 1 AS level r.level + 1 AS level
FROM node n FROM node n
INNER JOIN recurse r ON n.parent_id = r.id AND r.level = 0 INNER JOIN recurse r ON n.parent_id = r.id AND r.level = 0
@ -195,12 +198,13 @@ func RetrieveNode(userID, nodeID int) (node Node, err error) {// {{{
} }
if row.Level == 0 { if row.Level == 0 {
node.ID = row.ID node.ID = row.ID
node.UserID = row.UserID node.UserID = row.UserID
node.ParentID = row.ParentID node.ParentID = row.ParentID
node.CryptoKeyID = row.CryptoKeyID node.CryptoKeyID = row.CryptoKeyID
node.Name = row.Name node.Name = row.Name
node.Complete = true node.Complete = true
node.Markdown = row.Markdown
if node.CryptoKeyID > 0 { if node.CryptoKeyID > 0 {
node.Content = row.ContentEncrypted node.Content = row.ContentEncrypted
@ -224,8 +228,8 @@ func RetrieveNode(userID, nodeID int) (node Node, err error) {// {{{
node.Files, err = Files(userID, node.ID, 0) node.Files, err = Files(userID, node.ID, 0)
return return
}// }}} } // }}}
func NodeCrumbs(nodeID int) (nodes []Node, err error) {// {{{ func NodeCrumbs(nodeID int) (nodes []Node, err error) { // {{{
var rows *sqlx.Rows var rows *sqlx.Rows
rows, err = service.Db.Conn.Queryx(` rows, err = service.Db.Conn.Queryx(`
WITH RECURSIVE nodes AS ( WITH RECURSIVE nodes AS (
@ -252,7 +256,7 @@ func NodeCrumbs(nodeID int) (nodes []Node, err error) {// {{{
return return
} }
defer rows.Close() defer rows.Close()
nodes = []Node{} nodes = []Node{}
for rows.Next() { for rows.Next() {
node := Node{} node := Node{}
@ -262,8 +266,8 @@ func NodeCrumbs(nodeID int) (nodes []Node, err error) {// {{{
nodes = append(nodes, node) nodes = append(nodes, node)
} }
return return
}// }}} } // }}}
func CreateNode(userID, parentID int, name string) (node Node, err error) {// {{{ func CreateNode(userID, parentID int, name string) (node Node, err error) { // {{{
var rows *sqlx.Rows var rows *sqlx.Rows
rows, err = service.Db.Conn.Queryx(` rows, err = service.Db.Conn.Queryx(`
@ -297,14 +301,15 @@ func CreateNode(userID, parentID int, name string) (node Node, err error) {// {{
node.Crumbs, err = NodeCrumbs(node.ID) node.Crumbs, err = NodeCrumbs(node.ID)
return return
}// }}} } // }}}
func UpdateNode(userID, nodeID int, content string, cryptoKeyID int) (err error) {// {{{ func UpdateNode(userID, nodeID int, content string, cryptoKeyID int, markdown bool) (err error) { // {{{
if cryptoKeyID > 0 { if cryptoKeyID > 0 {
_, err = service.Db.Conn.Exec(` _, err = service.Db.Conn.Exec(`
UPDATE node UPDATE node
SET SET
content = '', content = '',
content_encrypted = $1, content_encrypted = $1,
markdown = $5,
crypto_key_id = CASE $2::int crypto_key_id = CASE $2::int
WHEN 0 THEN NULL WHEN 0 THEN NULL
ELSE $2 ELSE $2
@ -317,6 +322,7 @@ func UpdateNode(userID, nodeID int, content string, cryptoKeyID int) (err error)
cryptoKeyID, cryptoKeyID,
nodeID, nodeID,
userID, userID,
markdown,
) )
} else { } else {
_, err = service.Db.Conn.Exec(` _, err = service.Db.Conn.Exec(`
@ -340,8 +346,8 @@ func UpdateNode(userID, nodeID int, content string, cryptoKeyID int) (err error)
} }
return return
}// }}} } // }}}
func RenameNode(userID, nodeID int, name string) (err error) {// {{{ func RenameNode(userID, nodeID int, name string) (err error) { // {{{
_, err = service.Db.Conn.Exec(` _, err = service.Db.Conn.Exec(`
UPDATE node SET name = $1 WHERE user_id = $2 AND id = $3 UPDATE node SET name = $1 WHERE user_id = $2 AND id = $3
`, `,
@ -350,8 +356,8 @@ func RenameNode(userID, nodeID int, name string) (err error) {// {{{
nodeID, nodeID,
) )
return return
}// }}} } // }}}
func DeleteNode(userID, nodeID int) (err error) {// {{{ func DeleteNode(userID, nodeID int) (err error) { // {{{
_, err = service.Db.Conn.Exec(` _, err = service.Db.Conn.Exec(`
WITH RECURSIVE nodetree AS ( WITH RECURSIVE nodetree AS (
SELECT SELECT
@ -375,8 +381,8 @@ func DeleteNode(userID, nodeID int) (err error) {// {{{
nodeID, nodeID,
) )
return return
}// }}} } // }}}
func SearchNodes(userID int, search string) (nodes []Node, err error) {// {{{ func SearchNodes(userID int, search string) (nodes []Node, err error) { // {{{
nodes = []Node{} nodes = []Node{}
var rows *sqlx.Rows var rows *sqlx.Rows
rows, err = service.Db.Conn.Queryx(` rows, err = service.Db.Conn.Queryx(`
@ -412,6 +418,6 @@ func SearchNodes(userID int, search string) (nodes []Node, err error) {// {{{
} }
return return
}// }}} } // }}}
// vim: foldmethod=marker // vim: foldmethod=marker

1
sql/00013.sql Normal file
View File

@ -0,0 +1 @@
ALTER TABLE public.node ADD COLUMN markdown bool NOT NULL DEFAULT false;

View File

@ -168,11 +168,13 @@ header .name {
padding-left: 16px; padding-left: 16px;
font-size: 1.25em; font-size: 1.25em;
} }
header .markdown,
header .search, header .search,
header .add, header .add,
header .keys { header .keys {
padding-right: 16px; padding-right: 16px;
} }
header .markdown img,
header .search img, header .search img,
header .add img, header .add img,
header .keys img { header .keys img {
@ -304,6 +306,20 @@ header .menu {
background: #f5f5f5; background: #f5f5f5;
padding-top: 16px; padding-top: 16px;
} }
#markdown {
padding: 16px;
color: #333;
grid-area: content;
max-width: 900px;
}
#markdown table {
border-collapse: collapse;
}
#markdown table th,
#markdown table td {
border: 1px solid #ddd;
padding: 4px 8px;
}
/* ============================================================= * /* ============================================================= *
* Textarea replicates the height of an element expanding height * * Textarea replicates the height of an element expanding height *
* ============================================================= */ * ============================================================= */

View File

@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Uploaded to: SVG Repo, www.svgrepo.com, Generator: SVG Repo Mixer Tools -->
<svg
fill="#000000"
width="365.05487"
height="224.67957"
viewBox="0 0 365.05487 224.67956"
role="img"
version="1.1"
id="svg1"
sodipodi:docname="markdown.svg"
inkscape:version="1.3.2 (1:1.3.2+202311252150+091e20ef0f)"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/">
<defs
id="defs1" />
<sodipodi:namedview
id="namedview1"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
showgrid="false"
inkscape:zoom="1.4827692"
inkscape:cx="400.26458"
inkscape:cy="394.53206"
inkscape:window-width="1916"
inkscape:window-height="1404"
inkscape:window-x="1280"
inkscape:window-y="16"
inkscape:window-maximized="0"
inkscape:current-layer="svg1" />
<title
id="title1">Markdown icon</title>
<path
d="M 338.73829,224.67957 H 26.316564 A 26.316564,26.316564 0 0 1 0,198.363 V 26.316564 A 26.316564,26.316564 0 0 1 26.316564,0 H 338.73829 a 26.316564,26.316564 0 0 1 26.31657,26.316564 V 198.33258 a 26.316564,26.316564 0 0 1 -26.31657,26.33177 z M 87.742162,172.01601 v -68.45349 l 35.109038,43.8863 35.09382,-43.8863 v 68.45349 h 35.10903 V 52.678763 H 157.94502 L 122.8512,96.565057 87.742162,52.678763 H 52.633128 V 172.04644 Z M 322.94835,112.33978 H 287.83932 V 52.663552 H 252.7455 v 59.676228 h -35.10904 l 52.64834,61.44081 z"
id="path1"
style="stroke-width:15.2119;fill:#ffffff;fill-opacity:1" />
<metadata
id="metadata1">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:title>Markdown icon</dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
</svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

View File

@ -25,6 +25,7 @@
} }
</script> </script>
<script type="text/javascript" src="/js/{{ .VERSION }}/lib/sjcl.js"></script> <script type="text/javascript" src="/js/{{ .VERSION }}/lib/sjcl.js"></script>
<script type="text/javascript" src="/js/{{ .VERSION }}/lib/node_modules/marked/marked.min.js"></script>
</head> </head>
<body> <body>

1
static/js/lib/node_modules/.bin/marked generated vendored Symbolic link
View File

@ -0,0 +1 @@
../marked/bin/marked.js

18
static/js/lib/node_modules/.package-lock.json generated vendored Normal file
View File

@ -0,0 +1,18 @@
{
"name": "lib",
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/marked": {
"version": "11.1.1",
"resolved": "https://registry.npmjs.org/marked/-/marked-11.1.1.tgz",
"integrity": "sha512-EgxRjgK9axsQuUa/oKMx5DEY8oXpKJfk61rT5iY3aRlgU6QJtUcxU5OAymdhCvWvhYcd9FKmO5eQoX8m9VGJXg==",
"bin": {
"marked": "bin/marked.js"
},
"engines": {
"node": ">= 18"
}
}
}
}

44
static/js/lib/node_modules/marked/LICENSE.md generated vendored Normal file
View File

@ -0,0 +1,44 @@
# License information
## Contribution License Agreement
If you contribute code to this project, you are implicitly allowing your code
to be distributed under the MIT license. You are also implicitly verifying that
all code is your original work. `</legalese>`
## Marked
Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/)
Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## Markdown
Copyright © 2004, John Gruber
http://daringfireball.net/
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.

107
static/js/lib/node_modules/marked/README.md generated vendored Normal file
View File

@ -0,0 +1,107 @@
<a href="https://marked.js.org">
<img width="60px" height="60px" src="https://marked.js.org/img/logo-black.svg" align="right" />
</a>
# Marked
[![npm](https://badgen.net/npm/v/marked)](https://www.npmjs.com/package/marked)
[![gzip size](https://badgen.net/badgesize/gzip/https://cdn.jsdelivr.net/npm/marked/marked.min.js)](https://cdn.jsdelivr.net/npm/marked/marked.min.js)
[![install size](https://badgen.net/packagephobia/install/marked)](https://packagephobia.now.sh/result?p=marked)
[![downloads](https://badgen.net/npm/dt/marked)](https://www.npmjs.com/package/marked)
[![github actions](https://github.com/markedjs/marked/workflows/Tests/badge.svg)](https://github.com/markedjs/marked/actions)
[![snyk](https://snyk.io/test/npm/marked/badge.svg)](https://snyk.io/test/npm/marked)
- ⚡ built for speed
- ⬇️ low-level compiler for parsing markdown without caching or blocking for long periods of time
- ⚖️ light-weight while implementing all markdown features from the supported flavors & specifications
- 🌐 works in a browser, on a server, or from a command line interface (CLI)
## Demo
Checkout the [demo page](https://marked.js.org/demo/) to see marked in action ⛹️
## Docs
Our [documentation pages](https://marked.js.org) are also rendered using marked 💯
Also read about:
* [Options](https://marked.js.org/using_advanced)
* [Extensibility](https://marked.js.org/using_pro)
## Compatibility
**Node.js:** Only [current and LTS](https://nodejs.org/en/about/releases/) Node.js versions are supported. End of life Node.js versions may become incompatible with Marked at any point in time.
**Browser:** Not IE11 :)
## Installation
**CLI:**
```sh
npm install -g marked
```
**In-browser:**
```sh
npm install marked
```
## Usage
### Warning: 🚨 Marked does not [sanitize](https://marked.js.org/using_advanced#options) the output HTML. Please use a sanitize library, like [DOMPurify](https://github.com/cure53/DOMPurify) (recommended), [sanitize-html](https://github.com/apostrophecms/sanitize-html) or [insane](https://github.com/bevacqua/insane) on the *output* HTML! 🚨
```
DOMPurify.sanitize(marked.parse(`<img src="x" onerror="alert('not happening')">`));
```
**CLI**
``` bash
# Example with stdin input
$ marked -o hello.html
hello world
^D
$ cat hello.html
<p>hello world</p>
```
```bash
# Print all options
$ marked --help
```
**Browser**
```html
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>Marked in the browser</title>
</head>
<body>
<div id="content"></div>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
document.getElementById('content').innerHTML =
marked.parse('# Marked in the browser\n\nRendered by **marked**.');
</script>
</body>
</html>
```
or import esm module
```html
<script type="module">
import { marked } from "https://cdn.jsdelivr.net/npm/marked/lib/marked.esm.js";
document.getElementById('content').innerHTML =
marked.parse('# Marked in the browser\n\nRendered by **marked**.');
</script>
```
## License
Copyright (c) 2011-2022, Christopher Jeffrey. (MIT License)

279
static/js/lib/node_modules/marked/bin/main.js generated vendored Normal file
View File

@ -0,0 +1,279 @@
#!/usr/bin/env node
/**
* Marked CLI
* Copyright (c) 2011-2013, Christopher Jeffrey (MIT License)
*/
import { promises } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { homedir } from 'node:os';
import { createRequire } from 'node:module';
import { marked } from '../lib/marked.esm.js';
const { access, readFile, writeFile } = promises;
const require = createRequire(import.meta.url);
/**
* @param {Process} nodeProcess inject process so it can be mocked in tests.
*/
export async function main(nodeProcess) {
/**
* Man Page
*/
async function help() {
const { spawn } = await import('child_process');
const { fileURLToPath } = await import('url');
const options = {
cwd: nodeProcess.cwd(),
env: nodeProcess.env,
stdio: 'inherit'
};
const __dirname = dirname(fileURLToPath(import.meta.url));
const helpText = await readFile(resolve(__dirname, '../man/marked.1.md'), 'utf8');
// eslint-disable-next-line promise/param-names
await new Promise(res => {
spawn('man', [resolve(__dirname, '../man/marked.1')], options)
.on('error', () => {
console.log(helpText);
})
.on('close', res);
});
}
async function version() {
const pkg = require('../package.json');
console.log(pkg.version);
}
/**
* Main
*/
async function start(argv) {
const files = [];
const options = {};
let input;
let output;
let string;
let arg;
let tokens;
let config;
let opt;
let noclobber;
function getArg() {
let arg = argv.shift();
if (arg.indexOf('--') === 0) {
// e.g. --opt
arg = arg.split('=');
if (arg.length > 1) {
// e.g. --opt=val
argv.unshift(arg.slice(1).join('='));
}
arg = arg[0];
} else if (arg[0] === '-') {
if (arg.length > 2) {
// e.g. -abc
argv = arg.substring(1).split('').map(function(ch) {
return '-' + ch;
}).concat(argv);
arg = argv.shift();
} else {
// e.g. -a
}
} else {
// e.g. foo
}
return arg;
}
while (argv.length) {
arg = getArg();
switch (arg) {
case '-o':
case '--output':
output = argv.shift();
break;
case '-i':
case '--input':
input = argv.shift();
break;
case '-s':
case '--string':
string = argv.shift();
break;
case '-t':
case '--tokens':
tokens = true;
break;
case '-c':
case '--config':
config = argv.shift();
break;
case '-n':
case '--no-clobber':
noclobber = true;
break;
case '-h':
case '--help':
return await help();
case '-v':
case '--version':
return await version();
default:
if (arg.indexOf('--') === 0) {
opt = camelize(arg.replace(/^--(no-)?/, ''));
if (!marked.defaults.hasOwnProperty(opt)) {
continue;
}
if (arg.indexOf('--no-') === 0) {
options[opt] = typeof marked.defaults[opt] !== 'boolean'
? null
: false;
} else {
options[opt] = typeof marked.defaults[opt] !== 'boolean'
? argv.shift()
: true;
}
} else {
files.push(arg);
}
break;
}
}
async function getData() {
if (!input) {
if (files.length <= 2) {
if (string) {
return string;
}
return await getStdin();
}
input = files.pop();
}
return await readFile(input, 'utf8');
}
function resolveFile(file) {
return resolve(file.replace(/^~/, homedir));
}
function fileExists(file) {
return access(resolveFile(file)).then(() => true, () => false);
}
async function runConfig(file) {
const configFile = resolveFile(file);
let markedConfig;
try {
// try require for json
markedConfig = require(configFile);
} catch (err) {
if (err.code !== 'ERR_REQUIRE_ESM') {
throw err;
}
// must import esm
markedConfig = await import('file:///' + configFile);
}
if (markedConfig.default) {
markedConfig = markedConfig.default;
}
if (typeof markedConfig === 'function') {
markedConfig(marked);
} else {
marked.use(markedConfig);
}
}
const data = await getData();
if (config) {
if (!await fileExists(config)) {
throw Error(`Cannot load config file '${config}'`);
}
await runConfig(config);
} else {
const defaultConfig = [
'~/.marked.json',
'~/.marked.js',
'~/.marked/index.js'
];
for (const configFile of defaultConfig) {
if (await fileExists(configFile)) {
await runConfig(configFile);
break;
}
}
}
const html = tokens
? JSON.stringify(marked.lexer(data, options), null, 2)
: await marked.parse(data, options);
if (output) {
if (noclobber && await fileExists(output)) {
nodeProcess.stderr.write('marked: output file \'' + output + '\' already exists, disable the \'-n\' / \'--no-clobber\' flag to overwrite\n');
nodeProcess.exit(1);
}
return await writeFile(output, html);
}
nodeProcess.stdout.write(html + '\n');
}
/**
* Helpers
*/
function getStdin() {
return new Promise((resolve, reject) => {
const stdin = nodeProcess.stdin;
let buff = '';
stdin.setEncoding('utf8');
stdin.on('data', function(data) {
buff += data;
});
stdin.on('error', function(err) {
reject(err);
});
stdin.on('end', function() {
resolve(buff);
});
stdin.resume();
});
}
/**
* @param {string} text
*/
function camelize(text) {
return text.replace(/(\w)-(\w)/g, function(_, a, b) {
return a + b.toUpperCase();
});
}
try {
await start(nodeProcess.argv.slice());
nodeProcess.exit(0);
} catch (err) {
if (err.code === 'ENOENT') {
nodeProcess.stderr.write('marked: output to ' + err.path + ': No such directory');
}
nodeProcess.stderr.write(err);
return nodeProcess.exit(1);
}
}

15
static/js/lib/node_modules/marked/bin/marked.js generated vendored Executable file
View File

@ -0,0 +1,15 @@
#!/usr/bin/env node
/**
* Marked CLI
* Copyright (c) 2011-2013, Christopher Jeffrey (MIT License)
*/
import { main } from './main.js';
/**
* Expose / Entry Point
*/
process.title = 'marked';
main(process);

2442
static/js/lib/node_modules/marked/lib/marked.cjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

1
static/js/lib/node_modules/marked/lib/marked.cjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

638
static/js/lib/node_modules/marked/lib/marked.d.cts generated vendored Normal file
View File

@ -0,0 +1,638 @@
// Generated by dts-bundle-generator v9.0.0
export type Token = (Tokens.Space | Tokens.Code | Tokens.Heading | Tokens.Table | Tokens.Hr | Tokens.Blockquote | Tokens.List | Tokens.ListItem | Tokens.Paragraph | Tokens.HTML | Tokens.Text | Tokens.Def | Tokens.Escape | Tokens.Tag | Tokens.Image | Tokens.Link | Tokens.Strong | Tokens.Em | Tokens.Codespan | Tokens.Br | Tokens.Del | Tokens.Generic);
export declare namespace Tokens {
interface Space {
type: "space";
raw: string;
}
interface Code {
type: "code";
raw: string;
codeBlockStyle?: "indented" | undefined;
lang?: string | undefined;
text: string;
escaped?: boolean;
}
interface Heading {
type: "heading";
raw: string;
depth: number;
text: string;
tokens: Token[];
}
interface Table {
type: "table";
raw: string;
align: Array<"center" | "left" | "right" | null>;
header: TableCell[];
rows: TableCell[][];
}
interface TableCell {
text: string;
tokens: Token[];
}
interface Hr {
type: "hr";
raw: string;
}
interface Blockquote {
type: "blockquote";
raw: string;
text: string;
tokens: Token[];
}
interface List {
type: "list";
raw: string;
ordered: boolean;
start: number | "";
loose: boolean;
items: ListItem[];
}
interface ListItem {
type: "list_item";
raw: string;
task: boolean;
checked?: boolean | undefined;
loose: boolean;
text: string;
tokens: Token[];
}
interface Paragraph {
type: "paragraph";
raw: string;
pre?: boolean | undefined;
text: string;
tokens: Token[];
}
interface HTML {
type: "html";
raw: string;
pre: boolean;
text: string;
block: boolean;
}
interface Text {
type: "text";
raw: string;
text: string;
tokens?: Token[];
}
interface Def {
type: "def";
raw: string;
tag: string;
href: string;
title: string;
}
interface Escape {
type: "escape";
raw: string;
text: string;
}
interface Tag {
type: "text" | "html";
raw: string;
inLink: boolean;
inRawBlock: boolean;
text: string;
block: boolean;
}
interface Link {
type: "link";
raw: string;
href: string;
title?: string | null;
text: string;
tokens: Token[];
}
interface Image {
type: "image";
raw: string;
href: string;
title: string | null;
text: string;
}
interface Strong {
type: "strong";
raw: string;
text: string;
tokens: Token[];
}
interface Em {
type: "em";
raw: string;
text: string;
tokens: Token[];
}
interface Codespan {
type: "codespan";
raw: string;
text: string;
}
interface Br {
type: "br";
raw: string;
}
interface Del {
type: "del";
raw: string;
text: string;
tokens: Token[];
}
interface Generic {
[index: string]: any;
type: string;
raw: string;
tokens?: Token[] | undefined;
}
}
export type Links = Record<string, Pick<Tokens.Link | Tokens.Image, "href" | "title">>;
export type TokensList = Token[] & {
links: Links;
};
declare class _Renderer {
options: MarkedOptions;
constructor(options?: MarkedOptions);
code(code: string, infostring: string | undefined, escaped: boolean): string;
blockquote(quote: string): string;
html(html: string, block?: boolean): string;
heading(text: string, level: number, raw: string): string;
hr(): string;
list(body: string, ordered: boolean, start: number | ""): string;
listitem(text: string, task: boolean, checked: boolean): string;
checkbox(checked: boolean): string;
paragraph(text: string): string;
table(header: string, body: string): string;
tablerow(content: string): string;
tablecell(content: string, flags: {
header: boolean;
align: "center" | "left" | "right" | null;
}): string;
/**
* span level renderer
*/
strong(text: string): string;
em(text: string): string;
codespan(text: string): string;
br(): string;
del(text: string): string;
link(href: string, title: string | null | undefined, text: string): string;
image(href: string, title: string | null, text: string): string;
text(text: string): string;
}
declare class _TextRenderer {
strong(text: string): string;
em(text: string): string;
codespan(text: string): string;
del(text: string): string;
html(text: string): string;
text(text: string): string;
link(href: string, title: string | null | undefined, text: string): string;
image(href: string, title: string | null, text: string): string;
br(): string;
}
declare class _Parser {
options: MarkedOptions;
renderer: _Renderer;
textRenderer: _TextRenderer;
constructor(options?: MarkedOptions);
/**
* Static Parse Method
*/
static parse(tokens: Token[], options?: MarkedOptions): string;
/**
* Static Parse Inline Method
*/
static parseInline(tokens: Token[], options?: MarkedOptions): string;
/**
* Parse Loop
*/
parse(tokens: Token[], top?: boolean): string;
/**
* Parse Inline Tokens
*/
parseInline(tokens: Token[], renderer?: _Renderer | _TextRenderer): string;
}
declare const blockNormal: {
blockquote: RegExp;
code: RegExp;
def: RegExp;
fences: RegExp;
heading: RegExp;
hr: RegExp;
html: RegExp;
lheading: RegExp;
list: RegExp;
newline: RegExp;
paragraph: RegExp;
table: RegExp;
text: RegExp;
};
export type BlockKeys = keyof typeof blockNormal;
declare const inlineNormal: {
_backpedal: RegExp;
anyPunctuation: RegExp;
autolink: RegExp;
blockSkip: RegExp;
br: RegExp;
code: RegExp;
del: RegExp;
emStrongLDelim: RegExp;
emStrongRDelimAst: RegExp;
emStrongRDelimUnd: RegExp;
escape: RegExp;
link: RegExp;
nolink: RegExp;
punctuation: RegExp;
reflink: RegExp;
reflinkSearch: RegExp;
tag: RegExp;
text: RegExp;
url: RegExp;
};
export type InlineKeys = keyof typeof inlineNormal;
/**
* exports
*/
export declare const block: {
normal: {
blockquote: RegExp;
code: RegExp;
def: RegExp;
fences: RegExp;
heading: RegExp;
hr: RegExp;
html: RegExp;
lheading: RegExp;
list: RegExp;
newline: RegExp;
paragraph: RegExp;
table: RegExp;
text: RegExp;
};
gfm: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>;
pedantic: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>;
};
export declare const inline: {
normal: {
_backpedal: RegExp;
anyPunctuation: RegExp;
autolink: RegExp;
blockSkip: RegExp;
br: RegExp;
code: RegExp;
del: RegExp;
emStrongLDelim: RegExp;
emStrongRDelimAst: RegExp;
emStrongRDelimUnd: RegExp;
escape: RegExp;
link: RegExp;
nolink: RegExp;
punctuation: RegExp;
reflink: RegExp;
reflinkSearch: RegExp;
tag: RegExp;
text: RegExp;
url: RegExp;
};
gfm: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>;
breaks: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>;
pedantic: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>;
};
export interface Rules {
block: Record<BlockKeys, RegExp>;
inline: Record<InlineKeys, RegExp>;
}
declare class _Tokenizer {
options: MarkedOptions;
rules: Rules;
lexer: _Lexer;
constructor(options?: MarkedOptions);
space(src: string): Tokens.Space | undefined;
code(src: string): Tokens.Code | undefined;
fences(src: string): Tokens.Code | undefined;
heading(src: string): Tokens.Heading | undefined;
hr(src: string): Tokens.Hr | undefined;
blockquote(src: string): Tokens.Blockquote | undefined;
list(src: string): Tokens.List | undefined;
html(src: string): Tokens.HTML | undefined;
def(src: string): Tokens.Def | undefined;
table(src: string): Tokens.Table | undefined;
lheading(src: string): Tokens.Heading | undefined;
paragraph(src: string): Tokens.Paragraph | undefined;
text(src: string): Tokens.Text | undefined;
escape(src: string): Tokens.Escape | undefined;
tag(src: string): Tokens.Tag | undefined;
link(src: string): Tokens.Link | Tokens.Image | undefined;
reflink(src: string, links: Links): Tokens.Link | Tokens.Image | Tokens.Text | undefined;
emStrong(src: string, maskedSrc: string, prevChar?: string): Tokens.Em | Tokens.Strong | undefined;
codespan(src: string): Tokens.Codespan | undefined;
br(src: string): Tokens.Br | undefined;
del(src: string): Tokens.Del | undefined;
autolink(src: string): Tokens.Link | undefined;
url(src: string): Tokens.Link | undefined;
inlineText(src: string): Tokens.Text | undefined;
}
declare class _Hooks {
options: MarkedOptions;
constructor(options?: MarkedOptions);
static passThroughHooks: Set<string>;
/**
* Process markdown before marked
*/
preprocess(markdown: string): string;
/**
* Process HTML after marked is finished
*/
postprocess(html: string): string;
/**
* Process all tokens before walk tokens
*/
processAllTokens(tokens: Token[] | TokensList): Token[] | TokensList;
}
export interface TokenizerThis {
lexer: _Lexer;
}
export type TokenizerExtensionFunction = (this: TokenizerThis, src: string, tokens: Token[] | TokensList) => Tokens.Generic | undefined;
export type TokenizerStartFunction = (this: TokenizerThis, src: string) => number | void;
export interface TokenizerExtension {
name: string;
level: "block" | "inline";
start?: TokenizerStartFunction | undefined;
tokenizer: TokenizerExtensionFunction;
childTokens?: string[] | undefined;
}
export interface RendererThis {
parser: _Parser;
}
export type RendererExtensionFunction = (this: RendererThis, token: Tokens.Generic) => string | false | undefined;
export interface RendererExtension {
name: string;
renderer: RendererExtensionFunction;
}
export type TokenizerAndRendererExtension = TokenizerExtension | RendererExtension | (TokenizerExtension & RendererExtension);
export type HooksApi = Omit<_Hooks, "constructor" | "options">;
export type HooksObject = {
[K in keyof HooksApi]?: (...args: Parameters<HooksApi[K]>) => ReturnType<HooksApi[K]> | Promise<ReturnType<HooksApi[K]>>;
};
export type RendererApi = Omit<_Renderer, "constructor" | "options">;
export type RendererObject = {
[K in keyof RendererApi]?: (...args: Parameters<RendererApi[K]>) => ReturnType<RendererApi[K]> | false;
};
export type TokenizerApi = Omit<_Tokenizer, "constructor" | "options" | "rules" | "lexer">;
export type TokenizerObject = {
[K in keyof TokenizerApi]?: (...args: Parameters<TokenizerApi[K]>) => ReturnType<TokenizerApi[K]> | false;
};
export interface MarkedExtension {
/**
* True will tell marked to await any walkTokens functions before parsing the tokens and returning an HTML string.
*/
async?: boolean;
/**
* Enable GFM line breaks. This option requires the gfm option to be true.
*/
breaks?: boolean | undefined;
/**
* Add tokenizers and renderers to marked
*/
extensions?: TokenizerAndRendererExtension[] | undefined | null;
/**
* Enable GitHub flavored markdown.
*/
gfm?: boolean | undefined;
/**
* Hooks are methods that hook into some part of marked.
* preprocess is called to process markdown before sending it to marked.
* processAllTokens is called with the TokensList before walkTokens.
* postprocess is called to process html after marked has finished parsing.
*/
hooks?: HooksObject | undefined | null;
/**
* Conform to obscure parts of markdown.pl as much as possible. Don't fix any of the original markdown bugs or poor behavior.
*/
pedantic?: boolean | undefined;
/**
* Type: object Default: new Renderer()
*
* An object containing functions to render tokens to HTML.
*/
renderer?: RendererObject | undefined | null;
/**
* Shows an HTML error message when rendering fails.
*/
silent?: boolean | undefined;
/**
* The tokenizer defines how to turn markdown text into tokens.
*/
tokenizer?: TokenizerObject | undefined | null;
/**
* The walkTokens function gets called with every token.
* Child tokens are called before moving on to sibling tokens.
* Each token is passed by reference so updates are persisted when passed to the parser.
* The return value of the function is ignored.
*/
walkTokens?: ((token: Token) => void | Promise<void>) | undefined | null;
}
export interface MarkedOptions extends Omit<MarkedExtension, "hooks" | "renderer" | "tokenizer" | "extensions" | "walkTokens"> {
/**
* Hooks are methods that hook into some part of marked.
*/
hooks?: _Hooks | undefined | null;
/**
* Type: object Default: new Renderer()
*
* An object containing functions to render tokens to HTML.
*/
renderer?: _Renderer | undefined | null;
/**
* The tokenizer defines how to turn markdown text into tokens.
*/
tokenizer?: _Tokenizer | undefined | null;
/**
* Custom extensions
*/
extensions?: null | {
renderers: {
[name: string]: RendererExtensionFunction;
};
childTokens: {
[name: string]: string[];
};
inline?: TokenizerExtensionFunction[];
block?: TokenizerExtensionFunction[];
startInline?: TokenizerStartFunction[];
startBlock?: TokenizerStartFunction[];
};
/**
* walkTokens function returns array of values for Promise.all
*/
walkTokens?: null | ((token: Token) => void | Promise<void> | (void | Promise<void>)[]);
}
declare class _Lexer {
tokens: TokensList;
options: MarkedOptions;
state: {
inLink: boolean;
inRawBlock: boolean;
top: boolean;
};
private tokenizer;
private inlineQueue;
constructor(options?: MarkedOptions);
/**
* Expose Rules
*/
static get rules(): {
block: {
normal: {
blockquote: RegExp;
code: RegExp;
def: RegExp;
fences: RegExp;
heading: RegExp;
hr: RegExp;
html: RegExp;
lheading: RegExp;
list: RegExp;
newline: RegExp;
paragraph: RegExp;
table: RegExp;
text: RegExp;
};
gfm: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>;
pedantic: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>;
};
inline: {
normal: {
_backpedal: RegExp;
anyPunctuation: RegExp;
autolink: RegExp;
blockSkip: RegExp;
br: RegExp;
code: RegExp;
del: RegExp;
emStrongLDelim: RegExp;
emStrongRDelimAst: RegExp;
emStrongRDelimUnd: RegExp;
escape: RegExp;
link: RegExp;
nolink: RegExp;
punctuation: RegExp;
reflink: RegExp;
reflinkSearch: RegExp;
tag: RegExp;
text: RegExp;
url: RegExp;
};
gfm: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>;
breaks: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>;
pedantic: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>;
};
};
/**
* Static Lex Method
*/
static lex(src: string, options?: MarkedOptions): TokensList;
/**
* Static Lex Inline Method
*/
static lexInline(src: string, options?: MarkedOptions): Token[];
/**
* Preprocessing
*/
lex(src: string): TokensList;
/**
* Lexing
*/
blockTokens(src: string, tokens?: Token[]): Token[];
blockTokens(src: string, tokens?: TokensList): TokensList;
inline(src: string, tokens?: Token[]): Token[];
/**
* Lexing/Compiling
*/
inlineTokens(src: string, tokens?: Token[]): Token[];
}
declare function _getDefaults(): MarkedOptions;
declare let _defaults: MarkedOptions;
export type MaybePromise = void | Promise<void>;
export declare class Marked {
#private;
defaults: MarkedOptions;
options: (opt: MarkedOptions) => this;
parse: (src: string, options?: MarkedOptions | undefined | null) => string | Promise<string>;
parseInline: (src: string, options?: MarkedOptions | undefined | null) => string | Promise<string>;
Parser: typeof _Parser;
Renderer: typeof _Renderer;
TextRenderer: typeof _TextRenderer;
Lexer: typeof _Lexer;
Tokenizer: typeof _Tokenizer;
Hooks: typeof _Hooks;
constructor(...args: MarkedExtension[]);
/**
* Run callback for every token
*/
walkTokens(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]): MaybePromise[];
use(...args: MarkedExtension[]): this;
setOptions(opt: MarkedOptions): this;
lexer(src: string, options?: MarkedOptions): TokensList;
parser(tokens: Token[], options?: MarkedOptions): string;
}
/**
* Compiles markdown to HTML asynchronously.
*
* @param src String of markdown source to be compiled
* @param options Hash of options, having async: true
* @return Promise of string of compiled HTML
*/
export declare function marked(src: string, options: MarkedOptions & {
async: true;
}): Promise<string>;
/**
* Compiles markdown to HTML.
*
* @param src String of markdown source to be compiled
* @param options Optional hash of options
* @return String of compiled HTML. Wil be a Promise of string if async is set to true by any extensions.
*/
export declare function marked(src: string, options?: MarkedOptions): string | Promise<string>;
export declare namespace marked {
var options: (options: MarkedOptions) => typeof marked;
var setOptions: (options: MarkedOptions) => typeof marked;
var getDefaults: typeof _getDefaults;
var defaults: MarkedOptions;
var use: (...args: MarkedExtension[]) => typeof marked;
var walkTokens: (tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) => MaybePromise[];
var parseInline: (src: string, options?: MarkedOptions | null | undefined) => string | Promise<string>;
var Parser: typeof _Parser;
var parser: typeof _Parser.parse;
var Renderer: typeof _Renderer;
var TextRenderer: typeof _TextRenderer;
var Lexer: typeof _Lexer;
var lexer: typeof _Lexer.lex;
var Tokenizer: typeof _Tokenizer;
var Hooks: typeof _Hooks;
var parse: typeof marked;
}
export declare const options: (options: MarkedOptions) => typeof marked;
export declare const setOptions: (options: MarkedOptions) => typeof marked;
export declare const use: (...args: MarkedExtension[]) => typeof marked;
export declare const walkTokens: (tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) => MaybePromise[];
export declare const parseInline: (src: string, options?: MarkedOptions | null | undefined) => string | Promise<string>;
export declare const parse: typeof marked;
export declare const parser: typeof _Parser.parse;
export declare const lexer: typeof _Lexer.lex;
export {
_Hooks as Hooks,
_Lexer as Lexer,
_Parser as Parser,
_Renderer as Renderer,
_TextRenderer as TextRenderer,
_Tokenizer as Tokenizer,
_defaults as defaults,
_getDefaults as getDefaults,
};
export {};

638
static/js/lib/node_modules/marked/lib/marked.d.ts generated vendored Normal file
View File

@ -0,0 +1,638 @@
// Generated by dts-bundle-generator v9.0.0
export type Token = (Tokens.Space | Tokens.Code | Tokens.Heading | Tokens.Table | Tokens.Hr | Tokens.Blockquote | Tokens.List | Tokens.ListItem | Tokens.Paragraph | Tokens.HTML | Tokens.Text | Tokens.Def | Tokens.Escape | Tokens.Tag | Tokens.Image | Tokens.Link | Tokens.Strong | Tokens.Em | Tokens.Codespan | Tokens.Br | Tokens.Del | Tokens.Generic);
export declare namespace Tokens {
interface Space {
type: "space";
raw: string;
}
interface Code {
type: "code";
raw: string;
codeBlockStyle?: "indented" | undefined;
lang?: string | undefined;
text: string;
escaped?: boolean;
}
interface Heading {
type: "heading";
raw: string;
depth: number;
text: string;
tokens: Token[];
}
interface Table {
type: "table";
raw: string;
align: Array<"center" | "left" | "right" | null>;
header: TableCell[];
rows: TableCell[][];
}
interface TableCell {
text: string;
tokens: Token[];
}
interface Hr {
type: "hr";
raw: string;
}
interface Blockquote {
type: "blockquote";
raw: string;
text: string;
tokens: Token[];
}
interface List {
type: "list";
raw: string;
ordered: boolean;
start: number | "";
loose: boolean;
items: ListItem[];
}
interface ListItem {
type: "list_item";
raw: string;
task: boolean;
checked?: boolean | undefined;
loose: boolean;
text: string;
tokens: Token[];
}
interface Paragraph {
type: "paragraph";
raw: string;
pre?: boolean | undefined;
text: string;
tokens: Token[];
}
interface HTML {
type: "html";
raw: string;
pre: boolean;
text: string;
block: boolean;
}
interface Text {
type: "text";
raw: string;
text: string;
tokens?: Token[];
}
interface Def {
type: "def";
raw: string;
tag: string;
href: string;
title: string;
}
interface Escape {
type: "escape";
raw: string;
text: string;
}
interface Tag {
type: "text" | "html";
raw: string;
inLink: boolean;
inRawBlock: boolean;
text: string;
block: boolean;
}
interface Link {
type: "link";
raw: string;
href: string;
title?: string | null;
text: string;
tokens: Token[];
}
interface Image {
type: "image";
raw: string;
href: string;
title: string | null;
text: string;
}
interface Strong {
type: "strong";
raw: string;
text: string;
tokens: Token[];
}
interface Em {
type: "em";
raw: string;
text: string;
tokens: Token[];
}
interface Codespan {
type: "codespan";
raw: string;
text: string;
}
interface Br {
type: "br";
raw: string;
}
interface Del {
type: "del";
raw: string;
text: string;
tokens: Token[];
}
interface Generic {
[index: string]: any;
type: string;
raw: string;
tokens?: Token[] | undefined;
}
}
export type Links = Record<string, Pick<Tokens.Link | Tokens.Image, "href" | "title">>;
export type TokensList = Token[] & {
links: Links;
};
declare class _Renderer {
options: MarkedOptions;
constructor(options?: MarkedOptions);
code(code: string, infostring: string | undefined, escaped: boolean): string;
blockquote(quote: string): string;
html(html: string, block?: boolean): string;
heading(text: string, level: number, raw: string): string;
hr(): string;
list(body: string, ordered: boolean, start: number | ""): string;
listitem(text: string, task: boolean, checked: boolean): string;
checkbox(checked: boolean): string;
paragraph(text: string): string;
table(header: string, body: string): string;
tablerow(content: string): string;
tablecell(content: string, flags: {
header: boolean;
align: "center" | "left" | "right" | null;
}): string;
/**
* span level renderer
*/
strong(text: string): string;
em(text: string): string;
codespan(text: string): string;
br(): string;
del(text: string): string;
link(href: string, title: string | null | undefined, text: string): string;
image(href: string, title: string | null, text: string): string;
text(text: string): string;
}
declare class _TextRenderer {
strong(text: string): string;
em(text: string): string;
codespan(text: string): string;
del(text: string): string;
html(text: string): string;
text(text: string): string;
link(href: string, title: string | null | undefined, text: string): string;
image(href: string, title: string | null, text: string): string;
br(): string;
}
declare class _Parser {
options: MarkedOptions;
renderer: _Renderer;
textRenderer: _TextRenderer;
constructor(options?: MarkedOptions);
/**
* Static Parse Method
*/
static parse(tokens: Token[], options?: MarkedOptions): string;
/**
* Static Parse Inline Method
*/
static parseInline(tokens: Token[], options?: MarkedOptions): string;
/**
* Parse Loop
*/
parse(tokens: Token[], top?: boolean): string;
/**
* Parse Inline Tokens
*/
parseInline(tokens: Token[], renderer?: _Renderer | _TextRenderer): string;
}
declare const blockNormal: {
blockquote: RegExp;
code: RegExp;
def: RegExp;
fences: RegExp;
heading: RegExp;
hr: RegExp;
html: RegExp;
lheading: RegExp;
list: RegExp;
newline: RegExp;
paragraph: RegExp;
table: RegExp;
text: RegExp;
};
export type BlockKeys = keyof typeof blockNormal;
declare const inlineNormal: {
_backpedal: RegExp;
anyPunctuation: RegExp;
autolink: RegExp;
blockSkip: RegExp;
br: RegExp;
code: RegExp;
del: RegExp;
emStrongLDelim: RegExp;
emStrongRDelimAst: RegExp;
emStrongRDelimUnd: RegExp;
escape: RegExp;
link: RegExp;
nolink: RegExp;
punctuation: RegExp;
reflink: RegExp;
reflinkSearch: RegExp;
tag: RegExp;
text: RegExp;
url: RegExp;
};
export type InlineKeys = keyof typeof inlineNormal;
/**
* exports
*/
export declare const block: {
normal: {
blockquote: RegExp;
code: RegExp;
def: RegExp;
fences: RegExp;
heading: RegExp;
hr: RegExp;
html: RegExp;
lheading: RegExp;
list: RegExp;
newline: RegExp;
paragraph: RegExp;
table: RegExp;
text: RegExp;
};
gfm: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>;
pedantic: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>;
};
export declare const inline: {
normal: {
_backpedal: RegExp;
anyPunctuation: RegExp;
autolink: RegExp;
blockSkip: RegExp;
br: RegExp;
code: RegExp;
del: RegExp;
emStrongLDelim: RegExp;
emStrongRDelimAst: RegExp;
emStrongRDelimUnd: RegExp;
escape: RegExp;
link: RegExp;
nolink: RegExp;
punctuation: RegExp;
reflink: RegExp;
reflinkSearch: RegExp;
tag: RegExp;
text: RegExp;
url: RegExp;
};
gfm: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>;
breaks: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>;
pedantic: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>;
};
export interface Rules {
block: Record<BlockKeys, RegExp>;
inline: Record<InlineKeys, RegExp>;
}
declare class _Tokenizer {
options: MarkedOptions;
rules: Rules;
lexer: _Lexer;
constructor(options?: MarkedOptions);
space(src: string): Tokens.Space | undefined;
code(src: string): Tokens.Code | undefined;
fences(src: string): Tokens.Code | undefined;
heading(src: string): Tokens.Heading | undefined;
hr(src: string): Tokens.Hr | undefined;
blockquote(src: string): Tokens.Blockquote | undefined;
list(src: string): Tokens.List | undefined;
html(src: string): Tokens.HTML | undefined;
def(src: string): Tokens.Def | undefined;
table(src: string): Tokens.Table | undefined;
lheading(src: string): Tokens.Heading | undefined;
paragraph(src: string): Tokens.Paragraph | undefined;
text(src: string): Tokens.Text | undefined;
escape(src: string): Tokens.Escape | undefined;
tag(src: string): Tokens.Tag | undefined;
link(src: string): Tokens.Link | Tokens.Image | undefined;
reflink(src: string, links: Links): Tokens.Link | Tokens.Image | Tokens.Text | undefined;
emStrong(src: string, maskedSrc: string, prevChar?: string): Tokens.Em | Tokens.Strong | undefined;
codespan(src: string): Tokens.Codespan | undefined;
br(src: string): Tokens.Br | undefined;
del(src: string): Tokens.Del | undefined;
autolink(src: string): Tokens.Link | undefined;
url(src: string): Tokens.Link | undefined;
inlineText(src: string): Tokens.Text | undefined;
}
declare class _Hooks {
options: MarkedOptions;
constructor(options?: MarkedOptions);
static passThroughHooks: Set<string>;
/**
* Process markdown before marked
*/
preprocess(markdown: string): string;
/**
* Process HTML after marked is finished
*/
postprocess(html: string): string;
/**
* Process all tokens before walk tokens
*/
processAllTokens(tokens: Token[] | TokensList): Token[] | TokensList;
}
export interface TokenizerThis {
lexer: _Lexer;
}
export type TokenizerExtensionFunction = (this: TokenizerThis, src: string, tokens: Token[] | TokensList) => Tokens.Generic | undefined;
export type TokenizerStartFunction = (this: TokenizerThis, src: string) => number | void;
export interface TokenizerExtension {
name: string;
level: "block" | "inline";
start?: TokenizerStartFunction | undefined;
tokenizer: TokenizerExtensionFunction;
childTokens?: string[] | undefined;
}
export interface RendererThis {
parser: _Parser;
}
export type RendererExtensionFunction = (this: RendererThis, token: Tokens.Generic) => string | false | undefined;
export interface RendererExtension {
name: string;
renderer: RendererExtensionFunction;
}
export type TokenizerAndRendererExtension = TokenizerExtension | RendererExtension | (TokenizerExtension & RendererExtension);
export type HooksApi = Omit<_Hooks, "constructor" | "options">;
export type HooksObject = {
[K in keyof HooksApi]?: (...args: Parameters<HooksApi[K]>) => ReturnType<HooksApi[K]> | Promise<ReturnType<HooksApi[K]>>;
};
export type RendererApi = Omit<_Renderer, "constructor" | "options">;
export type RendererObject = {
[K in keyof RendererApi]?: (...args: Parameters<RendererApi[K]>) => ReturnType<RendererApi[K]> | false;
};
export type TokenizerApi = Omit<_Tokenizer, "constructor" | "options" | "rules" | "lexer">;
export type TokenizerObject = {
[K in keyof TokenizerApi]?: (...args: Parameters<TokenizerApi[K]>) => ReturnType<TokenizerApi[K]> | false;
};
export interface MarkedExtension {
/**
* True will tell marked to await any walkTokens functions before parsing the tokens and returning an HTML string.
*/
async?: boolean;
/**
* Enable GFM line breaks. This option requires the gfm option to be true.
*/
breaks?: boolean | undefined;
/**
* Add tokenizers and renderers to marked
*/
extensions?: TokenizerAndRendererExtension[] | undefined | null;
/**
* Enable GitHub flavored markdown.
*/
gfm?: boolean | undefined;
/**
* Hooks are methods that hook into some part of marked.
* preprocess is called to process markdown before sending it to marked.
* processAllTokens is called with the TokensList before walkTokens.
* postprocess is called to process html after marked has finished parsing.
*/
hooks?: HooksObject | undefined | null;
/**
* Conform to obscure parts of markdown.pl as much as possible. Don't fix any of the original markdown bugs or poor behavior.
*/
pedantic?: boolean | undefined;
/**
* Type: object Default: new Renderer()
*
* An object containing functions to render tokens to HTML.
*/
renderer?: RendererObject | undefined | null;
/**
* Shows an HTML error message when rendering fails.
*/
silent?: boolean | undefined;
/**
* The tokenizer defines how to turn markdown text into tokens.
*/
tokenizer?: TokenizerObject | undefined | null;
/**
* The walkTokens function gets called with every token.
* Child tokens are called before moving on to sibling tokens.
* Each token is passed by reference so updates are persisted when passed to the parser.
* The return value of the function is ignored.
*/
walkTokens?: ((token: Token) => void | Promise<void>) | undefined | null;
}
export interface MarkedOptions extends Omit<MarkedExtension, "hooks" | "renderer" | "tokenizer" | "extensions" | "walkTokens"> {
/**
* Hooks are methods that hook into some part of marked.
*/
hooks?: _Hooks | undefined | null;
/**
* Type: object Default: new Renderer()
*
* An object containing functions to render tokens to HTML.
*/
renderer?: _Renderer | undefined | null;
/**
* The tokenizer defines how to turn markdown text into tokens.
*/
tokenizer?: _Tokenizer | undefined | null;
/**
* Custom extensions
*/
extensions?: null | {
renderers: {
[name: string]: RendererExtensionFunction;
};
childTokens: {
[name: string]: string[];
};
inline?: TokenizerExtensionFunction[];
block?: TokenizerExtensionFunction[];
startInline?: TokenizerStartFunction[];
startBlock?: TokenizerStartFunction[];
};
/**
* walkTokens function returns array of values for Promise.all
*/
walkTokens?: null | ((token: Token) => void | Promise<void> | (void | Promise<void>)[]);
}
declare class _Lexer {
tokens: TokensList;
options: MarkedOptions;
state: {
inLink: boolean;
inRawBlock: boolean;
top: boolean;
};
private tokenizer;
private inlineQueue;
constructor(options?: MarkedOptions);
/**
* Expose Rules
*/
static get rules(): {
block: {
normal: {
blockquote: RegExp;
code: RegExp;
def: RegExp;
fences: RegExp;
heading: RegExp;
hr: RegExp;
html: RegExp;
lheading: RegExp;
list: RegExp;
newline: RegExp;
paragraph: RegExp;
table: RegExp;
text: RegExp;
};
gfm: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>;
pedantic: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "heading" | "list" | "paragraph" | "def" | "fences" | "lheading" | "newline", RegExp>;
};
inline: {
normal: {
_backpedal: RegExp;
anyPunctuation: RegExp;
autolink: RegExp;
blockSkip: RegExp;
br: RegExp;
code: RegExp;
del: RegExp;
emStrongLDelim: RegExp;
emStrongRDelimAst: RegExp;
emStrongRDelimUnd: RegExp;
escape: RegExp;
link: RegExp;
nolink: RegExp;
punctuation: RegExp;
reflink: RegExp;
reflinkSearch: RegExp;
tag: RegExp;
text: RegExp;
url: RegExp;
};
gfm: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>;
breaks: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>;
pedantic: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "autolink" | "nolink" | "_backpedal" | "anyPunctuation" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>;
};
};
/**
* Static Lex Method
*/
static lex(src: string, options?: MarkedOptions): TokensList;
/**
* Static Lex Inline Method
*/
static lexInline(src: string, options?: MarkedOptions): Token[];
/**
* Preprocessing
*/
lex(src: string): TokensList;
/**
* Lexing
*/
blockTokens(src: string, tokens?: Token[]): Token[];
blockTokens(src: string, tokens?: TokensList): TokensList;
inline(src: string, tokens?: Token[]): Token[];
/**
* Lexing/Compiling
*/
inlineTokens(src: string, tokens?: Token[]): Token[];
}
declare function _getDefaults(): MarkedOptions;
declare let _defaults: MarkedOptions;
export type MaybePromise = void | Promise<void>;
export declare class Marked {
#private;
defaults: MarkedOptions;
options: (opt: MarkedOptions) => this;
parse: (src: string, options?: MarkedOptions | undefined | null) => string | Promise<string>;
parseInline: (src: string, options?: MarkedOptions | undefined | null) => string | Promise<string>;
Parser: typeof _Parser;
Renderer: typeof _Renderer;
TextRenderer: typeof _TextRenderer;
Lexer: typeof _Lexer;
Tokenizer: typeof _Tokenizer;
Hooks: typeof _Hooks;
constructor(...args: MarkedExtension[]);
/**
* Run callback for every token
*/
walkTokens(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]): MaybePromise[];
use(...args: MarkedExtension[]): this;
setOptions(opt: MarkedOptions): this;
lexer(src: string, options?: MarkedOptions): TokensList;
parser(tokens: Token[], options?: MarkedOptions): string;
}
/**
* Compiles markdown to HTML asynchronously.
*
* @param src String of markdown source to be compiled
* @param options Hash of options, having async: true
* @return Promise of string of compiled HTML
*/
export declare function marked(src: string, options: MarkedOptions & {
async: true;
}): Promise<string>;
/**
* Compiles markdown to HTML.
*
* @param src String of markdown source to be compiled
* @param options Optional hash of options
* @return String of compiled HTML. Wil be a Promise of string if async is set to true by any extensions.
*/
export declare function marked(src: string, options?: MarkedOptions): string | Promise<string>;
export declare namespace marked {
var options: (options: MarkedOptions) => typeof marked;
var setOptions: (options: MarkedOptions) => typeof marked;
var getDefaults: typeof _getDefaults;
var defaults: MarkedOptions;
var use: (...args: MarkedExtension[]) => typeof marked;
var walkTokens: (tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) => MaybePromise[];
var parseInline: (src: string, options?: MarkedOptions | null | undefined) => string | Promise<string>;
var Parser: typeof _Parser;
var parser: typeof _Parser.parse;
var Renderer: typeof _Renderer;
var TextRenderer: typeof _TextRenderer;
var Lexer: typeof _Lexer;
var lexer: typeof _Lexer.lex;
var Tokenizer: typeof _Tokenizer;
var Hooks: typeof _Hooks;
var parse: typeof marked;
}
export declare const options: (options: MarkedOptions) => typeof marked;
export declare const setOptions: (options: MarkedOptions) => typeof marked;
export declare const use: (...args: MarkedExtension[]) => typeof marked;
export declare const walkTokens: (tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) => MaybePromise[];
export declare const parseInline: (src: string, options?: MarkedOptions | null | undefined) => string | Promise<string>;
export declare const parse: typeof marked;
export declare const parser: typeof _Parser.parse;
export declare const lexer: typeof _Lexer.lex;
export {
_Hooks as Hooks,
_Lexer as Lexer,
_Parser as Parser,
_Renderer as Renderer,
_TextRenderer as TextRenderer,
_Tokenizer as Tokenizer,
_defaults as defaults,
_getDefaults as getDefaults,
};
export {};

2424
static/js/lib/node_modules/marked/lib/marked.esm.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

2448
static/js/lib/node_modules/marked/lib/marked.umd.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

111
static/js/lib/node_modules/marked/man/marked.1 generated vendored Normal file
View File

@ -0,0 +1,111 @@
.TH "MARKED" "1" "December 2023" "11.1.0"
.SH "NAME"
\fBmarked\fR \- a javascript markdown parser
.SH SYNOPSIS
.P
\fBmarked\fP [\fB\-o\fP <output file>] [\fB\-i\fP <input file>] [\fB\-s\fP <markdown string>] [\fB\-c\fP <config file>] [\fB\-\-help\fP] [\fB\-\-version\fP] [\fB\-\-tokens\fP] [\fB\-\-no\-clobber\fP] [\fB\-\-pedantic\fP] [\fB\-\-gfm\fP] [\fB\-\-breaks\fP] [\fB\-\-no\-etc\.\.\.\fP] [\fB\-\-silent\fP] [filename]
.SH DESCRIPTION
.P
marked is a full\-featured javascript markdown parser, built for speed\.
.br
It also includes multiple GFM features\.
.SH EXAMPLES
.RS 2
.nf
cat in\.md | marked > out\.html
.fi
.RE
.RS 2
.nf
echo "hello *world*" | marked
.fi
.RE
.RS 2
.nf
marked \-o out\.html \-i in\.md \-\-gfm
.fi
.RE
.RS 2
.nf
marked \-\-output="hello world\.html" \-i in\.md \-\-no\-breaks
.fi
.RE
.SH OPTIONS
.RS 1
.IP \(bu 2
\-o, \-\-output [output file]
.br
Specify file output\. If none is specified, write to stdout\.
.IP \(bu 2
\-i, \-\-input [input file]
.br
Specify file input, otherwise use last argument as input file\.
.br
If no input file is specified, read from stdin\.
.IP \(bu 2
\-s, \-\-string [markdown string]
.br
Specify string input instead of a file\.
.IP \(bu 2
\-c, \-\-config [config file]
.br
Specify config file to use instead of the default \fB~/\.marked\.json\fP or \fB~/\.marked\.js\fP or \fB~/\.marked/index\.js\fP\|\.
.IP \(bu 2
\-t, \-\-tokens
.br
Output a token list instead of html\.
.IP \(bu 2
\-n, \-\-no\-clobber
.br
Do not overwrite \fBoutput\fP if it exists\.
.IP \(bu 2
\-\-pedantic
.br
Conform to obscure parts of markdown\.pl as much as possible\.
.br
Don't fix original markdown bugs\.
.IP \(bu 2
\-\-gfm
.br
Enable github flavored markdown\.
.IP \(bu 2
\-\-breaks
.br
Enable GFM line breaks\. Only works with the gfm option\.
.IP \(bu 2
\-\-no\-breaks, \-no\-etc\.\.\.
.br
The inverse of any of the marked options above\.
.IP \(bu 2
\-\-silent
.br
Silence error output\.
.IP \(bu 2
\-h, \-\-help
.br
Display help information\.
.RE
.SH CONFIGURATION
.P
For configuring and running programmatically\.
.P
Example
.RS 2
.nf
import { Marked } from 'marked';
const marked = new Marked({ gfm: true });
marked\.parse('*foo*');
.fi
.RE
.SH BUGS
.P
Please report any bugs to https://github.com/markedjs/marked
.SH LICENSE
.P
Copyright (c) 2011\-2014, Christopher Jeffrey (MIT License)\.
.SH SEE ALSO
.P
markdown(1), nodejs(1)

92
static/js/lib/node_modules/marked/man/marked.1.md generated vendored Normal file
View File

@ -0,0 +1,92 @@
# marked(1) -- a javascript markdown parser
## SYNOPSIS
`marked` [`-o` <output file>] [`-i` <input file>] [`-s` <markdown string>] [`-c` <config file>] [`--help`] [`--version`] [`--tokens`] [`--no-clobber`] [`--pedantic`] [`--gfm`] [`--breaks`] [`--no-etc...`] [`--silent`] [filename]
## DESCRIPTION
marked is a full-featured javascript markdown parser, built for speed.
It also includes multiple GFM features.
## EXAMPLES
```sh
cat in.md | marked > out.html
```
```sh
echo "hello *world*" | marked
```
```sh
marked -o out.html -i in.md --gfm
```
```sh
marked --output="hello world.html" -i in.md --no-breaks
```
## OPTIONS
* -o, --output [output file]
Specify file output. If none is specified, write to stdout.
* -i, --input [input file]
Specify file input, otherwise use last argument as input file.
If no input file is specified, read from stdin.
* -s, --string [markdown string]
Specify string input instead of a file.
* -c, --config [config file]
Specify config file to use instead of the default `~/.marked.json` or `~/.marked.js` or `~/.marked/index.js`.
* -t, --tokens
Output a token list instead of html.
* -n, --no-clobber
Do not overwrite `output` if it exists.
* --pedantic
Conform to obscure parts of markdown.pl as much as possible.
Don't fix original markdown bugs.
* --gfm
Enable github flavored markdown.
* --breaks
Enable GFM line breaks. Only works with the gfm option.
* --no-breaks, -no-etc...
The inverse of any of the marked options above.
* --silent
Silence error output.
* -h, --help
Display help information.
## CONFIGURATION
For configuring and running programmatically.
Example
```js
import { Marked } from 'marked';
const marked = new Marked({ gfm: true });
marked.parse('*foo*');
```
## BUGS
Please report any bugs to <https://github.com/markedjs/marked>.
## LICENSE
Copyright (c) 2011-2014, Christopher Jeffrey (MIT License).
## SEE ALSO
markdown(1), nodejs(1)

6
static/js/lib/node_modules/marked/marked.min.js generated vendored Normal file

File diff suppressed because one or more lines are too long

108
static/js/lib/node_modules/marked/package.json generated vendored Normal file
View File

@ -0,0 +1,108 @@
{
"name": "marked",
"description": "A markdown parser built for speed",
"author": "Christopher Jeffrey",
"version": "11.1.1",
"type": "module",
"main": "./lib/marked.cjs",
"module": "./lib/marked.esm.js",
"browser": "./lib/marked.umd.js",
"types": "./lib/marked.d.ts",
"bin": {
"marked": "bin/marked.js"
},
"man": "./man/marked.1",
"files": [
"bin/",
"lib/",
"man/",
"marked.min.js"
],
"exports": {
".": {
"import": {
"types": "./lib/marked.d.ts",
"default": "./lib/marked.esm.js"
},
"default": {
"types": "./lib/marked.d.cts",
"default": "./lib/marked.cjs"
}
},
"./bin/marked": "./bin/marked.js",
"./marked.min.js": "./marked.min.js",
"./package.json": "./package.json"
},
"repository": "git://github.com/markedjs/marked.git",
"homepage": "https://marked.js.org",
"bugs": {
"url": "http://github.com/markedjs/marked/issues"
},
"license": "MIT",
"keywords": [
"markdown",
"markup",
"html"
],
"tags": [
"markdown",
"markup",
"html"
],
"devDependencies": {
"@markedjs/testutils": "9.1.5-0",
"@arethetypeswrong/cli": "^0.13.5",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.5",
"@semantic-release/commit-analyzer": "^11.1.0",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.6",
"@semantic-release/npm": "^11.0.2",
"@semantic-release/release-notes-generator": "^12.1.0",
"@typescript-eslint/eslint-plugin": "^6.15.0",
"@typescript-eslint/parser": "^6.13.2",
"cheerio": "^1.0.0-rc.12",
"commonmark": "0.30.0",
"cross-env": "^7.0.3",
"dts-bundle-generator": "^9.0.0",
"eslint": "^8.56.0",
"eslint-config-standard": "^17.1.0",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-n": "^16.5.0",
"eslint-plugin-promise": "^6.1.1",
"highlight.js": "^11.9.0",
"markdown-it": "13.0.2",
"marked-highlight": "^2.1.0",
"marked-man": "^2.0.0",
"node-fetch": "^3.3.2",
"recheck": "^4.4.5",
"rollup": "^4.9.1",
"semantic-release": "^22.0.12",
"titleize": "^4.0.0",
"ts-expect": "^1.3.0",
"typescript": "5.3.3"
},
"scripts": {
"test": "npm run build && npm run test:specs && npm run test:unit",
"test:all": "npm test && npm run test:umd && npm run test:types && npm run test:lint",
"test:unit": "node --test --test-reporter=spec test/unit",
"test:specs": "node --test --test-reporter=spec test/run-spec-tests.js",
"test:lint": "eslint .",
"test:redos": "node test/recheck.js > vuln.js",
"test:types": "tsc --project tsconfig-type-test.json && attw -P --exclude-entrypoints ./bin/marked ./marked.min.js",
"test:umd": "node test/umd-test.js",
"test:update": "node test/update-specs.js",
"rules": "node test/rules.js",
"bench": "npm run build && node test/bench.js",
"lint": "eslint --fix .",
"build:reset": "git checkout upstream/master lib/marked.cjs lib/marked.umd.js lib/marked.esm.js marked.min.js",
"build": "npm run rollup && npm run build:types && npm run build:man",
"build:docs": "npm run build && node docs/build.js",
"build:types": "tsc && dts-bundle-generator --project tsconfig.json -o lib/marked.d.ts src/marked.ts && dts-bundle-generator --project tsconfig.json -o lib/marked.d.cts src/marked.ts",
"build:man": "marked-man man/marked.1.md > man/marked.1",
"rollup": "rollup -c rollup.config.js"
},
"engines": {
"node": ">= 18"
}
}

23
static/js/lib/package-lock.json generated Normal file
View File

@ -0,0 +1,23 @@
{
"name": "lib",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"dependencies": {
"marked": "^11.1.1"
}
},
"node_modules/marked": {
"version": "11.1.1",
"resolved": "https://registry.npmjs.org/marked/-/marked-11.1.1.tgz",
"integrity": "sha512-EgxRjgK9axsQuUa/oKMx5DEY8oXpKJfk61rT5iY3aRlgU6QJtUcxU5OAymdhCvWvhYcd9FKmO5eQoX8m9VGJXg==",
"bin": {
"marked": "bin/marked.js"
},
"engines": {
"node": ">= 18"
}
}
}
}

View File

@ -0,0 +1,5 @@
{
"dependencies": {
"marked": "^11.1.1"
}
}

View File

@ -3,6 +3,7 @@ import htm from 'htm'
import { signal } from 'preact/signals' import { signal } from 'preact/signals'
import { Keys, Key } from 'key' import { Keys, Key } from 'key'
import Crypto from 'crypto' import Crypto from 'crypto'
//import { marked } from 'marked'
const html = htm.bind(h) const html = htm.bind(h)
export class NodeUI extends Component { export class NodeUI extends Component {
@ -14,54 +15,54 @@ export class NodeUI extends Component {
this.keys = signal([]) this.keys = signal([])
this.page = signal('node') this.page = signal('node')
window.addEventListener('popstate', evt=>{ window.addEventListener('popstate', evt => {
if(evt.state && evt.state.hasOwnProperty('nodeID')) if (evt.state && evt.state.hasOwnProperty('nodeID'))
this.goToNode(evt.state.nodeID, true) this.goToNode(evt.state.nodeID, true)
else else
this.goToNode(0, true) this.goToNode(0, true)
}) })
window.addEventListener('keydown', evt=>this.keyHandler(evt)) window.addEventListener('keydown', evt => this.keyHandler(evt))
}//}}} }//}}}
render() {//{{{ render() {//{{{
if(this.node.value === null) if (this.node.value === null)
return return
let node = this.node.value let node = this.node.value
document.title = `N: ${node.Name}` document.title = `N: ${node.Name}`
let crumbs = [ let crumbs = [
html`<div class="crumb" onclick=${()=>this.goToNode(0)}>Start</div>` html`<div class="crumb" onclick=${() => this.goToNode(0)}>Start</div>`
] ]
crumbs = crumbs.concat(node.Crumbs.slice(0).map(node=> crumbs = crumbs.concat(node.Crumbs.slice(0).map(node =>
html`<div class="crumb" onclick=${()=>this.goToNode(node.ID)}>${node.Name}</div>` html`<div class="crumb" onclick=${() => this.goToNode(node.ID)}>${node.Name}</div>`
).reverse()) ).reverse())
let children = node.Children.sort((a,b)=>{ let children = node.Children.sort((a, b) => {
if(a.Name.toLowerCase() > b.Name.toLowerCase()) return 1 if (a.Name.toLowerCase() > b.Name.toLowerCase()) return 1
if(a.Name.toLowerCase() < b.Name.toLowerCase()) return -1 if (a.Name.toLowerCase() < b.Name.toLowerCase()) return -1
return 0 return 0
}).map(child=>html` }).map(child => html`
<div class="child-node" onclick=${()=>this.goToNode(child.ID)}>${child.Name}</div> <div class="child-node" onclick=${() => this.goToNode(child.ID)}>${child.Name}</div>
`) `)
let modified = '' let modified = ''
if(this.props.app.nodeModified.value) if (this.props.app.nodeModified.value)
modified = 'modified' modified = 'modified'
// Page to display // Page to display
let page = '' let page = ''
switch(this.page.value) { switch (this.page.value) {
case 'node': case 'node':
if(node.ID == 0) { if (node.ID == 0) {
page = html` page = html`
${children.length > 0 ? html`<div class="child-nodes">${children}</div><div id="notes-version">Notes version ${window._VERSION}</div>` : html``} ${children.length > 0 ? html`<div class="child-nodes">${children}</div><div id="notes-version">Notes version ${window._VERSION}</div>` : html``}
` `
} else { } else {
let padlock = '' let padlock = ''
if(node.CryptoKeyID > 0) if (node.CryptoKeyID > 0)
padlock = html`<img src="/images/${window._VERSION}/padlock-black.svg" style="height: 24px;" />` padlock = html`<img src="/images/${window._VERSION}/padlock-black.svg" style="height: 24px;" />`
page = html` page = html`
${children.length > 0 ? html`<div class="child-nodes">${children}</div>` : html``} ${children.length > 0 ? html`<div class="child-nodes">${children}</div>` : html``}
@ -96,18 +97,19 @@ export class NodeUI extends Component {
} }
let menu = '' let menu = ''
if(this.menu.value) if (this.menu.value)
menu = html`<${Menu} nodeui=${this} />` menu = html`<${Menu} nodeui=${this} />`
return html` return html`
${menu} ${menu}
<header class="${modified}" onclick=${()=>this.saveNode()}> <header class="${modified}" onclick=${() => this.saveNode()}>
<div class="tree"><img src="/images/${window._VERSION}/tree.svg" onclick=${()=>document.getElementById('app').classList.toggle('toggle-tree')} /></div> <div class="tree"><img src="/images/${window._VERSION}/tree.svg" onclick=${() => document.getElementById('app').classList.toggle('toggle-tree')} /></div>
<div class="name">Notes</div> <div class="name">Notes</div>
<div class="search" onclick=${evt=>{ evt.stopPropagation(); this.showPage('search')}}><img src="/images/${window._VERSION}/search.svg" /></div> <div class="markdown" onclick=${evt => { evt.stopPropagation(); this.toggleMarkdown() }}><img src="/images/${window._VERSION}/markdown.svg" /></div>
<div class="add" onclick=${evt=>this.createNode(evt)}><img src="/images/${window._VERSION}/add.svg" /></div> <div class="search" onclick=${evt => { evt.stopPropagation(); this.showPage('search') }}><img src="/images/${window._VERSION}/search.svg" /></div>
<div class="keys" onclick=${evt=>{ evt.stopPropagation(); this.showPage('keys')}}><img src="/images/${window._VERSION}/padlock.svg" /></div> <div class="add" onclick=${evt => this.createNode(evt)}><img src="/images/${window._VERSION}/add.svg" /></div>
<div class="menu" onclick=${evt=>this.showMenu(evt)}></div> <div class="keys" onclick=${evt => { evt.stopPropagation(); this.showPage('keys') }}><img src="/images/${window._VERSION}/padlock.svg" /></div>
<div class="menu" onclick=${evt => this.showMenu(evt)}></div>
</header> </header>
<div id="crumbs"> <div id="crumbs">
@ -122,7 +124,7 @@ export class NodeUI extends Component {
// decrypt the content. // decrypt the content.
await this.retrieveKeys() await this.retrieveKeys()
this.props.app.startNode.retrieve(node=>{ this.props.app.startNode.retrieve(node => {
this.node.value = node this.node.value = node
// The tree isn't guaranteed to have loaded yet. This is also run from // The tree isn't guaranteed to have loaded yet. This is also run from
@ -137,14 +139,18 @@ export class NodeUI extends Component {
// All keybindings is Alt+Shift, since the popular browsers at the time (2023) allows to override thees. // All keybindings is Alt+Shift, since the popular browsers at the time (2023) allows to override thees.
// Ctrl+S is the exception to using Alt+Shift, since it is overridable and in such widespread use for saving. // Ctrl+S is the exception to using Alt+Shift, since it is overridable and in such widespread use for saving.
// Thus, the exception is acceptable to consequent use of alt+shift. // Thus, the exception is acceptable to consequent use of alt+shift.
if(!(evt.shiftKey && evt.altKey) && !(evt.key.toUpperCase() == 'S' && evt.ctrlKey)) if (!(evt.shiftKey && evt.altKey) && !(evt.key.toUpperCase() == 'S' && evt.ctrlKey))
return return
switch(evt.key.toUpperCase()) { switch (evt.key.toUpperCase()) {
case 'E': case 'E':
this.showPage('keys') this.showPage('keys')
break break
case 'M':
this.toggleMarkdown()
break
case 'N': case 'N':
this.createNode() this.createNode()
break break
@ -169,7 +175,7 @@ export class NodeUI extends Component {
handled = false handled = false
} }
if(handled) { if (handled) {
evt.preventDefault() evt.preventDefault()
evt.stopPropagation() evt.stopPropagation()
} }
@ -184,18 +190,18 @@ export class NodeUI extends Component {
}//}}} }//}}}
goToNode(nodeID, dontPush) {//{{{ goToNode(nodeID, dontPush) {//{{{
if(this.props.app.nodeModified.value) { if (this.props.app.nodeModified.value) {
if(!confirm("Changes not saved. Do you want to discard changes?")) if (!confirm("Changes not saved. Do you want to discard changes?"))
return return
} }
if(!dontPush) if (!dontPush)
history.pushState({ nodeID }, '', `/?node=${nodeID}`) history.pushState({ nodeID }, '', `/?node=${nodeID}`)
// New node is fetched in order to retrieve content and files. // New node is fetched in order to retrieve content and files.
// Such data is unnecessary to transfer for tree/navigational purposes. // Such data is unnecessary to transfer for tree/navigational purposes.
let node = new Node(this.props.app, nodeID) let node = new Node(this.props.app, nodeID)
node.retrieve(node=>{ node.retrieve(node => {
this.props.app.nodeModified.value = false this.props.app.nodeModified.value = false
this.node.value = node this.node.value = node
this.showPage('node') this.showPage('node')
@ -210,53 +216,55 @@ export class NodeUI extends Component {
}) })
}//}}} }//}}}
createNode(evt) {//{{{ createNode(evt) {//{{{
if(evt) if (evt)
evt.stopPropagation() evt.stopPropagation()
let name = prompt("Name") let name = prompt("Name")
if(!name) if (!name)
return return
this.node.value.create(name, nodeID=>{ this.node.value.create(name, nodeID => {
console.log('before', this.props.app.startNode) console.log('before', this.props.app.startNode)
this.props.app.startNode = new Node(this.props.app, nodeID) this.props.app.startNode = new Node(this.props.app, nodeID)
console.log('after', this.props.app.startNode) console.log('after', this.props.app.startNode)
this.props.app.tree.retrieve(()=>{ this.props.app.tree.retrieve(() => {
this.goToNode(nodeID) this.goToNode(nodeID)
}) })
}) })
}//}}} }//}}}
saveNode() {//{{{ saveNode() {//{{{
/*
let nodeContent = this.nodeContent.current let nodeContent = this.nodeContent.current
if(this.page.value != 'node' || nodeContent === null) if (this.page.value != 'node' || nodeContent === null)
return return
*/
let content = nodeContent.contentDiv.current.value let content = this.node.value.content()
this.node.value.setContent(content) this.node.value.setContent(content)
this.node.value.save(()=>this.props.app.nodeModified.value = false) this.node.value.save(() => this.props.app.nodeModified.value = false)
}//}}} }//}}}
renameNode() {//{{{ renameNode() {//{{{
let name = prompt("New name") let name = prompt("New name")
if(!name) if (!name)
return return
this.node.value.rename(name, ()=>{ this.node.value.rename(name, () => {
this.goToNode(this.node.value.ID) this.goToNode(this.node.value.ID)
this.menu.value = false this.menu.value = false
}) })
}//}}} }//}}}
deleteNode() {//{{{ deleteNode() {//{{{
if(!confirm("Do you want to delete this note and all sub-notes?")) if (!confirm("Do you want to delete this note and all sub-notes?"))
return return
this.node.value.delete(()=>{ this.node.value.delete(() => {
this.goToNode(this.node.value.ParentID) this.goToNode(this.node.value.ParentID)
this.menu.value = false this.menu.value = false
}) })
}//}}} }//}}}
async retrieveKeys() {//{{{ async retrieveKeys() {//{{{
return new Promise((resolve, reject)=>{ return new Promise((resolve, reject) => {
this.props.app.request('/key/retrieve', {}) this.props.app.request('/key/retrieve', {})
.then(res=>{ .then(res => {
this.keys.value = res.Keys.map(keyData=>new Key(keyData, this.keyCounter)) this.keys.value = res.Keys.map(keyData => new Key(keyData, this.keyCounter))
resolve(this.keys.value) resolve(this.keys.value)
}) })
.catch(reject) .catch(reject)
@ -264,13 +272,13 @@ export class NodeUI extends Component {
}//}}} }//}}}
keyCounter() {//{{{ keyCounter() {//{{{
return window._app.current.request('/key/counter', {}) return window._app.current.request('/key/counter', {})
.then(res=>BigInt(res.Counter)) .then(res => BigInt(res.Counter))
.catch(window._app.current.responseError) .catch(window._app.current.responseError)
}//}}} }//}}}
getKey(id) {//{{{ getKey(id) {//{{{
let keys = this.keys.value let keys = this.keys.value
for(let i = 0; i < keys.length; i++) for (let i = 0; i < keys.length; i++)
if(keys[i].ID == id) if (keys[i].ID == id)
return keys[i] return keys[i]
return null return null
}//}}} }//}}}
@ -278,6 +286,9 @@ export class NodeUI extends Component {
showPage(pg) {//{{{ showPage(pg) {//{{{
this.page.value = pg this.page.value = pg
}//}}} }//}}}
toggleMarkdown() {//{{{
this.node.value.RenderMarkdown.value = !this.node.value.RenderMarkdown.value
}//}}}
} }
class NodeContent extends Component { class NodeContent extends Component {
@ -292,43 +303,69 @@ class NodeContent extends Component {
let content = '' let content = ''
try { try {
content = node.content() content = node.content()
} catch(err) { } catch (err) {
return html` return html`
<div id="node-content" class="node-content encrypted">${err.message}</div> <div id="node-content" class="node-content encrypted">${err.message}</div>
` `
} }
return html` var element
<div class="grow-wrap"> if (node.RenderMarkdown.value)
<textarea id="node-content" class="node-content" ref=${this.contentDiv} oninput=${()=>this.contentChanged()} required rows=1>${content}</textarea> element = html`<div id="markdown"></div>`
</div> else
` element = html`
<div class="grow-wrap">
<textarea id="node-content" class="node-content" ref=${this.contentDiv} oninput=${evt => this.contentChanged(evt)} required rows=1>${content}</textarea>
</div>
`
return element
}//}}} }//}}}
componentDidMount() {//{{{ componentDidMount() {//{{{
const markdown = document.getElementById('markdown')
if (markdown)
markdown.innerHTML = marked.parse(this.props.node.content())
this.resize() this.resize()
window.addEventListener('resize', ()=>this.resize()) window.addEventListener('resize', () => this.resize())
}//}}} }//}}}
componentDidUpdate() {//{{{ componentDidUpdate() {//{{{
const markdown = document.getElementById('markdown')
if (markdown)
markdown.innerHTML = marked.parse(this.props.node.content())
this.resize() this.resize()
}//}}} }//}}}
contentChanged() {//{{{ contentChanged(evt) {//{{{
window._app.current.nodeModified.value = true window._app.current.nodeModified.value = true
const content = evt.target.value
this.props.node.setContent(content)
this.resize() this.resize()
}//}}} }//}}}
resize() {//{{{ resize() {//{{{
let textarea = document.getElementById('node-content') let textarea = document.getElementById('node-content')
if(textarea) if (textarea)
textarea.parentNode.dataset.replicatedValue = textarea.value textarea.parentNode.dataset.replicatedValue = textarea.value
let crumbsEl = document.getElementById('crumbs')
let markdown = document.getElementById('markdown')
if (markdown) {
let margins = (crumbsEl.clientWidth - 900) / 2.0
if (margins < 0)
margins = 0
markdown.style.marginLeft = `${margins}px`
markdown.style.marginRight = `${margins}px`
}
}//}}} }//}}}
unlock() {//{{{ unlock() {//{{{
let pass = prompt(`Password for "${this.props.model.description}"`) let pass = prompt(`Password for "${this.props.model.description}"`)
if(!pass) if (!pass)
return return
try { try {
this.props.model.unlock(pass) this.props.model.unlock(pass)
this.forceUpdate() this.forceUpdate()
} catch(err) { } catch (err) {
alert(err) alert(err)
} }
}//}}} }//}}}
@ -336,18 +373,18 @@ class NodeContent extends Component {
class NodeFiles extends Component { class NodeFiles extends Component {
render({ node }) {//{{{ render({ node }) {//{{{
if(node.Files === null || node.Files.length == 0) if (node.Files === null || node.Files.length == 0)
return return
let files = node.Files let files = node.Files
.sort((a, b)=>{ .sort((a, b) => {
if(a.Filename.toUpperCase() < b.Filename.toUpperCase()) return -1 if (a.Filename.toUpperCase() < b.Filename.toUpperCase()) return -1
if(a.Filename.toUpperCase() > b.Filename.toUpperCase()) return 1 if (a.Filename.toUpperCase() > b.Filename.toUpperCase()) return 1
return 0 return 0
}) })
.map(file=> .map(file =>
html` html`
<div class="filename" onclick=${()=>node.download(file.ID)}>${file.Filename}</div> <div class="filename" onclick=${() => node.download(file.ID)}>${file.Filename}</div>
<div class="size">${this.formatSize(file.Size)}</div> <div class="size">${this.formatSize(file.Size)}</div>
` `
) )
@ -362,7 +399,7 @@ class NodeFiles extends Component {
` `
}//}}} }//}}}
formatSize(size) {//{{{ formatSize(size) {//{{{
if(size < 1048576) { if (size < 1048576) {
return `${Math.round(size / 1024)} KiB` return `${Math.round(size / 1024)} KiB`
} else { } else {
return `${Math.round(size / 1048576)} MiB` return `${Math.round(size / 1048576)} MiB`
@ -372,52 +409,56 @@ class NodeFiles extends Component {
export class Node { export class Node {
constructor(app, nodeID) {//{{{ constructor(app, nodeID) {//{{{
this.app = app this.app = app
this.ID = nodeID this.ID = nodeID
this.ParentID = 0 this.ParentID = 0
this.UserID = 0 this.UserID = 0
this.CryptoKeyID = 0 this.CryptoKeyID = 0
this.Name = '' this.Name = ''
this._content = '' this.RenderMarkdown = signal(false)
this.Children = [] this.Markdown = false
this.Crumbs = [] this._content = ''
this.Files = [] this.Children = []
this.Crumbs = []
this.Files = []
this._decrypted = false this._decrypted = false
this._expanded = false // start value for the TreeNode component, this._expanded = false // start value for the TreeNode component,
// it doesn't control it afterwards. // it doesn't control it afterwards.
// Used to expand the crumbs upon site loading. // Used to expand the crumbs upon site loading.
}//}}} }//}}}
retrieve(callback) {//{{{ retrieve(callback) {//{{{
this.app.request('/node/retrieve', { ID: this.ID }) this.app.request('/node/retrieve', { ID: this.ID })
.then(res=>{ .then(res => {
this.ParentID = res.Node.ParentID this.ParentID = res.Node.ParentID
this.UserID = res.Node.UserID this.UserID = res.Node.UserID
this.CryptoKeyID = res.Node.CryptoKeyID this.CryptoKeyID = res.Node.CryptoKeyID
this.Name = res.Node.Name this.Name = res.Node.Name
this._content = res.Node.Content this._content = res.Node.Content
this.Children = res.Node.Children this.Children = res.Node.Children
this.Crumbs = res.Node.Crumbs this.Crumbs = res.Node.Crumbs
this.Files = res.Node.Files this.Files = res.Node.Files
callback(this) this.Markdown = res.Node.Markdown
}) this.RenderMarkdown.value = this.Markdown
.catch(this.app.responseError) callback(this)
})
.catch(this.app.responseError)
}//}}} }//}}}
delete(callback) {//{{{ delete(callback) {//{{{
this.app.request('/node/delete', { this.app.request('/node/delete', {
NodeID: this.ID, NodeID: this.ID,
}) })
.then(callback) .then(callback)
.catch(this.app.responseError) .catch(this.app.responseError)
}//}}} }//}}}
create(name, callback) {//{{{ create(name, callback) {//{{{
this.app.request('/node/create', { this.app.request('/node/create', {
Name: name.trim(), Name: name.trim(),
ParentID: this.ID, ParentID: this.ID,
}) })
.then(res=>{ .then(res => {
callback(res.Node.ID) callback(res.Node.ID)
}) })
.catch(this.app.responseError) .catch(this.app.responseError)
}//}}} }//}}}
async save(callback) {//{{{ async save(callback) {//{{{
try { try {
@ -427,6 +468,7 @@ export class Node {
NodeID: this.ID, NodeID: this.ID,
Content: this._content, Content: this._content,
CryptoKeyID: this.CryptoKeyID, CryptoKeyID: this.CryptoKeyID,
Markdown: this.Markdown,
} }
this.app.request('/node/update', req) this.app.request('/node/update', req)
.then(callback) .then(callback)
@ -440,15 +482,15 @@ export class Node {
Name: name.trim(), Name: name.trim(),
NodeID: this.ID, NodeID: this.ID,
}) })
.then(callback) .then(callback)
.catch(this.app.responseError) .catch(this.app.responseError)
}//}}} }//}}}
download(fileID) {//{{{ download(fileID) {//{{{
let headers = { let headers = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
} }
if(this.app.session.UUID !== '') if (this.app.session.UUID !== '')
headers['X-Session-Id'] = this.app.session.UUID headers['X-Session-Id'] = this.app.session.UUID
let fname = "" let fname = ""
@ -460,29 +502,29 @@ export class Node {
FileID: fileID, FileID: fileID,
}), }),
}) })
.then(response=>{ .then(response => {
let match = response.headers.get('content-disposition').match(/filename="([^"]*)"/) let match = response.headers.get('content-disposition').match(/filename="([^"]*)"/)
fname = match[1] fname = match[1]
return response.blob() return response.blob()
}) })
.then(blob=>{ .then(blob => {
let url = window.URL.createObjectURL(blob) let url = window.URL.createObjectURL(blob)
let a = document.createElement('a') let a = document.createElement('a')
a.href = url a.href = url
a.download = fname a.download = fname
document.body.appendChild(a) // we need to append the element to the dom -> otherwise it will not work in firefox document.body.appendChild(a) // we need to append the element to the dom -> otherwise it will not work in firefox
a.click() a.click()
a.remove() //afterwards we remove the element again a.remove() //afterwards we remove the element again
}) })
}//}}} }//}}}
content() {//{{{ content() {//{{{
if(this.CryptoKeyID != 0 && !this._decrypted) if (this.CryptoKeyID != 0 && !this._decrypted)
this.#decrypt() this.#decrypt()
return this._content return this._content
}//}}} }//}}}
setContent(new_content) {//{{{ setContent(new_content) {//{{{
this._content = new_content this._content = new_content
if(this.CryptoKeyID == 0) if (this.CryptoKeyID == 0)
// Logic behind plaintext not being decrypted is that // Logic behind plaintext not being decrypted is that
// only encrypted values can be in a decrypted state. // only encrypted values can be in a decrypted state.
this._decrypted = false this._decrypted = false
@ -493,29 +535,29 @@ export class Node {
return this.#encrypt(true, new_key) return this.#encrypt(true, new_key)
}//}}} }//}}}
#decrypt() {//{{{ #decrypt() {//{{{
if(this.CryptoKeyID == 0 || this._decrypted) if (this.CryptoKeyID == 0 || this._decrypted)
return return
let obj_key = this.app.nodeUI.current.getKey(this.CryptoKeyID) let obj_key = this.app.nodeUI.current.getKey(this.CryptoKeyID)
if(obj_key === null || obj_key.ID != this.CryptoKeyID) if (obj_key === null || obj_key.ID != this.CryptoKeyID)
throw('Invalid key') throw ('Invalid key')
// Ask user to unlock key first // Ask user to unlock key first
var pass = null var pass = null
while(pass || obj_key.status() == 'locked') { while (pass || obj_key.status() == 'locked') {
pass = prompt(`Password for "${obj_key.description}"`) pass = prompt(`Password for "${obj_key.description}"`)
if(!pass) if (!pass)
throw new Error(`Key "${obj_key.description}" is locked`) throw new Error(`Key "${obj_key.description}" is locked`)
try { try {
obj_key.unlock(pass) obj_key.unlock(pass)
} catch(err) { } catch (err) {
alert(err) alert(err)
} }
pass = null pass = null
} }
if(obj_key.status() == 'locked') if (obj_key.status() == 'locked')
throw new Error(`Key "${obj_key.description}" is locked`) throw new Error(`Key "${obj_key.description}" is locked`)
let crypto = new Crypto(obj_key.key) let crypto = new Crypto(obj_key.key)
@ -526,7 +568,7 @@ export class Node {
}//}}} }//}}}
async #encrypt(change_key = false, new_key = null) {//{{{ async #encrypt(change_key = false, new_key = null) {//{{{
// Nothing to do if not changing key and already encrypted. // Nothing to do if not changing key and already encrypted.
if(!change_key && this.CryptoKeyID != 0 && !this._decrypted) if (!change_key && this.CryptoKeyID != 0 && !this._decrypted)
return this._content return this._content
let content = this.content() let content = this.content()
@ -534,7 +576,7 @@ export class Node {
// Changing key to no encryption or already at no encryption - // Changing key to no encryption or already at no encryption -
// set to not decrypted (only encrypted values can be // set to not decrypted (only encrypted values can be
// decrypted) and return plain value. // decrypted) and return plain value.
if((change_key && new_key === null) || (!change_key && this.CryptoKeyID == 0)) { if ((change_key && new_key === null) || (!change_key && this.CryptoKeyID == 0)) {
this._decrypted = false this._decrypted = false
this.CryptoKeyID = 0 this.CryptoKeyID = 0
return content return content
@ -542,10 +584,10 @@ export class Node {
let key_id = change_key ? new_key.ID : this.CryptoKeyID let key_id = change_key ? new_key.ID : this.CryptoKeyID
let obj_key = this.app.nodeUI.current.getKey(key_id) let obj_key = this.app.nodeUI.current.getKey(key_id)
if(obj_key === null || obj_key.ID != key_id) if (obj_key === null || obj_key.ID != key_id)
throw('Invalid key') throw ('Invalid key')
if(obj_key.status() == 'locked') if (obj_key.status() == 'locked')
throw new Error(`Key "${obj_key.description}" is locked`) throw new Error(`Key "${obj_key.description}" is locked`)
let crypto = new Crypto(obj_key.key) let crypto = new Crypto(obj_key.key)
@ -561,17 +603,17 @@ export class Node {
class Menu extends Component { class Menu extends Component {
render({ nodeui }) {//{{{ render({ nodeui }) {//{{{
return html` return html`
<div id="blackout" onclick=${()=>nodeui.menu.value = false}></div> <div id="blackout" onclick=${() => nodeui.menu.value = false}></div>
<div id="menu"> <div id="menu">
<div class="section">Current note</div> <div class="section">Current note</div>
<div class="item" onclick=${()=>{ nodeui.renameNode(); nodeui.menu.value = false }}>Rename</div> <div class="item" onclick=${() => { nodeui.renameNode(); nodeui.menu.value = false }}>Rename</div>
<div class="item" onclick=${()=>{ nodeui.showPage('upload'); nodeui.menu.value = false }}>Upload</div> <div class="item" onclick=${() => { nodeui.showPage('upload'); nodeui.menu.value = false }}>Upload</div>
<div class="item " onclick=${()=>{ nodeui.showPage('node-properties'); nodeui.menu.value = false }}>Properties</div> <div class="item " onclick=${() => { nodeui.showPage('node-properties'); nodeui.menu.value = false }}>Properties</div>
<div class="item separator" onclick=${()=>{ nodeui.deleteNode(); nodeui.menu.value = false }}>Delete</div> <div class="item separator" onclick=${() => { nodeui.deleteNode(); nodeui.menu.value = false }}>Delete</div>
<div class="section">User</div> <div class="section">User</div>
<div class="item" onclick=${()=>{ nodeui.showPage('profile-settings'); nodeui.menu.value = false }}>Settings</div> <div class="item" onclick=${() => { nodeui.showPage('profile-settings'); nodeui.menu.value = false }}>Settings</div>
<div class="item" onclick=${()=>{ nodeui.logout(); nodeui.menu.value = false }}>Log out</div> <div class="item" onclick=${() => { nodeui.logout(); nodeui.menu.value = false }}>Log out</div>
</div> </div>
` `
}//}}} }//}}}
@ -587,14 +629,14 @@ class UploadUI extends Component {
render({ nodeui }) {//{{{ render({ nodeui }) {//{{{
let filelist = this.filelist.value let filelist = this.filelist.value
let files = [] let files = []
for(let i = 0; i < filelist.length; i++) { for (let i = 0; i < filelist.length; i++) {
files.push(html`<div key=file_${i} ref=${this.fileRefs[i]} class="file">${filelist.item(i).name}</div><div class="progress" ref=${this.progressRefs[i]}></div>`) files.push(html`<div key=file_${i} ref=${this.fileRefs[i]} class="file">${filelist.item(i).name}</div><div class="progress" ref=${this.progressRefs[i]}></div>`)
} }
return html` return html`
<div id="blackout" onclick=${()=>nodeui.showPage('node')}></div> <div id="blackout" onclick=${() => nodeui.showPage('node')}></div>
<div id="upload"> <div id="upload">
<input type="file" ref=${this.file} onchange=${()=>this.upload()} multiple /> <input type="file" ref=${this.file} onchange=${() => this.upload()} multiple />
<div class="files"> <div class="files">
${files} ${files}
</div> </div>
@ -612,17 +654,17 @@ class UploadUI extends Component {
let input = this.file.current let input = this.file.current
this.filelist.value = input.files this.filelist.value = input.files
for(let i = 0; i < input.files.length; i++) { for (let i = 0; i < input.files.length; i++) {
this.fileRefs.push(createRef()) this.fileRefs.push(createRef())
this.progressRefs.push(createRef()) this.progressRefs.push(createRef())
this.postFile( this.postFile(
input.files[i], input.files[i],
nodeID, nodeID,
progress=>{ progress => {
this.progressRefs[i].current.innerHTML = `${progress}%` this.progressRefs[i].current.innerHTML = `${progress}%`
}, },
res=>{ res => {
this.props.nodeui.node.value.Files.push(res.File) this.props.nodeui.node.value.Files.push(res.File)
this.props.nodeui.forceUpdate() this.props.nodeui.forceUpdate()
@ -640,18 +682,18 @@ class UploadUI extends Component {
var request = new XMLHttpRequest() var request = new XMLHttpRequest()
request.addEventListener("error", ()=>{ request.addEventListener("error", () => {
window._app.current.responseError({ upload: "An unknown error occured" }) window._app.current.responseError({ upload: "An unknown error occured" })
}) })
request.addEventListener("loadend", ()=>{ request.addEventListener("loadend", () => {
if(request.status != 200) { if (request.status != 200) {
window._app.current.responseError({ upload: request.statusText }) window._app.current.responseError({ upload: request.statusText })
return return
} }
let response = JSON.parse(request.response) let response = JSON.parse(request.response)
if(!response.OK) { if (!response.OK) {
window._app.current.responseError({ upload: response.Error }) window._app.current.responseError({ upload: response.Error })
return return
} }
@ -659,14 +701,14 @@ class UploadUI extends Component {
doneCallback(response) doneCallback(response)
}) })
request.upload.addEventListener('progress', evt=>{ request.upload.addEventListener('progress', evt => {
var fileSize = file.size var fileSize = file.size
if(evt.loaded <= fileSize) if (evt.loaded <= fileSize)
progressCallback(Math.round(evt.loaded / fileSize * 100)) progressCallback(Math.round(evt.loaded / fileSize * 100))
if(evt.loaded == evt.total) if (evt.loaded == evt.total)
progressCallback(100) progressCallback(100)
}) })
request.open('post', '/node/upload') request.open('post', '/node/upload')
request.setRequestHeader("X-Session-Id", window._app.current.session.UUID) request.setRequestHeader("X-Session-Id", window._app.current.session.UUID)
@ -681,24 +723,26 @@ class NodeProperties extends Component {
this.selected_key_id = 0 this.selected_key_id = 0
}//}}} }//}}}
render({ nodeui }) {//{{{ render({ nodeui }) {//{{{
let save = true
let keys = nodeui.keys.value let keys = nodeui.keys.value
.sort((a, b)=>{ .sort((a, b) => {
if(a.description < b.description) return -1 if (a.description < b.description) return -1
if(a.description > b.description) return 1 if (a.description > b.description) return 1
return 0 return 0
}) })
.map(key=>{ .map(key => {
this.props.nodeui.keys.value.some(uikey=>{ this.props.nodeui.keys.value.some(uikey => {
if(uikey.ID == nodeui.node.value.ID) { if (uikey.ID == nodeui.node.value.ID) {
save = (uikey.status() == 'unlocked') this.selected_key_id = nodeui.node.value.ID
return true return true
} }
}) })
if (nodeui.node.value.CryptoKeyID == key.ID)
this.selected_key_id = key.ID
return html` return html`
<div class="key ${key.status()}"> <div class="key ${key.status()}">
<input type="radio" name="key" id="key-${key.ID}" checked=${nodeui.node.value.CryptoKeyID == key.ID} disabled=${key.status() == 'locked'} oninput=${()=>this.selected_key_id = key.ID} /> <input type="radio" name="key" id="key-${key.ID}" checked=${nodeui.node.value.CryptoKeyID == key.ID} disabled=${key.status() == 'locked'} oninput=${() => this.selected_key_id = key.ID} />
<label for="key-${key.ID}">${key.description}</label> <label for="key-${key.ID}">${key.description}</label>
</div>` </div>`
}) })
@ -709,14 +753,17 @@ class NodeProperties extends Component {
These properties are only for this note. These properties are only for this note.
<h2>Markdown</h2>
<input type="checkbox" id="render-markdown" checked=${nodeui.node.value.Markdown} onchange=${evt=>nodeui.node.value.Markdown = evt.target.checked} /> <label for="render-markdown">Render this node with markdown.</label>
<h2>Encryption</h2> <h2>Encryption</h2>
<div class="key"> <div class="key">
<input type="radio" id="key-none" name="key" checked=${nodeui.node.value.CryptoKeyID == 0} oninput=${()=>this.selected_key_id = 0} /> <input type="radio" id="key-none" name="key" checked=${nodeui.node.value.CryptoKeyID == 0} oninput=${() => this.selected_key_id = 0} />
<label for="key-none">None</label> <label for="key-none">None</label>
</div> </div>
${keys} ${keys}
${save ? html`<button style="margin-top: 32px" onclick=${()=>this.save()}>Save</button>` : ''} <button style="margin-top: 32px" onclick=${() => this.save()}>Save</button>
</div> </div>
` `
}//}}} }//}}}
@ -728,18 +775,22 @@ class NodeProperties extends Component {
let new_key = nodeui.getKey(this.selected_key_id) let new_key = nodeui.getKey(this.selected_key_id)
let current_key = nodeui.getKey(node.CryptoKeyID) let current_key = nodeui.getKey(node.CryptoKeyID)
if(current_key && current_key.status() == 'locked') { if (current_key && current_key.status() == 'locked') {
alert("Decryption key is locked and can not be used.") alert("Decryption key is locked and can not be used.")
return return
} }
if(new_key && new_key.status() == 'locked') { if (new_key && new_key.status() == 'locked') {
alert("Key is locked and can not be used.") alert("Key is locked and can not be used.")
return return
} }
await node.setCryptoKey(new_key) await node.setCryptoKey(new_key)
node.save(()=>this.props.nodeui.showPage('node'))
if (node.Markdown != node.RenderMarkdown.value)
node.RenderMarkdown.value = node.Markdown
node.save(() => this.props.nodeui.showPage('node'))
}//}}} }//}}}
} }
@ -755,8 +806,8 @@ class Search extends Component {
let match_elements = [ let match_elements = [
html`<h2>Results</h2>`, html`<h2>Results</h2>`,
] ]
let matched_nodes = matches.map(node=>html` let matched_nodes = matches.map(node => html`
<div class="matched-node" onclick=${()=>nodeui.goToNode(node.ID)}> <div class="matched-node" onclick=${() => nodeui.goToNode(node.ID)}>
${node.Name} ${node.Name}
</div> </div>
`) `)
@ -766,8 +817,8 @@ class Search extends Component {
<div id="search"> <div id="search">
<h1>Search</h1> <h1>Search</h1>
<input type="text" id="search-for" placeholder="Search for" onkeydown=${evt=>this.keyHandler(evt)} /> <input type="text" id="search-for" placeholder="Search for" onkeydown=${evt => this.keyHandler(evt)} />
<button onclick=${()=>this.search()}>Search</button> <button onclick=${() => this.search()}>Search</button>
${results_returned ? match_elements : ''} ${results_returned ? match_elements : ''}
</div>` </div>`
@ -779,7 +830,7 @@ class Search extends Component {
keyHandler(evt) {//{{{ keyHandler(evt) {//{{{
let handled = true let handled = true
switch(evt.key.toUpperCase()) { switch (evt.key.toUpperCase()) {
case 'ENTER': case 'ENTER':
this.search() this.search()
break break
@ -788,7 +839,7 @@ class Search extends Component {
handled = false handled = false
} }
if(handled) { if (handled) {
evt.preventDefault() evt.preventDefault()
evt.stopPropagation() evt.stopPropagation()
} }
@ -797,19 +848,19 @@ class Search extends Component {
let Search = document.getElementById('search-for').value let Search = document.getElementById('search-for').value
window._app.current.request('/node/search', { Search }) window._app.current.request('/node/search', { Search })
.then(res=>{ .then(res => {
this.setState({ this.setState({
matches: res.Nodes, matches: res.Nodes,
results_returned: true, results_returned: true,
})
}) })
}) .catch(window._app.current.responseError)
.catch(window._app.current.responseError)
}//}}} }//}}}
} }
class ProfileSettings extends Component { class ProfileSettings extends Component {
render({ nodeui }, {}) {//{{{ render({ nodeui }, { }) {//{{{
return html` return html`
<div id="profile-settings"> <div id="profile-settings">
<h1>User settings</h1> <h1>User settings</h1>
@ -817,16 +868,16 @@ class ProfileSettings extends Component {
<h2>Password</h2> <h2>Password</h2>
<div class="passwords"> <div class="passwords">
<div>Current</div> <div>Current</div>
<input type="password" id="current-password" placeholder="Current password" onkeydown=${evt=>this.keyHandler(evt)} /> <input type="password" id="current-password" placeholder="Current password" onkeydown=${evt => this.keyHandler(evt)} />
<div>New</div> <div>New</div>
<input type="password" id="new-password1" placeholder="Password" onkeydown=${evt=>this.keyHandler(evt)} /> <input type="password" id="new-password1" placeholder="Password" onkeydown=${evt => this.keyHandler(evt)} />
<div>Repeat</div> <div>Repeat</div>
<input type="password" id="new-password2" placeholder="Repeat password" onkeydown=${evt=>this.keyHandler(evt)} /> <input type="password" id="new-password2" placeholder="Repeat password" onkeydown=${evt => this.keyHandler(evt)} />
</div> </div>
<button onclick=${()=>this.updatePassword()}>Change password</button> <button onclick=${() => this.updatePassword()}>Change password</button>
</div>` </div>`
}//}}} }//}}}
componentDidMount() {//{{{ componentDidMount() {//{{{
@ -836,7 +887,7 @@ class ProfileSettings extends Component {
keyHandler(evt) {//{{{ keyHandler(evt) {//{{{
let handled = true let handled = true
switch(evt.key.toUpperCase()) { switch (evt.key.toUpperCase()) {
case 'ENTER': case 'ENTER':
this.updatePassword() this.updatePassword()
break break
@ -845,7 +896,7 @@ class ProfileSettings extends Component {
handled = false handled = false
} }
if(handled) { if (handled) {
evt.preventDefault() evt.preventDefault()
evt.stopPropagation() evt.stopPropagation()
} }
@ -856,11 +907,11 @@ class ProfileSettings extends Component {
let pass2 = document.getElementById('new-password2').value let pass2 = document.getElementById('new-password2').value
try { try {
if(pass1.length < 4) { if (pass1.length < 4) {
throw new Error('Password has to be at least 4 characters long') throw new Error('Password has to be at least 4 characters long')
} }
if(pass1 != pass2) { if (pass1 != pass2) {
throw new Error(`Passwords don't match`) throw new Error(`Passwords don't match`)
} }
@ -868,13 +919,13 @@ class ProfileSettings extends Component {
CurrentPassword: curr_pass, CurrentPassword: curr_pass,
NewPassword: pass1, NewPassword: pass1,
}) })
.then(res=>{ .then(res => {
if(res.CurrentPasswordOK) if (res.CurrentPasswordOK)
alert('Password is changed successfully') alert('Password is changed successfully')
else else
alert('Current password is invalid') alert('Current password is invalid')
}) })
} catch(err) { } catch (err) {
alert(err.message) alert(err.message)
} }

View File

@ -189,7 +189,7 @@ header {
font-size: 1.25em; font-size: 1.25em;
} }
.search, .add, .keys { .markdown, .search, .add, .keys {
padding-right: 16px; padding-right: 16px;
img { img {
@ -351,6 +351,22 @@ header {
} }
} }
#markdown {
padding: 16px;
color: #333;
grid-area: content;
max-width: 900px;
table {
border-collapse: collapse;
th, td {
border: 1px solid #ddd;
padding: 4px 8px;
}
}
}
/* ============================================================= * /* ============================================================= *
* Textarea replicates the height of an element expanding height * * Textarea replicates the height of an element expanding height *
* ============================================================= */ * ============================================================= */