ai-editor-tree-engine-dev 1.0.176__py3-none-any.whl

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 (121) hide show
  1. ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
  2. ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
  3. ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
  4. ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
  5. ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
  6. tree_engine/PUBLIC_API.md +161 -0
  7. tree_engine/__init__.py +327 -0
  8. tree_engine/checks/__init__.py +60 -0
  9. tree_engine/checks/builtin/__init__.py +5 -0
  10. tree_engine/checks/builtin/compile_check.py +53 -0
  11. tree_engine/checks/builtin/csv_syntax.py +51 -0
  12. tree_engine/checks/builtin/docstrings.py +211 -0
  13. tree_engine/checks/builtin/encoding.py +55 -0
  14. tree_engine/checks/builtin/fleet_rules.py +227 -0
  15. tree_engine/checks/builtin/format_syntax.py +82 -0
  16. tree_engine/checks/builtin/jsonl_syntax.py +49 -0
  17. tree_engine/checks/builtin/shipped.py +52 -0
  18. tree_engine/checks/builtin/syntax.py +118 -0
  19. tree_engine/checks/builtin/xml_wellformed.py +51 -0
  20. tree_engine/checks/chain.py +332 -0
  21. tree_engine/checks/external/__init__.py +5 -0
  22. tree_engine/checks/external/_base.py +61 -0
  23. tree_engine/checks/external/bandit.py +53 -0
  24. tree_engine/checks/external/black.py +48 -0
  25. tree_engine/checks/external/flake8.py +38 -0
  26. tree_engine/checks/external/isort.py +38 -0
  27. tree_engine/checks/external/mypy.py +45 -0
  28. tree_engine/checks/external/ruff.py +45 -0
  29. tree_engine/checks/external/runner.py +197 -0
  30. tree_engine/checks/model.py +110 -0
  31. tree_engine/checks/options.py +73 -0
  32. tree_engine/checks/plugin.py +171 -0
  33. tree_engine/checks/registry.py +349 -0
  34. tree_engine/core/address.py +376 -0
  35. tree_engine/core/identifier_map.py +266 -0
  36. tree_engine/core/identity.py +226 -0
  37. tree_engine/core/instrumentation.py +399 -0
  38. tree_engine/core/integrity.py +341 -0
  39. tree_engine/core/integrity_full.py +382 -0
  40. tree_engine/core/journal.py +260 -0
  41. tree_engine/core/journal_compose.py +571 -0
  42. tree_engine/core/live_tree.py +785 -0
  43. tree_engine/core/locking.py +188 -0
  44. tree_engine/core/move.py +585 -0
  45. tree_engine/core/move_references.py +323 -0
  46. tree_engine/core/node_types.py +408 -0
  47. tree_engine/core/nodes.py +348 -0
  48. tree_engine/core/offsets.py +24 -0
  49. tree_engine/core/operations.py +825 -0
  50. tree_engine/core/plugin_boundary.py +160 -0
  51. tree_engine/core/position_map.py +263 -0
  52. tree_engine/core/position_transfer.py +512 -0
  53. tree_engine/core/range_refresh.py +366 -0
  54. tree_engine/core/reference_cache.py +360 -0
  55. tree_engine/core/references.py +223 -0
  56. tree_engine/core/reparse.py +378 -0
  57. tree_engine/core/short_id.py +296 -0
  58. tree_engine/core/subtree_apply.py +397 -0
  59. tree_engine/core/subtree_copy.py +399 -0
  60. tree_engine/core/transactions.py +397 -0
  61. tree_engine/core/trivia.py +396 -0
  62. tree_engine/core/updates.py +398 -0
  63. tree_engine/core/validation.py +377 -0
  64. tree_engine/errors.py +104 -0
  65. tree_engine/exceptions.py +376 -0
  66. tree_engine/facade.py +4524 -0
  67. tree_engine/plugins/_statements.py +369 -0
  68. tree_engine/plugins/bsl/block_edit.py +449 -0
  69. tree_engine/plugins/bsl/blocks.py +127 -0
  70. tree_engine/plugins/bsl/checker.py +297 -0
  71. tree_engine/plugins/bsl/dialects.py +303 -0
  72. tree_engine/plugins/bsl/generator.py +481 -0
  73. tree_engine/plugins/bsl/import_map.py +995 -0
  74. tree_engine/plugins/bsl/plugin.py +452 -0
  75. tree_engine/plugins/contract.py +355 -0
  76. tree_engine/plugins/cpp/import_map.py +505 -0
  77. tree_engine/plugins/cpp/languages.py +99 -0
  78. tree_engine/plugins/cpp/plugin.py +501 -0
  79. tree_engine/plugins/csv_format.py +676 -0
  80. tree_engine/plugins/detachable.py +156 -0
  81. tree_engine/plugins/fallback.py +421 -0
  82. tree_engine/plugins/ini_format.py +330 -0
  83. tree_engine/plugins/json_format.py +813 -0
  84. tree_engine/plugins/json_pointer.py +203 -0
  85. tree_engine/plugins/jsonl_format.py +392 -0
  86. tree_engine/plugins/markdown_format.py +748 -0
  87. tree_engine/plugins/onec_query_format.py +61 -0
  88. tree_engine/plugins/parse_position.py +54 -0
  89. tree_engine/plugins/plain_text.py +1543 -0
  90. tree_engine/plugins/python/export_map.py +306 -0
  91. tree_engine/plugins/python/import_map.py +429 -0
  92. tree_engine/plugins/python/plugin.py +1710 -0
  93. tree_engine/plugins/registry.py +497 -0
  94. tree_engine/plugins/scan.py +87 -0
  95. tree_engine/plugins/selection.py +228 -0
  96. tree_engine/plugins/sql_format.py +61 -0
  97. tree_engine/plugins/toml_format.py +1072 -0
  98. tree_engine/plugins/xml_format.py +911 -0
  99. tree_engine/plugins/yaml/builder.py +49 -0
  100. tree_engine/plugins/yaml/emitter.py +225 -0
  101. tree_engine/plugins/yaml/flow.py +227 -0
  102. tree_engine/plugins/yaml/plugin.py +458 -0
  103. tree_engine/plugins/yaml/ranges.py +52 -0
  104. tree_engine/plugins/yaml/reader.py +359 -0
  105. tree_engine/plugins/yaml/scanner.py +298 -0
  106. tree_engine/query/adapter.py +283 -0
  107. tree_engine/query/engine.py +853 -0
  108. tree_engine/query/inspection.py +498 -0
  109. tree_engine/query/outline.py +288 -0
  110. tree_engine/query/predicates.py +263 -0
  111. tree_engine/query/rendered_lines.py +46 -0
  112. tree_engine/query/results.py +206 -0
  113. tree_engine/query/selector.py +400 -0
  114. tree_engine/query/xml_query.py +747 -0
  115. tree_engine/storage/codec.py +400 -0
  116. tree_engine/storage/document_bridge.py +579 -0
  117. tree_engine/storage/file_txn.py +459 -0
  118. tree_engine/storage/history.py +106 -0
  119. tree_engine/storage/lifecycle.py +622 -0
  120. tree_engine/storage/schema.py +403 -0
  121. tree_engine/storage/session_guard.py +398 -0
