lexapi-client 0.1.0__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.
lexapi/models.py ADDED
@@ -0,0 +1,1253 @@
1
+ """Typed models over LexAPI response payloads.
2
+
3
+ Design rules (PLAN.md §3):
4
+
5
+ - plain dataclasses, no runtime dependencies beyond httpx;
6
+ - every model keeps the raw payload on ``.raw`` — the typed layer never
7
+ loses information;
8
+ - parsers are tolerant: missing/extra/mis-typed fields degrade to ``None``
9
+ (or empty lists) instead of raising, for forward compatibility.
10
+
11
+ Typed *response* wrappers subclass :class:`~lexapi._response.APIResponse`,
12
+ so the raw body stays accessible as a mapping and the credit-visibility
13
+ helpers (``units_charged`` / ``credits_remaining`` / ``resets_at``) are
14
+ available on every response. Partial/truncation signals from the API
15
+ (``truncated``, ``partial``, ``trimmed``, the ``X-Warning`` header, ...)
16
+ are surfaced as attributes — never silently dropped.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass, field
22
+ from typing import Any
23
+
24
+ from lexapi._response import APIResponse
25
+
26
+
27
+ def _s(data: dict, key: str) -> str | None:
28
+ value = data.get(key)
29
+ return value if isinstance(value, str) else None
30
+
31
+
32
+ def _i(data: dict, key: str) -> int | None:
33
+ value = data.get(key)
34
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
35
+ return None
36
+ return int(value)
37
+
38
+
39
+ def _b(data: dict, key: str) -> bool | None:
40
+ value = data.get(key)
41
+ return value if isinstance(value, bool) else None
42
+
43
+
44
+ def _dict(data: dict, key: str) -> dict:
45
+ value = data.get(key)
46
+ return value if isinstance(value, dict) else {}
47
+
48
+
49
+ def _list(data: dict, key: str) -> list:
50
+ value = data.get(key)
51
+ return value if isinstance(value, list) else []
52
+
53
+
54
+ def _str_list(data: dict, key: str) -> list[str]:
55
+ return [item for item in _list(data, key) if isinstance(item, str)]
56
+
57
+
58
+ def _parse_items(data: dict, key: str, cls: Any) -> list:
59
+ return [cls.from_dict(item) for item in _list(data, key) if isinstance(item, dict)]
60
+
61
+
62
+ def _header_int(value: str | None) -> int | None:
63
+ if value is None:
64
+ return None
65
+ try:
66
+ return int(value)
67
+ except ValueError:
68
+ return None
69
+
70
+
71
+ # ── Document building blocks ────────────────────────────────────────────
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class Article:
76
+ """A top-level article extracted from the document body."""
77
+
78
+ id: str | None
79
+ number: str | None
80
+ title: str | None
81
+ content: str | None
82
+ raw: dict = field(repr=False, default_factory=dict)
83
+
84
+ @classmethod
85
+ def from_dict(cls, data: dict) -> Article:
86
+ return cls(
87
+ id=_s(data, "id"),
88
+ number=_s(data, "number"),
89
+ title=_s(data, "title"),
90
+ content=_s(data, "content"),
91
+ raw=data,
92
+ )
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class Recital:
97
+ """A numbered prose block — preamble recital or judgment ground.
98
+
99
+ Used for both ``recitals[]`` (legislation) and ``paragraphs[]``
100
+ (case-law grounds / fullText fallback); the two arrays are mutually
101
+ exclusive on a given document.
102
+ """
103
+
104
+ number: int | None
105
+ text: str | None
106
+ raw: dict = field(repr=False, default_factory=dict)
107
+
108
+ @classmethod
109
+ def from_dict(cls, data: dict) -> Recital:
110
+ return cls(number=_i(data, "number"), text=_s(data, "text"), raw=data)
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class Section:
115
+ """Chapter/section hierarchy node."""
116
+
117
+ type: str | None
118
+ number: str | None
119
+ title: str | None
120
+ article_range: list[str] | None
121
+ raw: dict = field(repr=False, default_factory=dict)
122
+
123
+ @classmethod
124
+ def from_dict(cls, data: dict) -> Section:
125
+ rng = data.get("articleRange")
126
+ article_range = (
127
+ [item for item in rng if isinstance(item, str)] if isinstance(rng, list) else None
128
+ )
129
+ return cls(
130
+ type=_s(data, "type"),
131
+ number=_s(data, "number"),
132
+ title=_s(data, "title"),
133
+ article_range=article_range,
134
+ raw=data,
135
+ )
136
+
137
+
138
+ @dataclass(frozen=True)
139
+ class DocumentContent:
140
+ """Structured document body. Any piece may be absent under ``include``/``fields``."""
141
+
142
+ full_text: str | None
143
+ articles: list[Article]
144
+ recitals: list[Recital]
145
+ paragraphs: list[Recital]
146
+ sections: list[Section]
147
+ tables: list[dict]
148
+ annexes: list[dict]
149
+ raw: dict = field(repr=False, default_factory=dict)
150
+
151
+ @classmethod
152
+ def from_dict(cls, data: dict) -> DocumentContent:
153
+ return cls(
154
+ full_text=_s(data, "fullText"),
155
+ articles=_parse_items(data, "articles", Article),
156
+ recitals=_parse_items(data, "recitals", Recital),
157
+ paragraphs=_parse_items(data, "paragraphs", Recital),
158
+ sections=_parse_items(data, "sections", Section),
159
+ tables=[t for t in _list(data, "tables") if isinstance(t, dict)],
160
+ annexes=[a for a in _list(data, "annexes") if isinstance(a, dict)],
161
+ raw=data,
162
+ )
163
+
164
+
165
+ @dataclass(frozen=True)
166
+ class Document:
167
+ """A parsed document: normalized metadata plus (optionally) content.
168
+
169
+ Also used for metadata-only responses, where ``content`` is ``None``.
170
+ ISO date variants (``date_of_document_iso``, ...) are preferred over
171
+ the legacy DD/MM/YYYY strings.
172
+ """
173
+
174
+ celex: str | None
175
+ title: str | None
176
+ document_type: str | None
177
+ document_type_code: str | None
178
+ author: str | None
179
+ date_of_document: str | None
180
+ date_of_document_iso: str | None
181
+ date_of_effect: str | None
182
+ date_of_effect_iso: str | None
183
+ date_of_publication: str | None
184
+ date_of_publication_iso: str | None
185
+ date_type: str | None
186
+ ecli: str | None
187
+ eli: str | None
188
+ case_number: str | None
189
+ parties: str | None
190
+ keywords: list[str]
191
+ directory_codes: list[str]
192
+ subject: list[str]
193
+ language: str | None
194
+ language_requested: str | None
195
+ language_fallback: str | None
196
+ content: DocumentContent | None
197
+ urls: dict
198
+ raw: dict = field(repr=False, default_factory=dict)
199
+
200
+ @classmethod
201
+ def from_dict(cls, data: dict) -> Document:
202
+ content = data.get("content")
203
+ return cls(
204
+ celex=_s(data, "celex") or _s(data, "celexNumber"),
205
+ title=_s(data, "title"),
206
+ document_type=_s(data, "documentType"),
207
+ document_type_code=_s(data, "documentTypeCode"),
208
+ author=_s(data, "author"),
209
+ date_of_document=_s(data, "dateOfDocument"),
210
+ date_of_document_iso=_s(data, "dateOfDocumentISO"),
211
+ date_of_effect=_s(data, "dateOfEffect"),
212
+ date_of_effect_iso=_s(data, "dateOfEffectISO"),
213
+ date_of_publication=_s(data, "dateOfPublication"),
214
+ date_of_publication_iso=_s(data, "dateOfPublicationISO"),
215
+ date_type=_s(data, "dateType"),
216
+ ecli=_s(data, "ecli"),
217
+ eli=_s(data, "eli"),
218
+ case_number=_s(data, "caseNumber"),
219
+ parties=_s(data, "parties"),
220
+ keywords=_str_list(data, "keywords"),
221
+ directory_codes=_str_list(data, "directoryCodes"),
222
+ subject=_str_list(data, "subject"),
223
+ language=_s(data, "language"),
224
+ language_requested=_s(data, "languageRequested"),
225
+ language_fallback=_s(data, "languageFallback"),
226
+ content=DocumentContent.from_dict(content) if isinstance(content, dict) else None,
227
+ urls=_dict(data, "urls"),
228
+ raw=data,
229
+ )
230
+
231
+
232
+ @dataclass(frozen=True)
233
+ class SearchHit:
234
+ """A single entry in a search results page."""
235
+
236
+ title: str | None
237
+ celex: str | None
238
+ document_type: str | None
239
+ document_type_code: str | None
240
+ date: str | None
241
+ date_of_document_iso: str | None
242
+ author: str | None
243
+ available_languages: list[str]
244
+ url: str | None
245
+ raw: dict = field(repr=False, default_factory=dict)
246
+
247
+ @classmethod
248
+ def from_dict(cls, data: dict) -> SearchHit:
249
+ return cls(
250
+ title=_s(data, "title"),
251
+ celex=_s(data, "celex") or _s(data, "celexNumber"),
252
+ document_type=_s(data, "documentType") or _s(data, "form"),
253
+ document_type_code=_s(data, "documentTypeCode"),
254
+ date=_s(data, "date"),
255
+ date_of_document_iso=_s(data, "dateOfDocumentISO"),
256
+ author=_s(data, "author"),
257
+ available_languages=_str_list(data, "availableLanguages"),
258
+ url=_s(data, "url"),
259
+ raw=data,
260
+ )
261
+
262
+
263
+ @dataclass(frozen=True)
264
+ class BatchDocumentError:
265
+ """One failed CELEX from a batch fetch (does not abort the batch)."""
266
+
267
+ celex_number: str | None
268
+ error: str | None
269
+ message: str | None
270
+ raw: dict = field(repr=False, default_factory=dict)
271
+
272
+ @classmethod
273
+ def from_dict(cls, data: dict) -> BatchDocumentError:
274
+ return cls(
275
+ celex_number=_s(data, "celexNumber"),
276
+ error=_s(data, "error"),
277
+ message=_s(data, "message"),
278
+ raw=data,
279
+ )
280
+
281
+
282
+ # ── Typed responses ─────────────────────────────────────────────────────
283
+
284
+
285
+ class SearchResponse(APIResponse):
286
+ """``POST /search`` result page.
287
+
288
+ Truncation/partial signals are attributes, never hidden: ``truncated``
289
+ (tier-capped, more pages exist), ``partial`` (an upstream page fetch
290
+ timed out), ``post_filtered_by`` (controller-side post-filter dropped
291
+ rows), plus the ``X-Warning`` header via ``.warning``.
292
+ """
293
+
294
+ @property
295
+ def results(self) -> list[SearchHit]:
296
+ return _parse_items(self._map, "results", SearchHit)
297
+
298
+ @property
299
+ def total_results(self) -> int | None:
300
+ return _i(self._map, "totalResults")
301
+
302
+ @property
303
+ def total_pages(self) -> int | None:
304
+ return _i(self._map, "totalPages")
305
+
306
+ @property
307
+ def pages_fetched(self) -> int | None:
308
+ return _i(self._map, "pagesFetched")
309
+
310
+ @property
311
+ def result_count(self) -> int | None:
312
+ return _i(self._map, "resultCount")
313
+
314
+ @property
315
+ def truncated(self) -> bool:
316
+ """True when the result set was capped by the tier's maxPages."""
317
+ return _b(self._map, "truncated") or False
318
+
319
+ @property
320
+ def truncated_at(self) -> int | None:
321
+ return _i(self._map, "truncatedAt")
322
+
323
+ @property
324
+ def truncated_reason(self) -> str | None:
325
+ return _s(self._map, "truncatedReason")
326
+
327
+ @property
328
+ def partial(self) -> bool:
329
+ """True when an upstream timeout dropped one of the requested pages."""
330
+ return _b(self._map, "partial") or False
331
+
332
+ @property
333
+ def partial_reason(self) -> str | None:
334
+ return _s(self._map, "partialReason")
335
+
336
+ @property
337
+ def post_filtered_by(self) -> str | None:
338
+ """Comma-joined dimensions a controller-side post-filter fired on."""
339
+ return _s(self._map, "postFilteredBy")
340
+
341
+ @property
342
+ def hint(self) -> str | None:
343
+ """Routing hint present on empty result sets (try semantic search)."""
344
+ return _s(self._map, "hint")
345
+
346
+ @property
347
+ def ignored_document_types(self) -> list[str]:
348
+ """Requested documentType values that resolve to no EUR-Lex form code."""
349
+ return _str_list(self._map, "ignoredDocumentTypes")
350
+
351
+ @property
352
+ def document_type_fan_out(self) -> int | None:
353
+ """Size of the EUR-Lex fan-out for multi-value documentType requests."""
354
+ return _header_int(self.headers.get("x-documenttype-fanout"))
355
+
356
+ @property
357
+ def fetched_at(self) -> str | None:
358
+ return _s(self._map, "fetchedAt")
359
+
360
+
361
+ class DocumentResponse(APIResponse):
362
+ """``POST /documentContent`` — one parsed document plus read-path headers."""
363
+
364
+ @property
365
+ def document(self) -> Document:
366
+ return Document.from_dict(_dict(self._map, "document"))
367
+
368
+ @property
369
+ def source(self) -> str | None:
370
+ """``corpus`` or ``live`` (the ``X-Source`` header)."""
371
+ return self.headers.get("x-source")
372
+
373
+ @property
374
+ def corpus_version(self) -> int | None:
375
+ """Monotonic per-CELEX version (present when served from corpus)."""
376
+ return _header_int(self.headers.get("x-corpus-version"))
377
+
378
+ @property
379
+ def corpus_fetched_at(self) -> str | None:
380
+ return self.headers.get("x-corpus-fetchedat")
381
+
382
+ @property
383
+ def language_served(self) -> str | None:
384
+ """The language rendition actually served (``X-Language`` header)."""
385
+ return self.headers.get("x-language")
386
+
387
+ @property
388
+ def language_fallback(self) -> str | None:
389
+ """Set (to ``en``) when the requested language was unavailable."""
390
+ return self.headers.get("x-language-fallback")
391
+
392
+ @property
393
+ def cache(self) -> str | None:
394
+ return self.headers.get("x-cache")
395
+
396
+
397
+ class DocumentByUrlResponse(DocumentResponse):
398
+ """``POST /documents/url`` — document plus URL-extraction echo."""
399
+
400
+ @property
401
+ def source_url(self) -> str | None:
402
+ return _s(self._map, "sourceUrl")
403
+
404
+ @property
405
+ def extracted_celex(self) -> str | None:
406
+ return _s(self._map, "extractedCelex")
407
+
408
+
409
+ class DocumentMetadataResponse(APIResponse):
410
+ """``POST /documents/metadata`` — metadata only (no article content)."""
411
+
412
+ @property
413
+ def metadata(self) -> Document:
414
+ return Document.from_dict(_dict(self._map, "metadata"))
415
+
416
+ @property
417
+ def source(self) -> str | None:
418
+ return self.headers.get("x-source")
419
+
420
+ @property
421
+ def corpus_version(self) -> int | None:
422
+ return _header_int(self.headers.get("x-corpus-version"))
423
+
424
+ @property
425
+ def cache(self) -> str | None:
426
+ return self.headers.get("x-cache")
427
+
428
+
429
+ class DocumentBatchResponse(APIResponse):
430
+ """``POST /documentContent/batch`` — documents plus per-CELEX errors.
431
+
432
+ Tier clamping is surfaced, never silent: ``trimmed`` / ``trimmed_to`` /
433
+ ``trimmed_reason`` mirror the body flags and ``.warning`` carries the
434
+ ``X-Warning`` header.
435
+ """
436
+
437
+ @property
438
+ def documents(self) -> list[Document]:
439
+ return _parse_items(self._map, "documents", Document)
440
+
441
+ @property
442
+ def errors(self) -> list[BatchDocumentError]:
443
+ return _parse_items(self._map, "errors", BatchDocumentError)
444
+
445
+ @property
446
+ def requested(self) -> int | None:
447
+ return _i(self._map, "requested")
448
+
449
+ @property
450
+ def processed(self) -> int | None:
451
+ return _i(self._map, "processed")
452
+
453
+ @property
454
+ def successful(self) -> int | None:
455
+ return _i(self._map, "successful")
456
+
457
+ @property
458
+ def failed(self) -> int | None:
459
+ return _i(self._map, "failed")
460
+
461
+ @property
462
+ def trimmed(self) -> bool:
463
+ """True when the batch was clamped to the tier ceiling."""
464
+ return _b(self._map, "trimmed") or False
465
+
466
+ @property
467
+ def trimmed_to(self) -> int | None:
468
+ return _i(self._map, "trimmedTo")
469
+
470
+ @property
471
+ def trimmed_reason(self) -> str | None:
472
+ return _s(self._map, "trimmedReason")
473
+
474
+
475
+ class RecentDocumentsResponse(APIResponse):
476
+ """``GET /documents/recent`` — recently-published documents."""
477
+
478
+ @property
479
+ def results(self) -> list[SearchHit]:
480
+ return _parse_items(self._map, "results", SearchHit)
481
+
482
+ @property
483
+ def total_results(self) -> int | None:
484
+ return _i(self._map, "totalResults")
485
+
486
+ @property
487
+ def result_count(self) -> int | None:
488
+ return _i(self._map, "resultCount")
489
+
490
+ @property
491
+ def parameters(self) -> dict:
492
+ """Echo of the resolved query parameters (computed dateFrom/dateTo)."""
493
+ return _dict(self._map, "parameters")
494
+
495
+ @property
496
+ def language_filter(self) -> dict | None:
497
+ """Present only when the language post-filter dropped rows."""
498
+ value = self._map.get("languageFilter")
499
+ return value if isinstance(value, dict) else None
500
+
501
+
502
+ # ── Citations ───────────────────────────────────────────────────────────
503
+
504
+
505
+ @dataclass(frozen=True)
506
+ class CitationEdge:
507
+ """A single citation edge with classification and context."""
508
+
509
+ citation_type: str | None
510
+ context_snippet: str | None
511
+ target_celex: str | None
512
+ extracted_at: str | None
513
+ raw: dict = field(repr=False, default_factory=dict)
514
+
515
+ @classmethod
516
+ def from_dict(cls, data: dict) -> CitationEdge:
517
+ return cls(
518
+ citation_type=_s(data, "citationType"),
519
+ context_snippet=_s(data, "contextSnippet"),
520
+ target_celex=_s(data, "targetCelex"),
521
+ extracted_at=_s(data, "extractedAt"),
522
+ raw=data,
523
+ )
524
+
525
+
526
+ @dataclass(frozen=True)
527
+ class CitationDocumentGroup:
528
+ """All edges between one document and the queried document."""
529
+
530
+ celex_number: str | None
531
+ title: str | None
532
+ citation_count: int | None
533
+ citations: list[CitationEdge]
534
+ raw: dict = field(repr=False, default_factory=dict)
535
+
536
+ @classmethod
537
+ def from_dict(cls, data: dict) -> CitationDocumentGroup:
538
+ return cls(
539
+ celex_number=_s(data, "celexNumber"),
540
+ title=_s(data, "title"),
541
+ citation_count=_i(data, "citationCount"),
542
+ citations=_parse_items(data, "citations", CitationEdge),
543
+ raw=data,
544
+ )
545
+
546
+
547
+ @dataclass(frozen=True)
548
+ class CitationNeighbour:
549
+ """A neighbour in the citation graph, deduplicated across edge types."""
550
+
551
+ celex_number: str | None
552
+ title: str | None
553
+ count: int | None
554
+ types: list[str]
555
+ raw: dict = field(repr=False, default_factory=dict)
556
+
557
+ @classmethod
558
+ def from_dict(cls, data: dict) -> CitationNeighbour:
559
+ return cls(
560
+ celex_number=_s(data, "celexNumber"),
561
+ title=_s(data, "title"),
562
+ count=_i(data, "count"),
563
+ types=_str_list(data, "types"),
564
+ raw=data,
565
+ )
566
+
567
+
568
+ @dataclass(frozen=True)
569
+ class CitationPathNode:
570
+ celex_number: str | None
571
+ title: str | None
572
+ raw: dict = field(repr=False, default_factory=dict)
573
+
574
+ @classmethod
575
+ def from_dict(cls, data: dict) -> CitationPathNode:
576
+ return cls(celex_number=_s(data, "celexNumber"), title=_s(data, "title"), raw=data)
577
+
578
+
579
+ @dataclass(frozen=True)
580
+ class RelatedDocument:
581
+ """Bibliographic-coupling neighbour."""
582
+
583
+ celex_number: str | None
584
+ title: str | None
585
+ shared_count: int | None
586
+ shared_targets: list[str]
587
+ raw: dict = field(repr=False, default_factory=dict)
588
+
589
+ @classmethod
590
+ def from_dict(cls, data: dict) -> RelatedDocument:
591
+ return cls(
592
+ celex_number=_s(data, "celexNumber"),
593
+ title=_s(data, "title"),
594
+ shared_count=_i(data, "sharedCount"),
595
+ shared_targets=_str_list(data, "sharedTargets"),
596
+ raw=data,
597
+ )
598
+
599
+
600
+ @dataclass(frozen=True)
601
+ class CitationStatsEntry:
602
+ """One row of the mostCited / mostCiting top-10 lists."""
603
+
604
+ celex_number: str | None
605
+ title: str | None
606
+ cited_by_count: int | None
607
+ cites_count: int | None
608
+ raw: dict = field(repr=False, default_factory=dict)
609
+
610
+ @classmethod
611
+ def from_dict(cls, data: dict) -> CitationStatsEntry:
612
+ return cls(
613
+ celex_number=_s(data, "celexNumber"),
614
+ title=_s(data, "title"),
615
+ cited_by_count=_i(data, "citedByCount"),
616
+ cites_count=_i(data, "citesCount"),
617
+ raw=data,
618
+ )
619
+
620
+
621
+ class CitationExtractResponse(APIResponse):
622
+ """``POST /citations/extract`` — crawl a document and persist its edges."""
623
+
624
+ @property
625
+ def citation_count(self) -> int | None:
626
+ return _i(self._map, "citationCount")
627
+
628
+ @property
629
+ def citations(self) -> list[CitationEdge]:
630
+ """Edges just extracted. Empty when ``already_extracted`` is True."""
631
+ return _parse_items(self._map, "citations", CitationEdge)
632
+
633
+ @property
634
+ def already_extracted(self) -> bool:
635
+ return _b(self._map, "alreadyExtracted") or False
636
+
637
+ @property
638
+ def message(self) -> str | None:
639
+ return _s(self._map, "message")
640
+
641
+
642
+ class CitedByResponse(APIResponse):
643
+ """``GET /citations/cited-by/{celex}`` — inbound edges, grouped by source."""
644
+
645
+ @property
646
+ def target_document(self) -> str | None:
647
+ return _s(self._map, "targetDocument")
648
+
649
+ @property
650
+ def cited_by(self) -> list[CitationDocumentGroup]:
651
+ return _parse_items(self._map, "citedBy", CitationDocumentGroup)
652
+
653
+ @property
654
+ def total_citations(self) -> int | None:
655
+ """Total inbound edges matching the filter (across all pages)."""
656
+ return _i(self._map, "totalCitations")
657
+
658
+ @property
659
+ def unique_documents(self) -> int | None:
660
+ return _i(self._map, "uniqueDocuments")
661
+
662
+ @property
663
+ def limit(self) -> int | None:
664
+ return _i(self._map, "limit")
665
+
666
+ @property
667
+ def offset(self) -> int | None:
668
+ return _i(self._map, "offset")
669
+
670
+
671
+ class CitesResponse(APIResponse):
672
+ """``GET /citations/cites/{celex}`` — outbound edges, grouped by target."""
673
+
674
+ @property
675
+ def source_document(self) -> str | None:
676
+ return _s(self._map, "sourceDocument")
677
+
678
+ @property
679
+ def cites(self) -> list[CitationDocumentGroup]:
680
+ return _parse_items(self._map, "cites", CitationDocumentGroup)
681
+
682
+ @property
683
+ def total_citations(self) -> int | None:
684
+ return _i(self._map, "totalCitations")
685
+
686
+ @property
687
+ def unique_documents(self) -> int | None:
688
+ return _i(self._map, "uniqueDocuments")
689
+
690
+ @property
691
+ def limit(self) -> int | None:
692
+ return _i(self._map, "limit")
693
+
694
+ @property
695
+ def offset(self) -> int | None:
696
+ return _i(self._map, "offset")
697
+
698
+
699
+ class CitationNetworkResponse(APIResponse):
700
+ """``GET /citations/network/{celex}`` — both directions in one call.
701
+
702
+ Counts are page-scoped; unbounded totals live in ``cites_total`` /
703
+ ``cited_by_total`` (``None`` on partial responses). When the server-side
704
+ wall-clock budget expires the endpoint still returns 200 with
705
+ ``partial=True`` and empty arrays — check ``.partial``.
706
+ """
707
+
708
+ @property
709
+ def document(self) -> str | None:
710
+ return _s(self._map, "document")
711
+
712
+ @property
713
+ def cites(self) -> list[CitationNeighbour]:
714
+ return _parse_items(_dict(self._map, "network"), "cites", CitationNeighbour)
715
+
716
+ @property
717
+ def cited_by(self) -> list[CitationNeighbour]:
718
+ return _parse_items(_dict(self._map, "network"), "citedBy", CitationNeighbour)
719
+
720
+ @property
721
+ def cites_count(self) -> int | None:
722
+ """Unique outbound neighbours in this page (deduplicated)."""
723
+ return _i(_dict(self._map, "network"), "citesCount")
724
+
725
+ @property
726
+ def cited_by_count(self) -> int | None:
727
+ return _i(_dict(self._map, "network"), "citedByCount")
728
+
729
+ @property
730
+ def cites_total(self) -> int | None:
731
+ """Total outbound edges (unbounded COUNT); None when partial."""
732
+ return _i(_dict(self._map, "paging"), "citesTotal")
733
+
734
+ @property
735
+ def cited_by_total(self) -> int | None:
736
+ return _i(_dict(self._map, "paging"), "citedByTotal")
737
+
738
+ @property
739
+ def limit(self) -> int | None:
740
+ return _i(_dict(self._map, "paging"), "limit")
741
+
742
+ @property
743
+ def offset(self) -> int | None:
744
+ return _i(_dict(self._map, "paging"), "offset")
745
+
746
+ @property
747
+ def partial(self) -> bool:
748
+ """True when the server-side time budget expired (arrays are empty)."""
749
+ return _b(self._map, "partial") or False
750
+
751
+ @property
752
+ def partial_reason(self) -> str | None:
753
+ return _s(self._map, "partialReason")
754
+
755
+ @property
756
+ def message(self) -> str | None:
757
+ return _s(self._map, "message")
758
+
759
+ @property
760
+ def timeout_ms(self) -> int | None:
761
+ return _i(self._map, "timeoutMs")
762
+
763
+
764
+ class CitationStatsResponse(APIResponse):
765
+ """``GET /citations/stats`` — global citation-graph counters."""
766
+
767
+ @property
768
+ def total_citations(self) -> int | None:
769
+ return _i(_dict(self._map, "stats"), "totalCitations")
770
+
771
+ @property
772
+ def unique_source_documents(self) -> int | None:
773
+ return _i(_dict(self._map, "stats"), "uniqueSourceDocuments")
774
+
775
+ @property
776
+ def unique_target_documents(self) -> int | None:
777
+ return _i(_dict(self._map, "stats"), "uniqueTargetDocuments")
778
+
779
+ @property
780
+ def most_cited(self) -> list[CitationStatsEntry]:
781
+ return _parse_items(_dict(self._map, "stats"), "mostCited", CitationStatsEntry)
782
+
783
+ @property
784
+ def most_citing(self) -> list[CitationStatsEntry]:
785
+ return _parse_items(_dict(self._map, "stats"), "mostCiting", CitationStatsEntry)
786
+
787
+
788
+ class CitationPathResponse(APIResponse):
789
+ """``GET /citations/path/{from}/{to}`` — shortest citation path (BFS).
790
+
791
+ ``found=False`` is a graceful HTTP-200 response, not an error.
792
+ """
793
+
794
+ @property
795
+ def found(self) -> bool:
796
+ return _b(self._map, "found") or False
797
+
798
+ @property
799
+ def path(self) -> list[CitationPathNode]:
800
+ return _parse_items(self._map, "path", CitationPathNode)
801
+
802
+ @property
803
+ def path_length(self) -> int | None:
804
+ """Number of edges (0 for self-loops); None when not found."""
805
+ return _i(self._map, "pathLength")
806
+
807
+ @property
808
+ def max_depth(self) -> int | None:
809
+ return _i(self._map, "maxDepth")
810
+
811
+ @property
812
+ def from_celex(self) -> str | None:
813
+ return _s(self._map, "from")
814
+
815
+ @property
816
+ def to_celex(self) -> str | None:
817
+ return _s(self._map, "to")
818
+
819
+ @property
820
+ def message(self) -> str | None:
821
+ return _s(self._map, "message")
822
+
823
+
824
+ class RelatedDocumentsResponse(APIResponse):
825
+ """``GET /citations/related/{celex}`` — bibliographic-coupling neighbours."""
826
+
827
+ @property
828
+ def related(self) -> list[RelatedDocument]:
829
+ return _parse_items(self._map, "related", RelatedDocument)
830
+
831
+ @property
832
+ def celex_number(self) -> str | None:
833
+ return _s(self._map, "celexNumber")
834
+
835
+ @property
836
+ def method(self) -> str | None:
837
+ return _s(self._map, "method")
838
+
839
+ @property
840
+ def seed_citation_count(self) -> int | None:
841
+ return _i(self._map, "seedCitationCount")
842
+
843
+ @property
844
+ def count(self) -> int | None:
845
+ return _i(self._map, "count")
846
+
847
+ @property
848
+ def message(self) -> str | None:
849
+ """Present when the seed has no outbound citations to couple on."""
850
+ return _s(self._map, "message")
851
+
852
+
853
+ # ── Webhooks ────────────────────────────────────────────────────────────
854
+
855
+
856
+ @dataclass(frozen=True)
857
+ class WebhookDelivery:
858
+ """A single webhook delivery attempt."""
859
+
860
+ id: str | None
861
+ status: str | None
862
+ payload: dict
863
+ response_status: int | None
864
+ response_body: str | None
865
+ error_message: str | None
866
+ attempt_count: int | None
867
+ next_retry_at: str | None
868
+ delivered_at: str | None
869
+ created_at: str | None
870
+ raw: dict = field(repr=False, default_factory=dict)
871
+
872
+ @classmethod
873
+ def from_dict(cls, data: dict) -> WebhookDelivery:
874
+ return cls(
875
+ id=_s(data, "id"),
876
+ status=_s(data, "status"),
877
+ payload=_dict(data, "payload"),
878
+ response_status=_i(data, "responseStatus"),
879
+ response_body=_s(data, "responseBody"),
880
+ error_message=_s(data, "errorMessage"),
881
+ attempt_count=_i(data, "attemptCount"),
882
+ next_retry_at=_s(data, "nextRetryAt"),
883
+ delivered_at=_s(data, "deliveredAt"),
884
+ created_at=_s(data, "createdAt"),
885
+ raw=data,
886
+ )
887
+
888
+
889
+ @dataclass(frozen=True)
890
+ class Webhook:
891
+ """A webhook subscription.
892
+
893
+ ``secret`` is populated **only** on the create response — the API never
894
+ returns it again; store it then. ``recent_deliveries`` is populated only
895
+ by ``GET /webhooks/{id}`` (up to 20, newest first).
896
+ """
897
+
898
+ id: str | None
899
+ name: str | None
900
+ url: str | None
901
+ status: str | None
902
+ search_criteria: dict
903
+ secret: str | None
904
+ last_checked: str | None
905
+ last_triggered: str | None
906
+ consecutive_failures: int | None
907
+ delivery_count: int | None
908
+ max_retries: int | None
909
+ created_at: str | None
910
+ updated_at: str | None
911
+ recent_deliveries: list[WebhookDelivery]
912
+ raw: dict = field(repr=False, default_factory=dict)
913
+
914
+ @classmethod
915
+ def from_dict(cls, data: dict) -> Webhook:
916
+ return cls(
917
+ id=_s(data, "id"),
918
+ name=_s(data, "name"),
919
+ url=_s(data, "url"),
920
+ status=_s(data, "status"),
921
+ search_criteria=_dict(data, "searchCriteria"),
922
+ secret=_s(data, "secret"),
923
+ last_checked=_s(data, "lastChecked"),
924
+ last_triggered=_s(data, "lastTriggered"),
925
+ consecutive_failures=_i(data, "consecutiveFailures"),
926
+ delivery_count=_i(data, "deliveryCount"),
927
+ max_retries=_i(data, "maxRetries"),
928
+ created_at=_s(data, "createdAt"),
929
+ updated_at=_s(data, "updatedAt"),
930
+ recent_deliveries=_parse_items(data, "recentDeliveries", WebhookDelivery),
931
+ raw=data,
932
+ )
933
+
934
+
935
+ class WebhookListResponse(APIResponse):
936
+ """``GET /webhooks`` — the caller's subscriptions (no secrets)."""
937
+
938
+ @property
939
+ def webhooks(self) -> list[Webhook]:
940
+ return _parse_items(self._map, "webhooks", Webhook)
941
+
942
+ @property
943
+ def count(self) -> int | None:
944
+ return _i(self._map, "count")
945
+
946
+
947
+ class WebhookResponse(APIResponse):
948
+ """``GET /webhooks/{id}`` / ``POST /webhooks`` / ``PUT /webhooks/{id}``."""
949
+
950
+ @property
951
+ def webhook(self) -> Webhook:
952
+ return Webhook.from_dict(_dict(self._map, "webhook"))
953
+
954
+ @property
955
+ def message(self) -> str | None:
956
+ return _s(self._map, "message")
957
+
958
+
959
+ class WebhookTestResponse(APIResponse):
960
+ """``POST /webhooks/{id}/test`` — synchronous test delivery result.
961
+
962
+ ``ok`` mirrors the body's ``success`` flag: ``False`` (still HTTP 200)
963
+ when the upstream returned non-2xx or the delivery failed — inspect
964
+ ``delivery.error_message``.
965
+ """
966
+
967
+ @property
968
+ def ok(self) -> bool:
969
+ return _b(self._map, "success") or False
970
+
971
+ @property
972
+ def delivery(self) -> WebhookDelivery:
973
+ return WebhookDelivery.from_dict(_dict(self._map, "delivery"))
974
+
975
+ @property
976
+ def message(self) -> str | None:
977
+ return _s(self._map, "message")
978
+
979
+
980
+ class WebhookDeliveriesResponse(APIResponse):
981
+ """``GET /webhooks/{id}/deliveries`` — delivery history, newest first."""
982
+
983
+ @property
984
+ def deliveries(self) -> list[WebhookDelivery]:
985
+ return _parse_items(self._map, "deliveries", WebhookDelivery)
986
+
987
+ @property
988
+ def total(self) -> int | None:
989
+ """Total deliveries for this webhook (across all pages)."""
990
+ return _i(self._map, "total")
991
+
992
+ @property
993
+ def limit(self) -> int | None:
994
+ return _i(self._map, "limit")
995
+
996
+ @property
997
+ def offset(self) -> int | None:
998
+ return _i(self._map, "offset")
999
+
1000
+
1001
+ # ── Semantic search ─────────────────────────────────────────────────────
1002
+
1003
+
1004
+ @dataclass(frozen=True)
1005
+ class SemanticCaseLawResult:
1006
+ """Single case-law match from ``/search/semantic``.
1007
+
1008
+ Persistent document identity is ``(celex, document_type)`` — read off
1009
+ ``metadata.celex_id`` / ``metadata.document_type``. ``case_id`` is
1010
+ snapshot-scoped and regenerated on index rebuilds; don't store it.
1011
+ """
1012
+
1013
+ score: float | None
1014
+ text: str | None
1015
+ case_id: str | None
1016
+ case_name: str | None
1017
+ case_number: str | None
1018
+ ecli: str | None
1019
+ court: str | None
1020
+ celex: str | None
1021
+ document_type: str | None
1022
+ metadata: dict
1023
+ raw: dict = field(repr=False, default_factory=dict)
1024
+
1025
+ @classmethod
1026
+ def from_dict(cls, data: dict) -> SemanticCaseLawResult:
1027
+ metadata = _dict(data, "metadata")
1028
+ score = data.get("score")
1029
+ return cls(
1030
+ score=float(score) if isinstance(score, (int, float)) else None,
1031
+ text=_s(data, "text"),
1032
+ case_id=_s(data, "case_id"),
1033
+ case_name=_s(data, "case_name"),
1034
+ case_number=_s(data, "case_number"),
1035
+ ecli=_s(data, "ecli"),
1036
+ court=_s(data, "court"),
1037
+ celex=_s(metadata, "celex_id"),
1038
+ document_type=_s(metadata, "document_type"),
1039
+ metadata=metadata,
1040
+ raw=data,
1041
+ )
1042
+
1043
+
1044
+ @dataclass(frozen=True)
1045
+ class SemanticLegislationResult:
1046
+ """Single article-level match from ``/legislation/semantic``."""
1047
+
1048
+ score: float | None
1049
+ text: str | None
1050
+ article_ref: str | None
1051
+ law_id: str | None
1052
+ law_title: str | None
1053
+ metadata: dict
1054
+ raw: dict = field(repr=False, default_factory=dict)
1055
+
1056
+ @classmethod
1057
+ def from_dict(cls, data: dict) -> SemanticLegislationResult:
1058
+ score = data.get("score")
1059
+ return cls(
1060
+ score=float(score) if isinstance(score, (int, float)) else None,
1061
+ text=_s(data, "text"),
1062
+ article_ref=_s(data, "article_ref"),
1063
+ law_id=_s(data, "law_id"),
1064
+ law_title=_s(data, "law_title"),
1065
+ metadata=_dict(data, "metadata"),
1066
+ raw=data,
1067
+ )
1068
+
1069
+
1070
+ class _SemanticResponseBase(APIResponse):
1071
+ @property
1072
+ def search_type(self) -> str | None:
1073
+ return _s(self._map, "searchType")
1074
+
1075
+ @property
1076
+ def query(self) -> str | None:
1077
+ return _s(self._map, "query")
1078
+
1079
+ @property
1080
+ def result_count(self) -> int | None:
1081
+ return _i(self._map, "resultCount")
1082
+
1083
+ @property
1084
+ def hint(self) -> str | None:
1085
+ """Low-confidence signal: present only on best-effort responses.
1086
+
1087
+ When set, the adaptive relevance floor surfaced hits below your
1088
+ ``min_score`` (or fell back to the noise floor) — the string says
1089
+ what to do (rephrase, lower ``min_score``). Absent on confident
1090
+ responses; its presence is itself the signal.
1091
+ """
1092
+ return _s(self._map, "hint")
1093
+
1094
+ @property
1095
+ def took_ms(self) -> int | None:
1096
+ return _i(self._map, "tookMs")
1097
+
1098
+ @property
1099
+ def semantic_usage(self) -> dict | None:
1100
+ """Legacy daily-call plans only; credit plans meter from the pool."""
1101
+ value = self._map.get("semanticUsage")
1102
+ return value if isinstance(value, dict) else None
1103
+
1104
+
1105
+ class SemanticSearchResponse(_SemanticResponseBase):
1106
+ """``POST /search/semantic`` — ranked case-law matches.
1107
+
1108
+ HyDE visibility: ``hyde`` reports whether HyDE rewriting actually ran
1109
+ (``False`` after a fallback — the 10-credit premium was auto-refunded
1110
+ and ``credits.operation_weight`` reflects the base rate); the key is
1111
+ absent (``None``) when the request didn't ask for HyDE.
1112
+ ``hypothetical_document`` carries the LLM-drafted passage when HyDE ran.
1113
+ """
1114
+
1115
+ @property
1116
+ def results(self) -> list[SemanticCaseLawResult]:
1117
+ return _parse_items(self._map, "results", SemanticCaseLawResult)
1118
+
1119
+ @property
1120
+ def hyde(self) -> bool | None:
1121
+ """Whether HyDE ran: True/False when requested, None when not."""
1122
+ return _b(self._map, "hyde")
1123
+
1124
+ @property
1125
+ def hypothetical_document(self) -> str | None:
1126
+ """The LLM-drafted hypothetical passage (present only when HyDE ran)."""
1127
+ return _s(self._map, "hypotheticalDocument")
1128
+
1129
+
1130
+ class SemanticLegislationResponse(_SemanticResponseBase):
1131
+ """``POST /legislation/semantic`` — ranked article-level matches."""
1132
+
1133
+ @property
1134
+ def results(self) -> list[SemanticLegislationResult]:
1135
+ return _parse_items(self._map, "results", SemanticLegislationResult)
1136
+
1137
+
1138
+ class ResolveResponse(APIResponse):
1139
+ """``POST /resolve`` — canonical CELEX for any legal identifier."""
1140
+
1141
+ @property
1142
+ def celex(self) -> str | None:
1143
+ return _s(self._map, "celex")
1144
+
1145
+ @property
1146
+ def identifier(self) -> str | None:
1147
+ return _s(self._map, "identifier")
1148
+
1149
+ @property
1150
+ def identifier_type(self) -> str | None:
1151
+ """``celex`` / ``url`` / ``eli`` / ``ecli``."""
1152
+ return _s(self._map, "identifierType")
1153
+
1154
+ @property
1155
+ def resolved_via(self) -> str | None:
1156
+ return _s(self._map, "resolvedVia")
1157
+
1158
+ @property
1159
+ def urls(self) -> dict:
1160
+ return _dict(self._map, "urls")
1161
+
1162
+
1163
+ @dataclass(frozen=True)
1164
+ class VersionEntry:
1165
+ """One entry in a document's point-in-time version history.
1166
+
1167
+ Versions are LexAPI *observation snapshots* (content-hash changes
1168
+ between fetches), not legal in-force reconstructions. ``fetched_at``
1169
+ is when THIS version was fetched — version N is "current" from there
1170
+ until version N+1's ``fetched_at``.
1171
+ """
1172
+
1173
+ version: int | None
1174
+ is_current: bool | None
1175
+ content_hash: str | None
1176
+ fetched_at: str | None
1177
+ title: str | None
1178
+ document_type: str | None
1179
+ document_type_code: str | None
1180
+ parsed_content: dict | None
1181
+
1182
+ @classmethod
1183
+ def from_dict(cls, data: dict) -> VersionEntry:
1184
+ parsed = data.get("parsedContent")
1185
+ return cls(
1186
+ version=_i(data, "version"),
1187
+ is_current=_b(data, "isCurrent"),
1188
+ content_hash=_s(data, "contentHash"),
1189
+ fetched_at=_s(data, "fetchedAt"),
1190
+ title=_s(data, "title"),
1191
+ document_type=_s(data, "documentType"),
1192
+ document_type_code=_s(data, "documentTypeCode"),
1193
+ parsed_content=parsed if isinstance(parsed, dict) else None,
1194
+ )
1195
+
1196
+
1197
+ class DocumentVersionsResponse(APIResponse):
1198
+ """``GET /documents/{celex}/versions`` — history list, newest first."""
1199
+
1200
+ @property
1201
+ def celex(self) -> str | None:
1202
+ return _s(self._map, "celex")
1203
+
1204
+ @property
1205
+ def language(self) -> str | None:
1206
+ return _s(self._map, "language")
1207
+
1208
+ @property
1209
+ def current_version(self) -> int | None:
1210
+ return _i(self._map, "currentVersion")
1211
+
1212
+ @property
1213
+ def tracked_since(self) -> str | None:
1214
+ """When the document first entered the corpus — history starts here."""
1215
+ return _s(self._map, "trackedSince")
1216
+
1217
+ @property
1218
+ def semantics(self) -> str | None:
1219
+ """The server's restatement of the observation-snapshot semantics."""
1220
+ return _s(self._map, "semantics")
1221
+
1222
+ @property
1223
+ def versions(self) -> list[VersionEntry]:
1224
+ return _parse_items(self._map, "versions", VersionEntry)
1225
+
1226
+
1227
+ class DocumentVersionResponse(APIResponse):
1228
+ """``GET /documents/{celex}/versions/{version}`` and ``/at/{date}``."""
1229
+
1230
+ @property
1231
+ def celex(self) -> str | None:
1232
+ return _s(self._map, "celex")
1233
+
1234
+ @property
1235
+ def language(self) -> str | None:
1236
+ return _s(self._map, "language")
1237
+
1238
+ @property
1239
+ def as_of(self) -> str | None:
1240
+ """Present on ``/at/{date}`` responses only — the requested date."""
1241
+ return _s(self._map, "asOf")
1242
+
1243
+ @property
1244
+ def semantics(self) -> str | None:
1245
+ return _s(self._map, "semantics")
1246
+
1247
+ @property
1248
+ def document(self) -> VersionEntry:
1249
+ return VersionEntry.from_dict(_dict(self._map, "document"))
1250
+
1251
+ @property
1252
+ def corpus_version(self) -> int | None:
1253
+ return _header_int(self.headers.get("x-corpus-version"))