Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ The package version runs on its own semver; the schema it is generated from is `

## Unreleased

- **Depth is counted in a file's text, before the parse** (folder format, serial 148), as the npm SDK counts it. Text this package did not write is past 200 levels when it opens an object or array deeper than 200, so each value of a repeated key counts and a file past the line is refused as nested too deep whatever else is wrong with it. Brackets inside a string are not counted, and a string left open runs to the end of the text. Before, the depth was read from the parsed value: a repeated key's plain value hid a deep one, and a file broken and deep was refused as not JSON.

## 0.154.0 (2026-11-25)

- **`name_finder` passes over what is no mention**, as the npm SDK's `nameFinder` 4.208.0 does. In any text, a bare web address (`http://` or `https://`, in any ASCII case, to the next white space or `<`) and an autolink (`<scheme:…>`) are now passed over, beside the addresses and Markdown links they were before. A call can say its text is Markdown, `find(text, markdown=True)`: then nothing is read inside an inline code span (backtick runs matched by length), a fenced code block (closed by its own character, at least as long, or open to the end), an HTML tag or comment, or a reference definition's line either. The option is off by default, so the answers without it change only inside web addresses. An indented code block, a fence inside a quote or a list, and a definition's title on the next line are read as prose. Held by version 3 of the shared cases (84 cases, 16 with the option; 14 timed recipes), with eight planted faults each red; the two packages gave the same answers on 4,000 made texts, read with the option and without.
Expand Down
41 changes: 24 additions & 17 deletions src/onlyworlds/_outside_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@

import json
import math
import re
import sys
from itertools import accumulate
from typing import Any

#: The deepest nesting read: a value at the top is depth 0, an object or array there depth 1, what it holds
Expand Down Expand Up @@ -50,32 +52,37 @@ def _int(text: str) -> int:
return int(text)


def _too_deep(value: Any) -> bool:
"""Whether any object or array sits deeper than ``MAX_DEPTH``. A loop with its own stack, never recursion."""
stack: list[tuple[Any, int]] = [(value, 1)]
while stack:
item, depth = stack.pop()
if isinstance(item, dict):
children: Any = item.values()
elif isinstance(item, list):
children = item
else:
continue
if depth > MAX_DEPTH:
return True
stack.extend((child, depth + 1) for child in children if isinstance(child, (dict, list)))
return False
#: A whole JSON string: a backslash escapes the character after it.
_STRING = re.compile(r'"[^"\\]*(?:\\.[^"\\]*)*"', re.DOTALL)
_BRACKET = re.compile(r"[\[\]{}]")
_STEP = {"[": 1, "{": 1, "]": -1, "}": -1}


def _text_too_deep(text: str) -> bool:
"""Whether the text opens an object or array deeper than ``MAX_DEPTH``, counted in the text itself as each
one opens, before any parse (the folder format's rule since serial 148): so each value of a repeated key
counts, and a text past the line is too deep whatever else is wrong with it. Brackets inside a string are
not counted; a string left open runs to the end of the text, as the npm SDK's scan reads it."""
outside = _STRING.sub("", text)
open_quote = outside.find('"')
if open_quote >= 0:
outside = outside[:open_quote]
brackets = "".join(_BRACKET.findall(outside))
# No text can open more levels than it has opening brackets.
if brackets.count("[") + brackets.count("{") <= MAX_DEPTH:
return False
return max(accumulate(_STEP[b] for b in brackets)) > MAX_DEPTH


def loads(text: str, **kwargs: Any) -> Any:
"""``json.loads(text, **kwargs)``, with the cases above raised as ``ValueError``."""
kwargs.setdefault("parse_int", _int)
kwargs.setdefault("parse_float", _float)
kwargs.setdefault("parse_constant", _constant)
if _text_too_deep(text):
raise ValueError(_TOO_DEEP)
try:
value = json.loads(text, **kwargs)
except RecursionError:
raise ValueError(_TOO_DEEP) from None
if _too_deep(value):
raise ValueError(_TOO_DEEP)
return value
32 changes: 32 additions & 0 deletions tests/test_outside_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,38 @@ def nest(depth: int, open_: str, close: str) -> str:
_outside_json.loads('{"a": ' + nest(200, "[", "]") + "}")


NEST_200 = "[" * 200 + "]" * 200 # as a field's value in an element object, it reaches 201


@pytest.mark.parametrize(
("text", "deep"),
[
# Counted in the text as each object or array opens (serial 148): what the parse keeps does not decide it.
('{"x": ' + NEST_200 + ', "x": 1}', True),
('{"x": , ' + NEST_200 + "}", True),
('{"x": ' + "[" * 199 + "{}" + "]" * 199 + "}", True),
('{"x": ' + json.dumps("[" * 300) + "}", False),
('{"x": "a\\"' + "{" * 300 + '"}', False),
('{"x": ["\\\\", ' + "[" * 199 + "]" * 199 + "]}", True),
('{"x": "open ' + "[" * 300, False),
],
ids=[
"a repeated key, its deep value first",
"broken JSON before a part past the line",
"an empty object at 201",
"brackets inside a string",
"an escaped quote, then brackets still inside the string",
"an escaped backslash, then a real bracket at 201",
"a string left open runs to the end",
],
)
def test_the_depth_is_counted_in_the_text_before_the_parse(text: str, deep: bool) -> None:
assert _outside_json._text_too_deep(text) is deep
if deep:
with pytest.raises(ValueError, match="nested more than 200 deep"):
_outside_json.loads(text)


def test_text_that_is_not_json_is_still_a_decode_error() -> None:
with pytest.raises(json.JSONDecodeError):
_outside_json.loads('{"id": ')
Expand Down