enigma-api-client 0.3.1__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.
- enigma_api_client/__init__.py +16 -0
- enigma_api_client/client.py +134 -0
- enigma_api_client/client_inject_id_and_typename_helper.py +248 -0
- enigma_api_client/client_inject_urls_helper.py +26 -0
- enigma_api_client/plugins/.DS_Store +0 -0
- enigma_api_client/plugins/enigma-api/.claude-plugin/plugin.json +8 -0
- enigma_api_client/plugins/enigma-api/README.md +82 -0
- enigma_api_client/plugins/enigma-api/harness/conftest.py +42 -0
- enigma_api_client/plugins/enigma-api/harness/test_linter.py +863 -0
- enigma_api_client/plugins/enigma-api/harness/test_queries.py +143 -0
- enigma_api_client/plugins/enigma-api/harness/test_skill_rules.py +351 -0
- enigma_api_client/plugins/enigma-api/pyproject.toml +9 -0
- enigma_api_client/plugins/enigma-api/scripts/__pycache__/lint_query.cpython-313.pyc +0 -0
- enigma_api_client/plugins/enigma-api/scripts/__pycache__/query_validator.cpython-313.pyc +0 -0
- enigma_api_client/plugins/enigma-api/scripts/__pycache__/query_validator.cpython-314.pyc +0 -0
- enigma_api_client/plugins/enigma-api/scripts/generate_report.py +384 -0
- enigma_api_client/plugins/enigma-api/scripts/lint_query.py +712 -0
- enigma_api_client/plugins/enigma-api/scripts/query_validator.py +352 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/SKILL.md +620 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/brand/03_brand_profile.md +163 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/brand/13_brand_dump.md +95 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/derived/07_coalesce_ein_formation.md +146 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/discovery/01_coffee_shops_zip.md +287 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/discovery/11_ol_industry_discovery.md +116 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/export/08_segment_export.md +96 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/kyb/02_officers_lookup.md +366 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/kyb/10_kyb_verify.md +176 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/legal_entity/09_legal_entity_profile.md +97 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/locations/05_brand_locations_by_state.md +120 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/person_search/04_find_person_companies.md +160 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/revenue/06_brand_revenue.md +176 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/risk/12_risk_signals.md +118 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/references/card_transactions.md +91 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/references/field_corrections.json +106 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/references/filter_syntax.md +203 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/references/naics_2022_mapping.json +184 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/references/pagination_template.py +115 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/schema.graphql +44971 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/scripts/test_examples.py +1122 -0
- enigma_api_client/plugins/enigma-api/skills/enigma-graphql/scripts/validate_query.py +177 -0
- enigma_api_client/plugins/enigma-api/test-cases/graphql-test-cases.md +196 -0
- enigma_api_client/plugins/enigma-api/tests/accuracy_cases.csv +116 -0
- enigma_api_client/plugins/enigma-api/tests/applicability_review.csv +64 -0
- enigma_api_client/plugins/enigma-api/tests/parallel-ground-truth.csv +101 -0
- enigma_api_client/plugins/enigma-api/tests/run_tests.sh +320 -0
- enigma_api_client/plugins/enigma-api/tests/test_cases.yaml +213 -0
- enigma_api_client/plugins/enigma-api/tests/validation_cases.csv +101 -0
- enigma_api_client/py.typed +0 -0
- enigma_api_client/query_router/__init__.py +3 -0
- enigma_api_client/query_router/geo.py +121 -0
- enigma_api_client/query_router/templates.py +475 -0
- enigma_api_client/strategies/__init__.py +16 -0
- enigma_api_client/strategies/agent.py +63 -0
- enigma_api_client/strategies/base.py +15 -0
- enigma_api_client/strategies/generative.py +143 -0
- enigma_api_client/strategies/llm_provider.py +137 -0
- enigma_api_client/strategies/service.py +103 -0
- enigma_api_client/strategies/template.py +189 -0
- enigma_api_client-0.3.1.dist-info/METADATA +257 -0
- enigma_api_client-0.3.1.dist-info/RECORD +63 -0
- enigma_api_client-0.3.1.dist-info/WHEEL +5 -0
- enigma_api_client-0.3.1.dist-info/licenses/LICENSE +201 -0
- enigma_api_client-0.3.1.dist-info/top_level.txt +5 -0
|
@@ -0,0 +1,712 @@
|
|
|
1
|
+
# ABOUTME: Core GraphQL query linter for the Enigma V2 API
|
|
2
|
+
# ABOUTME: 18 rules across 3 severity tiers, callable as lint_query(query_string)
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Enigma GraphQL Query Linter
|
|
6
|
+
|
|
7
|
+
Lints a raw GraphQL query string against 18 rules derived from
|
|
8
|
+
production issues, API quirks, and best practices for the Enigma V2 API.
|
|
9
|
+
|
|
10
|
+
Usage:
|
|
11
|
+
from lint_query import lint_query, LintResult, Severity
|
|
12
|
+
result = lint_query(query_string)
|
|
13
|
+
for finding in result.findings:
|
|
14
|
+
print(f"[{finding.severity.value}] {finding.rule_id}: {finding.message}")
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from enum import Enum
|
|
22
|
+
from typing import Optional
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Severity(Enum):
|
|
26
|
+
ERROR = "error"
|
|
27
|
+
WARNING = "warning"
|
|
28
|
+
INFO = "info"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Finding:
|
|
33
|
+
rule_id: str
|
|
34
|
+
severity: Severity
|
|
35
|
+
message: str
|
|
36
|
+
line: Optional[int] = None
|
|
37
|
+
|
|
38
|
+
def to_json(self) -> dict:
|
|
39
|
+
d = {"rule_id": self.rule_id, "severity": self.severity.value, "message": self.message}
|
|
40
|
+
if self.line is not None:
|
|
41
|
+
d["line"] = self.line
|
|
42
|
+
return d
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class LintResult:
|
|
47
|
+
findings: list[Finding] = field(default_factory=list)
|
|
48
|
+
query_valid: bool = True
|
|
49
|
+
|
|
50
|
+
def to_json(self) -> dict:
|
|
51
|
+
return {
|
|
52
|
+
"query_valid": self.query_valid,
|
|
53
|
+
"findings": [f.to_json() for f in self.findings],
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# ---------------------------------------------------------------------------
|
|
58
|
+
# Known connection fields on each entity type
|
|
59
|
+
# ---------------------------------------------------------------------------
|
|
60
|
+
|
|
61
|
+
CONNECTION_FIELDS = {
|
|
62
|
+
"names", "addresses", "phoneNumbers", "websites", "operatingStatuses",
|
|
63
|
+
"locationTypes", "reviewSummaries", "operatingLocations", "legalEntities",
|
|
64
|
+
"cardTransactions", "industries", "ranks", "technologiesUseds",
|
|
65
|
+
"registeredEntities", "registrations", "roles", "persons", "tins",
|
|
66
|
+
"types", "revenueQualities", "brands", "isFlaggedByWatchlistEntries",
|
|
67
|
+
"appearsOnWatchlistEntries", "bankruptcies", "cannabisLicenses",
|
|
68
|
+
"negativeNewses",
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
# Fields that are leaf-like but still use connection syntax.
|
|
72
|
+
# These return small result sets and don't need first: N pagination.
|
|
73
|
+
LEAF_CONNECTION_FIELDS = {
|
|
74
|
+
"names", "addresses", "phoneNumbers", "websites", "operatingStatuses",
|
|
75
|
+
"locationTypes", "reviewSummaries", "tins", "types", "revenueQualities",
|
|
76
|
+
"industries", "ranks", "isMarketables", "locationDescriptions",
|
|
77
|
+
"activities", "registeredEntities", "bankruptcies", "cannabisLicenses",
|
|
78
|
+
"negativeNewses", "isFlaggedByWatchlistEntries", "appearsOnWatchlistEntries",
|
|
79
|
+
"legalEntities", "registrations", "persons",
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
# Fields where conditions are NOT supported
|
|
83
|
+
NO_CONDITIONS_FIELDS = {"roles", "addresses", "phoneNumbers", "names", "websites"}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# ---------------------------------------------------------------------------
|
|
87
|
+
# Helpers
|
|
88
|
+
# ---------------------------------------------------------------------------
|
|
89
|
+
|
|
90
|
+
def _find_inline_fragments(query: str) -> list[tuple[str, int, int]]:
|
|
91
|
+
"""Return list of (type_name, start_pos, end_pos) for ... on Type { } blocks."""
|
|
92
|
+
fragments = []
|
|
93
|
+
for m in re.finditer(r'\.\.\.\s+on\s+(\w+)\s*\{', query):
|
|
94
|
+
type_name = m.group(1)
|
|
95
|
+
start = m.start()
|
|
96
|
+
# Find matching closing brace
|
|
97
|
+
depth = 0
|
|
98
|
+
end = m.end()
|
|
99
|
+
for i in range(m.end() - 1, len(query)):
|
|
100
|
+
if query[i] == '{':
|
|
101
|
+
depth += 1
|
|
102
|
+
elif query[i] == '}':
|
|
103
|
+
depth -= 1
|
|
104
|
+
if depth == 0:
|
|
105
|
+
end = i + 1
|
|
106
|
+
break
|
|
107
|
+
fragments.append((type_name, start, end))
|
|
108
|
+
return fragments
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _get_entity_context(query: str, pos: int) -> Optional[str]:
|
|
112
|
+
"""Given a position in the query, return which entity type context it's in."""
|
|
113
|
+
fragments = _find_inline_fragments(query)
|
|
114
|
+
# Find the innermost fragment containing this position
|
|
115
|
+
best = None
|
|
116
|
+
for type_name, start, end in fragments:
|
|
117
|
+
if start <= pos < end:
|
|
118
|
+
if best is None or (start > best[1]):
|
|
119
|
+
best = (type_name, start, end)
|
|
120
|
+
return best[0] if best else None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _extract_search_input_text(query: str) -> Optional[str]:
|
|
124
|
+
"""Extract the searchInput argument text from the query."""
|
|
125
|
+
m = re.search(r'search\s*\(\s*searchInput\s*:\s*', query)
|
|
126
|
+
if not m:
|
|
127
|
+
return None
|
|
128
|
+
# Check if it's a variable reference
|
|
129
|
+
rest = query[m.end():].strip()
|
|
130
|
+
if rest.startswith('$'):
|
|
131
|
+
return None # Variable — can't lint inline
|
|
132
|
+
# Find the matching brace
|
|
133
|
+
if not rest.startswith('{'):
|
|
134
|
+
return None
|
|
135
|
+
depth = 0
|
|
136
|
+
for i, ch in enumerate(rest):
|
|
137
|
+
if ch == '{':
|
|
138
|
+
depth += 1
|
|
139
|
+
elif ch == '}':
|
|
140
|
+
depth -= 1
|
|
141
|
+
if depth == 0:
|
|
142
|
+
return rest[:i + 1]
|
|
143
|
+
return None
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _count_connection_depth(query: str) -> int:
|
|
147
|
+
"""Count the maximum nesting depth of connection fields."""
|
|
148
|
+
max_depth = 0
|
|
149
|
+
lines = query.split('\n')
|
|
150
|
+
depth = 0
|
|
151
|
+
for line in lines:
|
|
152
|
+
stripped = line.strip()
|
|
153
|
+
# Count opening braces to track nesting
|
|
154
|
+
for ch in stripped:
|
|
155
|
+
if ch == '{':
|
|
156
|
+
depth += 1
|
|
157
|
+
elif ch == '}':
|
|
158
|
+
depth -= 1
|
|
159
|
+
# Check if this line has a connection field
|
|
160
|
+
for field_name in CONNECTION_FIELDS:
|
|
161
|
+
if re.search(rf'\b{field_name}\b', stripped):
|
|
162
|
+
if depth > max_depth:
|
|
163
|
+
max_depth = depth
|
|
164
|
+
# Alternative: count connection field keywords in nested braces
|
|
165
|
+
# Walk through and count connection keywords at each depth
|
|
166
|
+
conn_depth = 0
|
|
167
|
+
max_conn_depth = 0
|
|
168
|
+
brace_to_conn = {}
|
|
169
|
+
brace_depth = 0
|
|
170
|
+
for i, ch in enumerate(query):
|
|
171
|
+
if ch == '{':
|
|
172
|
+
brace_depth += 1
|
|
173
|
+
elif ch == '}':
|
|
174
|
+
if brace_depth in brace_to_conn:
|
|
175
|
+
conn_depth -= 1
|
|
176
|
+
del brace_to_conn[brace_depth]
|
|
177
|
+
brace_depth -= 1
|
|
178
|
+
# Check if we're at the start of a connection field
|
|
179
|
+
for field_name in CONNECTION_FIELDS - LEAF_CONNECTION_FIELDS:
|
|
180
|
+
pattern = rf'\b{field_name}\s*(\(|{{)'
|
|
181
|
+
# Look backward from current position for field name
|
|
182
|
+
snippet = query[max(0, i - 80):i + 1]
|
|
183
|
+
if re.search(pattern, snippet) and ch == '{':
|
|
184
|
+
conn_depth += 1
|
|
185
|
+
brace_to_conn[brace_depth] = field_name
|
|
186
|
+
if conn_depth > max_conn_depth:
|
|
187
|
+
max_conn_depth = conn_depth
|
|
188
|
+
break
|
|
189
|
+
return max_conn_depth
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _has_filter_key(text: str, key: str) -> bool:
|
|
193
|
+
"""Check if a filter condition object has a specific key like EQ, NE, HAS etc."""
|
|
194
|
+
return bool(re.search(rf'[{{,]\s*{key}\s*:', text))
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _line_of(query: str, pos: int) -> int:
|
|
198
|
+
"""Get 1-indexed line number for a position in the query."""
|
|
199
|
+
return query[:pos].count('\n') + 1
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
# ---------------------------------------------------------------------------
|
|
203
|
+
# Rule implementations
|
|
204
|
+
# ---------------------------------------------------------------------------
|
|
205
|
+
|
|
206
|
+
def _check_001_persons_on_le(query: str) -> list[Finding]:
|
|
207
|
+
"""ENIGMA-001: LegalEntity.persons is usually empty (direct child only).
|
|
208
|
+
|
|
209
|
+
persons nested inside roles (e.g. registeredEntities → registrations →
|
|
210
|
+
roles → persons) is the correct path and should NOT be flagged.
|
|
211
|
+
"""
|
|
212
|
+
findings = []
|
|
213
|
+
fragments = _find_inline_fragments(query)
|
|
214
|
+
for m in re.finditer(r'\bpersons\b', query):
|
|
215
|
+
ctx = _get_entity_context(query, m.start())
|
|
216
|
+
if ctx != "LegalEntity":
|
|
217
|
+
continue
|
|
218
|
+
# Find the LegalEntity fragment that contains this match
|
|
219
|
+
le_start = None
|
|
220
|
+
for type_name, start, end in fragments:
|
|
221
|
+
if type_name == "LegalEntity" and start <= m.start() < end:
|
|
222
|
+
le_start = start
|
|
223
|
+
break
|
|
224
|
+
if le_start is not None:
|
|
225
|
+
between = query[le_start:m.start()]
|
|
226
|
+
# If persons is nested under roles, it's the correct traversal path
|
|
227
|
+
if re.search(r'\broles\s*[\({]', between):
|
|
228
|
+
continue
|
|
229
|
+
findings.append(Finding(
|
|
230
|
+
"ENIGMA-001", Severity.ERROR,
|
|
231
|
+
"LegalEntity.persons is usually empty. Use the registeredEntities -> "
|
|
232
|
+
"registrations -> roles path to find people.",
|
|
233
|
+
_line_of(query, m.start()),
|
|
234
|
+
))
|
|
235
|
+
return findings
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _check_002_direct_roles_on_le(query: str) -> list[Finding]:
|
|
239
|
+
"""ENIGMA-002: Direct roles on LegalEntity (should be under registeredEntities)."""
|
|
240
|
+
findings = []
|
|
241
|
+
for m in re.finditer(r'\broles\s*(\(|{)', query):
|
|
242
|
+
ctx = _get_entity_context(query, m.start())
|
|
243
|
+
if ctx != "LegalEntity":
|
|
244
|
+
continue
|
|
245
|
+
# Check if there's a registeredEntities ancestor between LegalEntity and roles
|
|
246
|
+
fragments = _find_inline_fragments(query)
|
|
247
|
+
le_start = None
|
|
248
|
+
for type_name, start, end in fragments:
|
|
249
|
+
if type_name == "LegalEntity" and start <= m.start() < end:
|
|
250
|
+
le_start = start
|
|
251
|
+
break
|
|
252
|
+
if le_start is not None:
|
|
253
|
+
between = query[le_start:m.start()]
|
|
254
|
+
if "registeredEntities" not in between:
|
|
255
|
+
findings.append(Finding(
|
|
256
|
+
"ENIGMA-002", Severity.ERROR,
|
|
257
|
+
"Direct roles on LegalEntity. Use registeredEntities -> "
|
|
258
|
+
"registrations -> roles path instead.",
|
|
259
|
+
_line_of(query, m.start()),
|
|
260
|
+
))
|
|
261
|
+
return findings
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _is_inside_skip_block(query: str, pos: int) -> bool:
|
|
265
|
+
"""Check if a position in the query is inside a @skip(if: true) annotated block."""
|
|
266
|
+
# Look for any field with @skip(if: true) whose brace scope contains pos
|
|
267
|
+
for m in re.finditer(r'@skip\s*\(\s*if\s*:\s*true\s*\)\s*\{', query):
|
|
268
|
+
skip_brace_start = m.end() - 1 # Position of the {
|
|
269
|
+
# Find matching closing brace
|
|
270
|
+
depth = 0
|
|
271
|
+
for i in range(skip_brace_start, len(query)):
|
|
272
|
+
if query[i] == '{':
|
|
273
|
+
depth += 1
|
|
274
|
+
elif query[i] == '}':
|
|
275
|
+
depth -= 1
|
|
276
|
+
if depth == 0:
|
|
277
|
+
if skip_brace_start <= pos <= i:
|
|
278
|
+
return True
|
|
279
|
+
break
|
|
280
|
+
return False
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _check_003_missing_pagination(query: str) -> list[Finding]:
|
|
284
|
+
"""ENIGMA-003: Connection fields without first: N."""
|
|
285
|
+
findings = []
|
|
286
|
+
# Only check non-leaf connection fields — leaf fields return small result sets
|
|
287
|
+
check_fields = CONNECTION_FIELDS - LEAF_CONNECTION_FIELDS
|
|
288
|
+
for field_name in check_fields:
|
|
289
|
+
for m in re.finditer(rf'\b{field_name}\s*(?:\(([^)]*)\))?\s*\{{', query):
|
|
290
|
+
args = m.group(1) or ""
|
|
291
|
+
if "first" not in args:
|
|
292
|
+
# Check if it's inside @skip(if: true) — those are declaration-only
|
|
293
|
+
line_start = query.rfind('\n', 0, m.start()) + 1
|
|
294
|
+
line_end = query.find('\n', m.start())
|
|
295
|
+
line_text = query[line_start:line_end if line_end > 0 else len(query)]
|
|
296
|
+
if "@skip" in line_text:
|
|
297
|
+
continue
|
|
298
|
+
# Check if nested inside a @skip block ancestor
|
|
299
|
+
if _is_inside_skip_block(query, m.start()):
|
|
300
|
+
continue
|
|
301
|
+
# _fn fields are virtual — skip
|
|
302
|
+
if field_name == "_fn":
|
|
303
|
+
continue
|
|
304
|
+
findings.append(Finding(
|
|
305
|
+
"ENIGMA-003", Severity.ERROR,
|
|
306
|
+
f"Connection field '{field_name}' missing pagination (first: N).",
|
|
307
|
+
_line_of(query, m.start()),
|
|
308
|
+
))
|
|
309
|
+
return findings
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _check_004_missing_entity_type(query: str) -> list[Finding]:
|
|
313
|
+
"""ENIGMA-004: searchInput without entityType."""
|
|
314
|
+
findings = []
|
|
315
|
+
si_text = _extract_search_input_text(query)
|
|
316
|
+
if si_text is None:
|
|
317
|
+
return findings # Variable-based or no search — can't check
|
|
318
|
+
if "entityType" not in si_text:
|
|
319
|
+
findings.append(Finding(
|
|
320
|
+
"ENIGMA-004", Severity.ERROR,
|
|
321
|
+
"searchInput is missing entityType.",
|
|
322
|
+
))
|
|
323
|
+
return findings
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _check_005_prompt_non_brand(query: str) -> list[Finding]:
|
|
327
|
+
"""ENIGMA-005: prompt only works with BRAND."""
|
|
328
|
+
findings = []
|
|
329
|
+
si_text = _extract_search_input_text(query)
|
|
330
|
+
if si_text is None:
|
|
331
|
+
return findings
|
|
332
|
+
if "prompt" in si_text:
|
|
333
|
+
# Check entityType
|
|
334
|
+
et_match = re.search(r'entityType\s*:\s*(\w+)', si_text)
|
|
335
|
+
if et_match and et_match.group(1) != "BRAND":
|
|
336
|
+
findings.append(Finding(
|
|
337
|
+
"ENIGMA-005", Severity.ERROR,
|
|
338
|
+
f"prompt search only works with entityType: BRAND, "
|
|
339
|
+
f"got {et_match.group(1)}.",
|
|
340
|
+
))
|
|
341
|
+
return findings
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _check_006_unfiltered_card_transactions(query: str) -> list[Finding]:
|
|
345
|
+
"""ENIGMA-006: cardTransactions without conditions."""
|
|
346
|
+
findings = []
|
|
347
|
+
for m in re.finditer(r'\bcardTransactions\s*\(([^)]*)\)\s*\{', query):
|
|
348
|
+
args = m.group(1)
|
|
349
|
+
if "conditions" not in args:
|
|
350
|
+
findings.append(Finding(
|
|
351
|
+
"ENIGMA-006", Severity.ERROR,
|
|
352
|
+
"cardTransactions without conditions filter. Always use conditions "
|
|
353
|
+
"with period, quantityType, and rank filters.",
|
|
354
|
+
_line_of(query, m.start()),
|
|
355
|
+
))
|
|
356
|
+
return findings
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _check_007_deep_traversal(query: str) -> list[Finding]:
|
|
360
|
+
"""ENIGMA-007: More than 5 connection nesting levels."""
|
|
361
|
+
findings = []
|
|
362
|
+
# Simple approach: count non-leaf connection keywords in nested braces
|
|
363
|
+
depth = 0
|
|
364
|
+
max_depth = 0
|
|
365
|
+
stack = []
|
|
366
|
+
non_leaf = CONNECTION_FIELDS - LEAF_CONNECTION_FIELDS
|
|
367
|
+
i = 0
|
|
368
|
+
while i < len(query):
|
|
369
|
+
# Check for connection field followed by ( or {
|
|
370
|
+
matched_field = None
|
|
371
|
+
for fn in non_leaf:
|
|
372
|
+
if query[i:].startswith(fn):
|
|
373
|
+
# Verify it's a word boundary
|
|
374
|
+
before = query[i - 1] if i > 0 else ' '
|
|
375
|
+
after_pos = i + len(fn)
|
|
376
|
+
after = query[after_pos] if after_pos < len(query) else ' '
|
|
377
|
+
if not before.isalnum() and before != '_':
|
|
378
|
+
if after in ('(', '{', ' ', '\n', '\t'):
|
|
379
|
+
matched_field = fn
|
|
380
|
+
break
|
|
381
|
+
if matched_field:
|
|
382
|
+
depth += 1
|
|
383
|
+
if depth > max_depth:
|
|
384
|
+
max_depth = depth
|
|
385
|
+
# Find the opening brace for this field
|
|
386
|
+
j = i + len(matched_field)
|
|
387
|
+
while j < len(query) and query[j] != '{':
|
|
388
|
+
j += 1
|
|
389
|
+
if j < len(query):
|
|
390
|
+
stack.append(j)
|
|
391
|
+
i = j + 1
|
|
392
|
+
continue
|
|
393
|
+
if query[i] == '}' and stack:
|
|
394
|
+
# Check if this closes one of our tracked braces
|
|
395
|
+
# Simple: just count braces from the last stack entry
|
|
396
|
+
brace_count = 0
|
|
397
|
+
for k in range(stack[-1], i + 1):
|
|
398
|
+
if query[k] == '{':
|
|
399
|
+
brace_count += 1
|
|
400
|
+
elif query[k] == '}':
|
|
401
|
+
brace_count -= 1
|
|
402
|
+
if brace_count <= 0:
|
|
403
|
+
stack.pop()
|
|
404
|
+
depth -= 1
|
|
405
|
+
i += 1
|
|
406
|
+
|
|
407
|
+
if max_depth > 5:
|
|
408
|
+
findings.append(Finding(
|
|
409
|
+
"ENIGMA-007", Severity.ERROR,
|
|
410
|
+
f"Query has {max_depth} levels of connection nesting (max 5).",
|
|
411
|
+
))
|
|
412
|
+
return findings
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def _check_008_roles_on_brand(query: str) -> list[Finding]:
|
|
416
|
+
"""ENIGMA-008: Brand doesn't have roles field."""
|
|
417
|
+
findings = []
|
|
418
|
+
for m in re.finditer(r'\broles\s*(\(|{)', query):
|
|
419
|
+
ctx = _get_entity_context(query, m.start())
|
|
420
|
+
if ctx == "Brand":
|
|
421
|
+
# Check it's a direct child, not nested under operatingLocations etc.
|
|
422
|
+
fragments = _find_inline_fragments(query)
|
|
423
|
+
brand_start = None
|
|
424
|
+
for type_name, start, end in fragments:
|
|
425
|
+
if type_name == "Brand" and start <= m.start() < end:
|
|
426
|
+
brand_start = start
|
|
427
|
+
break
|
|
428
|
+
if brand_start is not None:
|
|
429
|
+
between = query[brand_start:m.start()]
|
|
430
|
+
# If there's another entity context in between, it's not direct
|
|
431
|
+
if "operatingLocations" not in between and "legalEntities" not in between:
|
|
432
|
+
findings.append(Finding(
|
|
433
|
+
"ENIGMA-008", Severity.ERROR,
|
|
434
|
+
"Brand does not have a 'roles' field.",
|
|
435
|
+
_line_of(query, m.start()),
|
|
436
|
+
))
|
|
437
|
+
return findings
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _check_009_multi_field_filter(query: str) -> list[Finding]:
|
|
441
|
+
"""ENIGMA-009: Multiple filter keys without AND/OR wrapper."""
|
|
442
|
+
findings = []
|
|
443
|
+
# Find filter: { ... } blocks
|
|
444
|
+
for m in re.finditer(r'filter\s*:\s*\{', query):
|
|
445
|
+
# Extract the filter object
|
|
446
|
+
depth = 0
|
|
447
|
+
start = m.end() - 1
|
|
448
|
+
end = start
|
|
449
|
+
for j in range(start, len(query)):
|
|
450
|
+
if query[j] == '{':
|
|
451
|
+
depth += 1
|
|
452
|
+
elif query[j] == '}':
|
|
453
|
+
depth -= 1
|
|
454
|
+
if depth == 0:
|
|
455
|
+
end = j + 1
|
|
456
|
+
break
|
|
457
|
+
filter_text = query[start:end]
|
|
458
|
+
# Count top-level keys (EQ, NE, IN, NOT, GT, LT, GTE, LTE, HAS, BETWEEN, AND, OR)
|
|
459
|
+
# Only at the first nesting level
|
|
460
|
+
inner = filter_text[1:-1].strip() # Remove outer braces
|
|
461
|
+
filter_keys = re.findall(r'(?:^|[,{])\s*(EQ|NEQ?|IN|NOT|GT|LT|GTE|LTE|HAS|BETWEEN|AND|OR|NOT_IN|HAS_PROPERTY|CONTAINS_TOKEN)\s*:', inner)
|
|
462
|
+
if len(filter_keys) > 1:
|
|
463
|
+
has_wrapper = any(k in ("AND", "OR") for k in filter_keys)
|
|
464
|
+
if not has_wrapper:
|
|
465
|
+
findings.append(Finding(
|
|
466
|
+
"ENIGMA-009", Severity.ERROR,
|
|
467
|
+
"Multiple filter conditions without AND/OR wrapper. "
|
|
468
|
+
"Use { AND: [...] } or { OR: [...] } to combine filters.",
|
|
469
|
+
_line_of(query, m.start()),
|
|
470
|
+
))
|
|
471
|
+
return findings
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _check_010_missing_search_limit(query: str) -> list[Finding]:
|
|
475
|
+
"""ENIGMA-010: No conditions.limit on searchInput."""
|
|
476
|
+
findings = []
|
|
477
|
+
si_text = _extract_search_input_text(query)
|
|
478
|
+
if si_text is None:
|
|
479
|
+
return findings # Variable-based — can't check
|
|
480
|
+
# Check for conditions with limit
|
|
481
|
+
if "conditions" not in si_text or "limit" not in si_text:
|
|
482
|
+
findings.append(Finding(
|
|
483
|
+
"ENIGMA-010", Severity.ERROR,
|
|
484
|
+
"searchInput missing conditions.limit. Always set a limit to "
|
|
485
|
+
"avoid unbounded result sets.",
|
|
486
|
+
))
|
|
487
|
+
return findings
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def _check_011_has_operator(query: str) -> list[Finding]:
|
|
491
|
+
"""ENIGMA-011: Unreliable HAS operator."""
|
|
492
|
+
findings = []
|
|
493
|
+
for m in re.finditer(r'\bHAS\s*:', query):
|
|
494
|
+
findings.append(Finding(
|
|
495
|
+
"ENIGMA-011", Severity.WARNING,
|
|
496
|
+
"HAS operator is unreliable in the Enigma API. Results may be "
|
|
497
|
+
"inconsistent. Consider alternative filtering approaches.",
|
|
498
|
+
_line_of(query, m.start()),
|
|
499
|
+
))
|
|
500
|
+
return findings
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def _check_012_conditions_unsupported(query: str) -> list[Finding]:
|
|
504
|
+
"""ENIGMA-012: conditions on fields that don't support it."""
|
|
505
|
+
findings = []
|
|
506
|
+
for field_name in NO_CONDITIONS_FIELDS:
|
|
507
|
+
pattern = rf'\b{field_name}\s*\([^)]*conditions\s*:'
|
|
508
|
+
for m in re.finditer(pattern, query):
|
|
509
|
+
findings.append(Finding(
|
|
510
|
+
"ENIGMA-012", Severity.WARNING,
|
|
511
|
+
f"conditions on '{field_name}' may not be supported. "
|
|
512
|
+
f"Server-side filtering is limited on this field.",
|
|
513
|
+
_line_of(query, m.start()),
|
|
514
|
+
))
|
|
515
|
+
return findings
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _check_013_address_only_search(query: str) -> list[Finding]:
|
|
519
|
+
"""ENIGMA-013: Address without name/website/prompt."""
|
|
520
|
+
findings = []
|
|
521
|
+
si_text = _extract_search_input_text(query)
|
|
522
|
+
if si_text is None:
|
|
523
|
+
return findings
|
|
524
|
+
has_address = "address" in si_text and "address" not in ("addresses",)
|
|
525
|
+
has_name = "name" in si_text and re.search(r'\bname\s*:', si_text)
|
|
526
|
+
has_prompt = "prompt" in si_text
|
|
527
|
+
has_website = "website" in si_text
|
|
528
|
+
if has_address and not has_name and not has_prompt and not has_website:
|
|
529
|
+
findings.append(Finding(
|
|
530
|
+
"ENIGMA-013", Severity.WARNING,
|
|
531
|
+
"Search with address only (no name, website, or prompt). "
|
|
532
|
+
"This may return poor or no results. Include a name for reliable matching.",
|
|
533
|
+
))
|
|
534
|
+
return findings
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _check_014_raw_quantity(query: str) -> list[Finding]:
|
|
538
|
+
"""ENIGMA-014: rawQuantity instead of projectedQuantity."""
|
|
539
|
+
findings = []
|
|
540
|
+
for m in re.finditer(r'\brawQuantity\b', query):
|
|
541
|
+
# Check it's not alongside projectedQuantity (which is fine)
|
|
542
|
+
line_start = query.rfind('\n', 0, m.start()) + 1
|
|
543
|
+
line_end = query.find('\n', m.start())
|
|
544
|
+
line = query[line_start:line_end if line_end > 0 else len(query)]
|
|
545
|
+
# Check the broader context — if projectedQuantity is also selected, just warn
|
|
546
|
+
findings.append(Finding(
|
|
547
|
+
"ENIGMA-014", Severity.WARNING,
|
|
548
|
+
"rawQuantity is the raw panel observation. Use projectedQuantity "
|
|
549
|
+
"for the scaled estimate (primary display value).",
|
|
550
|
+
_line_of(query, m.start()),
|
|
551
|
+
))
|
|
552
|
+
return findings
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _check_015_postal_code_in_return(query: str) -> list[Finding]:
|
|
556
|
+
"""ENIGMA-015: postalCode in address return fields (should be zip)."""
|
|
557
|
+
findings = []
|
|
558
|
+
# Find postalCode inside node { ... } blocks (return fields, not input)
|
|
559
|
+
for m in re.finditer(r'\bpostalCode\b', query):
|
|
560
|
+
# Check if this is inside an Address return context (node { ... })
|
|
561
|
+
# vs inside searchInput (which correctly uses postalCode)
|
|
562
|
+
si_text = _extract_search_input_text(query)
|
|
563
|
+
if si_text and m.start() >= query.find(si_text) and m.start() < query.find(si_text) + len(si_text):
|
|
564
|
+
continue # Inside searchInput — postalCode is correct there
|
|
565
|
+
# Check if inside a node { } that's under addresses
|
|
566
|
+
before = query[max(0, m.start() - 200):m.start()]
|
|
567
|
+
if "addresses" in before and "node" in before:
|
|
568
|
+
findings.append(Finding(
|
|
569
|
+
"ENIGMA-015", Severity.WARNING,
|
|
570
|
+
"Use 'zip' instead of 'postalCode' in Address return fields. "
|
|
571
|
+
"'postalCode' is only valid in AddressInput.",
|
|
572
|
+
_line_of(query, m.start()),
|
|
573
|
+
))
|
|
574
|
+
return findings
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def _check_016_address_ranking(query: str) -> list[Finding]:
|
|
578
|
+
"""ENIGMA-016: Address on person search ranks, doesn't filter."""
|
|
579
|
+
findings = []
|
|
580
|
+
si_text = _extract_search_input_text(query)
|
|
581
|
+
if si_text is None:
|
|
582
|
+
return findings
|
|
583
|
+
et_match = re.search(r'entityType\s*:\s*(\w+)', si_text)
|
|
584
|
+
if et_match and et_match.group(1) == "PERSON" and "address" in si_text:
|
|
585
|
+
findings.append(Finding(
|
|
586
|
+
"ENIGMA-016", Severity.INFO,
|
|
587
|
+
"Address on PERSON search is used for ranking, not filtering. "
|
|
588
|
+
"Results may include people from other locations.",
|
|
589
|
+
))
|
|
590
|
+
return findings
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _check_017_le_brand_trust(query: str) -> list[Finding]:
|
|
594
|
+
"""ENIGMA-017: ~30% error rate on LegalEntity → Brand traversal."""
|
|
595
|
+
findings = []
|
|
596
|
+
fragments = _find_inline_fragments(query)
|
|
597
|
+
for type_name, start, end in fragments:
|
|
598
|
+
if type_name == "LegalEntity":
|
|
599
|
+
body = query[start:end]
|
|
600
|
+
if re.search(r'\bbrands\s*(\(|{)', body):
|
|
601
|
+
findings.append(Finding(
|
|
602
|
+
"ENIGMA-017", Severity.INFO,
|
|
603
|
+
"LegalEntity -> brands traversal has ~30% error rate. "
|
|
604
|
+
"Verify results manually or use Brand search instead.",
|
|
605
|
+
))
|
|
606
|
+
break
|
|
607
|
+
return findings
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _check_018_missing_operation_name(query: str) -> list[Finding]:
|
|
611
|
+
"""ENIGMA-018: Missing operation name."""
|
|
612
|
+
findings = []
|
|
613
|
+
stripped = query.strip()
|
|
614
|
+
# Check for anonymous query (starts with { or has query/mutation without name)
|
|
615
|
+
if stripped.startswith('{'):
|
|
616
|
+
findings.append(Finding(
|
|
617
|
+
"ENIGMA-018", Severity.INFO,
|
|
618
|
+
"Anonymous query (no operation name). Add a name for better "
|
|
619
|
+
"debugging and logging: query MyQueryName { ... }",
|
|
620
|
+
))
|
|
621
|
+
elif re.match(r'^(query|mutation|subscription)\s*[\({$]', stripped):
|
|
622
|
+
findings.append(Finding(
|
|
623
|
+
"ENIGMA-018", Severity.INFO,
|
|
624
|
+
"Query/mutation without operation name. Add a name: "
|
|
625
|
+
"query MyQueryName(...) { ... }",
|
|
626
|
+
))
|
|
627
|
+
return findings
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
# ---------------------------------------------------------------------------
|
|
631
|
+
# Rule registry
|
|
632
|
+
# ---------------------------------------------------------------------------
|
|
633
|
+
|
|
634
|
+
ALL_RULES = [
|
|
635
|
+
("ENIGMA-001", _check_001_persons_on_le),
|
|
636
|
+
("ENIGMA-002", _check_002_direct_roles_on_le),
|
|
637
|
+
("ENIGMA-003", _check_003_missing_pagination),
|
|
638
|
+
("ENIGMA-004", _check_004_missing_entity_type),
|
|
639
|
+
("ENIGMA-005", _check_005_prompt_non_brand),
|
|
640
|
+
("ENIGMA-006", _check_006_unfiltered_card_transactions),
|
|
641
|
+
("ENIGMA-007", _check_007_deep_traversal),
|
|
642
|
+
("ENIGMA-008", _check_008_roles_on_brand),
|
|
643
|
+
("ENIGMA-009", _check_009_multi_field_filter),
|
|
644
|
+
("ENIGMA-010", _check_010_missing_search_limit),
|
|
645
|
+
("ENIGMA-011", _check_011_has_operator),
|
|
646
|
+
("ENIGMA-012", _check_012_conditions_unsupported),
|
|
647
|
+
("ENIGMA-013", _check_013_address_only_search),
|
|
648
|
+
("ENIGMA-014", _check_014_raw_quantity),
|
|
649
|
+
("ENIGMA-015", _check_015_postal_code_in_return),
|
|
650
|
+
("ENIGMA-016", _check_016_address_ranking),
|
|
651
|
+
("ENIGMA-017", _check_017_le_brand_trust),
|
|
652
|
+
("ENIGMA-018", _check_018_missing_operation_name),
|
|
653
|
+
]
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
# ---------------------------------------------------------------------------
|
|
657
|
+
# Public API
|
|
658
|
+
# ---------------------------------------------------------------------------
|
|
659
|
+
|
|
660
|
+
def lint_query(query: str) -> LintResult:
|
|
661
|
+
"""Lint a GraphQL query string and return findings."""
|
|
662
|
+
result = LintResult()
|
|
663
|
+
|
|
664
|
+
# Basic validity check
|
|
665
|
+
stripped = query.strip()
|
|
666
|
+
if not stripped:
|
|
667
|
+
result.query_valid = False
|
|
668
|
+
result.findings.append(Finding(
|
|
669
|
+
"PARSE", Severity.ERROR, "Empty query string."
|
|
670
|
+
))
|
|
671
|
+
return result
|
|
672
|
+
|
|
673
|
+
# Check for basic structure (must have at least one { })
|
|
674
|
+
if '{' not in stripped or '}' not in stripped:
|
|
675
|
+
result.query_valid = False
|
|
676
|
+
result.findings.append(Finding(
|
|
677
|
+
"PARSE", Severity.ERROR, "Query missing braces — not valid GraphQL."
|
|
678
|
+
))
|
|
679
|
+
return result
|
|
680
|
+
|
|
681
|
+
# Check balanced braces
|
|
682
|
+
depth = 0
|
|
683
|
+
for ch in stripped:
|
|
684
|
+
if ch == '{':
|
|
685
|
+
depth += 1
|
|
686
|
+
elif ch == '}':
|
|
687
|
+
depth -= 1
|
|
688
|
+
if depth < 0:
|
|
689
|
+
result.query_valid = False
|
|
690
|
+
result.findings.append(Finding(
|
|
691
|
+
"PARSE", Severity.ERROR, "Unbalanced braces in query."
|
|
692
|
+
))
|
|
693
|
+
return result
|
|
694
|
+
if depth != 0:
|
|
695
|
+
result.query_valid = False
|
|
696
|
+
result.findings.append(Finding(
|
|
697
|
+
"PARSE", Severity.ERROR, "Unbalanced braces in query."
|
|
698
|
+
))
|
|
699
|
+
return result
|
|
700
|
+
|
|
701
|
+
# Run all rules
|
|
702
|
+
for rule_id, check_fn in ALL_RULES:
|
|
703
|
+
try:
|
|
704
|
+
findings = check_fn(query)
|
|
705
|
+
result.findings.extend(findings)
|
|
706
|
+
except Exception as e:
|
|
707
|
+
result.findings.append(Finding(
|
|
708
|
+
rule_id, Severity.WARNING,
|
|
709
|
+
f"Rule {rule_id} failed to execute: {e}",
|
|
710
|
+
))
|
|
711
|
+
|
|
712
|
+
return result
|