tokensafe 4.12.1 → 4.12.2

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.
@@ -0,0 +1,445 @@
1
+ """
2
+ String-catalog (i18n) parser and reducer.
3
+
4
+ A localization catalog is the one file type where TokenSafe's normal edge —
5
+ AST folding — does not apply: 100% of the payload is prose. A single
6
+ ``messages/<locale>/<ns>.ts`` file holds 100-500 string leaves, and a review
7
+ pass over 12 locales means 12 x 19 files x ~1.4k keys of raw context.
8
+
9
+ This module gives the read path a real slice instead:
10
+
11
+ * ``parse()`` walks the TypeScript object literal and returns every string
12
+ leaf with its exact character span (needed for byte-preserving write-back).
13
+ * ``reduce()`` returns a digest — group prefixes with key counts and length
14
+ ranges, array shapes, and a reversible stash anchor — instead of the file.
15
+
16
+ It is deliberately a tokenizer, not a regex: Prettier wraps values onto the
17
+ next line, comments sit between keys, and values may contain the other quote
18
+ character.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import os
24
+ import re
25
+ from dataclasses import dataclass
26
+ from typing import Any, Dict, List, Optional, Tuple
27
+
28
+ from src.stash import stash_block
29
+
30
+ # Directories that conventionally hold message catalogs.
31
+ _CATALOG_DIR_RE = re.compile(
32
+ r"(?:^|[\\/])(messages|locales|locale|i18n|lang|langs|translations)(?:[\\/]|$)",
33
+ re.IGNORECASE,
34
+ )
35
+ _CATALOG_EXTS = (".ts", ".js", ".mjs", ".cjs", ".cts", ".json")
36
+
37
+ # Rich-text markers used by the site's fill() helper: they are markup, not data.
38
+ RICH_MARKERS = frozenset({"em", "/em", "b", "/b", "c", "/c"})
39
+
40
+ # A key followed by a quoted value — inline (`k: 'v'`) or after `{`/`,`.
41
+ _SNIFF_KEY_RE = re.compile(r"(?:^|[{,]\s*)[A-Za-z_$][\w$]*\s*:\s*[\"']", re.MULTILINE)
42
+ # Code constructs that mean "this is a module, not a catalog".
43
+ _SNIFF_CODE_RE = re.compile(
44
+ r"^\s*(?:import\s|export\s+(?:function|class|const\s+\w+\s*=\s*(?:\(|async))|function\s|=>)",
45
+ re.MULTILINE,
46
+ )
47
+
48
+ MAX_DIGEST_GROUPS = 40
49
+ MIN_ENTRIES = 15
50
+ MIN_LINES = 40
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class CatalogEntry:
55
+ """One string leaf of a catalog."""
56
+
57
+ path: str # "landing.hero.title1", "landing.painLedger.rows[0].body"
58
+ value: str # decoded value
59
+ value_start: int # index of the opening quote in the source text
60
+ value_end: int # index just past the closing quote
61
+ quote: str # "'" or '"'
62
+ line: int # 1-based line of the opening quote
63
+
64
+
65
+ class CatalogParseError(ValueError):
66
+ """Raised when the text is not a parsable catalog literal."""
67
+
68
+
69
+ def _line_of(text: str, index: int) -> int:
70
+ return text.count("\n", 0, index) + 1
71
+
72
+
73
+ def _decode_escapes(raw: str) -> str:
74
+ if "\\" not in raw:
75
+ return raw
76
+ out: List[str] = []
77
+ i = 0
78
+ while i < len(raw):
79
+ ch = raw[i]
80
+ if ch != "\\" or i + 1 >= len(raw):
81
+ out.append(ch)
82
+ i += 1
83
+ continue
84
+ nxt = raw[i + 1]
85
+ if nxt == "n":
86
+ out.append("\n")
87
+ i += 2
88
+ elif nxt == "t":
89
+ out.append("\t")
90
+ i += 2
91
+ elif nxt == "r":
92
+ out.append("\r")
93
+ i += 2
94
+ elif nxt in ("'", '"', "\\", "/"):
95
+ out.append(nxt)
96
+ i += 2
97
+ elif nxt == "u" and i + 5 < len(raw):
98
+ try:
99
+ out.append(chr(int(raw[i + 2:i + 6], 16)))
100
+ i += 6
101
+ except ValueError:
102
+ out.append(ch)
103
+ i += 1
104
+ else:
105
+ out.append(ch)
106
+ i += 1
107
+ return "".join(out)
108
+
109
+
110
+ class _Parser:
111
+ """Recursive-descent parser for the catalog object-literal subset."""
112
+
113
+ def __init__(self, text: str) -> None:
114
+ self.text = text
115
+ self.pos = 0
116
+ self.entries: List[CatalogEntry] = []
117
+
118
+ # -- trivia ---------------------------------------------------------
119
+ def _skip_trivia(self) -> None:
120
+ text, n = self.text, len(self.text)
121
+ while self.pos < n:
122
+ ch = text[self.pos]
123
+ if ch in " \t\r\n":
124
+ self.pos += 1
125
+ elif text.startswith("//", self.pos):
126
+ nl = text.find("\n", self.pos)
127
+ self.pos = n if nl < 0 else nl + 1
128
+ elif text.startswith("/*", self.pos):
129
+ end = text.find("*/", self.pos + 2)
130
+ self.pos = n if end < 0 else end + 2
131
+ else:
132
+ return
133
+
134
+ def _peek(self) -> str:
135
+ self._skip_trivia()
136
+ return self.text[self.pos] if self.pos < len(self.text) else ""
137
+
138
+ def _expect(self, ch: str) -> None:
139
+ if self._peek() != ch:
140
+ raise CatalogParseError(
141
+ f"expected {ch!r} at offset {self.pos} (line {_line_of(self.text, self.pos)})"
142
+ )
143
+ self.pos += 1
144
+
145
+ # -- terminals ------------------------------------------------------
146
+ def _parse_string(self) -> Tuple[str, int, int, str]:
147
+ quote = self._peek()
148
+ if quote not in ("'", '"'):
149
+ raise CatalogParseError(
150
+ f"expected string at offset {self.pos} (line {_line_of(self.text, self.pos)})"
151
+ )
152
+ start = self.pos
153
+ i = self.pos + 1
154
+ n = len(self.text)
155
+ while i < n:
156
+ ch = self.text[i]
157
+ if ch == "\\":
158
+ i += 2
159
+ continue
160
+ if ch == quote:
161
+ raw = self.text[start + 1:i]
162
+ self.pos = i + 1
163
+ return _decode_escapes(raw), start, i + 1, quote
164
+ i += 1
165
+ raise CatalogParseError(f"unterminated string at offset {start}")
166
+
167
+ def _parse_identifier(self) -> str:
168
+ self._skip_trivia()
169
+ m = re.match(r"[A-Za-z_$][\w$]*", self.text[self.pos:])
170
+ if not m:
171
+ raise CatalogParseError(
172
+ f"expected identifier at offset {self.pos} (line {_line_of(self.text, self.pos)})"
173
+ )
174
+ self.pos += m.end()
175
+ return m.group(0)
176
+
177
+ # -- grammar --------------------------------------------------------
178
+ def parse_root(self) -> List[CatalogEntry]:
179
+ prefix = self._move_to_root()
180
+ self._expect("{")
181
+ self._parse_object_body(prefix)
182
+ return self.entries
183
+
184
+ def _move_to_root(self) -> str:
185
+ """Positions the cursor on the root `{`; returns the namespace prefix.
186
+
187
+ `export const landing = { ... }` -> "landing"; `export default { ... }` -> "".
188
+ """
189
+ brace = self.text.find("{")
190
+ if brace < 0:
191
+ raise CatalogParseError("no object literal found")
192
+ head = self.text[:brace]
193
+ m = re.search(r"(?:const|let|var)\s+([A-Za-z_$][\w$]*)", head)
194
+ self.pos = brace
195
+ return m.group(1) if m else ""
196
+
197
+ def _parse_object_body(self, prefix: str) -> None:
198
+ while True:
199
+ c = self._peek()
200
+ if c == "}":
201
+ self.pos += 1
202
+ return
203
+ if c == "":
204
+ raise CatalogParseError("unterminated object literal")
205
+ key = self._parse_key()
206
+ c = self._peek()
207
+ if c != ":":
208
+ # Shorthand property (`{ common, nav }` in the index aggregator).
209
+ if c == ",":
210
+ self.pos += 1
211
+ continue
212
+ if c == "}":
213
+ self.pos += 1
214
+ return
215
+ raise CatalogParseError(
216
+ f"expected ':' after key {key!r} at offset {self.pos} "
217
+ f"(line {_line_of(self.text, self.pos)})"
218
+ )
219
+ self.pos += 1
220
+ path = f"{prefix}.{key}" if prefix else key
221
+ self._parse_value(path)
222
+ c = self._peek()
223
+ if c == ",":
224
+ self.pos += 1
225
+ continue
226
+ if c == "}":
227
+ self.pos += 1
228
+ return
229
+ raise CatalogParseError(
230
+ f"expected ',' or '}}' at offset {self.pos} (line {_line_of(self.text, self.pos)})"
231
+ )
232
+
233
+ def _parse_key(self) -> str:
234
+ c = self._peek()
235
+ if c in ("'", '"'):
236
+ value, _start, _end, _q = self._parse_string()
237
+ return value
238
+ return self._parse_identifier()
239
+
240
+ def _parse_value(self, path: str) -> None:
241
+ c = self._peek()
242
+ if c in ("'", '"'):
243
+ value, start, end, quote = self._parse_string()
244
+ self.entries.append(CatalogEntry(path, value, start, end, quote, _line_of(self.text, start)))
245
+ return
246
+ if c == "{":
247
+ self.pos += 1
248
+ self._parse_object_body(path)
249
+ return
250
+ if c == "[":
251
+ self.pos += 1
252
+ self._parse_array_body(path)
253
+ return
254
+ # Non-string scalars are not expected in a catalog; tolerate and skip.
255
+ start = self.pos
256
+ while self.pos < len(self.text) and self.text[self.pos] not in ",}]":
257
+ self.pos += 1
258
+ if self.pos == start:
259
+ raise CatalogParseError(
260
+ f"unexpected {c!r} at offset {self.pos} (line {_line_of(self.text, self.pos)})"
261
+ )
262
+
263
+ def _parse_array_body(self, prefix: str) -> None:
264
+ index = 0
265
+ while True:
266
+ c = self._peek()
267
+ if c == "]":
268
+ self.pos += 1
269
+ return
270
+ if c == "":
271
+ raise CatalogParseError("unterminated array literal")
272
+ self._parse_value(f"{prefix}[{index}]")
273
+ index += 1
274
+ c = self._peek()
275
+ if c == ",":
276
+ self.pos += 1
277
+ continue
278
+ if c == "]":
279
+ self.pos += 1
280
+ return
281
+ raise CatalogParseError(
282
+ f"expected ',' or ']' at offset {self.pos} (line {_line_of(self.text, self.pos)})"
283
+ )
284
+
285
+
286
+ def parse(text: str) -> List[CatalogEntry]:
287
+ """Parses a catalog literal into string leaves. Raises CatalogParseError."""
288
+ if not text or "{" not in text:
289
+ raise CatalogParseError("no object literal found")
290
+ return _Parser(text).parse_root()
291
+
292
+
293
+ def try_parse(text: str) -> Tuple[List[CatalogEntry], Optional[str]]:
294
+ """Returns (entries, error). Never raises."""
295
+ try:
296
+ return parse(text), None
297
+ except CatalogParseError as exc:
298
+ return [], str(exc)
299
+ except Exception as exc: # pragma: no cover - defensive
300
+ return [], f"{type(exc).__name__}: {exc}"
301
+
302
+
303
+ def placeholders(value: str) -> List[str]:
304
+ """Sorted placeholder multiset, rich-text markup stripped."""
305
+ found = [m for m in re.findall(r"\{([^}]+)\}", value) if m not in RICH_MARKERS]
306
+ return sorted(found)
307
+
308
+
309
+ def placeholder_mismatch(base: str, target: str) -> bool:
310
+ return placeholders(base) != placeholders(target)
311
+
312
+
313
+ def sniff(text: str, min_keys: int = 15) -> bool:
314
+ """Content-based catalog detection, for tool results with no path."""
315
+ if not text or len(text) < 200:
316
+ return False
317
+ keys = len(_SNIFF_KEY_RE.findall(text))
318
+ if keys < min_keys:
319
+ return False
320
+ code = len(_SNIFF_CODE_RE.findall(text))
321
+ return keys >= code * 4
322
+
323
+
324
+ def locale_namespace_from_path(path: str) -> Tuple[str, str]:
325
+ """`.../messages/ru/dashboard.ts` -> ("ru", "dashboard")."""
326
+ parts = re.split(r"[\\/]+", os.path.normpath(path))
327
+ name = parts[-1] if parts else ""
328
+ ns = os.path.splitext(name)[0]
329
+ locale = parts[-2] if len(parts) >= 2 else ""
330
+ return locale, ns
331
+
332
+
333
+ def _group_prefixes(entries: List[CatalogEntry]) -> Dict[str, List[CatalogEntry]]:
334
+ """Buckets entries by a display prefix, drilling down past dominant groups."""
335
+ def first_segment(path: str) -> str:
336
+ return re.split(r"[.\[]", path, maxsplit=1)[0]
337
+
338
+ groups: Dict[str, List[CatalogEntry]] = {}
339
+ for entry in entries:
340
+ groups.setdefault(first_segment(entry.path), []).append(entry)
341
+
342
+ total = max(1, len(entries))
343
+ refined: Dict[str, List[CatalogEntry]] = {}
344
+ for segment, bucket in groups.items():
345
+ if len(bucket) > total * 0.4 and len({e.path for e in bucket}) > 12:
346
+ for entry in bucket:
347
+ parts = re.split(r"(?=[.\[])", entry.path, maxsplit=2)
348
+ key = "".join(parts[:2])
349
+ refined.setdefault(key, []).append(entry)
350
+ else:
351
+ refined[segment] = bucket
352
+ return refined
353
+
354
+
355
+ def render_digest(
356
+ content: str,
357
+ entries: List[CatalogEntry],
358
+ filename: str = "",
359
+ ) -> str:
360
+ """Builds the digest text (without the stash marker)."""
361
+ locale, namespace = locale_namespace_from_path(filename) if filename else ("", "")
362
+ groups = _group_prefixes(entries)
363
+ ordered = sorted(groups.items(), key=lambda kv: (-len(kv[1]), kv[0]))[:MAX_DIGEST_GROUPS]
364
+
365
+ header_bits = [f"file={os.path.basename(filename) or 'catalog'}"]
366
+ if locale:
367
+ header_bits.append(f"locale={locale}")
368
+ if namespace:
369
+ header_bits.append(f"ns={namespace}")
370
+ lines = [
371
+ f"# [TokenSafe Catalog Digest: {' | '.join(header_bits)} | "
372
+ f"{len(entries)} keys, {len(content.splitlines())} lines, {len(groups)} groups]",
373
+ "# groups (prefix: key count, value length range):",
374
+ ]
375
+ for prefix, bucket in ordered:
376
+ lengths = [len(e.value) for e in bucket]
377
+ lines.append(f"{prefix}: {len(bucket)} keys ({min(lengths)}-{max(lengths)} chars)")
378
+
379
+ arrays = _array_shapes(entries)
380
+ if arrays:
381
+ lines.append("# arrays: " + "; ".join(arrays[:8]))
382
+
383
+ lines.append(
384
+ '# values: run_helper(action=\'dict\', command="show <locale> <path>") '
385
+ "or smart_read_file(start_line=..., end_line=...)"
386
+ )
387
+ return "\n".join(lines)
388
+
389
+
390
+ def _array_shapes(entries: List[CatalogEntry]) -> List[str]:
391
+ """`rows (3 items x {kicker,title,body})` for arrays of flat objects."""
392
+ shapes: Dict[str, Dict[str, Any]] = {}
393
+ for entry in entries:
394
+ m = re.match(r"^(.*)\[(\d+)\]\.(\w+)$", entry.path)
395
+ if m:
396
+ prefix, idx, key = m.group(1), int(m.group(2)), m.group(3)
397
+ shape = shapes.setdefault(prefix, {"max": -1, "keys": set()})
398
+ shape["max"] = max(shape["max"], idx)
399
+ shape["keys"].add(key)
400
+ continue
401
+ m = re.match(r"^(.*)\[(\d+)\]$", entry.path)
402
+ if m:
403
+ prefix, idx = m.group(1), int(m.group(2))
404
+ shape = shapes.setdefault(prefix, {"max": -1, "keys": set()})
405
+ shape["max"] = max(shape["max"], idx)
406
+ out = []
407
+ for prefix, shape in sorted(shapes.items()):
408
+ count = shape["max"] + 1
409
+ keys = sorted(shape["keys"])
410
+ if keys:
411
+ out.append(f"{prefix} ({count} items x {{{','.join(keys)}}})")
412
+ else:
413
+ out.append(f"{prefix} ({count} items)")
414
+ return out
415
+
416
+
417
+ class StringCatalogReducer:
418
+ """Format-parser contract: (text, was_reduced)."""
419
+
420
+ @classmethod
421
+ def is_string_catalog(cls, filename_or_path: str) -> bool:
422
+ if not filename_or_path:
423
+ return False
424
+ path = str(filename_or_path)
425
+ if not path.lower().endswith(_CATALOG_EXTS):
426
+ return False
427
+ return bool(_CATALOG_DIR_RE.search(path))
428
+
429
+ @classmethod
430
+ def parse(cls, content: str) -> List[CatalogEntry]:
431
+ return parse(content)
432
+
433
+ @classmethod
434
+ def reduce(cls, content: str, filename: str = "") -> Tuple[str, bool]:
435
+ if not content or content.count("\n") + 1 < MIN_LINES:
436
+ return content, False
437
+ entries, error = try_parse(content)
438
+ if error or len(entries) < MIN_ENTRIES:
439
+ return content, False
440
+
441
+ digest = render_digest(content, entries, filename)
442
+ if len(digest) >= len(content):
443
+ return content, False
444
+ _hash8, marker = stash_block(content, source="catalog")
445
+ return f"{digest}\n{marker}" if marker else digest, True