marktip 0.3.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.
Files changed (37) hide show
  1. {marktip-0.3.0 → marktip-0.5.0}/CMakeLists.txt +1 -1
  2. marktip-0.5.0/PKG-INFO +278 -0
  3. marktip-0.5.0/README.md +250 -0
  4. {marktip-0.3.0 → marktip-0.5.0}/pyproject.toml +1 -1
  5. {marktip-0.3.0 → marktip-0.5.0}/python/marktip/__init__.py +23 -2
  6. marktip-0.5.0/src/ast.cpp +1047 -0
  7. marktip-0.5.0/src/ast.h +116 -0
  8. marktip-0.5.0/src/errors.h +73 -0
  9. marktip-0.5.0/src/marktip.cpp +148 -0
  10. {marktip-0.3.0 → marktip-0.5.0}/src/parser.cpp +44 -52
  11. marktip-0.5.0/src/parser.h +13 -0
  12. {marktip-0.3.0 → marktip-0.5.0}/src/serializer.cpp +40 -18
  13. {marktip-0.3.0 → marktip-0.5.0}/tests/test_document.py +3 -3
  14. marktip-0.5.0/tests/test_errors.py +205 -0
  15. {marktip-0.3.0 → marktip-0.5.0}/tests/test_roundtrip.py +18 -1
  16. {marktip-0.3.0 → marktip-0.5.0}/tests/test_serialize.py +88 -1
  17. marktip-0.5.0/tests/test_strict.py +311 -0
  18. marktip-0.5.0/tests/test_uri_policy.py +418 -0
  19. {marktip-0.3.0 → marktip-0.5.0}/tests/test_validate.py +19 -10
  20. {marktip-0.3.0 → marktip-0.5.0}/third_party/md4c/upstream_metadata/README.md +8 -0
  21. marktip-0.3.0/PKG-INFO +0 -146
  22. marktip-0.3.0/README.md +0 -118
  23. marktip-0.3.0/src/ast.cpp +0 -405
  24. marktip-0.3.0/src/ast.h +0 -98
  25. marktip-0.3.0/src/marktip.cpp +0 -62
  26. marktip-0.3.0/src/parser.h +0 -11
  27. {marktip-0.3.0 → marktip-0.5.0}/.github/workflows/build-distributions.yml +0 -0
  28. {marktip-0.3.0 → marktip-0.5.0}/.gitignore +0 -0
  29. {marktip-0.3.0 → marktip-0.5.0}/LICENSE +0 -0
  30. {marktip-0.3.0 → marktip-0.5.0}/scripts/benchmark.py +0 -0
  31. {marktip-0.3.0 → marktip-0.5.0}/src/serializer.h +0 -0
  32. {marktip-0.3.0 → marktip-0.5.0}/tests/test_parse.py +0 -0
  33. {marktip-0.3.0 → marktip-0.5.0}/third_party/md4c/LICENSE.md +0 -0
  34. {marktip-0.3.0 → marktip-0.5.0}/third_party/md4c/src/entity.c +0 -0
  35. {marktip-0.3.0 → marktip-0.5.0}/third_party/md4c/src/entity.h +0 -0
  36. {marktip-0.3.0 → marktip-0.5.0}/third_party/md4c/src/md4c.c +0 -0
  37. {marktip-0.3.0 → marktip-0.5.0}/third_party/md4c/src/md4c.h +0 -0
@@ -7,7 +7,7 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
7
7
  set(CMAKE_CXX_EXTENSIONS OFF)
8
8
 
9
9
  if(NOT DEFINED SKBUILD_PROJECT_VERSION)
10
- set(SKBUILD_PROJECT_VERSION "0.3.0")
10
+ set(SKBUILD_PROJECT_VERSION "0.5.0")
11
11
  endif()
12
12
 
13
13
  set(PYBIND11_FINDPYTHON ON)
