marktip 0.4.0__tar.gz → 0.5.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {marktip-0.4.0 → marktip-0.5.0}/CMakeLists.txt +1 -1
- {marktip-0.4.0 → marktip-0.5.0}/PKG-INFO +103 -4
- marktip-0.5.0/README.md +250 -0
- {marktip-0.4.0 → marktip-0.5.0}/pyproject.toml +1 -1
- marktip-0.5.0/src/ast.cpp +1047 -0
- marktip-0.5.0/src/ast.h +116 -0
- {marktip-0.4.0 → marktip-0.5.0}/src/errors.h +4 -1
- {marktip-0.4.0 → marktip-0.5.0}/src/marktip.cpp +44 -7
- {marktip-0.4.0 → marktip-0.5.0}/src/parser.cpp +11 -1
- marktip-0.5.0/src/parser.h +13 -0
- {marktip-0.4.0 → marktip-0.5.0}/src/serializer.cpp +37 -16
- {marktip-0.4.0 → marktip-0.5.0}/tests/test_errors.py +15 -0
- {marktip-0.4.0 → marktip-0.5.0}/tests/test_roundtrip.py +18 -1
- {marktip-0.4.0 → marktip-0.5.0}/tests/test_serialize.py +87 -0
- marktip-0.5.0/tests/test_strict.py +311 -0
- marktip-0.5.0/tests/test_uri_policy.py +418 -0
- {marktip-0.4.0 → marktip-0.5.0}/tests/test_validate.py +3 -0
- {marktip-0.4.0 → marktip-0.5.0}/third_party/md4c/upstream_metadata/README.md +8 -0
- marktip-0.4.0/README.md +0 -151
- marktip-0.4.0/src/ast.cpp +0 -408
- marktip-0.4.0/src/ast.h +0 -78
- marktip-0.4.0/src/parser.h +0 -11
- {marktip-0.4.0 → marktip-0.5.0}/.github/workflows/build-distributions.yml +0 -0
- {marktip-0.4.0 → marktip-0.5.0}/.gitignore +0 -0
- {marktip-0.4.0 → marktip-0.5.0}/LICENSE +0 -0
- {marktip-0.4.0 → marktip-0.5.0}/python/marktip/__init__.py +0 -0
- {marktip-0.4.0 → marktip-0.5.0}/scripts/benchmark.py +0 -0
- {marktip-0.4.0 → marktip-0.5.0}/src/serializer.h +0 -0
- {marktip-0.4.0 → marktip-0.5.0}/tests/test_document.py +0 -0
- {marktip-0.4.0 → marktip-0.5.0}/tests/test_parse.py +0 -0
- {marktip-0.4.0 → marktip-0.5.0}/third_party/md4c/LICENSE.md +0 -0
- {marktip-0.4.0 → marktip-0.5.0}/third_party/md4c/src/entity.c +0 -0
- {marktip-0.4.0 → marktip-0.5.0}/third_party/md4c/src/entity.h +0 -0
- {marktip-0.4.0 → marktip-0.5.0}/third_party/md4c/src/md4c.c +0 -0
- {marktip-0.4.0 → marktip-0.5.0}/third_party/md4c/src/md4c.h +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: marktip
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.0
|
|
4
4
|
Summary: Fast C++/MD4C Markdown parser and canonical Markdown serializer for Tiptap-style JSON
|
|
5
5
|
Keywords: markdown,tiptap,md4c,parser
|
|
6
6
|
Author: Saneaven (Minjae Kyung)
|
|
@@ -71,6 +71,77 @@ doc = tm.from_markdown("a <u>x</u> b", html=False)
|
|
|
71
71
|
|
|
72
72
|
marktip targets GFM core syntax and canonical Markdown output rather than byte-identical source preservation.
|
|
73
73
|
|
|
74
|
+
### Restricting link and image URIs
|
|
75
|
+
|
|
76
|
+
`[click](javascript:alert(1))` is valid Markdown, so marktip converts it by default.
|
|
77
|
+
A consumer that *stores* the result and renders it later can opt into a scheme allowlist, enforced in C++ rather than as a second traversal in Python:
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
doc = tm.from_dict(ast, link_schemes=("http", "https", "mailto"), image_schemes=("https",))
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`link_schemes` and `image_schemes` are separate because the asymmetry is the common case, and both default to `None`, which allows every scheme.
|
|
84
|
+
An empty tuple allows none.
|
|
85
|
+
Scheme comparison is case-insensitive, and entity references are resolved first, so neither `JavaScript:` nor `javascript:` slips past an `https`-only list.
|
|
86
|
+
|
|
87
|
+
`link_relative` and `image_relative` govern references that carry no scheme at all:
|
|
88
|
+
|
|
89
|
+
| | `/foo`, `#anchor`, `./x.png` | `//evil.com/x` |
|
|
90
|
+
| --- | --- | --- |
|
|
91
|
+
| `"allow"` (default) | passes | passes |
|
|
92
|
+
| `"path_only"` | passes | rejected |
|
|
93
|
+
| `"reject"` | rejected | rejected |
|
|
94
|
+
|
|
95
|
+
The two axes are independent: `link_relative="reject"` with no allowlist means "any scheme, but it must be absolute".
|
|
96
|
+
|
|
97
|
+
Both write boundaries take the same options, which matters when an editor submits an AST but agents and imports submit Markdown strings:
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
doc = tm.from_markdown(untrusted, link_schemes=("https",), image_relative="reject")
|
|
101
|
+
# InvalidNodeError: link href scheme 'javascript' is not allowed
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Violations raise `InvalidNodeError` with `.field` set to `"href"` or `"src"`.
|
|
105
|
+
The options are keyword-only.
|
|
106
|
+
|
|
107
|
+
### Refusing lossy conversions
|
|
108
|
+
|
|
109
|
+
Node and mark *types* are closed, but `attrs` are not.
|
|
110
|
+
An attr the serializer never reads is dropped without a word, so a `colspan: 2` cell quietly becomes a plain one:
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
tm.from_dict(ast).to_markdown() # '| x |\n| --- |' — the colspan is gone
|
|
114
|
+
tm.from_dict(ast, strict=True) # InvalidNodeError: attr 'colspan' cannot be
|
|
115
|
+
# expressed in markdown: GFM tables have no cell spanning
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
`strict=True` refuses anything markdown would drop or alter, from the walk that is already happening, so a consumer does not have to re-traverse the tree in Python to find out whether the document survives intact.
|
|
119
|
+
It is off by default and keyword-only, and it is a `from_dict` option only — the parser emits nothing but attrs it understands, with values in range, so there is nothing on the `from_markdown` path for it to catch.
|
|
120
|
+
|
|
121
|
+
| Node | Accepted attrs |
|
|
122
|
+
| --- | --- |
|
|
123
|
+
| `heading` | `level`: 1–6 |
|
|
124
|
+
| `codeBlock` | `language`, `info`: single-line `str` |
|
|
125
|
+
| `bulletList`, `taskList` | `tight`: `bool` |
|
|
126
|
+
| `orderedList` | `start`: 0–999999999, `tight`: `bool` |
|
|
127
|
+
| `taskItem` | `checked`: `bool` |
|
|
128
|
+
| `table` | `colCount`: non-negative `int` |
|
|
129
|
+
| `tableHeader`, `tableCell` | `align`: `"left"`/`"center"`/`"right"`/`None`, `colspan`: `1`, `rowspan`: `1`, `colwidth`: `None` |
|
|
130
|
+
| `image` | `src`, `alt`, `title`: `str` |
|
|
131
|
+
| `htmlBlock`, `htmlInline` | `html`: `str` |
|
|
132
|
+
| `link` mark | `href`, `title`: `str` |
|
|
133
|
+
|
|
134
|
+
Every other type takes no attrs at all.
|
|
135
|
+
Under strict, `bool` and `int` stay distinct — `{"level": True}` is refused rather than read as `1`.
|
|
136
|
+
|
|
137
|
+
`colspan`/`rowspan`/`colwidth` are *known* attrs whose only accepted values are the no-ops Tiptap's table extension puts on every cell.
|
|
138
|
+
Refusing the names outright would leave strict unusable for the documents it exists to check.
|
|
139
|
+
Tiptap's Link extension is the other direction: its default `target` and `rel` have no markdown form, so they are refused, which is the same rule that stops an `onclick` from vanishing silently.
|
|
140
|
+
|
|
141
|
+
Two attrs are accepted and then ignored, and they are the only two.
|
|
142
|
+
The serializer derives a table's column count from its rows, so `colCount` is never read, and it takes cell alignment from the header row only, so `align` on a body row is never read either.
|
|
143
|
+
Both are refused nowhere because `from_markdown` emits both: rejecting them would break re-parsing stored canonical Markdown on the read path, where a write-time refusal is much harder to notice.
|
|
144
|
+
|
|
74
145
|
## Errors
|
|
75
146
|
|
|
76
147
|
Every rejection marktip raises derives from `marktip.MarktipError`, so "the input is malformed" is a single `except` — no need to catch a bare `ValueError` wide enough to swallow an unrelated bug:
|
|
@@ -91,6 +162,7 @@ Exception
|
|
|
91
162
|
```
|
|
92
163
|
|
|
93
164
|
`.path` is a breadcrumb into the input, e.g. `content[1].content[0].marks[0]`; it is `""` when the failure is at the root or has no location.
|
|
165
|
+
For `from_markdown` it locates the node in the parsed document, since the input itself is a string.
|
|
94
166
|
`.detail` is the same string as `str(e)`.
|
|
95
167
|
`.code` is a stable machine key:
|
|
96
168
|
|
|
@@ -102,14 +174,28 @@ Exception
|
|
|
102
174
|
| `invalid_root` | `InvalidNodeError` | the root node's type is not `doc` |
|
|
103
175
|
| `wrong_type` | `InvalidNodeError` | `attrs`/`content`/`marks`/a child has the wrong Python type |
|
|
104
176
|
| `max_depth` | `InvalidNodeError` | dict nesting exceeds 2048 |
|
|
177
|
+
| `disallowed_scheme` | `InvalidNodeError` | a link `href` / image `src` scheme is outside the allowlist |
|
|
178
|
+
| `disallowed_relative_url` | `InvalidNodeError` | a scheme-less `href`/`src` violates the relative policy |
|
|
179
|
+
| `invalid_uri_char` | `InvalidNodeError` | an `href`/`src` contains an ASCII control character |
|
|
180
|
+
| `unknown_attr` | `InvalidNodeError` | `strict`: the attr has no markdown form for that type |
|
|
181
|
+
| `invalid_attr_value` | `InvalidNodeError` | `strict`: the attr's value has the wrong type or is out of range |
|
|
182
|
+
| `unrepresentable` | `InvalidNodeError` | `strict`: the value is well-formed, but GFM cannot carry it |
|
|
105
183
|
| `markdown_max_depth` | `ParseError` | markdown nesting exceeds 2048 |
|
|
106
184
|
| `parse_failed` | `ParseError` | MD4C could not parse the input |
|
|
107
185
|
|
|
108
186
|
`from_markdown` still raises a plain `TypeError` when the argument is not `str`/`bytes` — that is a caller bug, not a malformed document.
|
|
187
|
+
So is a bad URI-policy option: a non-iterable `link_schemes` raises `TypeError`, and `link_schemes=("https://",)` or `link_relative="nope"` raises `ValueError`.
|
|
109
188
|
|
|
110
189
|
> **Changed in 0.4.0** — these were previously `ValueError` (`from_dict`) and `RuntimeError` (`from_markdown`).
|
|
111
190
|
> `MarktipError` derives from `Exception` directly, so `except ValueError` no longer catches them.
|
|
112
191
|
|
|
192
|
+
> **Changed in 0.5.0** — an ASCII control character in a link `href` or image `src` is now rejected outright, with or without the URI policy.
|
|
193
|
+
> A URI cannot carry one unencoded (`%09` is the encoded form), and leaving it in would defeat the allowlist itself, because browsers strip tab/LF/CR before reading the scheme.
|
|
194
|
+
> This also rejects `[x](<a\tb>)`, which CommonMark otherwise accepts.
|
|
195
|
+
|
|
196
|
+
> **Changed in 0.5.0** — an `orderedList` `start` outside 0–999999999 is clamped instead of emitted verbatim, and a code fence `language` is truncated at the first newline.
|
|
197
|
+
> Both previously produced output that reparsed into a different document; see [Defined normalizations](#defined-normalizations).
|
|
198
|
+
|
|
113
199
|
## What `from_dict` validates
|
|
114
200
|
|
|
115
201
|
The Tiptap-side schema is closed: every node/mark type must have a markdown mapping.
|
|
@@ -124,18 +210,29 @@ It guarantees, for the whole tree:
|
|
|
124
210
|
- **The root is a `doc`.**
|
|
125
211
|
- **Shapes**: `attrs` is a dict, `content` and `marks` are lists, and every entry of `content`/`marks` is a dict.
|
|
126
212
|
- **Depth** is at most 2048 levels.
|
|
213
|
+
- **No ASCII control character** in a link `href` or image `src`, entity references included (`	`, `	`).
|
|
214
|
+
- **The URI policy**, when `link_schemes`/`image_schemes`/`link_relative`/`image_relative` ask for it — see [Restricting link and image URIs](#restricting-link-and-image-uris).
|
|
127
215
|
|
|
128
216
|
A document that survives `from_dict` always serializes; callers do not need to re-check any of the above.
|
|
217
|
+
`from_markdown` enforces the same two URI rules on what it parses.
|
|
129
218
|
|
|
130
|
-
It deliberately does **not** validate:
|
|
219
|
+
It deliberately does **not** validate, unless `strict=True` asks it to:
|
|
131
220
|
|
|
132
|
-
- **`attrs` value types.**
|
|
221
|
+
- **`attrs` names and value types.**
|
|
133
222
|
Keys are free-form.
|
|
134
223
|
`str`, `int`, and `bool` round-trip unchanged; anything else is coerced to a string (`[1, 2]` → `"[1, 2]"`, `1.5` → `"1.5"`, `None` → `""`), so `to_dict()` will not always give back what you passed in.
|
|
135
|
-
|
|
224
|
+
An attr with no markdown form is dropped at serialization — see [Refusing lossy conversions](#refusing-lossy-conversions).
|
|
225
|
+
- **Per-node required attrs**, `strict` included.
|
|
136
226
|
A `heading` without `level`, an `image` without `src`, or a `link` mark without `href` is accepted; the serializer substitutes a default rather than failing.
|
|
227
|
+
`strict` governs the attrs that are present, not which ones must be.
|
|
137
228
|
- **Content models.**
|
|
138
229
|
Which node may contain which is not checked — a `text` node directly under `doc` is accepted and serialized.
|
|
230
|
+
- **Raw HTML.**
|
|
231
|
+
The URI policy governs `link` marks and `image` nodes, not markup inside `htmlBlock`/`htmlInline`, so `<a href="javascript:...">` passes it.
|
|
232
|
+
Pair the policy with `html=False` to close that.
|
|
233
|
+
- **URI syntax beyond the scheme.**
|
|
234
|
+
Everything after the scheme is opaque, and the stored value is never rewritten — an `href` is checked in its entity-decoded form but stored exactly as given.
|
|
235
|
+
Under `link_relative="allow"` a protocol-relative `//evil.com/x` also passes, since it carries no scheme; `"path_only"` is the setting that rejects it.
|
|
139
236
|
|
|
140
237
|
Structural violations report where they happened:
|
|
141
238
|
|
|
@@ -158,6 +255,8 @@ Rather than emitting markdown that reparses into a different structure, marktip
|
|
|
158
255
|
- **Multi-block table cells** — blocks inside a cell are joined with `<br>` and the cell is flattened to one line; two paragraphs in a cell reparse as one paragraph containing a `hardBreak`.
|
|
159
256
|
- **Headerless tables** — GFM tables require a header row, so the first row is always emitted as the header; a leading `tableCell` row reparses as `tableHeader`.
|
|
160
257
|
- **Heading levels** — clamped to 1–6 at serialization (`0` → `#`, `7` → `######`).
|
|
258
|
+
- **Ordered list start** — clamped to CommonMark's 0–999999999 (`-5` → `0.`), and the running number stops at that ceiling rather than emitting a 10-digit marker. Only the first number is honoured on reparse, so a repeated ceiling changes nothing.
|
|
259
|
+
- **Code fence info strings** — a `language` is truncated at the first newline, since an info string is a single line; one containing a backtick switches the fence to `~~~`, which carries it losslessly.
|
|
161
260
|
- **Emphasis boundary whitespace** — whitespace touching an emphasis delimiter has no valid markdown form and is expelled outside the marks (`bold("굵게 ")` → `**굵게** `), cf. prosemirror-markdown's `expelEnclosingWhitespace`.
|
|
162
261
|
- **Adjacent same-family lists** — consecutive lists of the same family alternate markers (`-`/`*`, `1.`/`1)`) so they stay separate lists on reparse instead of merging (which would renumber ordered items or spread task checkboxes).
|
|
163
262
|
|
marktip-0.5.0/README.md
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
# marktip
|
|
2
|
+
|
|
3
|
+
Fast C++/MD4C Markdown conversion for Tiptap-style JSON.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
python -m pip install marktip
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Release wheels are built for common CPython versions on Linux, macOS, and Windows.
|
|
12
|
+
If a wheel is not available for a platform, pip can build from the source distribution with a C++17 compiler and standard Python build tooling.
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
import marktip as tm
|
|
18
|
+
|
|
19
|
+
doc = tm.from_markdown("# Hello")
|
|
20
|
+
ast = doc.to_dict()
|
|
21
|
+
markdown = doc.to_markdown()
|
|
22
|
+
|
|
23
|
+
doc = tm.from_dict(ast)
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
`from_markdown` follows GFM/CommonMark by default.
|
|
27
|
+
Pass `cjk_friendly=True` to relax the emphasis and strikethrough rules so delimiters next to CJK text still open and close (e.g. `**볼드**은` parses as bold), a non-standard extension that is off by default:
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
doc = tm.from_markdown("**볼드**은 강조", cjk_friendly=True)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Strikethrough follows the GFM reference implementations (cmark-gfm/micromark): intra-word `~~` strikes (`a~~b~~c`), including next to CJK letters (`~~삭제~~은`).
|
|
34
|
+
`cjk_friendly` still matters for `*`/`_`, and for `~` in punctuation-adjacent cases such as `~~"인용"~~라고`.
|
|
35
|
+
|
|
36
|
+
Pass `html=False` to parse raw HTML as literal text instead of `htmlBlock`/`htmlInline` nodes.
|
|
37
|
+
Content is preserved (the serializer escapes it), and `<br>` inside table cells still maps to `hardBreak` so marktip's own table output round-trips:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
doc = tm.from_markdown("a <u>x</u> b", html=False)
|
|
41
|
+
# paragraph with the literal text "a <u>x</u> b"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
marktip targets GFM core syntax and canonical Markdown output rather than byte-identical source preservation.
|
|
45
|
+
|
|
46
|
+
### Restricting link and image URIs
|
|
47
|
+
|
|
48
|
+
`[click](javascript:alert(1))` is valid Markdown, so marktip converts it by default.
|
|
49
|
+
A consumer that *stores* the result and renders it later can opt into a scheme allowlist, enforced in C++ rather than as a second traversal in Python:
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
doc = tm.from_dict(ast, link_schemes=("http", "https", "mailto"), image_schemes=("https",))
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`link_schemes` and `image_schemes` are separate because the asymmetry is the common case, and both default to `None`, which allows every scheme.
|
|
56
|
+
An empty tuple allows none.
|
|
57
|
+
Scheme comparison is case-insensitive, and entity references are resolved first, so neither `JavaScript:` nor `javascript:` slips past an `https`-only list.
|
|
58
|
+
|
|
59
|
+
`link_relative` and `image_relative` govern references that carry no scheme at all:
|
|
60
|
+
|
|
61
|
+
| | `/foo`, `#anchor`, `./x.png` | `//evil.com/x` |
|
|
62
|
+
| --- | --- | --- |
|
|
63
|
+
| `"allow"` (default) | passes | passes |
|
|
64
|
+
| `"path_only"` | passes | rejected |
|
|
65
|
+
| `"reject"` | rejected | rejected |
|
|
66
|
+
|
|
67
|
+
The two axes are independent: `link_relative="reject"` with no allowlist means "any scheme, but it must be absolute".
|
|
68
|
+
|
|
69
|
+
Both write boundaries take the same options, which matters when an editor submits an AST but agents and imports submit Markdown strings:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
doc = tm.from_markdown(untrusted, link_schemes=("https",), image_relative="reject")
|
|
73
|
+
# InvalidNodeError: link href scheme 'javascript' is not allowed
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Violations raise `InvalidNodeError` with `.field` set to `"href"` or `"src"`.
|
|
77
|
+
The options are keyword-only.
|
|
78
|
+
|
|
79
|
+
### Refusing lossy conversions
|
|
80
|
+
|
|
81
|
+
Node and mark *types* are closed, but `attrs` are not.
|
|
82
|
+
An attr the serializer never reads is dropped without a word, so a `colspan: 2` cell quietly becomes a plain one:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
tm.from_dict(ast).to_markdown() # '| x |\n| --- |' — the colspan is gone
|
|
86
|
+
tm.from_dict(ast, strict=True) # InvalidNodeError: attr 'colspan' cannot be
|
|
87
|
+
# expressed in markdown: GFM tables have no cell spanning
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
`strict=True` refuses anything markdown would drop or alter, from the walk that is already happening, so a consumer does not have to re-traverse the tree in Python to find out whether the document survives intact.
|
|
91
|
+
It is off by default and keyword-only, and it is a `from_dict` option only — the parser emits nothing but attrs it understands, with values in range, so there is nothing on the `from_markdown` path for it to catch.
|
|
92
|
+
|
|
93
|
+
| Node | Accepted attrs |
|
|
94
|
+
| --- | --- |
|
|
95
|
+
| `heading` | `level`: 1–6 |
|
|
96
|
+
| `codeBlock` | `language`, `info`: single-line `str` |
|
|
97
|
+
| `bulletList`, `taskList` | `tight`: `bool` |
|
|
98
|
+
| `orderedList` | `start`: 0–999999999, `tight`: `bool` |
|
|
99
|
+
| `taskItem` | `checked`: `bool` |
|
|
100
|
+
| `table` | `colCount`: non-negative `int` |
|
|
101
|
+
| `tableHeader`, `tableCell` | `align`: `"left"`/`"center"`/`"right"`/`None`, `colspan`: `1`, `rowspan`: `1`, `colwidth`: `None` |
|
|
102
|
+
| `image` | `src`, `alt`, `title`: `str` |
|
|
103
|
+
| `htmlBlock`, `htmlInline` | `html`: `str` |
|
|
104
|
+
| `link` mark | `href`, `title`: `str` |
|
|
105
|
+
|
|
106
|
+
Every other type takes no attrs at all.
|
|
107
|
+
Under strict, `bool` and `int` stay distinct — `{"level": True}` is refused rather than read as `1`.
|
|
108
|
+
|
|
109
|
+
`colspan`/`rowspan`/`colwidth` are *known* attrs whose only accepted values are the no-ops Tiptap's table extension puts on every cell.
|
|
110
|
+
Refusing the names outright would leave strict unusable for the documents it exists to check.
|
|
111
|
+
Tiptap's Link extension is the other direction: its default `target` and `rel` have no markdown form, so they are refused, which is the same rule that stops an `onclick` from vanishing silently.
|
|
112
|
+
|
|
113
|
+
Two attrs are accepted and then ignored, and they are the only two.
|
|
114
|
+
The serializer derives a table's column count from its rows, so `colCount` is never read, and it takes cell alignment from the header row only, so `align` on a body row is never read either.
|
|
115
|
+
Both are refused nowhere because `from_markdown` emits both: rejecting them would break re-parsing stored canonical Markdown on the read path, where a write-time refusal is much harder to notice.
|
|
116
|
+
|
|
117
|
+
## Errors
|
|
118
|
+
|
|
119
|
+
Every rejection marktip raises derives from `marktip.MarktipError`, so "the input is malformed" is a single `except` — no need to catch a bare `ValueError` wide enough to swallow an unrelated bug:
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
try:
|
|
123
|
+
tm.from_dict(payload).to_markdown()
|
|
124
|
+
except tm.MarktipError as e:
|
|
125
|
+
return 422, {"code": e.code, "path": e.path, "detail": e.detail}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
```
|
|
129
|
+
Exception
|
|
130
|
+
└─ MarktipError .code, .path, .detail
|
|
131
|
+
├─ UnknownTypeError + .type, .kind — type outside the closed schema
|
|
132
|
+
├─ InvalidNodeError + .field — violates the node grammar
|
|
133
|
+
└─ ParseError — markdown could not be parsed
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
`.path` is a breadcrumb into the input, e.g. `content[1].content[0].marks[0]`; it is `""` when the failure is at the root or has no location.
|
|
137
|
+
For `from_markdown` it locates the node in the parsed document, since the input itself is a string.
|
|
138
|
+
`.detail` is the same string as `str(e)`.
|
|
139
|
+
`.code` is a stable machine key:
|
|
140
|
+
|
|
141
|
+
| `.code` | Class | Raised when |
|
|
142
|
+
| --- | --- | --- |
|
|
143
|
+
| `unknown_node_type` | `UnknownTypeError` | node `type` is outside the closed schema |
|
|
144
|
+
| `unknown_mark_type` | `UnknownTypeError` | mark `type` is outside the closed schema |
|
|
145
|
+
| `missing_type` | `InvalidNodeError` | a node or mark has no `type` key |
|
|
146
|
+
| `invalid_root` | `InvalidNodeError` | the root node's type is not `doc` |
|
|
147
|
+
| `wrong_type` | `InvalidNodeError` | `attrs`/`content`/`marks`/a child has the wrong Python type |
|
|
148
|
+
| `max_depth` | `InvalidNodeError` | dict nesting exceeds 2048 |
|
|
149
|
+
| `disallowed_scheme` | `InvalidNodeError` | a link `href` / image `src` scheme is outside the allowlist |
|
|
150
|
+
| `disallowed_relative_url` | `InvalidNodeError` | a scheme-less `href`/`src` violates the relative policy |
|
|
151
|
+
| `invalid_uri_char` | `InvalidNodeError` | an `href`/`src` contains an ASCII control character |
|
|
152
|
+
| `unknown_attr` | `InvalidNodeError` | `strict`: the attr has no markdown form for that type |
|
|
153
|
+
| `invalid_attr_value` | `InvalidNodeError` | `strict`: the attr's value has the wrong type or is out of range |
|
|
154
|
+
| `unrepresentable` | `InvalidNodeError` | `strict`: the value is well-formed, but GFM cannot carry it |
|
|
155
|
+
| `markdown_max_depth` | `ParseError` | markdown nesting exceeds 2048 |
|
|
156
|
+
| `parse_failed` | `ParseError` | MD4C could not parse the input |
|
|
157
|
+
|
|
158
|
+
`from_markdown` still raises a plain `TypeError` when the argument is not `str`/`bytes` — that is a caller bug, not a malformed document.
|
|
159
|
+
So is a bad URI-policy option: a non-iterable `link_schemes` raises `TypeError`, and `link_schemes=("https://",)` or `link_relative="nope"` raises `ValueError`.
|
|
160
|
+
|
|
161
|
+
> **Changed in 0.4.0** — these were previously `ValueError` (`from_dict`) and `RuntimeError` (`from_markdown`).
|
|
162
|
+
> `MarktipError` derives from `Exception` directly, so `except ValueError` no longer catches them.
|
|
163
|
+
|
|
164
|
+
> **Changed in 0.5.0** — an ASCII control character in a link `href` or image `src` is now rejected outright, with or without the URI policy.
|
|
165
|
+
> A URI cannot carry one unencoded (`%09` is the encoded form), and leaving it in would defeat the allowlist itself, because browsers strip tab/LF/CR before reading the scheme.
|
|
166
|
+
> This also rejects `[x](<a\tb>)`, which CommonMark otherwise accepts.
|
|
167
|
+
|
|
168
|
+
> **Changed in 0.5.0** — an `orderedList` `start` outside 0–999999999 is clamped instead of emitted verbatim, and a code fence `language` is truncated at the first newline.
|
|
169
|
+
> Both previously produced output that reparsed into a different document; see [Defined normalizations](#defined-normalizations).
|
|
170
|
+
|
|
171
|
+
## What `from_dict` validates
|
|
172
|
+
|
|
173
|
+
The Tiptap-side schema is closed: every node/mark type must have a markdown mapping.
|
|
174
|
+
`from_dict` is the single enforcement point and rejects unknown types instead of silently dropping content.
|
|
175
|
+
It guarantees, for the whole tree:
|
|
176
|
+
|
|
177
|
+
- **Closed schema.**
|
|
178
|
+
Node types are `doc`, `paragraph`, `text`, `hardBreak`, `heading`, `blockquote`, `codeBlock`, `horizontalRule`, `bulletList`, `orderedList`, `listItem`, `taskList`, `taskItem`, `table`, `tableRow`, `tableHeader`, `tableCell`, `image`, `htmlBlock`, `htmlInline`.
|
|
179
|
+
Marks are `bold`, `italic`, `strike`, `code`, `link`.
|
|
180
|
+
Anything else → `UnknownTypeError`.
|
|
181
|
+
- **`type` is required** on every node and mark.
|
|
182
|
+
- **The root is a `doc`.**
|
|
183
|
+
- **Shapes**: `attrs` is a dict, `content` and `marks` are lists, and every entry of `content`/`marks` is a dict.
|
|
184
|
+
- **Depth** is at most 2048 levels.
|
|
185
|
+
- **No ASCII control character** in a link `href` or image `src`, entity references included (`	`, `	`).
|
|
186
|
+
- **The URI policy**, when `link_schemes`/`image_schemes`/`link_relative`/`image_relative` ask for it — see [Restricting link and image URIs](#restricting-link-and-image-uris).
|
|
187
|
+
|
|
188
|
+
A document that survives `from_dict` always serializes; callers do not need to re-check any of the above.
|
|
189
|
+
`from_markdown` enforces the same two URI rules on what it parses.
|
|
190
|
+
|
|
191
|
+
It deliberately does **not** validate, unless `strict=True` asks it to:
|
|
192
|
+
|
|
193
|
+
- **`attrs` names and value types.**
|
|
194
|
+
Keys are free-form.
|
|
195
|
+
`str`, `int`, and `bool` round-trip unchanged; anything else is coerced to a string (`[1, 2]` → `"[1, 2]"`, `1.5` → `"1.5"`, `None` → `""`), so `to_dict()` will not always give back what you passed in.
|
|
196
|
+
An attr with no markdown form is dropped at serialization — see [Refusing lossy conversions](#refusing-lossy-conversions).
|
|
197
|
+
- **Per-node required attrs**, `strict` included.
|
|
198
|
+
A `heading` without `level`, an `image` without `src`, or a `link` mark without `href` is accepted; the serializer substitutes a default rather than failing.
|
|
199
|
+
`strict` governs the attrs that are present, not which ones must be.
|
|
200
|
+
- **Content models.**
|
|
201
|
+
Which node may contain which is not checked — a `text` node directly under `doc` is accepted and serialized.
|
|
202
|
+
- **Raw HTML.**
|
|
203
|
+
The URI policy governs `link` marks and `image` nodes, not markup inside `htmlBlock`/`htmlInline`, so `<a href="javascript:...">` passes it.
|
|
204
|
+
Pair the policy with `html=False` to close that.
|
|
205
|
+
- **URI syntax beyond the scheme.**
|
|
206
|
+
Everything after the scheme is opaque, and the stored value is never rewritten — an `href` is checked in its entity-decoded form but stored exactly as given.
|
|
207
|
+
Under `link_relative="allow"` a protocol-relative `//evil.com/x` also passes, since it carries no scheme; `"path_only"` is the setting that rejects it.
|
|
208
|
+
|
|
209
|
+
Structural violations report where they happened:
|
|
210
|
+
|
|
211
|
+
```python
|
|
212
|
+
try:
|
|
213
|
+
tm.from_dict({"type": "doc", "content": [{"content": []}]})
|
|
214
|
+
except tm.InvalidNodeError as e:
|
|
215
|
+
e.code # "missing_type"
|
|
216
|
+
e.field # "type"
|
|
217
|
+
e.path # "content[0]"
|
|
218
|
+
e.detail # "node is missing required key 'type'"
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
## Defined normalizations
|
|
222
|
+
|
|
223
|
+
Markdown cannot represent every Tiptap document exactly.
|
|
224
|
+
Rather than emitting markdown that reparses into a different structure, marktip applies these deterministic (and idempotent) normalizations at serialization time:
|
|
225
|
+
|
|
226
|
+
- **Hard breaks in headings** — ATX headings are single-line, so a `hardBreak` (or a literal newline carried over from setext input) inside a heading serializes as a single space: `heading("a", hardBreak, "b")` → `# a b`.
|
|
227
|
+
- **Multi-block table cells** — blocks inside a cell are joined with `<br>` and the cell is flattened to one line; two paragraphs in a cell reparse as one paragraph containing a `hardBreak`.
|
|
228
|
+
- **Headerless tables** — GFM tables require a header row, so the first row is always emitted as the header; a leading `tableCell` row reparses as `tableHeader`.
|
|
229
|
+
- **Heading levels** — clamped to 1–6 at serialization (`0` → `#`, `7` → `######`).
|
|
230
|
+
- **Ordered list start** — clamped to CommonMark's 0–999999999 (`-5` → `0.`), and the running number stops at that ceiling rather than emitting a 10-digit marker. Only the first number is honoured on reparse, so a repeated ceiling changes nothing.
|
|
231
|
+
- **Code fence info strings** — a `language` is truncated at the first newline, since an info string is a single line; one containing a backtick switches the fence to `~~~`, which carries it losslessly.
|
|
232
|
+
- **Emphasis boundary whitespace** — whitespace touching an emphasis delimiter has no valid markdown form and is expelled outside the marks (`bold("굵게 ")` → `**굵게** `), cf. prosemirror-markdown's `expelEnclosingWhitespace`.
|
|
233
|
+
- **Adjacent same-family lists** — consecutive lists of the same family alternate markers (`-`/`*`, `1.`/`1)`) so they stay separate lists on reparse instead of merging (which would renumber ordered items or spread task checkboxes).
|
|
234
|
+
|
|
235
|
+
## Development
|
|
236
|
+
|
|
237
|
+
```bash
|
|
238
|
+
python -m pip install .[test]
|
|
239
|
+
python -m pytest
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
For a direct local CMake build:
|
|
243
|
+
|
|
244
|
+
```bash
|
|
245
|
+
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \
|
|
246
|
+
-Dpybind11_DIR="$(python -m pybind11 --cmakedir)"
|
|
247
|
+
cmake --build build
|
|
248
|
+
PYTHONPATH=python python -m pytest
|
|
249
|
+
PYTHONPATH=python python scripts/benchmark.py
|
|
250
|
+
```
|
|
@@ -4,7 +4,7 @@ build-backend = "scikit_build_core.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "marktip"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.5.0"
|
|
8
8
|
description = "Fast C++/MD4C Markdown parser and canonical Markdown serializer for Tiptap-style JSON"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.9"
|