tokensafe 4.3.3 → 4.4.1
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.
- package/.codex-plugin/plugin.json +1 -1
- package/hooks/post_tool_use.py +38 -0
- package/hooks/pre_invocation.py +18 -0
- package/hooks/pre_tool_use.py +56 -0
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +2 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +4 -2
- package/src/format_parsers/lockfiles.py +452 -0
- package/src/installer.py +4 -2
- package/src/mcp_server.py +107 -4
- package/src/mistakes.py +130 -9
- package/src/result_ledger.py +11 -2
- package/src/schema_slicer.py +245 -9
- package/src/team_cache.py +70 -3
- package/src/telemetry_sync.py +1 -1
- package/src/type_slicer.py +434 -0
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +255 -13
package/src/team_cache.py
CHANGED
|
@@ -12,7 +12,7 @@ import threading
|
|
|
12
12
|
import urllib.request
|
|
13
13
|
import urllib.error
|
|
14
14
|
import urllib.parse
|
|
15
|
-
from typing import Optional, Dict, Any, Tuple
|
|
15
|
+
from typing import Optional, Dict, Any, Tuple, List
|
|
16
16
|
from src.license_manager import LicenseManager
|
|
17
17
|
from src.ssl_context import shared_ssl_context
|
|
18
18
|
|
|
@@ -25,6 +25,11 @@ class TeamCache:
|
|
|
25
25
|
_cooldowns: Dict[str, float] = {}
|
|
26
26
|
_cooldown_lock = threading.Lock()
|
|
27
27
|
|
|
28
|
+
ALLOWED_CACHE_TYPES = frozenset({
|
|
29
|
+
"PROMPT", "PROMPT_TMPL", "SKELETON", "ARCH_INDEX",
|
|
30
|
+
"WEB_DOCS", "LOCKFILE_INDEX", "TEAM_MISTAKE", "3RD_PARTY_DTS", "SCHEMA_CONTRACTS"
|
|
31
|
+
})
|
|
32
|
+
|
|
28
33
|
@classmethod
|
|
29
34
|
def _is_in_cooldown(cls, cloud_url: Optional[str] = None) -> bool:
|
|
30
35
|
now = time.monotonic()
|
|
@@ -93,8 +98,12 @@ class TeamCache:
|
|
|
93
98
|
if not cache_type or not key_text:
|
|
94
99
|
return None
|
|
95
100
|
|
|
101
|
+
norm_type = cache_type.strip().upper()
|
|
102
|
+
if norm_type not in cls.ALLOWED_CACHE_TYPES:
|
|
103
|
+
return None
|
|
104
|
+
|
|
96
105
|
h = cls.hash_key(key_text)
|
|
97
|
-
endpoint = f"{cloud_url}/api/team/cache?type={urllib.parse.quote(
|
|
106
|
+
endpoint = f"{cloud_url}/api/team/cache?type={urllib.parse.quote(norm_type)}&hash={h}"
|
|
98
107
|
|
|
99
108
|
req = urllib.request.Request(
|
|
100
109
|
endpoint,
|
|
@@ -149,6 +158,14 @@ class TeamCache:
|
|
|
149
158
|
if not cache_type or not key_text or not value:
|
|
150
159
|
return
|
|
151
160
|
|
|
161
|
+
norm_type = cache_type.strip().upper()
|
|
162
|
+
if norm_type not in cls.ALLOWED_CACHE_TYPES:
|
|
163
|
+
return
|
|
164
|
+
|
|
165
|
+
# Hard bounded payload (256 KB)
|
|
166
|
+
if len(value) > 262_144:
|
|
167
|
+
return
|
|
168
|
+
|
|
152
169
|
safe_value = value
|
|
153
170
|
try:
|
|
154
171
|
from src.secret_redactor import SecretRedactor
|
|
@@ -156,11 +173,14 @@ class TeamCache:
|
|
|
156
173
|
except Exception:
|
|
157
174
|
pass
|
|
158
175
|
|
|
176
|
+
if len(safe_value) > 262_144:
|
|
177
|
+
return
|
|
178
|
+
|
|
159
179
|
h = cls.hash_key(key_text)
|
|
160
180
|
|
|
161
181
|
def _worker():
|
|
162
182
|
payload = {
|
|
163
|
-
"type":
|
|
183
|
+
"type": norm_type,
|
|
164
184
|
"hash": h,
|
|
165
185
|
"value": safe_value,
|
|
166
186
|
"tokens_saved": max(0, int(tokens_saved or 0)),
|
|
@@ -188,6 +208,53 @@ class TeamCache:
|
|
|
188
208
|
t = threading.Thread(target=_worker, daemon=True)
|
|
189
209
|
t.start()
|
|
190
210
|
|
|
211
|
+
@classmethod
|
|
212
|
+
def list_entries(
|
|
213
|
+
cls,
|
|
214
|
+
cache_type: str,
|
|
215
|
+
limit: int = 10,
|
|
216
|
+
timeout: Optional[float] = None,
|
|
217
|
+
lic_key: Optional[str] = None,
|
|
218
|
+
) -> List[Dict[str, Any]]:
|
|
219
|
+
"""Queries Shared Team Cache for recent entries of a specific type (e.g. TEAM_MISTAKE)."""
|
|
220
|
+
cloud_url = cls._get_cloud_url()
|
|
221
|
+
if cls._is_in_cooldown(cloud_url):
|
|
222
|
+
return []
|
|
223
|
+
if not lic_key:
|
|
224
|
+
is_team, resolved_key = cls._is_team_tier()
|
|
225
|
+
if not is_team:
|
|
226
|
+
return []
|
|
227
|
+
lic_key = resolved_key
|
|
228
|
+
if not cache_type:
|
|
229
|
+
return []
|
|
230
|
+
|
|
231
|
+
norm_type = cache_type.strip().upper()
|
|
232
|
+
if norm_type not in cls.ALLOWED_CACHE_TYPES:
|
|
233
|
+
return []
|
|
234
|
+
|
|
235
|
+
endpoint = f"{cloud_url}/api/team/cache/list?type={urllib.parse.quote(norm_type)}&limit={max(1, min(50, limit))}"
|
|
236
|
+
req = urllib.request.Request(
|
|
237
|
+
endpoint,
|
|
238
|
+
headers={
|
|
239
|
+
"Authorization": f"Bearer {lic_key}",
|
|
240
|
+
"User-Agent": "TokenSafe-TeamCache/1.0"
|
|
241
|
+
}
|
|
242
|
+
)
|
|
243
|
+
eff_timeout = cls.DEFAULT_TIMEOUT if timeout is None else max(0.05, float(timeout))
|
|
244
|
+
try:
|
|
245
|
+
with urllib.request.urlopen(req, timeout=eff_timeout, context=shared_ssl_context()) as resp:
|
|
246
|
+
if resp.status == 200:
|
|
247
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
248
|
+
cls._clear_cooldown(cloud_url)
|
|
249
|
+
return data.get("entries") or []
|
|
250
|
+
except urllib.error.HTTPError as he:
|
|
251
|
+
if he.code in (401, 403) or he.code >= 500:
|
|
252
|
+
cls._trip_cooldown(cloud_url)
|
|
253
|
+
return []
|
|
254
|
+
except Exception:
|
|
255
|
+
return []
|
|
256
|
+
return []
|
|
257
|
+
|
|
191
258
|
@classmethod
|
|
192
259
|
def get_stats(cls) -> Dict[str, Any]:
|
|
193
260
|
"""Retrieves team cache hit rates and token savings metrics."""
|
package/src/telemetry_sync.py
CHANGED
|
@@ -241,7 +241,7 @@ class TelemetrySync:
|
|
|
241
241
|
current_last_id = last_id
|
|
242
242
|
headers = {
|
|
243
243
|
"Content-Type": "application/json",
|
|
244
|
-
"User-Agent": "TokenSafe-Sync/4.
|
|
244
|
+
"User-Agent": "TokenSafe-Sync/4.4.1"
|
|
245
245
|
}
|
|
246
246
|
if active_key:
|
|
247
247
|
headers["Authorization"] = f"Bearer {active_key}"
|
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe 3rd-Party Type Slicer (v3.4.0).
|
|
3
|
+
|
|
4
|
+
Enables AI coding agents to extract precise method signatures, interfaces, and types
|
|
5
|
+
from external packages in node_modules without scanning entire dependency trees.
|
|
6
|
+
|
|
7
|
+
Architecture:
|
|
8
|
+
- Node module upward directory traversal (handles monorepos and Turborepo)
|
|
9
|
+
- Symlink resolution for pnpm virtual store (.pnpm) and bun
|
|
10
|
+
- Deep re-export following (export * from './...') up to 2 hops
|
|
11
|
+
- Local First (L1 memory, L2 SQLite type_cache.db with WAL) + L3 Team Sync (3RD_PARTY_DTS)
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import json
|
|
17
|
+
import sqlite3
|
|
18
|
+
import time
|
|
19
|
+
import hashlib
|
|
20
|
+
import threading
|
|
21
|
+
from collections import OrderedDict
|
|
22
|
+
from typing import Dict, Any, List, Optional, Tuple
|
|
23
|
+
|
|
24
|
+
from src.paths import resolve_data_dir
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class TypeSlicer:
|
|
28
|
+
"""Targeted extractor of external library types and interfaces."""
|
|
29
|
+
|
|
30
|
+
_mem_cache: "OrderedDict[str, str]" = OrderedDict()
|
|
31
|
+
_mem_lock = threading.Lock()
|
|
32
|
+
_db_init_done = False
|
|
33
|
+
_db_init_lock = threading.Lock()
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def clear_memory_cache(cls):
|
|
37
|
+
with cls._mem_lock:
|
|
38
|
+
cls._mem_cache.clear()
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def _mem_put(cls, key: str, val: str, max_items: int = 100) -> None:
|
|
42
|
+
"""Stores entry in LRU memory cache with fixed cap."""
|
|
43
|
+
with cls._mem_lock:
|
|
44
|
+
cls._mem_cache[key] = val
|
|
45
|
+
cls._mem_cache.move_to_end(key)
|
|
46
|
+
if len(cls._mem_cache) > max_items:
|
|
47
|
+
cls._mem_cache.popitem(last=False)
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def _maybe_evict(cls, conn: sqlite3.Connection, max_rows: int = 5000) -> None:
|
|
51
|
+
"""Evicts oldest entries when type cache exceeds max_rows."""
|
|
52
|
+
try:
|
|
53
|
+
row = conn.execute("SELECT COUNT(*) FROM type_cache;").fetchone()
|
|
54
|
+
count = row[0] if row else 0
|
|
55
|
+
if count > max_rows:
|
|
56
|
+
excess = count - max_rows
|
|
57
|
+
conn.execute(
|
|
58
|
+
"DELETE FROM type_cache WHERE type_key IN ("
|
|
59
|
+
"SELECT type_key FROM type_cache ORDER BY cached_at ASC LIMIT ?"
|
|
60
|
+
");", (excess,)
|
|
61
|
+
)
|
|
62
|
+
except Exception:
|
|
63
|
+
pass
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def _get_db_path(cls) -> str:
|
|
67
|
+
data_dir = resolve_data_dir()
|
|
68
|
+
os.makedirs(data_dir, exist_ok=True)
|
|
69
|
+
return os.path.join(data_dir, "type_cache.db")
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def _init_db(cls):
|
|
73
|
+
db_path = cls._get_db_path()
|
|
74
|
+
with cls._db_init_lock:
|
|
75
|
+
if cls._db_init_done == db_path and os.path.exists(db_path):
|
|
76
|
+
return
|
|
77
|
+
conn = None
|
|
78
|
+
try:
|
|
79
|
+
conn = sqlite3.connect(db_path, timeout=5.0)
|
|
80
|
+
conn.execute("PRAGMA journal_mode=WAL;")
|
|
81
|
+
conn.execute("PRAGMA busy_timeout=5000;")
|
|
82
|
+
conn.execute("""
|
|
83
|
+
CREATE TABLE IF NOT EXISTS type_cache (
|
|
84
|
+
type_key TEXT PRIMARY KEY,
|
|
85
|
+
package_name TEXT NOT NULL,
|
|
86
|
+
version TEXT NOT NULL,
|
|
87
|
+
symbol TEXT NOT NULL,
|
|
88
|
+
type_code TEXT NOT NULL,
|
|
89
|
+
dts_bytes INTEGER DEFAULT 0,
|
|
90
|
+
cached_at INTEGER NOT NULL,
|
|
91
|
+
hit_count INTEGER DEFAULT 1
|
|
92
|
+
);
|
|
93
|
+
""")
|
|
94
|
+
try:
|
|
95
|
+
conn.execute("ALTER TABLE type_cache ADD COLUMN dts_bytes INTEGER DEFAULT 0;")
|
|
96
|
+
except Exception:
|
|
97
|
+
pass
|
|
98
|
+
conn.execute("CREATE INDEX IF NOT EXISTS idx_type_pkg ON type_cache(package_name);")
|
|
99
|
+
conn.commit()
|
|
100
|
+
cls._db_init_done = db_path
|
|
101
|
+
except Exception:
|
|
102
|
+
pass
|
|
103
|
+
finally:
|
|
104
|
+
if conn:
|
|
105
|
+
try:
|
|
106
|
+
conn.close()
|
|
107
|
+
except Exception:
|
|
108
|
+
pass
|
|
109
|
+
|
|
110
|
+
@classmethod
|
|
111
|
+
def find_package_dir(cls, package_name: str, start_dir: Optional[str] = None) -> Optional[str]:
|
|
112
|
+
"""
|
|
113
|
+
Traverses upward to locate the package directory in node_modules.
|
|
114
|
+
Resolves symlinks for pnpm/bun and supports scoped packages (@scope/pkg).
|
|
115
|
+
"""
|
|
116
|
+
curr = os.path.abspath(start_dir or os.getcwd())
|
|
117
|
+
parts = package_name.strip().split("/")
|
|
118
|
+
|
|
119
|
+
for _ in range(8):
|
|
120
|
+
node_modules = os.path.join(curr, "node_modules")
|
|
121
|
+
if os.path.isdir(node_modules):
|
|
122
|
+
cand = os.path.join(node_modules, *parts)
|
|
123
|
+
if os.path.isdir(cand):
|
|
124
|
+
try:
|
|
125
|
+
return os.path.realpath(cand)
|
|
126
|
+
except Exception:
|
|
127
|
+
return cand
|
|
128
|
+
parent = os.path.dirname(curr)
|
|
129
|
+
if parent == curr:
|
|
130
|
+
break
|
|
131
|
+
curr = parent
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
@classmethod
|
|
135
|
+
def locate_type_file(cls, pkg_dir: str, pkg_name: str) -> Optional[str]:
|
|
136
|
+
"""Finds primary .d.ts declaration file via package.json or @types fallback."""
|
|
137
|
+
pkg_json_path = os.path.join(pkg_dir, "package.json")
|
|
138
|
+
types_rel: Optional[str] = None
|
|
139
|
+
if os.path.isfile(pkg_json_path):
|
|
140
|
+
try:
|
|
141
|
+
with open(pkg_json_path, "r", encoding="utf-8", errors="replace") as f:
|
|
142
|
+
meta = json.load(f)
|
|
143
|
+
types_rel = meta.get("types") or meta.get("typings")
|
|
144
|
+
if not types_rel and isinstance(meta.get("exports"), dict):
|
|
145
|
+
root_export = meta["exports"].get(".")
|
|
146
|
+
if isinstance(root_export, dict):
|
|
147
|
+
types_rel = root_export.get("types")
|
|
148
|
+
except Exception:
|
|
149
|
+
pass
|
|
150
|
+
|
|
151
|
+
if types_rel:
|
|
152
|
+
resolved = os.path.realpath(os.path.join(pkg_dir, types_rel))
|
|
153
|
+
if os.path.isfile(resolved):
|
|
154
|
+
return resolved
|
|
155
|
+
if os.path.isfile(resolved + ".d.ts"):
|
|
156
|
+
return resolved + ".d.ts"
|
|
157
|
+
|
|
158
|
+
# Check standard index.d.ts
|
|
159
|
+
standard_index = os.path.join(pkg_dir, "index.d.ts")
|
|
160
|
+
if os.path.isfile(standard_index):
|
|
161
|
+
return standard_index
|
|
162
|
+
|
|
163
|
+
# Check @types/<pkg> fallback in node_modules
|
|
164
|
+
node_modules_parent = os.path.dirname(pkg_dir)
|
|
165
|
+
if os.path.basename(node_modules_parent) != "node_modules":
|
|
166
|
+
# Scoped package parent
|
|
167
|
+
node_modules_parent = os.path.dirname(node_modules_parent)
|
|
168
|
+
|
|
169
|
+
if os.path.basename(node_modules_parent) == "node_modules":
|
|
170
|
+
types_scope_name = pkg_name.replace("@", "").replace("/", "__")
|
|
171
|
+
types_cand = os.path.join(node_modules_parent, "@types", types_scope_name, "index.d.ts")
|
|
172
|
+
if os.path.isfile(types_cand):
|
|
173
|
+
return types_cand
|
|
174
|
+
|
|
175
|
+
return None
|
|
176
|
+
|
|
177
|
+
@classmethod
|
|
178
|
+
def _extract_symbol_block(cls, content: str, symbol: str) -> Optional[str]:
|
|
179
|
+
"""Extracts full definition block for interface, type, class, function, enum, or namespace with balanced braces."""
|
|
180
|
+
pattern = re.compile(
|
|
181
|
+
rf'(?:export\s+)?(?:declare\s+)?(?:default\s+)?(interface|type|class|enum|function|const|namespace)\s+{re.escape(symbol)}\b',
|
|
182
|
+
re.MULTILINE
|
|
183
|
+
)
|
|
184
|
+
match = pattern.search(content)
|
|
185
|
+
if not match:
|
|
186
|
+
return None
|
|
187
|
+
|
|
188
|
+
kind = match.group(1)
|
|
189
|
+
is_namespace = (kind == "namespace")
|
|
190
|
+
max_lines = 400 if is_namespace else 150
|
|
191
|
+
|
|
192
|
+
start_pos = match.start()
|
|
193
|
+
rest = content[start_pos:]
|
|
194
|
+
lines = rest.splitlines()
|
|
195
|
+
|
|
196
|
+
collected: List[str] = []
|
|
197
|
+
open_braces = 0
|
|
198
|
+
brace_started = False
|
|
199
|
+
truncated = False
|
|
200
|
+
|
|
201
|
+
for line in lines:
|
|
202
|
+
collected.append(line)
|
|
203
|
+
open_braces += line.count("{") - line.count("}")
|
|
204
|
+
if "{" in line:
|
|
205
|
+
brace_started = True
|
|
206
|
+
|
|
207
|
+
# For type alias (type X = ...;) or single-line declarations
|
|
208
|
+
if not brace_started and line.strip().endswith(";"):
|
|
209
|
+
break
|
|
210
|
+
if brace_started and open_braces <= 0:
|
|
211
|
+
break
|
|
212
|
+
if len(collected) >= max_lines:
|
|
213
|
+
truncated = True
|
|
214
|
+
break
|
|
215
|
+
|
|
216
|
+
if truncated and open_braces > 0:
|
|
217
|
+
collected.append(f" // ... [TokenSafe: truncated {open_braces} nested block(s)]")
|
|
218
|
+
for _ in range(open_braces):
|
|
219
|
+
collected.append("}")
|
|
220
|
+
|
|
221
|
+
return "\n".join(collected)
|
|
222
|
+
|
|
223
|
+
@classmethod
|
|
224
|
+
def slice_symbol_from_file(cls, dts_path: str, symbol: str, depth: int = 0) -> Optional[str]:
|
|
225
|
+
"""Slices symbol from declaration file, following relative re-exports up to 2 hops."""
|
|
226
|
+
if not dts_path or not os.path.isfile(dts_path):
|
|
227
|
+
return None
|
|
228
|
+
|
|
229
|
+
try:
|
|
230
|
+
with open(dts_path, "r", encoding="utf-8", errors="replace") as f:
|
|
231
|
+
content = f.read()
|
|
232
|
+
except Exception:
|
|
233
|
+
return None
|
|
234
|
+
|
|
235
|
+
# 1. Direct match
|
|
236
|
+
block = cls._extract_symbol_block(content, symbol)
|
|
237
|
+
if block:
|
|
238
|
+
return block
|
|
239
|
+
|
|
240
|
+
# 2. Check relative re-exports (export * from './...') if depth < 2
|
|
241
|
+
if depth < 2:
|
|
242
|
+
base_dir = os.path.dirname(dts_path)
|
|
243
|
+
re_export_pattern = re.compile(r'export\s+(?:\*|\{[^}]+\})\s+from\s+[\'"](\.[^\'"]+)[\'"]')
|
|
244
|
+
for match in re_export_pattern.finditer(content):
|
|
245
|
+
rel_target = match.group(1)
|
|
246
|
+
cand_paths = [
|
|
247
|
+
os.path.join(base_dir, rel_target),
|
|
248
|
+
os.path.join(base_dir, f"{rel_target}.d.ts"),
|
|
249
|
+
os.path.join(base_dir, rel_target, "index.d.ts"),
|
|
250
|
+
]
|
|
251
|
+
for p in cand_paths:
|
|
252
|
+
if os.path.isfile(p):
|
|
253
|
+
found = cls.slice_symbol_from_file(p, symbol, depth=depth + 1)
|
|
254
|
+
if found:
|
|
255
|
+
return found
|
|
256
|
+
|
|
257
|
+
return None
|
|
258
|
+
|
|
259
|
+
@classmethod
|
|
260
|
+
def slice_package_type(
|
|
261
|
+
cls,
|
|
262
|
+
package_name: str,
|
|
263
|
+
symbol: str,
|
|
264
|
+
project_root: Optional[str] = None
|
|
265
|
+
) -> Dict[str, Any]:
|
|
266
|
+
"""
|
|
267
|
+
Targeted resolution of external library types.
|
|
268
|
+
Checks L1, L2 SQLite, L3 Team Cache, then parses declaration AST.
|
|
269
|
+
"""
|
|
270
|
+
pkg_name = package_name.strip()
|
|
271
|
+
sym = symbol.strip()
|
|
272
|
+
if not pkg_name or not sym:
|
|
273
|
+
return {"found": False, "error": "package_name and symbol are required"}
|
|
274
|
+
|
|
275
|
+
pkg_dir = cls.find_package_dir(pkg_name, start_dir=project_root)
|
|
276
|
+
version = "unknown"
|
|
277
|
+
if pkg_dir:
|
|
278
|
+
pkg_json = os.path.join(pkg_dir, "package.json")
|
|
279
|
+
if os.path.isfile(pkg_json):
|
|
280
|
+
try:
|
|
281
|
+
with open(pkg_json, "r", encoding="utf-8") as f:
|
|
282
|
+
version = json.load(f).get("version", "unknown")
|
|
283
|
+
except Exception:
|
|
284
|
+
pass
|
|
285
|
+
|
|
286
|
+
type_key = f"{pkg_name}@{version}::{sym}"
|
|
287
|
+
|
|
288
|
+
# 1. Check L1 Memory
|
|
289
|
+
with cls._mem_lock:
|
|
290
|
+
if type_key in cls._mem_cache:
|
|
291
|
+
cls._mem_cache.move_to_end(type_key)
|
|
292
|
+
return {
|
|
293
|
+
"found": True,
|
|
294
|
+
"package": pkg_name,
|
|
295
|
+
"version": version,
|
|
296
|
+
"symbol": sym,
|
|
297
|
+
"type_code": cls._mem_cache[type_key],
|
|
298
|
+
"source": "L1_memory"
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
# 2. Check L2 SQLite
|
|
302
|
+
cls._init_db()
|
|
303
|
+
db_path = cls._get_db_path()
|
|
304
|
+
l2_conn = None
|
|
305
|
+
try:
|
|
306
|
+
l2_conn = sqlite3.connect(db_path, timeout=5.0)
|
|
307
|
+
l2_conn.execute("PRAGMA busy_timeout=5000;")
|
|
308
|
+
row = l2_conn.execute(
|
|
309
|
+
"SELECT type_code, dts_bytes FROM type_cache WHERE type_key = ?",
|
|
310
|
+
(type_key,)
|
|
311
|
+
).fetchone()
|
|
312
|
+
if row:
|
|
313
|
+
code = row[0]
|
|
314
|
+
dts_b = row[1] if len(row) > 1 and row[1] else 0
|
|
315
|
+
cls._mem_put(type_key, code, max_items=100)
|
|
316
|
+
return {
|
|
317
|
+
"found": True,
|
|
318
|
+
"package": pkg_name,
|
|
319
|
+
"version": version,
|
|
320
|
+
"symbol": sym,
|
|
321
|
+
"type_code": code,
|
|
322
|
+
"source": "L2_sqlite",
|
|
323
|
+
"_dts_bytes": dts_b
|
|
324
|
+
}
|
|
325
|
+
except Exception:
|
|
326
|
+
pass
|
|
327
|
+
finally:
|
|
328
|
+
if l2_conn:
|
|
329
|
+
try:
|
|
330
|
+
l2_conn.close()
|
|
331
|
+
except Exception:
|
|
332
|
+
pass
|
|
333
|
+
|
|
334
|
+
# 3. Check L3 Team Sync
|
|
335
|
+
try:
|
|
336
|
+
from src.team_cache import TeamCache
|
|
337
|
+
team_val = TeamCache.get("3RD_PARTY_DTS", type_key, timeout=0.5)
|
|
338
|
+
if team_val:
|
|
339
|
+
cls._mem_put(type_key, team_val, max_items=100)
|
|
340
|
+
# Backfill L2
|
|
341
|
+
back_conn = None
|
|
342
|
+
try:
|
|
343
|
+
back_conn = sqlite3.connect(db_path, timeout=5.0)
|
|
344
|
+
back_conn.execute("""
|
|
345
|
+
INSERT OR REPLACE INTO type_cache (type_key, package_name, version, symbol, type_code, cached_at)
|
|
346
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
347
|
+
""", (type_key, pkg_name, version, sym, team_val, int(time.time())))
|
|
348
|
+
cls._maybe_evict(back_conn)
|
|
349
|
+
back_conn.commit()
|
|
350
|
+
except Exception:
|
|
351
|
+
pass
|
|
352
|
+
finally:
|
|
353
|
+
if back_conn:
|
|
354
|
+
try:
|
|
355
|
+
back_conn.close()
|
|
356
|
+
except Exception:
|
|
357
|
+
pass
|
|
358
|
+
return {
|
|
359
|
+
"found": True,
|
|
360
|
+
"package": pkg_name,
|
|
361
|
+
"version": version,
|
|
362
|
+
"symbol": sym,
|
|
363
|
+
"type_code": team_val,
|
|
364
|
+
"source": "L3_team_cache"
|
|
365
|
+
}
|
|
366
|
+
except Exception:
|
|
367
|
+
pass
|
|
368
|
+
|
|
369
|
+
# 4. Parse from disk
|
|
370
|
+
if not pkg_dir:
|
|
371
|
+
return {
|
|
372
|
+
"found": False,
|
|
373
|
+
"package": pkg_name,
|
|
374
|
+
"symbol": sym,
|
|
375
|
+
"error": f"Package '{pkg_name}' not found in node_modules."
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
dts_file = cls.locate_type_file(pkg_dir, pkg_name)
|
|
379
|
+
if not dts_file:
|
|
380
|
+
return {
|
|
381
|
+
"found": False,
|
|
382
|
+
"package": pkg_name,
|
|
383
|
+
"symbol": sym,
|
|
384
|
+
"error": f"No .d.ts declaration file located for '{pkg_name}'."
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
dts_bytes = os.path.getsize(dts_file) if os.path.isfile(dts_file) else 0
|
|
388
|
+
|
|
389
|
+
code_block = cls.slice_symbol_from_file(dts_file, sym)
|
|
390
|
+
if not code_block:
|
|
391
|
+
return {
|
|
392
|
+
"found": False,
|
|
393
|
+
"package": pkg_name,
|
|
394
|
+
"symbol": sym,
|
|
395
|
+
"dts_file": os.path.basename(dts_file),
|
|
396
|
+
"error": f"Symbol '{sym}' not found in type definitions of '{pkg_name}'."
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
# 5. Save to L1, L2 SQLite, and broadcast to L3 Team Sync
|
|
400
|
+
cls._mem_put(type_key, code_block, max_items=100)
|
|
401
|
+
|
|
402
|
+
save_conn = None
|
|
403
|
+
try:
|
|
404
|
+
save_conn = sqlite3.connect(db_path, timeout=5.0)
|
|
405
|
+
save_conn.execute("""
|
|
406
|
+
INSERT OR REPLACE INTO type_cache (type_key, package_name, version, symbol, type_code, dts_bytes, cached_at)
|
|
407
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
408
|
+
""", (type_key, pkg_name, version, sym, code_block, dts_bytes, int(time.time())))
|
|
409
|
+
cls._maybe_evict(save_conn)
|
|
410
|
+
save_conn.commit()
|
|
411
|
+
except Exception:
|
|
412
|
+
pass
|
|
413
|
+
finally:
|
|
414
|
+
if save_conn:
|
|
415
|
+
try:
|
|
416
|
+
save_conn.close()
|
|
417
|
+
except Exception:
|
|
418
|
+
pass
|
|
419
|
+
|
|
420
|
+
try:
|
|
421
|
+
from src.team_cache import TeamCache
|
|
422
|
+
TeamCache.put("3RD_PARTY_DTS", type_key, code_block, tokens_saved=max(30, len(code_block)//4))
|
|
423
|
+
except Exception:
|
|
424
|
+
pass
|
|
425
|
+
|
|
426
|
+
return {
|
|
427
|
+
"found": True,
|
|
428
|
+
"package": pkg_name,
|
|
429
|
+
"version": version,
|
|
430
|
+
"symbol": sym,
|
|
431
|
+
"type_code": code_block,
|
|
432
|
+
"source": "parsed_live",
|
|
433
|
+
"_dts_bytes": dts_bytes
|
|
434
|
+
}
|
package/src/version_checker.py
CHANGED
|
@@ -17,7 +17,7 @@ import urllib.request
|
|
|
17
17
|
import urllib.error
|
|
18
18
|
from typing import Dict, Any, Optional, Tuple
|
|
19
19
|
|
|
20
|
-
CURRENT_VERSION = "4.
|
|
20
|
+
CURRENT_VERSION = "4.4.1"
|
|
21
21
|
CACHE_TTL = 86400 # 24 hours
|
|
22
22
|
# When the cloud is unreachable we must NOT cache the synthesized "up to date"
|
|
23
23
|
# answer for a full day — otherwise an update released right after an outage
|