marktip-0.5.0/PKG-INFO ADDED
@@ -0,0 +1,278 @@
1
+ Metadata-Version: 2.4
2
+ Name: marktip
3
+ Version: 0.5.0
4
+ Summary: Fast C++/MD4C Markdown parser and canonical Markdown serializer for Tiptap-style JSON
5
+ Keywords: markdown,tiptap,md4c,parser
6
+ Author: Saneaven (Minjae Kyung)
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ License-File: third_party/md4c/LICENSE.md
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: MacOS
13
+ Classifier: Operating System :: Microsoft :: Windows
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Programming Language :: C++
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Text Processing :: Markup :: Markdown
24
+ Requires-Python: >=3.9
25
+ Provides-Extra: test
26
+ Requires-Dist: pytest>=8; extra == "test"
27
+ Description-Content-Type: text/markdown
28
+
29
+ # marktip
30
+
31
+ Fast C++/MD4C Markdown conversion for Tiptap-style JSON.
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ python -m pip install marktip
37
+ ```
38
+
39
+ Release wheels are built for common CPython versions on Linux, macOS, and Windows.
40
+ 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.
41
+
42
+ ## Usage
43
+
44
+ ```python
45
+ import marktip as tm
46
+
47
+ doc = tm.from_markdown("# Hello")
48
+ ast = doc.to_dict()
49
+ markdown = doc.to_markdown()
50
+
51
+ doc = tm.from_dict(ast)
52
+ ```
53
+
54
+ `from_markdown` follows GFM/CommonMark by default.
55
+ 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:
56
+
57
+ ```python
58
+ doc = tm.from_markdown("**볼드**은 강조", cjk_friendly=True)
59
+ ```
60
+
61
+ Strikethrough follows the GFM reference implementations (cmark-gfm/micromark): intra-word `~~` strikes (`a~~b~~c`), including next to CJK letters (`~~삭제~~은`).
62
+ `cjk_friendly` still matters for `*`/`_`, and for `~` in punctuation-adjacent cases such as `~~"인용"~~라고`.
63
+
64
+ Pass `html=False` to parse raw HTML as literal text instead of `htmlBlock`/`htmlInline` nodes.
65
+ Content is preserved (the serializer escapes it), and `<br>` inside table cells still maps to `hardBreak` so marktip's own table output round-trips:
66
+
67
+ ```python
68
+ doc = tm.from_markdown("a <u>x</u> b", html=False)
69
+ # paragraph with the literal text "a <u>x</u> b"
70
+ ```
71
+
72
+ marktip targets GFM core syntax and canonical Markdown output rather than byte-identical source preservation.
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 `&#106;avascript:` 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
+
145
+ ## Errors
146
+
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:
148
+
149
+ ```python
150
+ try:
151
+ tm.from_dict(payload).to_markdown()
152
+ except tm.MarktipError as e:
153
+ return 422, {"code": e.code, "path": e.path, "detail": e.detail}
154
+ ```
155
+
156
+ ```
157
+ Exception
158
+ └─ MarktipError .code, .path, .detail
159
+ ├─ UnknownTypeError + .type, .kind — type outside the closed schema
160
+ ├─ InvalidNodeError + .field — violates the node grammar
161
+ └─ ParseError — markdown could not be parsed
162
+ ```
163
+
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.
166
+ `.detail` is the same string as `str(e)`.
167
+ `.code` is a stable machine key:
168
+
169
+ | `.code` | Class | Raised when |
170
+ | --- | --- | --- |
171
+ | `unknown_node_type` | `UnknownTypeError` | node `type` is outside the closed schema |
172
+ | `unknown_mark_type` | `UnknownTypeError` | mark `type` is outside the closed schema |
173
+ | `missing_type` | `InvalidNodeError` | a node or mark has no `type` key |
174
+ | `invalid_root` | `InvalidNodeError` | the root node's type is not `doc` |
175
+ | `wrong_type` | `InvalidNodeError` | `attrs`/`content`/`marks`/a child has the wrong Python type |
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 |
183
+ | `markdown_max_depth` | `ParseError` | markdown nesting exceeds 2048 |
184
+ | `parse_failed` | `ParseError` | MD4C could not parse the input |
185
+
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`.
188
+
189
+ > **Changed in 0.4.0** — these were previously `ValueError` (`from_dict`) and `RuntimeError` (`from_markdown`).
190
+ > `MarktipError` derives from `Exception` directly, so `except ValueError` no longer catches them.
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
+
199
+ ## What `from_dict` validates
200
+
201
+ The Tiptap-side schema is closed: every node/mark type must have a markdown mapping.
202
+ `from_dict` is the single enforcement point and rejects unknown types instead of silently dropping content.
203
+ It guarantees, for the whole tree:
204
+
205
+ - **Closed schema.**
206
+ Node types are `doc`, `paragraph`, `text`, `hardBreak`, `heading`, `blockquote`, `codeBlock`, `horizontalRule`, `bulletList`, `orderedList`, `listItem`, `taskList`, `taskItem`, `table`, `tableRow`, `tableHeader`, `tableCell`, `image`, `htmlBlock`, `htmlInline`.
207
+ Marks are `bold`, `italic`, `strike`, `code`, `link`.
208
+ Anything else → `UnknownTypeError`.
209
+ - **`type` is required** on every node and mark.
210
+ - **The root is a `doc`.**
211
+ - **Shapes**: `attrs` is a dict, `content` and `marks` are lists, and every entry of `content`/`marks` is a dict.
212
+ - **Depth** is at most 2048 levels.
213
+ - **No ASCII control character** in a link `href` or image `src`, entity references included (`&Tab;`, `&#09;`).
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).
215
+
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.
218
+
219
+ It deliberately does **not** validate, unless `strict=True` asks it to:
220
+
221
+ - **`attrs` names and value types.**
222
+ Keys are free-form.
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.
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.
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.
228
+ - **Content models.**
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.
236
+
237
+ Structural violations report where they happened:
238
+
239
+ ```python
240
+ try:
241
+ tm.from_dict({"type": "doc", "content": [{"content": []}]})
242
+ except tm.InvalidNodeError as e:
243
+ e.code # "missing_type"
244
+ e.field # "type"
245
+ e.path # "content[0]"
246
+ e.detail # "node is missing required key 'type'"
247
+ ```
248
+
249
+ ## Defined normalizations
250
+
251
+ Markdown cannot represent every Tiptap document exactly.
252
+ Rather than emitting markdown that reparses into a different structure, marktip applies these deterministic (and idempotent) normalizations at serialization time:
253
+
254
+ - **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`.
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`.
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`.
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.
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`.
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).
262
+
263
+ ## Development
264
+
265
+ ```bash
266
+ python -m pip install .[test]
267
+ python -m pytest
268
+ ```
269
+
270
+ For a direct local CMake build:
271
+
272
+ ```bash
273
+ cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \
274
+ -Dpybind11_DIR="$(python -m pybind11 --cmakedir)"
275
+ cmake --build build
276
+ PYTHONPATH=python python -m pytest
277
+ PYTHONPATH=python python scripts/benchmark.py
278
+ ```
@@ -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 `&#106;avascript:` 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 (`&Tab;`, `&#09;`).
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.3.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"
@@ -1,7 +1,16 @@
1
1
  """Fast Markdown conversion for Tiptap-style JSON."""
