prism-code-workspace 1.0.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.
- prism_code_workspace-1.0.0.dist-info/METADATA +272 -0
- prism_code_workspace-1.0.0.dist-info/RECORD +30 -0
- prism_code_workspace-1.0.0.dist-info/WHEEL +4 -0
- prism_code_workspace-1.0.0.dist-info/entry_points.txt +3 -0
- prism_code_workspace-1.0.0.dist-info/licenses/LICENSE +21 -0
- python_app/__init__.py +3 -0
- python_app/ai.py +225 -0
- python_app/analysis.py +953 -0
- python_app/compare.py +685 -0
- python_app/compare_engine.py +284 -0
- python_app/compiled_analysis.py +727 -0
- python_app/desktop.py +181 -0
- python_app/function_pov/__init__.py +16 -0
- python_app/function_pov/analyzer.py +464 -0
- python_app/function_pov/graph.py +50 -0
- python_app/function_pov/models.py +53 -0
- python_app/function_pov/pov/__init__.py +17 -0
- python_app/function_pov/pov/engine.py +1630 -0
- python_app/function_pov/pov/exercises.py +1263 -0
- python_app/function_pov_ui.py +1749 -0
- python_app/i18n.py +570 -0
- python_app/installer.nsi +70 -0
- python_app/installer_runtime.nsi +70 -0
- python_app/js_analysis.py +709 -0
- python_app/launch.py +6 -0
- python_app/launch_native.py +14 -0
- python_app/metrics_advisor.py +79 -0
- python_app/native_app.py +1709 -0
- python_app/requirements.txt +7 -0
- python_app/server.py +453 -0
python_app/server.py
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
"""Local-only HTTP server for the Prism desktop application.
|
|
2
|
+
|
|
3
|
+
Serves the static Prism frontend and provides the same stateless AI proxy
|
|
4
|
+
contract as the original Node server. Standard library only, so it can be
|
|
5
|
+
bundled with PyInstaller without a runtime dependency on Python or Node.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import mimetypes
|
|
12
|
+
import socket
|
|
13
|
+
import ssl
|
|
14
|
+
import sys
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
import urllib.error
|
|
18
|
+
import urllib.parse
|
|
19
|
+
import urllib.request
|
|
20
|
+
from http import HTTPStatus
|
|
21
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
if __package__ in {None, ""}:
|
|
26
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
27
|
+
|
|
28
|
+
from python_app.analysis import analyze_python
|
|
29
|
+
|
|
30
|
+
APP_VERSION = "1.0.0"
|
|
31
|
+
AI_TIMEOUT_SECONDS = 120
|
|
32
|
+
MAX_BODY_BYTES = 2 * 1024 * 1024
|
|
33
|
+
PROVIDERS = {"openai", "deepseek", "grok", "anthropic", "gemini"}
|
|
34
|
+
SECURITY_HEADERS = {
|
|
35
|
+
"X-Content-Type-Options": "nosniff",
|
|
36
|
+
"Referrer-Policy": "no-referrer",
|
|
37
|
+
"X-Frame-Options": "DENY",
|
|
38
|
+
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
|
|
39
|
+
"Content-Security-Policy": (
|
|
40
|
+
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
|
|
41
|
+
"img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; "
|
|
42
|
+
"base-uri 'none'; form-action 'self'; frame-ancestors 'none'"
|
|
43
|
+
),
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ProviderError(Exception):
|
|
48
|
+
def __init__(self, message: str, status: int = 502):
|
|
49
|
+
super().__init__(message)
|
|
50
|
+
self.status = status
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _json_bytes(payload: Any) -> bytes:
|
|
54
|
+
return json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _string(value: Any) -> str:
|
|
58
|
+
return value if isinstance(value, str) else ""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _limit(value: Any, maximum: int) -> str:
|
|
62
|
+
return str(value or "")[:maximum]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _clamp(value: Any, low: float, high: float, fallback: float) -> float:
|
|
66
|
+
try:
|
|
67
|
+
number = float(value)
|
|
68
|
+
except (TypeError, ValueError):
|
|
69
|
+
return fallback
|
|
70
|
+
return min(high, max(low, number))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _openai_endpoint(base_url: str) -> str:
|
|
74
|
+
clean = base_url.rstrip("/")
|
|
75
|
+
if clean.endswith("/chat/completions"):
|
|
76
|
+
return clean
|
|
77
|
+
parsed = urllib.parse.urlsplit(clean)
|
|
78
|
+
if not parsed.path or parsed.path == "/":
|
|
79
|
+
suffix = "/v1/chat/completions" if parsed.hostname == "api.openai.com" else "/chat/completions"
|
|
80
|
+
return clean + suffix
|
|
81
|
+
return clean + "/chat/completions"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _append_path(base_url: str, suffix: str) -> str:
|
|
85
|
+
clean = base_url.rstrip("/")
|
|
86
|
+
if clean.endswith("/" + suffix):
|
|
87
|
+
return clean
|
|
88
|
+
if clean.endswith("/v1") and suffix.startswith("v1/"):
|
|
89
|
+
return clean + "/" + suffix[3:]
|
|
90
|
+
return clean + "/" + suffix
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _extract_error(data: Any) -> str:
|
|
94
|
+
if not isinstance(data, dict):
|
|
95
|
+
return ""
|
|
96
|
+
error = data.get("error")
|
|
97
|
+
if isinstance(error, str):
|
|
98
|
+
return error
|
|
99
|
+
if isinstance(error, dict) and isinstance(error.get("message"), str):
|
|
100
|
+
return error["message"]
|
|
101
|
+
if isinstance(data.get("message"), str):
|
|
102
|
+
return data["message"]
|
|
103
|
+
for key in ("errors",):
|
|
104
|
+
values = data.get(key)
|
|
105
|
+
if isinstance(values, list) and values and isinstance(values[0], dict):
|
|
106
|
+
if isinstance(values[0].get("message"), str):
|
|
107
|
+
return values[0]["message"]
|
|
108
|
+
if isinstance(error, dict) and isinstance(error.get("errors"), list):
|
|
109
|
+
values = error["errors"]
|
|
110
|
+
if values and isinstance(values[0], dict) and isinstance(values[0].get("message"), str):
|
|
111
|
+
return values[0]["message"]
|
|
112
|
+
return ""
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _fetch_provider(endpoint: str, headers: dict[str, str], body: dict[str, Any]) -> dict[str, Any]:
|
|
116
|
+
request = urllib.request.Request(
|
|
117
|
+
endpoint,
|
|
118
|
+
data=_json_bytes(body),
|
|
119
|
+
headers={"Content-Type": "application/json", **headers},
|
|
120
|
+
method="POST",
|
|
121
|
+
)
|
|
122
|
+
try:
|
|
123
|
+
with urllib.request.urlopen(request, timeout=AI_TIMEOUT_SECONDS) as response:
|
|
124
|
+
raw = response.read().decode("utf-8", errors="replace")
|
|
125
|
+
status = response.status
|
|
126
|
+
except urllib.error.HTTPError as error:
|
|
127
|
+
raw = error.read().decode("utf-8", errors="replace")
|
|
128
|
+
status = error.code
|
|
129
|
+
except (urllib.error.URLError, socket.timeout, TimeoutError) as error:
|
|
130
|
+
reason = getattr(error, "reason", error)
|
|
131
|
+
raise ProviderError(
|
|
132
|
+
f"Could not reach the provider at {urllib.parse.urlsplit(endpoint).netloc or 'the configured endpoint'}. "
|
|
133
|
+
"Check the base URL and your network connection."
|
|
134
|
+
) from error
|
|
135
|
+
try:
|
|
136
|
+
data = json.loads(raw) if raw else {}
|
|
137
|
+
except json.JSONDecodeError as error:
|
|
138
|
+
message = "The provider returned a response that was not valid JSON."
|
|
139
|
+
if status >= 400:
|
|
140
|
+
message = f"The provider returned HTTP {status} with a non-JSON error body."
|
|
141
|
+
raise ProviderError(message, status if 400 <= status < 600 else 502) from error
|
|
142
|
+
if status < 200 or status >= 300:
|
|
143
|
+
message = _extract_error(data) or f"The provider returned HTTP {status}."
|
|
144
|
+
raise ProviderError(message, status)
|
|
145
|
+
return data if isinstance(data, dict) else {}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _call_openai(provider: str, base_url: str, api_key: str, model: str, system: str,
|
|
149
|
+
messages: list[dict[str, str]], temperature: float, max_tokens: int) -> dict[str, Any]:
|
|
150
|
+
endpoint = _openai_endpoint(base_url)
|
|
151
|
+
gpt6 = provider == "openai" and model.lower().startswith("gpt-6")
|
|
152
|
+
request_messages = []
|
|
153
|
+
if system:
|
|
154
|
+
request_messages.append({"role": "developer" if gpt6 else "system", "content": system})
|
|
155
|
+
request_messages.extend(messages)
|
|
156
|
+
body: dict[str, Any] = {"model": model, "messages": request_messages, "stream": False}
|
|
157
|
+
if gpt6:
|
|
158
|
+
body["max_completion_tokens"] = max_tokens
|
|
159
|
+
else:
|
|
160
|
+
body["temperature"] = temperature
|
|
161
|
+
body["max_tokens"] = max_tokens
|
|
162
|
+
headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
|
|
163
|
+
data = _fetch_provider(endpoint, headers, body)
|
|
164
|
+
choices = data.get("choices") if isinstance(data.get("choices"), list) else []
|
|
165
|
+
content = choices[0].get("message", {}).get("content") if choices and isinstance(choices[0], dict) else ""
|
|
166
|
+
if isinstance(content, list):
|
|
167
|
+
content = "".join(part if isinstance(part, str) else part.get("text", "") for part in content)
|
|
168
|
+
if not isinstance(content, str):
|
|
169
|
+
content = choices[0].get("text", "") if choices and isinstance(choices[0], dict) else ""
|
|
170
|
+
text = str(content or "").strip()
|
|
171
|
+
if not text:
|
|
172
|
+
raise ProviderError("The provider returned an empty response.")
|
|
173
|
+
return {"text": text, "usage": data.get("usage")}
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _call_anthropic(base_url: str, api_key: str, model: str, system: str,
|
|
177
|
+
messages: list[dict[str, str]], temperature: float, max_tokens: int) -> dict[str, Any]:
|
|
178
|
+
if not api_key:
|
|
179
|
+
raise ProviderError("Anthropic requires an API key.", 400)
|
|
180
|
+
body: dict[str, Any] = {
|
|
181
|
+
"model": model,
|
|
182
|
+
"max_tokens": max_tokens,
|
|
183
|
+
"messages": [
|
|
184
|
+
{"role": "assistant" if message["role"] == "assistant" else "user", "content": message["content"]}
|
|
185
|
+
for message in messages
|
|
186
|
+
],
|
|
187
|
+
}
|
|
188
|
+
if system:
|
|
189
|
+
body["system"] = system
|
|
190
|
+
if not model.lower().startswith(("claude-fable-", "claude-mythos-")):
|
|
191
|
+
body["temperature"] = temperature
|
|
192
|
+
data = _fetch_provider(
|
|
193
|
+
_append_path(base_url, "v1/messages"),
|
|
194
|
+
{"x-api-key": api_key, "anthropic-version": "2023-06-01"},
|
|
195
|
+
body,
|
|
196
|
+
)
|
|
197
|
+
parts = data.get("content") if isinstance(data.get("content"), list) else []
|
|
198
|
+
text = "\n".join(
|
|
199
|
+
str(part.get("text", "")) for part in parts
|
|
200
|
+
if isinstance(part, dict) and part.get("type") == "text"
|
|
201
|
+
).strip()
|
|
202
|
+
if not text:
|
|
203
|
+
raise ProviderError("Anthropic returned an empty response.")
|
|
204
|
+
return {"text": text, "usage": data.get("usage")}
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _call_gemini(base_url: str, api_key: str, model: str, system: str,
|
|
208
|
+
messages: list[dict[str, str]], temperature: float, max_tokens: int) -> dict[str, Any]:
|
|
209
|
+
if not api_key:
|
|
210
|
+
raise ProviderError("Google Gemini requires an API key.", 400)
|
|
211
|
+
base = base_url.rstrip("/")
|
|
212
|
+
endpoint = base if ":generateContent" in base else (
|
|
213
|
+
f"{base}/v1beta/models/{urllib.parse.quote(model, safe='')}:generateContent"
|
|
214
|
+
f"?key={urllib.parse.quote(api_key, safe='')}"
|
|
215
|
+
)
|
|
216
|
+
body: dict[str, Any] = {
|
|
217
|
+
"contents": [
|
|
218
|
+
{"role": "model" if message["role"] == "assistant" else "user",
|
|
219
|
+
"parts": [{"text": message["content"]}]}
|
|
220
|
+
for message in messages
|
|
221
|
+
],
|
|
222
|
+
"generationConfig": {"temperature": temperature, "maxOutputTokens": max_tokens},
|
|
223
|
+
}
|
|
224
|
+
if system:
|
|
225
|
+
body["systemInstruction"] = {"parts": [{"text": system}]}
|
|
226
|
+
data = _fetch_provider(endpoint, {}, body)
|
|
227
|
+
candidates = data.get("candidates") if isinstance(data.get("candidates"), list) else []
|
|
228
|
+
candidate = candidates[0] if candidates and isinstance(candidates[0], dict) else {}
|
|
229
|
+
content = candidate.get("content") if isinstance(candidate.get("content"), dict) else {}
|
|
230
|
+
parts = content.get("parts") if isinstance(content.get("parts"), list) else []
|
|
231
|
+
text = "".join(
|
|
232
|
+
str(part.get("text", "")) for part in parts
|
|
233
|
+
if isinstance(part, dict) and not part.get("thought")
|
|
234
|
+
).strip()
|
|
235
|
+
if not text:
|
|
236
|
+
reason = data.get("promptFeedback", {}).get("blockReason") or candidate.get("finishReason", "")
|
|
237
|
+
raise ProviderError(f"Gemini blocked the request: {reason}." if reason else "Gemini returned an empty response.")
|
|
238
|
+
return {"text": text, "usage": data.get("usageMetadata")}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _redact(text: str, secret: str) -> str:
|
|
242
|
+
safe = str(text or "")
|
|
243
|
+
if secret:
|
|
244
|
+
safe = safe.replace(secret, "[redacted]")
|
|
245
|
+
return safe[:1000]
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def handle_ai(payload: dict[str, Any]) -> dict[str, Any]:
|
|
249
|
+
provider = _string(payload.get("provider")) or "openai"
|
|
250
|
+
if provider not in PROVIDERS:
|
|
251
|
+
raise ProviderError("Unsupported AI provider. Choose openai, deepseek, grok, anthropic, or gemini.", 400)
|
|
252
|
+
model = _string(payload.get("model")).strip()
|
|
253
|
+
if not model:
|
|
254
|
+
raise ProviderError("A model name is required.", 400)
|
|
255
|
+
base_url = _string(payload.get("baseUrl")).strip()
|
|
256
|
+
if not base_url:
|
|
257
|
+
raise ProviderError("A provider base URL is required.", 400)
|
|
258
|
+
parsed = urllib.parse.urlsplit(base_url)
|
|
259
|
+
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
|
260
|
+
raise ProviderError("The provider base URL must be a valid http:// or https:// URL.", 400)
|
|
261
|
+
raw_messages = payload.get("messages")
|
|
262
|
+
messages = []
|
|
263
|
+
if isinstance(raw_messages, list):
|
|
264
|
+
for message in raw_messages[-20:]:
|
|
265
|
+
if isinstance(message, dict) and message.get("role") in {"user", "assistant"}:
|
|
266
|
+
content = message.get("content")
|
|
267
|
+
if isinstance(content, str):
|
|
268
|
+
messages.append({"role": message["role"], "content": content[:60_000]})
|
|
269
|
+
if not messages:
|
|
270
|
+
raise ProviderError("At least one message is required.", 400)
|
|
271
|
+
system = _limit(_string(payload.get("system")), 30_000)
|
|
272
|
+
temperature = _clamp(payload.get("temperature"), 0, 1, 0.3)
|
|
273
|
+
max_tokens = round(_clamp(payload.get("maxTokens"), 64, 8000, 2600))
|
|
274
|
+
started = time.monotonic()
|
|
275
|
+
try:
|
|
276
|
+
if provider == "anthropic":
|
|
277
|
+
result = _call_anthropic(base_url, _string(payload.get("apiKey")), model, system, messages, temperature, max_tokens)
|
|
278
|
+
elif provider == "gemini":
|
|
279
|
+
result = _call_gemini(base_url, _string(payload.get("apiKey")), model, system, messages, temperature, max_tokens)
|
|
280
|
+
else:
|
|
281
|
+
result = _call_openai(provider, base_url, _string(payload.get("apiKey")), model, system, messages, temperature, max_tokens)
|
|
282
|
+
except ProviderError:
|
|
283
|
+
raise
|
|
284
|
+
except Exception as error: # pragma: no cover - defensive network boundary
|
|
285
|
+
raise ProviderError(_redact(str(error), _string(payload.get("apiKey")))) from error
|
|
286
|
+
return {
|
|
287
|
+
"text": result["text"],
|
|
288
|
+
"provider": provider,
|
|
289
|
+
"model": model,
|
|
290
|
+
"usage": result.get("usage"),
|
|
291
|
+
"elapsedMs": int((time.monotonic() - started) * 1000),
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
class PrismHTTPRequestHandler(BaseHTTPRequestHandler):
|
|
296
|
+
server_version = "PrismPython/1.0"
|
|
297
|
+
root: Path
|
|
298
|
+
|
|
299
|
+
def log_message(self, fmt: str, *args: Any) -> None:
|
|
300
|
+
print(f"[prism] {self.address_string()} {fmt % args}")
|
|
301
|
+
|
|
302
|
+
def do_HEAD(self) -> None: # noqa: N802
|
|
303
|
+
self._handle(head=True)
|
|
304
|
+
|
|
305
|
+
def do_GET(self) -> None: # noqa: N802
|
|
306
|
+
self._handle(head=False)
|
|
307
|
+
|
|
308
|
+
def do_POST(self) -> None: # noqa: N802
|
|
309
|
+
parsed = urllib.parse.urlsplit(self.path)
|
|
310
|
+
if parsed.path not in {"/api/ai", "/api/analyze-python"}:
|
|
311
|
+
self._json(HTTPStatus.NOT_FOUND, {"error": "Unknown API route."})
|
|
312
|
+
return
|
|
313
|
+
try:
|
|
314
|
+
length = int(self.headers.get("Content-Length", "0"))
|
|
315
|
+
if length <= 0:
|
|
316
|
+
raise ProviderError("Request body is required.", 400)
|
|
317
|
+
if length > MAX_BODY_BYTES:
|
|
318
|
+
raise ProviderError("Request body is too large.", 413)
|
|
319
|
+
raw = self.rfile.read(length)
|
|
320
|
+
try:
|
|
321
|
+
payload = json.loads(raw.decode("utf-8"))
|
|
322
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
|
323
|
+
raise ProviderError("Request body must be valid JSON.", 400) from error
|
|
324
|
+
if not isinstance(payload, dict):
|
|
325
|
+
raise ProviderError("Request body must be a JSON object.", 400)
|
|
326
|
+
if parsed.path == "/api/analyze-python":
|
|
327
|
+
source = payload.get("source")
|
|
328
|
+
if not isinstance(source, str) or not source.strip():
|
|
329
|
+
raise ProviderError("A Python source string is required.", 400)
|
|
330
|
+
if len(source) > 60_000:
|
|
331
|
+
raise ProviderError("Python source must stay under 60,000 characters.", 413)
|
|
332
|
+
try:
|
|
333
|
+
result = analyze_python(source)
|
|
334
|
+
except ValueError as error:
|
|
335
|
+
raise ProviderError(str(error), 400) from error
|
|
336
|
+
self._json(HTTPStatus.OK, result)
|
|
337
|
+
else:
|
|
338
|
+
self._json(HTTPStatus.OK, handle_ai(payload))
|
|
339
|
+
except ProviderError as error:
|
|
340
|
+
self._json(error.status, {"error": str(error)})
|
|
341
|
+
except Exception as error: # pragma: no cover
|
|
342
|
+
print(f"[prism] request failed: {error}")
|
|
343
|
+
self._json(HTTPStatus.BAD_GATEWAY, {"error": "The local Python service could not complete this request."})
|
|
344
|
+
|
|
345
|
+
def _handle(self, *, head: bool) -> None:
|
|
346
|
+
parsed = urllib.parse.urlsplit(self.path)
|
|
347
|
+
if parsed.path == "/api/health":
|
|
348
|
+
self._json(HTTPStatus.OK, {"ok": True, "app": "prism", "version": APP_VERSION, "proxy": True}, head=head)
|
|
349
|
+
return
|
|
350
|
+
if parsed.path.startswith("/api/"):
|
|
351
|
+
self._json(HTTPStatus.NOT_FOUND, {"error": "Unknown API route."}, head=head)
|
|
352
|
+
return
|
|
353
|
+
if self.command not in {"GET", "HEAD"}:
|
|
354
|
+
self.send_response(HTTPStatus.METHOD_NOT_ALLOWED)
|
|
355
|
+
self.send_header("Allow", "GET, HEAD")
|
|
356
|
+
self.end_headers()
|
|
357
|
+
return
|
|
358
|
+
self._serve_static(parsed.path, head=head)
|
|
359
|
+
|
|
360
|
+
def _serve_static(self, raw_path: str, *, head: bool) -> None:
|
|
361
|
+
try:
|
|
362
|
+
decoded = urllib.parse.unquote(raw_path, errors="strict")
|
|
363
|
+
except UnicodeDecodeError:
|
|
364
|
+
self.send_response(HTTPStatus.BAD_REQUEST)
|
|
365
|
+
self.end_headers()
|
|
366
|
+
return
|
|
367
|
+
relative = "index.html" if decoded == "/" else decoded.lstrip("/")
|
|
368
|
+
root = self.root.resolve()
|
|
369
|
+
candidate = (root / relative).resolve()
|
|
370
|
+
try:
|
|
371
|
+
candidate.relative_to(root)
|
|
372
|
+
except ValueError:
|
|
373
|
+
self.send_response(HTTPStatus.FORBIDDEN)
|
|
374
|
+
self.end_headers()
|
|
375
|
+
return
|
|
376
|
+
if candidate.is_dir():
|
|
377
|
+
candidate = candidate / "index.html"
|
|
378
|
+
if not candidate.exists() and not Path(relative).suffix:
|
|
379
|
+
candidate = root / "index.html"
|
|
380
|
+
if not candidate.is_file():
|
|
381
|
+
self.send_response(HTTPStatus.NOT_FOUND)
|
|
382
|
+
self.send_header("Content-Type", "text/plain; charset=utf-8")
|
|
383
|
+
self.end_headers()
|
|
384
|
+
if not head:
|
|
385
|
+
self.wfile.write(b"Not found")
|
|
386
|
+
return
|
|
387
|
+
try:
|
|
388
|
+
body = candidate.read_bytes()
|
|
389
|
+
except OSError:
|
|
390
|
+
self.send_response(HTTPStatus.NOT_FOUND)
|
|
391
|
+
self.end_headers()
|
|
392
|
+
return
|
|
393
|
+
content_type = mimetypes.guess_type(str(candidate))[0] or "application/octet-stream"
|
|
394
|
+
if content_type.startswith("text/") or content_type in {"application/javascript", "application/json"}:
|
|
395
|
+
content_type += "; charset=utf-8"
|
|
396
|
+
self.send_response(HTTPStatus.OK)
|
|
397
|
+
self.send_header("Content-Type", content_type)
|
|
398
|
+
self.send_header("Content-Length", str(len(body)))
|
|
399
|
+
self.send_header("Cache-Control", "no-store")
|
|
400
|
+
for key, value in SECURITY_HEADERS.items():
|
|
401
|
+
self.send_header(key, value)
|
|
402
|
+
self.end_headers()
|
|
403
|
+
if not head:
|
|
404
|
+
self.wfile.write(body)
|
|
405
|
+
|
|
406
|
+
def _json(self, status: int, payload: Any, *, head: bool = False) -> None:
|
|
407
|
+
body = _json_bytes(payload)
|
|
408
|
+
self.send_response(status)
|
|
409
|
+
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
410
|
+
self.send_header("Content-Length", str(len(body)))
|
|
411
|
+
self.send_header("Cache-Control", "no-store")
|
|
412
|
+
self.send_header("X-Content-Type-Options", "nosniff")
|
|
413
|
+
self.end_headers()
|
|
414
|
+
if not head:
|
|
415
|
+
self.wfile.write(body)
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def create_server(root: Path, host: str = "127.0.0.1", port: int = 0) -> ThreadingHTTPServer:
|
|
419
|
+
root = Path(root).resolve()
|
|
420
|
+
handler = type("PrismHandler", (PrismHTTPRequestHandler,), {"root": root})
|
|
421
|
+
server = ThreadingHTTPServer((host, port), handler)
|
|
422
|
+
server.daemon_threads = True
|
|
423
|
+
return server
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def start_server(root: Path, host: str = "127.0.0.1", port: int = 0) -> tuple[ThreadingHTTPServer, str]:
|
|
427
|
+
server = create_server(root, host, port)
|
|
428
|
+
thread = threading.Thread(target=server.serve_forever, name="prism-http", daemon=True)
|
|
429
|
+
thread.start()
|
|
430
|
+
actual_port = server.server_address[1]
|
|
431
|
+
return server, f"http://{host}:{actual_port}"
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def stop_server(server: ThreadingHTTPServer) -> None:
|
|
435
|
+
server.shutdown()
|
|
436
|
+
server.server_close()
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
if __name__ == "__main__":
|
|
440
|
+
import argparse
|
|
441
|
+
|
|
442
|
+
parser = argparse.ArgumentParser(description="Run the Prism local server.")
|
|
443
|
+
parser.add_argument("--root", default=str(Path(__file__).resolve().parent.parent))
|
|
444
|
+
parser.add_argument("--port", type=int, default=4173)
|
|
445
|
+
args = parser.parse_args()
|
|
446
|
+
srv, url = start_server(Path(args.root), port=args.port)
|
|
447
|
+
print(f"Prism local app: {url}")
|
|
448
|
+
try:
|
|
449
|
+
threading.Event().wait()
|
|
450
|
+
except KeyboardInterrupt:
|
|
451
|
+
pass
|
|
452
|
+
finally:
|
|
453
|
+
stop_server(srv)
|