cloudsprite 0.11.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.
Files changed (70) hide show
  1. cloudsprite/__init__.py +451 -0
  2. cloudsprite/_antenna.py +83 -0
  3. cloudsprite/_auth.py +295 -0
  4. cloudsprite/_client.py +502 -0
  5. cloudsprite/_config.py +203 -0
  6. cloudsprite/_consent.py +104 -0
  7. cloudsprite/_context.py +945 -0
  8. cloudsprite/_exceptions.py +136 -0
  9. cloudsprite/_figure_models.py +158 -0
  10. cloudsprite/_figure_validation.py +168 -0
  11. cloudsprite/_filter_foster.py +165 -0
  12. cloudsprite/_filter_synthesis.py +400 -0
  13. cloudsprite/_filtering.py +134 -0
  14. cloudsprite/_impedance_matching.py +262 -0
  15. cloudsprite/_interpolation.py +47 -0
  16. cloudsprite/_lineage.py +775 -0
  17. cloudsprite/_link_budget.py +99 -0
  18. cloudsprite/_logging.py +53 -0
  19. cloudsprite/_mixed_mode.py +49 -0
  20. cloudsprite/_monte_carlo.py +193 -0
  21. cloudsprite/_noise_figure.py +44 -0
  22. cloudsprite/_pagination.py +130 -0
  23. cloudsprite/_parsers.py +75 -0
  24. cloudsprite/_publish.py +162 -0
  25. cloudsprite/_redact.py +179 -0
  26. cloudsprite/_response.py +63 -0
  27. cloudsprite/_resultset.py +65 -0
  28. cloudsprite/_rf_network.py +111 -0
  29. cloudsprite/_run_config.py +46 -0
  30. cloudsprite/_script_runner.py +217 -0
  31. cloudsprite/_script_workspace.py +271 -0
  32. cloudsprite/_sparameter_metrics.py +75 -0
  33. cloudsprite/_tdr.py +283 -0
  34. cloudsprite/_trace.py +112 -0
  35. cloudsprite/_version.py +23 -0
  36. cloudsprite/_visualizer.py +380 -0
  37. cloudsprite/_visualizer_cli.py +412 -0
  38. cloudsprite/_visualizer_preview.py +864 -0
  39. cloudsprite/_work_context.py +116 -0
  40. cloudsprite/_ws.py +577 -0
  41. cloudsprite/cli.py +300 -0
  42. cloudsprite/py.typed +0 -0
  43. cloudsprite/resources/__init__.py +1 -0
  44. cloudsprite/resources/_base.py +293 -0
  45. cloudsprite/resources/_models.py +50 -0
  46. cloudsprite/resources/cloudscripts.py +173 -0
  47. cloudsprite/resources/datasets.py +431 -0
  48. cloudsprite/resources/figures.py +282 -0
  49. cloudsprite/resources/instruments.py +295 -0
  50. cloudsprite/resources/notebooks.py +183 -0
  51. cloudsprite/resources/orbs.py +99 -0
  52. cloudsprite/resources/parameters.py +77 -0
  53. cloudsprite/resources/projects.py +182 -0
  54. cloudsprite/resources/related.py +125 -0
  55. cloudsprite/resources/reports.py +992 -0
  56. cloudsprite/resources/search.py +245 -0
  57. cloudsprite/resources/shares.py +229 -0
  58. cloudsprite/resources/sprites.py +15 -0
  59. cloudsprite/resources/tags.py +107 -0
  60. cloudsprite/resources/teams.py +86 -0
  61. cloudsprite/resources/traces.py +147 -0
  62. cloudsprite/resources/usage.py +152 -0
  63. cloudsprite/resources/visualizer_templates.py +466 -0
  64. cloudsprite/resources/workflows.py +59 -0
  65. cloudsprite-0.11.0.dist-info/METADATA +358 -0
  66. cloudsprite-0.11.0.dist-info/RECORD +70 -0
  67. cloudsprite-0.11.0.dist-info/WHEEL +5 -0
  68. cloudsprite-0.11.0.dist-info/entry_points.txt +3 -0
  69. cloudsprite-0.11.0.dist-info/licenses/LICENSE +21 -0
  70. cloudsprite-0.11.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,864 @@