2
2
 
3
3
  try:
4
- from ._core import Document, UnknownTypeError, __version__, from_dict, from_markdown
4
+ from ._core import (
5
+ Document,
6
+ InvalidNodeError,
7
+ MarktipError,
8
+ ParseError,
9
+ UnknownTypeError,
10
+ __version__,
11
+ from_dict,
12
+ from_markdown,
13
+ )
5
14
  except ImportError: # pragma: no cover - development-only CMake build fallback
6
15
  import importlib.util
7
16
  import pathlib
@@ -21,8 +30,20 @@ except ImportError: # pragma: no cover - development-only CMake build fallback
21
30
 
22
31
  __version__ = _module.__version__
23
32
  Document = _module.Document
33
+ MarktipError = _module.MarktipError
24
34
  UnknownTypeError = _module.UnknownTypeError
35
+ InvalidNodeError = _module.InvalidNodeError
36
+ ParseError = _module.ParseError
25
37
  from_dict = _module.from_dict
26
38
  from_markdown = _module.from_markdown
27
39
 
28
- __all__ = ["__version__", "Document", "UnknownTypeError", "from_markdown", "from_dict"]
40
+ __all__ = [
41
+ "__version__",
42
+ "Document",
43
+ "MarktipError",
44
+ "UnknownTypeError",
45
+ "InvalidNodeError",
46
+ "ParseError",
47
+ "from_markdown",
48
+ "from_dict",
49
+ ]