@@ -0,0 +1,203 @@
1
+ """RFC 6901 JSON Pointer: the notation itself, and the walker plugins drive.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Scope: the *syntax* of JSON Pointer -- token escaping, joining and splitting --
7
+ plus one generic tree walk that turns a plugin's own structural knowledge into
8
+ the two directions of a pointer index. Nothing here knows what a JSON object,
9
+ a YAML mapping or a TOML table looks like: every structural decision is taken
10
+ by the ``step`` callable the plugin supplies to :class:`JsonPointerNotation`.
11
+ That is the whole point of this file living beside the plugins rather than in
12
+ the core: the core must never contain a branch testing ``if format == "json"``,
13
+ and three plugins must not each re-implement ``~0``/``~1`` escaping.
14
+
15
+ The contract a plugin's ``step`` implements, for one ``child`` of one
16
+ ``parent``:
17
+
18
+ * ``None`` -- ``child`` and its whole subtree carry no pointer. A YAML comment,
19
+ a TOML blank line and a JSON member key are not addressable by RFC 6901, and
20
+ saying so is the honest answer; a synthesized pointer would be a lie.
21
+ * ``(tokens, addressable)`` -- ``tokens`` are the pointer tokens ``child``
22
+ contributes below its parent's pointer (already unescaped: this module
23
+ escapes them), and ``addressable`` says whether ``child`` ITSELF is the node
24
+ that pointer names. A structural wrapper that routes but is not named --
25
+ ``json:Member``, ``yaml:Pair`` -- returns tokens with ``addressable=False``,
26
+ and its value child then returns ``((), True)`` to claim the pointer the
27
+ wrapper built.
28
+
29
+ ``ordinal`` is the number of preceding siblings that contributed at least one
30
+ token, which is exactly the array/sequence index a plugin needs and which no
31
+ plugin can compute on its own without re-walking its parent.
32
+
33
+ A pointer claimed by more than one node is not an identifier: it is dropped
34
+ from BOTH directions of the index and reported through
35
+ :attr:`PointerIndex.ambiguous`, so a duplicate mapping key can never make the
36
+ engine resolve a pointer to an arbitrary one of two nodes.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ from dataclasses import dataclass
42
+ from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Set, Tuple
43
+ from uuid import UUID
44
+
45
+ __all__ = [
46
+ "NOTATION",
47
+ "escape_token",
48
+ "unescape_token",
49
+ "build_pointer",
50
+ "parse_pointer",
51
+ "PointerStep",
52
+ "PointerIndex",
53
+ "JsonPointerNotation",
54
+ ]
55
+
56
+ #: The name a plugin publishes for this notation, carried alongside every
57
+ #: computed reference so a caller never has to guess how to parse one.
58
+ NOTATION = "json_pointer"
59
+
60
+ #: What one ``step`` call may answer. See the module docstring.
61
+ PointerStep = Callable[[Any, Any, int], Optional[Tuple[Sequence[str], bool]]]
62
+
63
+
64
+ def escape_token(token: str) -> str:
65
+ """Escape one reference token per RFC 6901 section 3 (``~`` then ``/``).
66
+
67
+ The order is not interchangeable: escaping ``/`` first would turn the
68
+ ``~1`` it produces into ``~01``.
69
+ """
70
+
71
+ return str(token).replace("~", "~0").replace("/", "~1")
72
+
73
+
74
+ def unescape_token(token: str) -> str:
75
+ """Reverse :func:`escape_token`, decoding ``~1`` before ``~0``."""
76
+
77
+ return str(token).replace("~1", "/").replace("~0", "~")
78
+
79
+
80
+ def build_pointer(tokens: Sequence[str]) -> str:
81
+ """Join already-escaped ``tokens`` into a pointer; ``()`` is the root ``""``."""
82
+
83
+ return "".join(f"/{token}" for token in tokens)
84
+
85
+
86
+ def parse_pointer(text: str) -> Tuple[str, ...]:
87
+ """Split a pointer into its unescaped tokens; ``""`` yields ``()``.
88
+
89
+ Raises ``ValueError`` for anything that is not a pointer -- a non-string,
90
+ or a non-empty value that does not start with ``"/"`` -- rather than
91
+ guessing at a caller's intent.
92
+ """
93
+
94
+ if not isinstance(text, str):
95
+ raise ValueError(f"a JSON Pointer must be a str, got {type(text).__name__}")
96
+ if text == "":
97
+ return ()
98
+ if not text.startswith("/"):
99
+ raise ValueError(f"a non-empty JSON Pointer must start with '/': {text!r}")
100
+ return tuple(unescape_token(part) for part in text[1:].split("/"))
101
+
102
+
103
+ @dataclass(frozen=True)
104
+ class PointerIndex:
105
+ """Both directions of a document's pointer index, plus what was refused.
106
+
107
+ ``by_node`` maps a node's canonical UUID4 to its pointer and ``by_pointer``
108
+ is its exact inverse -- the two are always consistent, because an ambiguous
109
+ pointer is removed from both. ``ambiguous`` holds every pointer more than
110
+ one node claimed, so the reason a node has no reference stays inspectable
111
+ instead of silently absent.
112
+ """
113
+
114
+ by_node: Dict[UUID, str]
115
+ by_pointer: Dict[str, UUID]
116
+ ambiguous: Tuple[str, ...]
117
+
118
+ def ref_for(self, node_id: UUID) -> Optional[str]:
119
+ """The pointer naming ``node_id``, or ``None`` when it has none."""
120
+
121
+ return self.by_node.get(node_id)
122
+
123
+ def node_for(self, ref: str) -> Optional[UUID]:
124
+ """The node ``ref`` names, or ``None`` when no node claims it."""
125
+
126
+ return self.by_pointer.get(ref)
127
+
128
+
129
+ def _children(node: Any) -> Sequence[Any]:
130
+ """The child sequence of a common-model or live node, or ``()``."""
131
+
132
+ children = getattr(node, "children", None)
133
+ return children if isinstance(children, (list, tuple)) else ()
134
+
135
+
136
+ class JsonPointerNotation:
137
+ """One plugin's JSON Pointer support: a ``step`` plus a root convention.
138
+
139
+ ``root_addressable`` says whether the tree's own root node is the node the
140
+ empty pointer names. JSON's root value is (``{}`` IS the whole document),
141
+ and so is a TOML document (the document IS the root table); a YAML
142
+ ``yaml:Document`` is not -- it is a stream wrapper whose single value block
143
+ is what ``""`` names, and that block claims the pointer by returning
144
+ ``((), True)``.
145
+
146
+ Instances are stateless and immutable: one is built at plugin-module import
147
+ and published as the plugin's ``native_reference`` attribute, exactly as
148
+ ``fragment_container_kinds`` is published today.
149
+ """
150
+
151
+ __slots__ = ("_step", "_root_addressable")
152
+
153
+ #: The notation name every :class:`PointerIndex` this object builds speaks.
154
+ notation = NOTATION
155
+
156
+ def __init__(self, step: PointerStep, *, root_addressable: bool = True) -> None:
157
+ self._step = step
158
+ self._root_addressable = root_addressable
159
+
160
+ def index(self, root: Any) -> PointerIndex:
161
+ """Walk ``root`` and build both directions of its pointer index."""
162
+
163
+ by_node: Dict[UUID, str] = {}
164
+ by_pointer: Dict[str, UUID] = {}
165
+ ambiguous: List[str] = []
166
+ seen: Set[str] = set()
167
+ for node, pointer in self._walk(root, (), self._root_addressable):
168
+ node_id = getattr(node, "node_id", None)
169
+ if not isinstance(node_id, UUID):
170
+ continue
171
+ if pointer in seen:
172
+ # A second claimant makes the pointer useless as an identifier:
173
+ # withdraw it from the first claimant too rather than resolve it
174
+ # to whichever node happened to be walked first.
175
+ if pointer not in ambiguous:
176
+ ambiguous.append(pointer)
177
+ owner = by_pointer.pop(pointer, None)
178
+ if owner is not None:
179
+ by_node.pop(owner, None)
180
+ by_node.pop(node_id, None)
181
+ continue
182
+ seen.add(pointer)
183
+ by_node[node_id] = pointer
184
+ by_pointer[pointer] = node_id
185
+ return PointerIndex(by_node=by_node, by_pointer=by_pointer,
186
+ ambiguous=tuple(ambiguous))
187
+
188
+ def _walk(self, node: Any, tokens: Tuple[str, ...],
189
+ addressable: bool) -> Iterator[Tuple[Any, str]]:
190
+ """Yield ``(node, pointer)`` for every addressable node of the subtree."""
191
+
192
+ if addressable:
193
+ yield node, build_pointer(tokens)
194
+ ordinal = 0
195
+ for child in _children(node):
196
+ outcome = self._step(node, child, ordinal)
197
+ if outcome is None:
198
+ continue
199
+ child_tokens, child_addressable = outcome
200
+ escaped = tuple(escape_token(token) for token in child_tokens)
201
+ if escaped:
202
+ ordinal += 1
203
+ yield from self._walk(child, tokens + escaped, bool(child_addressable))
@@ -0,0 +1,392 @@
1
+ """Lossless JSON Lines format plugin for the tree engine (``format_id='jsonl'``).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Model: a ``jsonl:document`` root with one child per line, in file order:
7
+
8
+ * ``jsonl:record`` -- a line holding one valid JSON value. Its single child is the value subtree
9
+ built by the json plugin itself (the SAME node model and JSON-pointer addressing), so a value
10
+ inside a record is addressed by its path below the record and its pointer is relative to the
11
+ record.
12
+ * ``jsonl:blank`` -- an empty or whitespace-only line (``raw`` holds the whitespace).
13
+ * ``jsonl:invalid_record`` -- a line that is not valid JSON (``raw`` holds the text, ``line`` the
14
+ 1-based line number and ``message`` the parser diagnostic). It never fails the file and never
15
+ triggers the plain-text fallback.
16
+
17
+ Every line node keeps its own terminator in ``eol`` (``"\\n"``, ``"\\r\\n"`` or ``""`` for a last
18
+ line without one); a leading UTF-8 byte order mark is kept on the document in ``bom``. Rendering
19
+ replays exactly these bytes, so ``dumps(loads(x)) == x`` for every input. A record's JSON text is
20
+ rendered by the json plugin, which reuses its stored ``raw`` until a pointwise edit invalidates it.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from dataclasses import replace
26
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
27
+ from uuid import UUID
28
+
29
+ from tree_engine.core.identity import generate_node_id
30
+ from tree_engine.core.nodes import Document, Node, make_node
31
+ from tree_engine.core.plugin_boundary import FormatBoundary
32
+ from tree_engine.exceptions import (
33
+ FormatContentParseFailed,
34
+ FormatFragmentParseFailed,
35
+ FormatPluginContractError,
36
+ UnsupportedTranslation,
37
+ )
38
+ from tree_engine.plugins.contract import (
39
+ FormatPluginContract,
40
+ FormatPluginMetadata,
41
+ SemanticRoleMapping,
42
+ )
43
+ from tree_engine.plugins.json_format import JSON_FORMAT_PLUGIN, JSON_POINTER
44
+ from tree_engine.plugins.json_pointer import PointerIndex
45
+
46
+ __all__ = ["FORMAT_ID", "JSONL_POINTER", "jsonl_failures", "JsonlFormatPlugin", "JSONL_FORMAT_PLUGIN"]
47
+
48
+ FORMAT_ID = "jsonl"
49
+ KIND_DOCUMENT = "jsonl:document"
50
+ KIND_RECORD = "jsonl:record"
51
+ KIND_BLANK = "jsonl:blank"
52
+ KIND_INVALID = "jsonl:invalid_record"
53
+ _LINE_KINDS = (KIND_RECORD, KIND_BLANK, KIND_INVALID)
54
+ _JSON_PREFIX = "json:"
55
+ _BOM = ""
56
+
57
+ _METADATA = FormatPluginMetadata(
58
+ format_id=FORMAT_ID,
59
+ aliases=(),
60
+ file_extensions=("jsonl", "ndjson"),
61
+ plugin_version="1.0.0",
62
+ contract_version="1.0.0",
63
+ capabilities={
64
+ # Whether the Code Analysis server can save a file of this format (decision D-CB.4); the editor reads it
65
+ # instead of keeping its own list of unsupported suffixes.
66
+ "ca_save_supported": True,
67
+ "semantic_role_mapping": True,
68
+ "byte_identical_round_trip": True,
69
+ "navigable": True,
70
+ "editable": True,
71
+ },
72
+ )
73
+ _ROLE_MAP = SemanticRoleMapping({})
74
+ _Source = Union[str, bytes]
75
+
76
+
77
+ def _contract_error(message: str) -> FormatPluginContractError:
78
+ return FormatPluginContractError(message, plugin_id=FORMAT_ID)
79
+
80
+
81
+ def _node(kind: str, fields: Mapping[str, Any], children: Sequence[Node] = ()) -> Node:
82
+ return replace(
83
+ make_node(kind, fields=dict(fields), children=tuple(children)),
84
+ node_id=generate_node_id(),
85
+ short_id=None,
86
+ )
87
+
88
+
89
+ def _split_eol(line: str) -> Tuple[str, str]:
90
+ if line.endswith("\r\n"):
91
+ return line[:-2], "\r\n"
92
+ if line.endswith("\n"):
93
+ return line[:-1], "\n"
94
+ return line, ""
95
+
96
+
97
+ def _json_value(body: str) -> Node:
98
+ """The json plugin's own tree of one line's JSON text, with fresh identity and no short ids."""
99
+ root = JSON_FORMAT_PLUGIN.parse_document(body).root
100
+ return _strip_short_ids(root)
101
+
102
+
103
+ def _strip_short_ids(node: Node) -> Node:
104
+ return replace(
105
+ node,
106
+ short_id=None,
107
+ children=tuple(_strip_short_ids(child) for child in node.children),
108
+ )
109
+
110
+
111
+ def _record_or_invalid(body: str, eol: Optional[str], line_number: int) -> Node:
112
+ fields: Dict[str, Any] = {} if eol is None else {"eol": eol}
113
+ try:
114
+ value = _json_value(body)
115
+ except Exception as exc: # noqa: BLE001 - every parse failure is a per-line diagnostic
116
+ message = str(exc).strip() or type(exc).__name__
117
+ return _node(KIND_INVALID, {**fields, "raw": body, "line": line_number, "message": message[:300]})
118
+ return _node(KIND_RECORD, fields, (value,))
119
+
120
+
121
+ def _parse(text: str) -> Document:
122
+ fields: Dict[str, Any] = {}
123
+ if text.startswith(_BOM):
124
+ fields["bom"] = _BOM
125
+ text = text[1:]
126
+ children: List[Node] = []
127
+ pos, number, size = 0, 0, len(text)
128
+ while pos < size:
129
+ end = text.find("\n", pos)
130
+ end = size if end < 0 else end + 1
131
+ body, eol = _split_eol(text[pos:end])
132
+ number += 1
133
+ if not body.strip():
134
+ children.append(_node(KIND_BLANK, {"raw": body, "eol": eol}))
135
+ else:
136
+ children.append(_record_or_invalid(body, eol, number))
137
+ pos = end
138
+ root = _node(KIND_DOCUMENT, fields, children)
139
+ return Document(root=root, source_format_id=FORMAT_ID)
140
+
141
+
142
+ def jsonl_failures(source: _Source) -> List[Dict[str, Any]]:
143
+ """Every invalid line of ``source`` as ``{"line": int, "message": str}`` in file order (builds no document).
144
+
145
+ A line is reported exactly when :func:`_parse` turns it into a ``jsonl:invalid_record`` node: the same
146
+ per-line classification. Non-UTF-8 bytes give one entry at line 1 (the file cannot be split into lines).
147
+ """
148
+ if isinstance(source, (bytes, bytearray)):
149
+ try:
150
+ text = bytes(source).decode("utf-8")
151
+ except UnicodeDecodeError as exc:
152
+ return [{"line": 1, "message": f"content is not valid UTF-8: {exc}"[:300]}]
153
+ else:
154
+ text = source
155
+ if text.startswith(_BOM):
156
+ text = text[1:]
157
+ out: List[Dict[str, Any]] = []
158
+ pos, number, size = 0, 0, len(text)
159
+ while pos < size:
160
+ end = text.find("\n", pos)
161
+ end = size if end < 0 else end + 1
162
+ body, eol = _split_eol(text[pos:end])
163
+ number += 1
164
+ if body.strip():
165
+ node = _record_or_invalid(body, eol, number)
166
+ if node.kind == KIND_INVALID:
167
+ out.append({"line": number, "message": str(node.fields.get("message", ""))})
168
+ pos = end
169
+ return out
170
+
171
+
172
+ def _render_json(node: Node) -> str:
173
+ out = JSON_FORMAT_PLUGIN.generate_output(node)
174
+ return out if isinstance(out, str) else bytes(out).decode("utf-8")
175
+
176
+
177
+ def _render_line(node: Node) -> str:
178
+ eol = node.fields.get("eol")
179
+ eol = "\n" if not isinstance(eol, str) else eol
180
+ if node.kind == KIND_RECORD:
181
+ return "".join(_render_json(child) for child in node.children) + eol
182
+ raw = node.fields.get("raw")
183
+ return (raw if isinstance(raw, str) else "") + eol
184
+
185
+
186
+ def _render(node: Node) -> str:
187
+ kind = str(node.kind)
188
+ if kind.startswith(_JSON_PREFIX):
189
+ return _render_json(node)
190
+ if kind == KIND_DOCUMENT:
191
+ bom = node.fields.get("bom")
192
+ parts = [_render_line(child) for child in node.children]
193
+ last = len(parts) - 1
194
+ for index, part in enumerate(parts[:last]):
195
+ if not part.endswith("\n"):
196
+ # A line that lost its terminator (it was the last line, or an insert followed it)
197
+ # still has to end before the next line starts.
198
+ parts[index] = part + "\n"
199
+ return (bom if isinstance(bom, str) else "") + "".join(parts)
200
+ if kind in _LINE_KINDS:
201
+ return _render_line(node)
202
+ raise UnsupportedTranslation(
203
+ f"node kind {kind!r} has no JSON Lines form", node_type=kind, format_id=FORMAT_ID
204
+ )
205
+
206
+
207
+ class _JsonlNotation:
208
+ """JSON Pointer notation of a JSON Lines document: each record's value is addressed by the
209
+ json plugin's own pointer, relative to the record. A pointer that more than one record
210
+ claims names no single node, so it is reported as ambiguous and resolves to nothing; the
211
+ forward direction (node -> pointer) is always available."""
212
+
213
+ notation = JSON_POINTER.notation
214
+
215
+ def index(self, root: Any) -> PointerIndex:
216
+ by_node: Dict[UUID, str] = {}
217
+ owners: Dict[str, Optional[UUID]] = {}
218
+ ambiguous: List[str] = []
219
+ for line in getattr(root, "children", ()) or ():
220
+ if line.kind != KIND_RECORD:
221
+ continue
222
+ for value in line.children:
223
+ inner = JSON_POINTER.index(value)
224
+ by_node.update(inner.by_node)
225
+ for node_id, pointer in inner.by_node.items():
226
+ if pointer in owners:
227
+ owners[pointer] = None
228
+ if pointer not in ambiguous:
229
+ ambiguous.append(pointer)
230
+ else:
231
+ owners[pointer] = node_id
232
+ by_pointer = {p: n for p, n in owners.items() if n is not None}
233
+ return PointerIndex(by_node=by_node, by_pointer=by_pointer, ambiguous=tuple(ambiguous))
234
+
235
+
236
+ JSONL_POINTER = _JsonlNotation()
237
+
238
+
239
+ class JsonlFormatPlugin(FormatPluginContract, FormatBoundary):
240
+ """Registered lossless ``format_id='jsonl'`` plugin."""
241
+
242
+ native_reference = JSONL_POINTER
243
+ #: Every node of a JSON Lines document gets a compact id under ``semantic_compact_ids``
244
+ #: (duck-typed; read by ``facade._semantic_short_id_order``): the record/blank/invalid line
245
+ #: nodes are not pointer-addressable but are the nodes a caller edits.
246
+ all_nodes_compact_ids = True
247
+
248
+ @staticmethod
249
+ def checker_plugin() -> Any:
250
+ """The builtin ``jsonl_syntax`` checker (loaded on first use)."""
251
+ from tree_engine.checks.builtin.jsonl_syntax import JsonlSyntaxChecker
252
+
253
+ return JsonlSyntaxChecker()
254
+
255
+ @property
256
+ def metadata(self) -> FormatPluginMetadata:
257
+ return _METADATA
258
+
259
+ @staticmethod
260
+ def _decode(source: _Source, label: str, error: type) -> str:
261
+ if isinstance(source, str):
262
+ return source
263
+ if isinstance(source, (bytes, bytearray)):
264
+ try:
265
+ return bytes(source).decode("utf-8")
266
+ except UnicodeDecodeError as exc:
267
+ raise error(f"cannot decode JSON Lines: {exc}", format_id=FORMAT_ID) from exc
268
+ raise _contract_error(f"{label} must be str or bytes, got {type(source).__name__}")
269
+
270
+ def parse_document(
271
+ self,
272
+ source: _Source,
273
+ options: Optional[Mapping[str, Any]] = None,
274
+ *,
275
+ source_format_id: Optional[str] = None,
276
+ ) -> Document:
277
+ del options, source_format_id
278
+ return _parse(self._decode(source, "source", FormatContentParseFailed))
279
+
280
+ def parse_fragment(
281
+ self,
282
+ source: _Source,
283
+ options: Optional[Mapping[str, Any]] = None,
284
+ *,
285
+ source_format_id: Optional[str] = None,
286
+ ) -> Node:
287
+ """A fragment inside a record (``context_kind`` of a ``json:`` node) is the json
288
+ plugin's; anywhere else it must be exactly one line of valid JSON, which becomes a
289
+ record. The terminator is not set here: ``adjust_replace_fragment`` and
290
+ ``adjust_after_insert`` give it the replaced line's, or the preceding line's."""
291
+ del source_format_id
292
+ context = str((options or {}).get("context_kind") or "")
293
+ if context.startswith(_JSON_PREFIX):
294
+ return JSON_FORMAT_PLUGIN.parse_fragment(source, options)
295
+ text = self._decode(source, "fragment", FormatFragmentParseFailed)
296
+ body, _eol = _split_eol(text)
297
+ if "\n" in body or not body.strip():
298
+ raise FormatFragmentParseFailed(
299
+ "a JSON Lines fragment must be exactly one line of JSON", format_id=FORMAT_ID
300
+ )
301
+ try:
302
+ value = _json_value(body)
303
+ except Exception as exc: # noqa: BLE001
304
+ raise FormatFragmentParseFailed(
305
+ f"fragment is not valid JSON: {exc}", format_id=FORMAT_ID
306
+ ) from exc
307
+ return _node(KIND_RECORD, {}, (value,))
308
+
309
+ # -- layout hooks (duck-typed, called by the facade) ---------------------
310
+
311
+ @staticmethod
312
+ def adjust_replace_fragment(deleted: Sequence[Any], incoming: Sequence[Any]) -> None:
313
+ """A replacement line takes the terminator of the line it replaces."""
314
+ if not deleted:
315
+ return
316
+ eol = deleted[-1].fields.get("eol")
317
+ for node in incoming:
318
+ if node.kind in _LINE_KINDS and "eol" not in node.fields:
319
+ node.fields = {**node.fields, "eol": eol if isinstance(eol, str) else "\n"}
320
+
321
+ @staticmethod
322
+ def adjust_after_insert(parent: Any, inserted: Sequence[Any]) -> None:
323
+ """An inserted line takes the terminator of the line before it, ``"\\n"`` when none."""
324
+ if parent is None or not inserted:
325
+ return
326
+ siblings = list(parent.children)
327
+ for node in inserted:
328
+ if node.kind not in _LINE_KINDS or "eol" in node.fields:
329
+ continue
330
+ index = next((i for i, s in enumerate(siblings) if s is node), 0)
331
+ previous = siblings[index - 1] if index > 0 else None
332
+ eol = previous.fields.get("eol") if previous is not None else "\n"
333
+ node.fields = {**node.fields, "eol": eol if isinstance(eol, str) else "\n"}
334
+
335
+ # -- contract surface -----------------------------------------------------
336
+
337
+ def import_external_tree(
338
+ self, external_tree: Any, options: Optional[Mapping[str, Any]] = None
339
+ ) -> Union[Node, Document]:
340
+ return self.import_to_common(external_tree, options)
341
+
342
+ def import_to_common(
343
+ self, external_representation: Any, options: Optional[Mapping[str, Any]] = None
344
+ ) -> Union[Node, Document]:
345
+ del options
346
+ if isinstance(external_representation, (str, bytes, bytearray)):
347
+ return self.parse_document(external_representation)
348
+ raise UnsupportedTranslation(
349
+ "expected JSON Lines source text",
350
+ node_type=type(external_representation).__name__,
351
+ format_id=FORMAT_ID,
352
+ )
353
+
354
+ def export_from_common(
355
+ self, nodes: Union[Node, Document], options: Optional[Mapping[str, Any]] = None
356
+ ) -> Any:
357
+ del options
358
+ if not isinstance(nodes, (Node, Document)):
359
+ raise _contract_error(f"expected Node or Document, got {type(nodes).__name__}")
360
+ return _render(nodes.root if isinstance(nodes, Document) else nodes)
361
+
362
+ def generate_output(
363
+ self, target: Union[Node, Document, Any], options: Optional[Mapping[str, Any]] = None
364
+ ) -> Union[str, bytes]:
365
+ options = options or {}
366
+ if isinstance(target, (Node, Document)):
367
+ text = _render(target.root if isinstance(target, Document) else target)
368
+ elif isinstance(target, str):
369
+ text = target
370
+ else:
371
+ raise _contract_error(
372
+ f"cannot render {type(target).__name__}; expected Node/Document/str"
373
+ )
374
+ return text.encode("utf-8") if options.get("as_bytes") else text
375
+
376
+ def semantic_role_mapping(self) -> SemanticRoleMapping:
377
+ return _ROLE_MAP
378
+
379
+ def render_document(self, document: Document) -> bytes:
380
+ result = self.generate_output(document, {"as_bytes": True})
381
+ if not isinstance(result, bytes):
382
+ raise _contract_error("render_document did not return bytes")
383
+ return result
384
+
385
+ def render_fragment(self, node: Node) -> str:
386
+ result = self.generate_output(node)
387
+ if not isinstance(result, str):
388
+ raise _contract_error("render_fragment did not return str")
389
+ return result
390
+
391
+
392
+ JSONL_FORMAT_PLUGIN = JsonlFormatPlugin()