1
+ """Local preview server for visualizer templates (``cloudsprite visualizer preview``).
2
+
3
+ The server renders a template file the way the app does, minus the network:
4
+
5
+ * the template runs in an ``<iframe sandbox="allow-scripts">`` (opaque origin: no
6
+ cookies, storage or parent access) and is served with the user-content origin's
7
+ CSP (``connect-src 'none'``, ``form-action 'none'``, images from ``data:``/``blob:``
8
+ only, scripts, styles and fonts from the user-content origin only), so a template
9
+ cannot fetch or post to your network or reach the page that hosts it. The CSP does not stop the frame navigating itself (``location = ...``, a
10
+ link or a meta refresh), so a hostile template could still send a request to an
11
+ external URL by navigating; preview only templates you trust;
12
+ * the real ``cs.js`` guest runtime and engine libraries are fetched from the
13
+ environment's user-content origin and served at ``/lib/<id>@<version>/<file>``,
14
+ verified against the API's lib manifest when the library is listed there;
15
+ * data reaches the template through the runtime's offline envelope
16
+ (``window.__CS_OFFLINE__``), so ``cs.data()`` selects and downsamples exactly as the
17
+ host does. The envelope is inlined into the served document; the template never
18
+ talks to this server for data.
19
+
20
+ The server binds to 127.0.0.1 only, refuses requests whose ``Host`` header is not a loopback name for its
21
+ own port (DNS rebinding), and requires a per-run random access key (``?k=``) on the host page and the
22
+ template frame, which carry your data, so another user on the same machine cannot read them. ``/lib/``
23
+ only serves public library files and needs no key.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import base64
29
+ import hashlib
30
+ import hmac
31
+ import html
32
+ import json
33
+ import math
34
+ import re
35
+ import secrets
36
+ import sys
37
+ import threading
38
+ from collections.abc import Callable
39
+ from dataclasses import dataclass, field
40
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
41
+ from pathlib import Path
42
+ from typing import Any
43
+ from urllib.parse import parse_qs, urlparse
44
+
45
+ import numpy as np
46
+
47
+ from cloudsprite._exceptions import APIError, ValidationError, validate_id
48
+ from cloudsprite._visualizer import CTS_VERSION, check_source, parse_manifest, scan_scripts
49
+
50
+ SURFACES = ("interactive", "compact", "thumbnail", "print", "public", "export")
51
+ THEMES = ("light", "dark")
52
+ LOOPBACK = "127.0.0.1"
53
+ MAX_SOURCE_BYTES = 8 * 1024 * 1024
54
+ MAX_LIB_BYTES = 16 * 1024 * 1024
55
+ MAX_TOTAL_POINTS = 2_000_000
56
+ MAX_SERIES_POINTS = 100_000
57
+
58
+ # Mirrors the runtime's per-surface budgets (cs-runtime limits.ts, CTS section 10).
59
+ _SURFACE_LIMITS: dict[str, dict[str, int]] = {
60
+ "interactive": {"maxPoints": 10_000, "maxSeries": 51, "maxPointsPerRequest": 20_000},
61
+ "compact": {"maxPoints": 2_000, "maxSeries": 51, "maxPointsPerRequest": 20_000},
62
+ "thumbnail": {"maxPoints": 2_000, "maxSeries": 51, "maxPointsPerRequest": 20_000},
63
+ "print": {"maxPoints": 5_000, "maxSeries": 51, "maxPointsPerRequest": 20_000},
64
+ "export": {"maxPoints": 5_000, "maxSeries": 51, "maxPointsPerRequest": 20_000},
65
+ "public": {"maxPoints": 2_000, "maxSeries": 16, "maxPointsPerRequest": 2_000},
66
+ }
67
+ _SURFACE_SIZE: dict[str, tuple[int, int]] = {
68
+ "interactive": (960, 560),
69
+ "compact": (480, 300),
70
+ "thumbnail": (320, 200),
71
+ "print": (794, 560),
72
+ "public": (960, 560),
73
+ "export": (960, 560),
74
+ }
75
+
76
+ _FONT = "system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif"
77
+ _MONO = "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"
78
+ _PALETTE = [
79
+ "#2f7ed8",
80
+ "#e8743b",
81
+ "#19a979",
82
+ "#945ecf",
83
+ "#13a4b4",
84
+ "#ed4a7b",
85
+ "#a8a826",
86
+ "#6c8893",
87
+ "#ee6868",
88
+ "#7b5fe0",
89
+ ]
90
+ _THEME_TOKENS = {
91
+ "light": {
92
+ "--cs-bg": "#ffffff",
93
+ "--cs-surface": "#f5f6f8",
94
+ "--cs-fg": "#1a1f29",
95
+ "--cs-fg-muted": "#5b6472",
96
+ "--cs-grid": "#e1e4ea",
97
+ "--cs-axis": "#b4bac6",
98
+ "--cs-border": "#d6dae2",
99
+ "--cs-accent": "#2f7ed8",
100
+ "--cs-danger": "#c8302f",
101
+ },
102
+ "dark": {
103
+ "--cs-bg": "#14181f",
104
+ "--cs-surface": "#1c222c",
105
+ "--cs-fg": "#e6e9ef",
106
+ "--cs-fg-muted": "#9aa3b2",
107
+ "--cs-grid": "#2a313d",
108
+ "--cs-axis": "#4a5465",
109
+ "--cs-border": "#303846",
110
+ "--cs-accent": "#6aa9f0",
111
+ "--cs-danger": "#f1888b",
112
+ },
113
+ }
114
+
115
+ _LIB_PATH_RE = re.compile(r"^/lib/(?P<id>[a-z0-9][a-z0-9-]*)@(?P<version>\d+\.\d+\.\d+)/(?P<file>[A-Za-z0-9._-]+)$")
116
+ _ORIGIN_RE = re.compile(r"^https://(dev|staging|prod)\.cloudsprite-usercontent\.io$")
117
+ _CONTENT_TYPES = {
118
+ ".js": "text/javascript; charset=utf-8",
119
+ ".mjs": "text/javascript; charset=utf-8",
120
+ ".css": "text/css; charset=utf-8",
121
+ ".json": "application/json",
122
+ ".wasm": "application/wasm",
123
+ }
124
+ # API hosts and the user-content origin that serves their libraries.
125
+ _ENV_BY_HOST = {
126
+ "dev.cloudsprite.io": "dev",
127
+ "api.dev.cloudsprite.io": "dev",
128
+ "staging.cloudsprite.io": "staging",
129
+ "api.staging.cloudsprite.io": "staging",
130
+ "cloudsprite.io": "prod",
131
+ "api.cloudsprite.io": "prod",
132
+ "localhost": "dev",
133
+ "127.0.0.1": "dev",
134
+ }
135
+
136
+
137
+ def usercontent_origin(base_url: str) -> str:
138
+ """The user-content origin for the environment an API ``base_url`` belongs to."""
139
+ host = (urlparse(base_url).hostname or "").lower()
140
+ env = _ENV_BY_HOST.get(host)
141
+ if env is None:
142
+ raise ValidationError(
143
+ f"Cannot tell which environment {host or base_url!r} belongs to, so there is no user-content "
144
+ "origin to load the visualizer runtime from. Point the SDK at an environment API "
145
+ "(for example `cloudsprite init --base-url https://dev.cloudsprite.io`)."
146
+ )
147
+ return f"https://{env}.cloudsprite-usercontent.io"
148
+
149
+
150
+ # --------------------------------------------------------------------------- data
151
+
152
+
153
+ @dataclass
154
+ class PreviewData:
155
+ """Channels and arrays to preview, in the runtime's offline-envelope vocabulary."""
156
+
157
+ label: str
158
+ channels: list[dict[str, Any]]
159
+ series: list[dict[str, Any]]
160
+ params: dict[str, Any] = field(default_factory=dict)
161
+ files: list[dict[str, Any]] = field(default_factory=list)
162
+ meta: dict[str, Any] = field(default_factory=dict)
163
+ target: dict[str, Any] = field(default_factory=lambda: {"type": "dataset", "name": "Preview"})
164
+ notes: list[str] = field(default_factory=list)
165
+
166
+
167
+ def _b64(values: Any) -> str:
168
+ return base64.b64encode(np.asarray(values, dtype="<f8").tobytes()).decode("ascii")
169
+
170
+
171
+ def _range(values: np.ndarray) -> list[float] | None:
172
+ finite = values[np.isfinite(values)]
173
+ return [float(finite.min()), float(finite.max())] if finite.size else None
174
+
175
+
176
+ def domain_for_unit(x_unit: str | None) -> str:
177
+ """Channel domain from the x-axis unit."""
178
+ unit = (x_unit or "").strip().lower()
179
+ if unit in {"hz", "khz", "mhz", "ghz", "thz"}:
180
+ return "frequency"
181
+ if unit in {"s", "sec", "ms", "us", "µs", "ns", "ps"}:
182
+ return "time"
183
+ if unit in {"m", "mm", "cm", "km", "in", "ft"}:
184
+ return "distance"
185
+ return "other"
186
+
187
+
188
+ def _channel(
189
+ channel_id: str,
190
+ label: str,
191
+ x: np.ndarray,
192
+ y: np.ndarray,
193
+ *,
194
+ x_unit: str | None,
195
+ y_unit: str | None,
196
+ domain: str | None = None,
197
+ quantity: str | None = None,
198
+ physical_kind: str | None = None,
199
+ total_points: int | None = None,
200
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
201
+ total = int(total_points if total_points is not None else x.size)
202
+ channel: dict[str, Any] = {
203
+ "id": channel_id,
204
+ "label": label,
205
+ "domain": domain or domain_for_unit(x_unit),
206
+ "xUnit": x_unit or None,
207
+ "yUnit": y_unit or None,
208
+ "xLabel": None,
209
+ "yLabel": None,
210
+ "quantity": quantity,
211
+ "physicalKind": physical_kind,
212
+ "points": total,
213
+ "xRange": _range(x),
214
+ "yRange": _range(y),
215
+ }
216
+ series = {
217
+ "id": channel_id,
218
+ "x": _b64(x),
219
+ "y": _b64(y),
220
+ "level": 0,
221
+ "method": "raw",
222
+ "envelope": False,
223
+ "totalPoints": total,
224
+ }
225
+ return channel, series
226
+
227
+
228
+ def sample_data(kind: str = "sparameters") -> PreviewData:
229
+ """Deterministic synthetic data: ``sparameters`` (frequency sweep, dB) or ``time-domain`` (volts)."""
230
+ rng = np.random.default_rng(7)
231
+ channels: list[dict[str, Any]] = []
232
+ series: list[dict[str, Any]] = []
233
+ if kind == "sparameters":
234
+ freq = np.linspace(1e9, 10e9, 801)
235
+ f0 = 5.5e9
236
+ s21 = -1.0 - 8.0 * ((freq - f0) / 3.0e9) ** 2 - 0.4 * np.sin(freq / 4e8) + rng.normal(0, 0.05, freq.size)
237
+ s11 = -12.0 - 10.0 * np.exp(-(((freq - f0) / 0.9e9) ** 2)) + rng.normal(0, 0.15, freq.size)
238
+ s22 = -14.0 - 7.0 * np.exp(-(((freq - f0 * 1.05) / 1.1e9) ** 2)) + rng.normal(0, 0.15, freq.size)
239
+ for name, values in (("S21", s21), ("S11", s11), ("S22", s22)):
240
+ ch, se = _channel(
241
+ f"sample:{name}",
242
+ name,
243
+ freq,
244
+ values,
245
+ x_unit="Hz",
246
+ y_unit="dB",
247
+ quantity="s_parameter",
248
+ physical_kind="s_parameter",
249
+ )
250
+ ch["xLabel"], ch["yLabel"] = "Frequency", f"{name} magnitude"
251
+ channels.append(ch)
252
+ series.append(se)
253
+ label = "sample data: S-parameter magnitude sweep (S11, S21, S22)"
254
+ meta = {"name": "Sample S-parameters", "tags": ["sample"], "source_type": "sample"}
255
+ elif kind == "time-domain":
256
+ t = np.linspace(0.0, 2e-6, 2001)
257
+ clock = 0.5 + 0.5 * np.sign(np.sin(2 * np.pi * 2.5e6 * t))
258
+ smooth = 1.0 + 0.9 * np.sin(2 * np.pi * 1.2e6 * t) * np.exp(-t / 1.4e-6) + rng.normal(0, 0.01, t.size)
259
+ for name, values in (("CH1", smooth), ("CH2", clock * 3.3)):
260
+ ch, se = _channel(f"sample:{name}", name, t, values, x_unit="s", y_unit="V", quantity="voltage")
261
+ ch["xLabel"], ch["yLabel"] = "Time", f"{name} voltage"
262
+ channels.append(ch)
263
+ series.append(se)
264
+ label = "sample data: two oscilloscope channels"
265
+ meta = {"name": "Sample waveforms", "tags": ["sample"], "source_type": "sample"}
266
+ else:
267
+ raise ValidationError("sample must be 'sparameters' or 'time-domain'")
268
+ files = [
269
+ {
270
+ "id": "sample-file",
271
+ "name": "sample.csv",
272
+ "type": "csv",
273
+ "sizeBytes": 0,
274
+ "channelIds": [c["id"] for c in channels],
275
+ }
276
+ ]
277
+ return PreviewData(
278
+ label=label,
279
+ channels=channels,
280
+ series=series,
281
+ files=files,
282
+ meta=meta,
283
+ target={"type": "dataset", "name": meta["name"]},
284
+ )
285
+
286
+
287
+ def file_data(path: Path) -> PreviewData:
288
+ """Load ``{"title": ..., "channels": [{"label", "x": [...], "y": [...], "xUnit", "yUnit", ...}]}``."""
289
+ try:
290
+ raw = json.loads(path.read_text(encoding="utf-8"))
291
+ except (OSError, ValueError) as exc:
292
+ raise ValidationError(f"Cannot read data file {path}: {exc}") from None
293
+ entries = raw.get("channels") if isinstance(raw, dict) else None
294
+ if not isinstance(entries, list) or not entries:
295
+ raise ValidationError('Data file must be a JSON object with a non-empty "channels" array.')
296
+ channels: list[dict[str, Any]] = []
297
+ series: list[dict[str, Any]] = []
298
+ for index, entry in enumerate(entries[:51]):
299
+ if not isinstance(entry, dict):
300
+ raise ValidationError(f"channels[{index}] must be an object")
301
+ try:
302
+ x = np.asarray(entry["x"], dtype=float)
303
+ y = np.asarray(entry["y"], dtype=float)
304
+ except (KeyError, TypeError, ValueError):
305
+ raise ValidationError(f'channels[{index}] needs numeric "x" and "y" arrays') from None
306
+ if x.ndim != 1 or x.shape != y.shape or x.size == 0:
307
+ raise ValidationError(f'channels[{index}] "x" and "y" must be non-empty arrays of equal length')
308
+ label = str(entry.get("label") or f"Channel {index + 1}")
309
+ ch, se = _channel(
310
+ f"file:{index}",
311
+ label,
312
+ x,
313
+ y,
314
+ x_unit=entry.get("xUnit"),
315
+ y_unit=entry.get("yUnit"),
316
+ domain=entry.get("domain") if entry.get("domain") in {"frequency", "time", "distance", "other"} else None,
317
+ quantity=entry.get("quantity"),
318
+ physical_kind=entry.get("physicalKind"),
319
+ )
320
+ ch["xLabel"], ch["yLabel"] = entry.get("xLabel"), entry.get("yLabel")
321
+ channels.append(ch)
322
+ series.append(se)
323
+ title = str(raw.get("title") or path.stem)
324
+ return PreviewData(
325
+ label=f"data file: {path.name}",
326
+ channels=channels,
327
+ series=series,
328
+ files=[
329
+ {
330
+ "id": "file",
331
+ "name": path.name,
332
+ "type": "json",
333
+ "sizeBytes": path.stat().st_size,
334
+ "channelIds": [c["id"] for c in channels],
335
+ }
336
+ ],
337
+ meta={"name": title, "tags": [], "source_type": "file"},
338
+ target={"type": "dataset", "name": title},
339
+ )
340
+
341
+
342
+ def dataset_data(client: Any, dataset_id: str, *, max_channels: int = 51) -> PreviewData:
343
+ """Download a dataset's traces through the SDK and shape them as channels.
344
+
345
+ Arrays longer than the preview budget are stride-decimated (the channel still reports its full
346
+ point count), so a very large capture previews quickly.
347
+ """
348
+ from cloudsprite.resources.datasets import Dataset
349
+
350
+ dataset_id = validate_id(dataset_id, "dataset_id")
351
+ http = client.client
352
+ dataset = Dataset(http, http.get(f"/api/datasets/{dataset_id}"))
353
+ refs = list(dataset.traces)
354
+ if not refs:
355
+ raise ValidationError(f"Dataset {dataset.name!r} has no traces to preview.")
356
+ notes: list[str] = []
357
+ if len(refs) > max_channels:
358
+ notes.append(f"previewing the first {max_channels} of {len(refs)} traces")
359
+ refs = refs[:max_channels]
360
+ per_series = max(2_000, min(MAX_SERIES_POINTS, MAX_TOTAL_POINTS // len(refs)))
361
+ channels: list[dict[str, Any]] = []
362
+ series: list[dict[str, Any]] = []
363
+ decimated = 0
364
+ for ref in refs:
365
+ try:
366
+ x = np.asarray(ref.x, dtype=float)
367
+ y = np.asarray(ref.y, dtype=float)
368
+ except ValueError as exc: # a screenshot or raw file in the dataset, not a plottable trace
369
+ notes.append(f"skipped {ref.name!r}: {exc}")
370
+ continue
371
+ if x.shape != y.shape or x.size == 0:
372
+ notes.append(f"skipped trace {ref.name!r}: no usable samples")
373
+ continue
374
+ total = int(x.size)
375
+ if total > per_series:
376
+ step = math.ceil(total / per_series)
377
+ x, y = x[::step], y[::step]
378
+ decimated += 1
379
+ ch, se = _channel(
380
+ f"{dataset.id}:{ref.id}",
381
+ ref.name,
382
+ x,
383
+ y,
384
+ x_unit=ref.x_unit,
385
+ y_unit=ref.y_unit,
386
+ total_points=total,
387
+ )
388
+ ch["fileType"] = str(ref._data.get("file_type") or "") or None
389
+ channels.append(ch)
390
+ series.append(se)
391
+ if not channels:
392
+ raise ValidationError(f"Dataset {dataset.name!r} has no traces with samples to preview.")
393
+ if decimated:
394
+ notes.append(f"{decimated} long trace(s) decimated to at most {per_series} points for the preview")
395
+ params = {
396
+ str(key): {"label": str(key), "value": value, "unit": None, "display": str(value)}
397
+ for key, value in dataset.params.items()
398
+ }
399
+ return PreviewData(
400
+ label=f"dataset: {dataset.name}",
401
+ channels=channels,
402
+ series=series,
403
+ params=params,
404
+ files=[],
405
+ meta={"name": dataset.name, "tags": [], "source_type": str(dataset._data.get("source_type") or "") or None},
406
+ target={"type": "dataset", "name": dataset.name},
407
+ notes=notes,
408
+ )
409
+
410
+
411
+ def default_sample_kind(manifest: dict[str, Any] | None) -> str:
412
+ """Pick the sample family from the manifest's ``accepts.domains`` (default S-parameters)."""
413
+ accepts = (manifest or {}).get("accepts")
414
+ domains = accepts.get("domains") if isinstance(accepts, dict) else None
415
+ if isinstance(domains, list) and "time" in domains and "frequency" not in domains:
416
+ return "time-domain"
417
+ return "sparameters"
418
+
419
+
420
+ # --------------------------------------------------------------------------- document
421
+
422
+
423
+ def option_defaults(manifest: dict[str, Any] | None) -> dict[str, Any]:
424
+ """Default option values from the manifest ``options`` schema."""
425
+ options = (manifest or {}).get("options")
426
+ props = options.get("properties") if isinstance(options, dict) else None
427
+ if not isinstance(props, dict):
428
+ return {}
429
+ return {k: v["default"] for k, v in props.items() if isinstance(v, dict) and "default" in v}
430
+
431
+
432
+ def build_envelope(
433
+ data: PreviewData,
434
+ *,
435
+ manifest: dict[str, Any] | None,
436
+ surface: str,
437
+ theme: str,
438
+ size: tuple[int, int] | None = None,
439
+ ) -> dict[str, Any]:
440
+ """The runtime's ``window.__CS_OFFLINE__`` envelope (version 1)."""
441
+ if surface not in SURFACES:
442
+ raise ValidationError(f"surface must be one of {', '.join(SURFACES)}")
443
+ if theme not in THEMES:
444
+ raise ValidationError(f"theme must be one of {', '.join(THEMES)}")
445
+ width, height = size or _SURFACE_SIZE[surface]
446
+ tokens = dict(_THEME_TOKENS[theme])
447
+ tokens["--cs-font"] = _FONT
448
+ tokens["--cs-font-mono"] = _MONO
449
+ for index, color in enumerate(_PALETTE, start=1):
450
+ tokens[f"--cs-series-{index}"] = color
451
+ init = {
452
+ "cts": CTS_VERSION,
453
+ "surface": surface,
454
+ "readOnly": surface == "public",
455
+ "locale": "en-US",
456
+ "size": {"width": width, "height": height},
457
+ "target": data.target,
458
+ "options": option_defaults(manifest),
459
+ "theme": {"mode": theme, "tokens": tokens, "palette": list(_PALETTE)},
460
+ "limits": dict(_SURFACE_LIMITS[surface]),
461
+ "channels": data.channels,
462
+ "params": data.params,
463
+ "files": data.files,
464
+ "meta": data.meta,
465
+ }
466
+ return {"version": 1, "init": init, "series": data.series}
467
+
468
+
469
+ def _script_safe_json(value: Any) -> str:
470
+ """JSON that cannot close or open a ``<script>`` element, whatever the values contain."""
471
+ text = json.dumps(value, separators=(",", ":"), ensure_ascii=True, allow_nan=False)
472
+ return text.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
473
+
474
+
475
+ def inject_envelope(source: str, envelope: dict[str, Any]) -> str:
476
+ """Insert the offline envelope before the ``cs.js`` script (or the head's end, or the top)."""
477
+ tag = f"<script>window.__CS_OFFLINE__={_script_safe_json(envelope)};</script>\n"
478
+ for script in scan_scripts(source):
479
+ if script.src and "/lib/cs@" in script.src:
480
+ return source[: script.tag_start] + tag + source[script.tag_start :]
481
+ head_end = re.search(r"</head\s*>", source, re.IGNORECASE)
482
+ if head_end:
483
+ return source[: head_end.start()] + tag + source[head_end.start() :]
484
+ return tag + source
485
+
486
+
487
+ def frame_headers(origin: str, host_origins: list[str]) -> list[tuple[str, str]]:
488
+ """Response headers for the template document: the user-content origin's policy, pointed at us."""
489
+ csp = (
490
+ "default-src 'none'; "
491
+ f"script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' {origin}; "
492
+ f"style-src 'unsafe-inline' {origin}; "
493
+ "img-src data: blob:; "
494
+ f"font-src data: {origin}; "
495
+ "worker-src blob:; connect-src 'none'; form-action 'none'; base-uri 'none'; "
496
+ f"frame-ancestors {' '.join(host_origins)}"
497
+ )
498
+ return [
499
+ ("Content-Type", "text/html; charset=utf-8"),
500
+ ("Content-Security-Policy", csp),
501
+ ("Content-Security-Policy", "sandbox allow-scripts"),
502
+ (
503
+ "Permissions-Policy",
504
+ "camera=(), microphone=(), geolocation=(), usb=(), serial=(), hid=(), clipboard-read=(), payment=(), display-capture=()",
505
+ ),
506
+ ("X-Content-Type-Options", "nosniff"),
507
+ ("Referrer-Policy", "no-referrer"),
508
+ ("Cache-Control", "no-store"),
509
+ ]
510
+
511
+
512
+ # --------------------------------------------------------------------------- libraries
513
+
514
+
515
+ class LibraryCache:
516
+ """Fetch ``/lib/<id>@<version>/<file>`` from the user-content origin, verified when possible.
517
+
518
+ Only the pinned ``https://<env>.cloudsprite-usercontent.io`` origin is contacted, redirects are
519
+ not followed and responses are size-capped. A library the API lib manifest lists must match its
520
+ ``sha256``; one it does not list (the ``cs`` runtime today) is served over TLS only and reported
521
+ through ``warn``. Verified files are cached under ``cache_dir`` and re-hashed on every read.
522
+ """
523
+
524
+ def __init__(
525
+ self,
526
+ origin: str,
527
+ manifest: dict[str, Any] | None,
528
+ *,
529
+ cache_dir: Path | None = None,
530
+ warn: Callable[[str], None] | None = None,
531
+ ) -> None:
532
+ if not _ORIGIN_RE.match(origin):
533
+ raise ValidationError(f"Refusing to load libraries from {origin!r}")
534
+ self.origin = origin
535
+ self._libs = {
536
+ (str(lib.get("id")), str(lib.get("version"))): lib
537
+ for lib in (manifest or {}).get("libs", [])
538
+ if isinstance(lib, dict)
539
+ }
540
+ self._cache_dir = cache_dir
541
+ self._memory: dict[tuple[str, str, str], bytes] = {}
542
+ self._warned: set[tuple[str, str]] = set()
543
+ self._warn = warn or (lambda message: print(message, file=sys.stderr))
544
+ self._lock = threading.Lock()
545
+
546
+ def get(self, lib_id: str, version: str, filename: str) -> tuple[bytes, str]:
547
+ """Return ``(bytes, content_type)`` or raise ``ValidationError`` / ``APIError``."""
548
+ suffix = Path(filename).suffix.lower()
549
+ if suffix not in _CONTENT_TYPES:
550
+ raise ValidationError(f"Refusing to serve {filename!r}: unsupported library file type")
551
+ content_type = _CONTENT_TYPES[suffix]
552
+ listed = self._libs.get((lib_id, version))
553
+ key = (lib_id, version, filename)
554
+ with self._lock:
555
+ if key in self._memory:
556
+ return self._memory[key], content_type
557
+ expected = str(listed["sha256"]).lower() if listed and listed.get("sha256") else None
558
+ cached = self._read_cache(key) if expected else None
559
+ if cached is not None and hashlib.sha256(cached).hexdigest() == expected:
560
+ self._memory[key] = cached
561
+ return cached, content_type
562
+ body = self._download(
563
+ lib_id, version, filename, cap=int(listed["size"]) if listed and listed.get("size") else None
564
+ )
565
+ if expected is not None:
566
+ actual = hashlib.sha256(body).hexdigest()
567
+ if actual != expected:
568
+ raise ValidationError(
569
+ f"{lib_id}@{version}/{filename} does not match the lib manifest sha256 "
570
+ f"(expected {expected[:12]}…, got {actual[:12]}…); refusing to serve it"
571
+ )
572
+ self._write_cache(key, body)
573
+ elif (lib_id, version) not in self._warned:
574
+ self._warned.add((lib_id, version))
575
+ self._warn(f"note: {lib_id}@{version} is not in the lib manifest; loaded over TLS without a hash check")
576
+ self._memory[key] = body
577
+ return body, content_type
578
+
579
+ def _path(self, key: tuple[str, str, str]) -> Path | None:
580
+ if self._cache_dir is None:
581
+ return None
582
+ return self._cache_dir / f"{key[0]}@{key[1]}" / key[2]
583
+
584
+ def _read_cache(self, key: tuple[str, str, str]) -> bytes | None:
585
+ path = self._path(key)
586
+ try:
587
+ return path.read_bytes() if path is not None and path.is_file() else None
588
+ except OSError:
589
+ return None
590
+
591
+ def _write_cache(self, key: tuple[str, str, str], body: bytes) -> None:
592
+ path = self._path(key)
593
+ if path is None:
594
+ return
595
+ try:
596
+ path.parent.mkdir(parents=True, exist_ok=True)
597
+ tmp = path.with_name(path.name + ".tmp")
598
+ tmp.write_bytes(body)
599
+ tmp.replace(path)
600
+ except OSError:
601
+ pass # a cache that cannot be written only costs a re-download
602
+
603
+ def _download(self, lib_id: str, version: str, filename: str, *, cap: int | None) -> bytes:
604
+ import requests
605
+
606
+ url = f"{self.origin}/lib/{lib_id}@{version}/{filename}"
607
+ limit = min(MAX_LIB_BYTES, int(cap * 1.05) + 1024) if cap else MAX_LIB_BYTES
608
+ try:
609
+ with requests.get(url, timeout=30, stream=True, allow_redirects=False) as resp:
610
+ if resp.status_code != 200:
611
+ raise APIError(resp.status_code, f"{url} answered HTTP {resp.status_code}", None)
612
+ chunks: list[bytes] = []
613
+ total = 0
614
+ for chunk in resp.iter_content(65536):
615
+ total += len(chunk)
616
+ if total > limit:
617
+ raise ValidationError(f"{lib_id}@{version}/{filename} is larger than the allowed {limit} bytes")
618
+ chunks.append(chunk)
619
+ except requests.RequestException as exc:
620
+ raise APIError(0, f"Could not fetch {url}: {exc}", None) from exc
621
+ return b"".join(chunks)
622
+
623
+
624
+ # --------------------------------------------------------------------------- server
625
+
626
+
627
+ def _findings_html(findings: list[dict[str, Any]], heading: str) -> str:
628
+ if not findings:
629
+ return f"<section><h2>{html.escape(heading)}</h2><p class=ok>No findings.</p></section>"
630
+ rows = []
631
+ for f in findings:
632
+ line = f.get("line")
633
+ rows.append(
634
+ "<tr class='{sev}'><td>{sev}</td><td>{rule}</td><td>{msg}</td><td>{line}</td></tr>".format(
635
+ sev=html.escape(str(f.get("severity", ""))),
636
+ rule=html.escape(str(f.get("rule", ""))),
637
+ msg=html.escape(str(f.get("message", ""))),
638
+ line=html.escape(str(line)) if line else "",
639
+ )
640
+ )
641
+ return (
642
+ f"<section><h2>{html.escape(heading)}</h2><table><thead><tr><th>Severity</th><th>Rule</th>"
643
+ f"<th>Message</th><th>Line</th></tr></thead><tbody>{''.join(rows)}</tbody></table></section>"
644
+ )
645
+
646
+
647
+ _HOST_CSS = """
648
+ body{font:14px/1.45 system-ui,sans-serif;margin:0;background:#f0f2f5;color:#1a1f29}
649
+ header{padding:12px 20px;background:#fff;border-bottom:1px solid #d6dae2}
650
+ h1{font-size:16px;margin:0 0 4px}h2{font-size:14px;margin:0 0 6px}
651
+ .meta{color:#5b6472;font-size:12px}
652
+ main{padding:16px 20px}form{display:flex;gap:12px;align-items:center;margin:0 0 12px}
653
+ select,button{font:inherit;padding:3px 8px}
654
+ iframe{background:#fff;border:1px solid #b4bac6;display:block}
655
+ section{margin-top:16px}table{border-collapse:collapse;background:#fff;font-size:13px}
656
+ td,th{border:1px solid #d6dae2;padding:4px 8px;text-align:left}
657
+ tr.block td:first-child{color:#c8302f;font-weight:600}tr.warn td:first-child{color:#a15c00}
658
+ .ok{color:#19734f}.note{color:#5b6472;font-size:12px}
659
+ """
660
+
661
+
662
+ class PreviewServer(ThreadingHTTPServer):
663
+ """Loopback HTTP server: host page, sandboxed template frame and library proxy."""
664
+
665
+ daemon_threads = True
666
+
667
+ def __init__(
668
+ self,
669
+ template_path: Path,
670
+ data: PreviewData,
671
+ libs: LibraryCache,
672
+ *,
673
+ port: int = 0,
674
+ size: tuple[int, int] | None = None,
675
+ reviewer: list[dict[str, Any]] | None = None,
676
+ reviewer_note: str = "",
677
+ default_surface: str = "interactive",
678
+ default_theme: str = "light",
679
+ log: Callable[[str], None] | None = None,
680
+ token: str | None = None,
681
+ ) -> None:
682
+ self.template_path = template_path
683
+ self.token = token or secrets.token_urlsafe(18)
684
+ self.data = data
685
+ self.libs = libs
686
+ self.size = size
687
+ self.reviewer = reviewer
688
+ self.reviewer_note = reviewer_note
689
+ self.default_surface = default_surface
690
+ self.default_theme = default_theme
691
+ self.log = log or (lambda message: None)
692
+ super().__init__((LOOPBACK, port), _Handler)
693
+
694
+ @property
695
+ def origin(self) -> str:
696
+ return f"http://{LOOPBACK}:{self.server_address[1]}"
697
+
698
+ @property
699
+ def url(self) -> str:
700
+ """The address to open: the origin plus this run's access key."""
701
+ return f"{self.origin}/?k={self.token}"
702
+
703
+ def key_ok(self, supplied: str | None) -> bool:
704
+ """Constant-time check of the access key."""
705
+ return supplied is not None and hmac.compare_digest(supplied.encode("utf-8"), self.token.encode("utf-8"))
706
+
707
+ @property
708
+ def allowed_hosts(self) -> set[str]:
709
+ port = self.server_address[1]
710
+ return {f"{LOOPBACK}:{port}", f"localhost:{port}", f"[::1]:{port}"}
711
+
712
+ def read_source(self) -> str:
713
+ if self.template_path.stat().st_size > MAX_SOURCE_BYTES:
714
+ raise ValidationError(f"{self.template_path} is larger than {MAX_SOURCE_BYTES} bytes")
715
+ return self.template_path.read_text(encoding="utf-8")
716
+
717
+ def start(self) -> threading.Thread:
718
+ """Serve in a daemon thread (tests); the CLI calls ``serve_forever`` directly."""
719
+ thread = threading.Thread(target=self.serve_forever, daemon=True)
720
+ thread.start()
721
+ return thread
722
+
723
+ def render_frame(self, surface: str, theme: str) -> str:
724
+ source = self.read_source()
725
+ manifest, _ = parse_manifest(source)
726
+ envelope = build_envelope(self.data, manifest=manifest, surface=surface, theme=theme, size=self.size)
727
+ return inject_envelope(source, envelope)
728
+
729
+ def render_host(self, surface: str, theme: str) -> str:
730
+ source = self.read_source()
731
+ manifest, _ = parse_manifest(source)
732
+ local = check_source(source)
733
+ width, height = self.size or _SURFACE_SIZE[surface]
734
+ title = str((manifest or {}).get("name") or self.template_path.name)
735
+ version = str((manifest or {}).get("version") or "?")
736
+ surface_opts = "".join(f"<option{' selected' if s == surface else ''}>{s}</option>" for s in SURFACES)
737
+ theme_opts = "".join(f"<option{' selected' if t == theme else ''}>{t}</option>" for t in THEMES)
738
+ reviewer_html = (
739
+ _findings_html(self.reviewer, "Reviewer findings (API)")
740
+ if self.reviewer is not None
741
+ else f"<section><h2>Reviewer findings (API)</h2><p class=note>{html.escape(self.reviewer_note or 'not run')}</p></section>"
742
+ )
743
+ notes = "".join(f"<li>{html.escape(n)}</li>" for n in self.data.notes)
744
+ return (
745
+ "<!doctype html><html lang=en><head><meta charset=utf-8>"
746
+ f"<title>Preview: {html.escape(title)}</title><style>{_HOST_CSS}</style></head><body>"
747
+ f"<header><h1>{html.escape(title)} <span class=meta>v{html.escape(version)} · {html.escape(self.template_path.name)}</span></h1>"
748
+ f"<div class=meta>{html.escape(self.data.label)}</div></header><main>"
749
+ "<form method=get action=/>"
750
+ f"<input type=hidden name=k value='{html.escape(self.token)}'>"
751
+ f"<label>Surface <select name=surface>{surface_opts}</select></label>"
752
+ f"<label>Theme <select name=theme>{theme_opts}</select></label>"
753
+ "<button type=submit>Reload</button></form>"
754
+ f"<iframe title='Template preview' sandbox='allow-scripts' referrerpolicy='no-referrer' allow='' "
755
+ f"width={int(width)} height={int(height)} src='/frame?surface={html.escape(surface)}&theme={html.escape(theme)}&k={html.escape(self.token)}'></iframe>"
756
+ + (f"<ul class=note>{notes}</ul>" if notes else "")
757
+ + _findings_html(local, "Local checks (manifest and /lib/ rules)")
758
+ + reviewer_html
759
+ + "</main></body></html>"
760
+ )
761
+
762
+
763
+ class _Handler(BaseHTTPRequestHandler):
764
+ server: PreviewServer
765
+ server_version = "cloudsprite-preview"
766
+ sys_version = ""
767
+
768
+ def log_message(self, format: str, *args: Any) -> None: # noqa: A002 - signature fixed by the base class
769
+ self.server.log(f"{self.address_string()} {format % args}")
770
+
771
+ def _send(self, status: int, body: bytes, headers: list[tuple[str, str]]) -> None:
772
+ self.send_response(status)
773
+ for name, value in headers:
774
+ self.send_header(name, value)
775
+ self.send_header("Content-Length", str(len(body)))
776
+ self.end_headers()
777
+ if self.command != "HEAD":
778
+ self.wfile.write(body)
779
+
780
+ def _text(self, status: int, message: str) -> None:
781
+ self._send(
782
+ status,
783
+ message.encode("utf-8"),
784
+ [
785
+ ("Content-Type", "text/plain; charset=utf-8"),
786
+ ("X-Content-Type-Options", "nosniff"),
787
+ ("Cache-Control", "no-store"),
788
+ ],
789
+ )
790
+
791
+ def do_HEAD(self) -> None: # noqa: N802
792
+ self.do_GET()
793
+
794
+ def do_GET(self) -> None: # noqa: N802
795
+ if self.headers.get("Host", "").lower() not in self.server.allowed_hosts:
796
+ self._text(403, "Forbidden: unexpected Host header")
797
+ return
798
+ parsed = urlparse(self.path)
799
+ query = parse_qs(parsed.query)
800
+ surface = (query.get("surface") or [self.server.default_surface])[0]
801
+ theme = (query.get("theme") or [self.server.default_theme])[0]
802
+ try:
803
+ if parsed.path in ("/", "/index.html", "/frame") and not self.server.key_ok((query.get("k") or [""])[0]):
804
+ self._text(
805
+ 403,
806
+ "Forbidden: open the address `cloudsprite visualizer preview` printed (it carries the access key)",
807
+ )
808
+ elif parsed.path in ("/", "/index.html"):
809
+ self._host(surface, theme)
810
+ elif parsed.path == "/frame":
811
+ self._frame(surface, theme)
812
+ elif parsed.path.startswith("/lib/"):
813
+ self._lib(parsed.path)
814
+ else:
815
+ self._text(404, "Not found")
816
+ except ValidationError as exc:
817
+ self._text(400, str(exc))
818
+ except APIError as exc:
819
+ self._text(502, str(exc))
820
+ except OSError as exc:
821
+ self._text(500, f"Cannot read the template: {exc}")
822
+
823
+ def _host(self, surface: str, theme: str) -> None:
824
+ if surface not in SURFACES or theme not in THEMES:
825
+ raise ValidationError("unknown surface or theme")
826
+ origin = self.server.origin
827
+ csp = (
828
+ f"default-src 'none'; style-src 'unsafe-inline'; frame-src {origin}; "
829
+ "base-uri 'none'; form-action 'self'; frame-ancestors 'none'"
830
+ )
831
+ headers = [
832
+ ("Content-Type", "text/html; charset=utf-8"),
833
+ ("Content-Security-Policy", csp),
834
+ ("X-Content-Type-Options", "nosniff"),
835
+ ("Referrer-Policy", "no-referrer"),
836
+ ("Cache-Control", "no-store"),
837
+ ]
838
+ self._send(200, self.server.render_host(surface, theme).encode("utf-8"), headers)
839
+
840
+ def _frame(self, surface: str, theme: str) -> None:
841
+ if surface not in SURFACES or theme not in THEMES:
842
+ raise ValidationError("unknown surface or theme")
843
+ origin = self.server.origin
844
+ port = self.server.server_address[1]
845
+ ancestors = [origin, f"http://localhost:{port}"]
846
+ self._send(200, self.server.render_frame(surface, theme).encode("utf-8"), frame_headers(origin, ancestors))
847
+
848
+ def _lib(self, path: str) -> None:
849
+ match = _LIB_PATH_RE.match(path)
850
+ if match is None:
851
+ self._text(404, "Not found")
852
+ return
853
+ body, content_type = self.server.libs.get(match.group("id"), match.group("version"), match.group("file"))
854
+ self._send(
855
+ 200,
856
+ body,
857
+ [
858
+ ("Content-Type", content_type),
859
+ ("Access-Control-Allow-Origin", "*"),
860
+ ("Cross-Origin-Resource-Policy", "cross-origin"),
861
+ ("X-Content-Type-Options", "nosniff"),
862
+ ("Cache-Control", "no-store"),
863
+ ],
864
+ )