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,380 @@
1
+ """Local helpers for visualizer templates (CTS 0.1): manifest parsing, semver, offline checks.
2
+
3
+ The API's static reviewer (``POST /api/visualizer-templates/validate/``) is the
4
+ authority on whether a template can be published. Everything here is a cheap,
5
+ dependency-free subset for fast feedback before a network call: size limits,
6
+ the single manifest block, required manifest fields, semver and the ``/lib/``
7
+ script rules. It uses the same rule ids as the reviewer so a finding reads the
8
+ same offline and online.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import re
15
+ import unicodedata
16
+ from collections.abc import Iterable
17
+ from dataclasses import dataclass
18
+ from html.parser import HTMLParser
19
+ from typing import Any
20
+
21
+ MANIFEST_TYPE = "application/cloudsprite-template+json"
22
+ CTS_VERSION = "0.1"
23
+
24
+ SOURCE_MAX_BYTES = 1024 * 1024 # CTS-PKG-01 (block)
25
+ SOURCE_WARN_BYTES = 256 * 1024 # CTS-PKG-02 (warn)
26
+ MANIFEST_MAX_BYTES = 16 * 1024 # CTS-PKG-03 (block)
27
+ README_MAX_BYTES = 64 * 1024
28
+ DESCRIPTION_MAX_LENGTH = 2000
29
+ DESCRIPTION_MIN_LENGTH = 20 # CTS-DOC-01 (info)
30
+
31
+ RULE_SIZE = "CTS-PKG-01"
32
+ RULE_SIZE_WARN = "CTS-PKG-02"
33
+ RULE_MANIFEST = "CTS-PKG-03"
34
+ RULE_LIBS = "CTS-PKG-04"
35
+ RULE_DOC = "CTS-DOC-01"
36
+
37
+ BUMP_PARTS = ("patch", "minor", "major")
38
+
39
+ _SEMVER_RE = re.compile(
40
+ r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)"
41
+ r"(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?$"
42
+ )
43
+ _LIB_SRC_RE = re.compile(r"^/lib/(?P<id>[a-z0-9][a-z0-9-]*)@(?P<version>\d+\.\d+\.\d+)/(?P<file>[A-Za-z0-9._-]+)$")
44
+ _LIB_PREFIX_RE = re.compile(r"^/lib/(?P<id>[a-z0-9][a-z0-9-]*)@(?P<version>[^/]*)/")
45
+ _ENGINE_RE = re.compile(r"^(?P<id>[a-z0-9][a-z0-9-]*)@(?P<version>\d+\.\d+\.\d+)$")
46
+ _SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
47
+
48
+
49
+ # --------------------------------------------------------------------------- semver
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Semver:
54
+ """A strict ``MAJOR.MINOR.PATCH[-prerelease]`` version (build metadata is refused)."""
55
+
56
+ major: int
57
+ minor: int
58
+ patch: int
59
+ prerelease: tuple[str, ...] = ()
60
+
61
+ @classmethod
62
+ def parse(cls, text: str) -> Semver:
63
+ """Parse *text*; raise ``ValueError`` when it is not a strict semver."""
64
+ match = _SEMVER_RE.match(text) if isinstance(text, str) else None
65
+ if match is None:
66
+ raise ValueError(f"{text!r} is not a valid semver (expected MAJOR.MINOR.PATCH)")
67
+ pre = tuple(match.group(4).split(".")) if match.group(4) else ()
68
+ return cls(int(match.group(1)), int(match.group(2)), int(match.group(3)), pre)
69
+
70
+ def _key(self) -> tuple[Any, ...]:
71
+ # A release outranks any of its prereleases; numeric identifiers sort below alphanumeric ones.
72
+ pre = tuple((0, int(p), "") if p.isdigit() else (1, 0, p) for p in self.prerelease)
73
+ return (self.major, self.minor, self.patch, 0 if self.prerelease else 1, pre)
74
+
75
+ def __lt__(self, other: Semver) -> bool:
76
+ return self._key() < other._key()
77
+
78
+ def __le__(self, other: Semver) -> bool:
79
+ return self._key() <= other._key()
80
+
81
+ def __str__(self) -> str:
82
+ core = f"{self.major}.{self.minor}.{self.patch}"
83
+ return f"{core}-{'.'.join(self.prerelease)}" if self.prerelease else core
84
+
85
+ def bump(self, part: str) -> Semver:
86
+ """Next ``patch``, ``minor`` or ``major``. A prerelease cannot be bumped (set it by hand)."""
87
+ if part not in BUMP_PARTS:
88
+ raise ValueError(f"bump must be one of {', '.join(BUMP_PARTS)}")
89
+ if self.prerelease:
90
+ raise ValueError(f"cannot bump the prerelease version {self}; set the version manually")
91
+ if part == "major":
92
+ return Semver(self.major + 1, 0, 0)
93
+ if part == "minor":
94
+ return Semver(self.major, self.minor + 1, 0)
95
+ return Semver(self.major, self.minor, self.patch + 1)
96
+
97
+
98
+ def highest_semver(values: Iterable[str]) -> str | None:
99
+ """The greatest valid semver among *values* (invalid entries are ignored), or ``None``."""
100
+ best: Semver | None = None
101
+ for value in values:
102
+ try:
103
+ parsed = Semver.parse(value)
104
+ except ValueError:
105
+ continue
106
+ if best is None or best <= parsed:
107
+ best = parsed
108
+ return str(best) if best is not None else None
109
+
110
+
111
+ def normalize_slug(value: str) -> str:
112
+ """Package slug for a template name, the way the registry derives it (ASCII slug, 64 chars)."""
113
+ text = unicodedata.normalize("NFKD", value or "").encode("ascii", "ignore").decode("ascii")
114
+ text = re.sub(r"[^\w\s-]", "", text.lower())
115
+ slug = re.sub(r"[-\s]+", "-", text).strip("-_")[:64].strip("-_.")
116
+ if not _SLUG_RE.match(slug):
117
+ raise ValueError("The template name must contain letters or digits.")
118
+ return slug
119
+
120
+
121
+ # --------------------------------------------------------------------------- html scan
122
+
123
+
124
+ @dataclass(frozen=True)
125
+ class ScriptTag:
126
+ """One ``<script>`` element: attributes, body, and where it sits in the source."""
127
+
128
+ attrs: dict[str, str]
129
+ body: str
130
+ tag_start: int # offset of ``<script``
131
+ body_start: int # offset of the first body character
132
+ body_end: int # offset of ``</script``
133
+ line: int
134
+
135
+ @property
136
+ def src(self) -> str | None:
137
+ return self.attrs.get("src")
138
+
139
+ @property
140
+ def type(self) -> str:
141
+ return self.attrs.get("type", "").strip().lower()
142
+
143
+
144
+ class _ScriptScanner(HTMLParser):
145
+ def __init__(self, source: str) -> None:
146
+ super().__init__(convert_charrefs=False)
147
+ self._source = source
148
+ self._line_starts = [0]
149
+ for match in re.finditer(r"\n", source):
150
+ self._line_starts.append(match.end())
151
+ self.scripts: list[ScriptTag] = []
152
+ self._open: tuple[dict[str, str], int, int, int] | None = None
153
+
154
+ def _offset(self) -> int:
155
+ line, col = self.getpos()
156
+ return self._line_starts[line - 1] + col
157
+
158
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
159
+ if tag != "script" or self._open is not None:
160
+ return
161
+ start = self._offset()
162
+ text = self.get_starttag_text() or ""
163
+ mapped = {name.lower(): (value if value is not None else "") for name, value in attrs}
164
+ self._open = (mapped, start, start + len(text), self.getpos()[0])
165
+
166
+ def handle_endtag(self, tag: str) -> None:
167
+ if tag != "script" or self._open is None:
168
+ return
169
+ attrs, start, body_start, line = self._open
170
+ end = self._offset()
171
+ self.scripts.append(ScriptTag(attrs, self._source[body_start:end], start, body_start, end, line))
172
+ self._open = None
173
+
174
+
175
+ def scan_scripts(source: str) -> list[ScriptTag]:
176
+ """Every complete ``<script>`` element in document order."""
177
+ scanner = _ScriptScanner(source)
178
+ try:
179
+ scanner.feed(source)
180
+ scanner.close()
181
+ except Exception: # noqa: BLE001 - malformed markup must degrade to "fewer scripts", never crash
182
+ pass
183
+ return scanner.scripts
184
+
185
+
186
+ def manifest_blocks(source: str) -> list[ScriptTag]:
187
+ """The ``<script type="application/cloudsprite-template+json">`` elements."""
188
+ return [s for s in scan_scripts(source) if s.type == MANIFEST_TYPE]
189
+
190
+
191
+ def parse_manifest(source: str) -> tuple[dict[str, Any] | None, list[dict[str, Any]]]:
192
+ """Return ``(manifest, findings)``; ``manifest`` is ``None`` when it cannot be read."""
193
+ blocks = manifest_blocks(source)
194
+ if len(blocks) != 1:
195
+ message = (
196
+ 'The template has no CloudSprite manifest (<script type="application/cloudsprite-template+json">).'
197
+ if not blocks
198
+ else f"The template has {len(blocks)} manifests; exactly one is allowed."
199
+ )
200
+ return None, [_finding(RULE_MANIFEST, "block", message, blocks[1].line if len(blocks) > 1 else None)]
201
+ block = blocks[0]
202
+ if len(block.body.encode("utf-8")) > MANIFEST_MAX_BYTES:
203
+ return None, [
204
+ _finding(RULE_MANIFEST, "block", f"The manifest is larger than {MANIFEST_MAX_BYTES} bytes.", block.line)
205
+ ]
206
+ try:
207
+ data = json.loads(block.body)
208
+ except ValueError as exc:
209
+ return None, [_finding(RULE_MANIFEST, "block", f"The manifest is not valid JSON: {exc}", block.line)]
210
+ if not isinstance(data, dict):
211
+ return None, [_finding(RULE_MANIFEST, "block", "The manifest must be a JSON object.", block.line)]
212
+ return data, []
213
+
214
+
215
+ def _finding(rule: str, severity: str, message: str, line: int | None = None) -> dict[str, Any]:
216
+ return {"rule": rule, "severity": severity, "message": message, "line": line, "column": None}
217
+
218
+
219
+ # --------------------------------------------------------------------------- offline checks
220
+
221
+
222
+ def check_source(source: str) -> list[dict[str, Any]]:
223
+ """Basic offline CTS checks. The API reviewer stays authoritative for everything else."""
224
+ if not isinstance(source, str) or not source.strip():
225
+ return [_finding(RULE_SIZE, "block", "The template source is empty.")]
226
+ size = len(source.encode("utf-8", "surrogatepass"))
227
+ findings: list[dict[str, Any]] = []
228
+ if size > SOURCE_MAX_BYTES:
229
+ findings.append(_finding(RULE_SIZE, "block", f"The template is {size} bytes; the limit is {SOURCE_MAX_BYTES}."))
230
+ elif size > SOURCE_WARN_BYTES:
231
+ findings.append(
232
+ _finding(
233
+ RULE_SIZE_WARN, "warn", f"The template is {size} bytes; at most {SOURCE_WARN_BYTES} is recommended."
234
+ )
235
+ )
236
+
237
+ manifest, problems = parse_manifest(source)
238
+ findings.extend(problems)
239
+ engines: list[str] = []
240
+ if manifest is not None:
241
+ manifest_line = manifest_blocks(source)[0].line
242
+ findings.extend(_check_manifest_fields(manifest, manifest_line))
243
+ raw_engines = manifest.get("engines")
244
+ if isinstance(raw_engines, list):
245
+ engines = [e for e in raw_engines if isinstance(e, str)]
246
+ findings.extend(_check_lib_scripts(source, engines))
247
+ return findings
248
+
249
+
250
+ def _check_manifest_fields(manifest: dict[str, Any], line: int) -> list[dict[str, Any]]:
251
+ out: list[dict[str, Any]] = []
252
+
253
+ def block(message: str) -> None:
254
+ out.append(_finding(RULE_MANIFEST, "block", message, line))
255
+
256
+ if manifest.get("cts") != CTS_VERSION:
257
+ block(f'The manifest "cts" must be "{CTS_VERSION}".')
258
+ version = manifest.get("version")
259
+ if not isinstance(version, str):
260
+ block('The manifest needs a semver string "version" (for example "1.0.0").')
261
+ else:
262
+ try:
263
+ Semver.parse(version)
264
+ except ValueError as exc:
265
+ block(f'The manifest "version" is invalid: {exc}.')
266
+ name = manifest.get("name")
267
+ if not isinstance(name, str) or not name.strip():
268
+ block('The manifest needs a non-empty "name".')
269
+ description = manifest.get("description")
270
+ if not isinstance(description, str) or not description.strip():
271
+ block('The manifest needs a non-empty "description".')
272
+ elif len(description) > DESCRIPTION_MAX_LENGTH:
273
+ block(f'The manifest "description" is longer than {DESCRIPTION_MAX_LENGTH} characters.')
274
+ elif len(description) < DESCRIPTION_MIN_LENGTH:
275
+ out.append(
276
+ _finding(
277
+ RULE_DOC,
278
+ "info",
279
+ f'The manifest "description" is shorter than {DESCRIPTION_MIN_LENGTH} characters.',
280
+ line,
281
+ )
282
+ )
283
+ engines = manifest.get("engines")
284
+ if not isinstance(engines, list) or not engines:
285
+ block('The manifest needs "engines", for example ["plotly-cs@4.2.0"].')
286
+ else:
287
+ for engine in engines:
288
+ if not isinstance(engine, str) or not _ENGINE_RE.match(engine):
289
+ block(f'Engine {engine!r} must be "<id>@<exact version>" (no ranges or "latest").')
290
+ return out
291
+
292
+
293
+ def lib_refs(source: str) -> list[tuple[str, str, str]]:
294
+ """``(id, version, file)`` for every ``/lib/<id>@<exact>/<file>`` script, in document order."""
295
+ refs = []
296
+ for script in scan_scripts(source):
297
+ match = _LIB_SRC_RE.match(script.src or "")
298
+ if match:
299
+ refs.append((match.group("id"), match.group("version"), match.group("file")))
300
+ return refs
301
+
302
+
303
+ def _check_lib_scripts(source: str, engines: list[str]) -> list[dict[str, Any]]:
304
+ out: list[dict[str, Any]] = []
305
+ allowed = {m.group("id") for e in engines if (m := _ENGINE_RE.match(e))} | {"cs"}
306
+ first = True
307
+ for script in scan_scripts(source):
308
+ if script.src is None:
309
+ continue
310
+ match = _LIB_SRC_RE.match(script.src)
311
+ if match is None:
312
+ floating = _LIB_PREFIX_RE.match(script.src)
313
+ reason = (
314
+ f"{script.src!r} pins no exact version (floating versions are rejected)"
315
+ if floating
316
+ else f"{script.src!r} is not a /lib/<id>@<exact-version>/ path"
317
+ )
318
+ out.append(_finding(RULE_LIBS, "block", f"Scripts may only load from /lib/: {reason}.", script.line))
319
+ elif match.group("id") not in allowed:
320
+ out.append(
321
+ _finding(
322
+ RULE_LIBS,
323
+ "block",
324
+ f"Library {match.group('id')!r} is not declared in the manifest engines.",
325
+ script.line,
326
+ )
327
+ )
328
+ if first:
329
+ first = False
330
+ if match is None or match.group("id") != "cs" or match.group("file") != "cs.js":
331
+ out.append(
332
+ _finding(
333
+ RULE_LIBS,
334
+ "block",
335
+ "The first script with a src must be /lib/cs@<exact-version>/cs.js.",
336
+ script.line,
337
+ )
338
+ )
339
+ return out
340
+
341
+
342
+ def has_blocking(findings: Iterable[dict[str, Any]]) -> bool:
343
+ """True when any finding has severity ``block``."""
344
+ return any(f.get("severity") == "block" for f in findings)
345
+
346
+
347
+ # --------------------------------------------------------------------------- version bump
348
+
349
+
350
+ def manifest_version(source: str) -> str:
351
+ """The manifest ``version`` string; raise ``ValueError`` when the manifest is unreadable."""
352
+ manifest, problems = parse_manifest(source)
353
+ if manifest is None:
354
+ raise ValueError(problems[0]["message"])
355
+ version = manifest.get("version")
356
+ if not isinstance(version, str):
357
+ raise ValueError('The manifest has no string "version".')
358
+ Semver.parse(version)
359
+ return version
360
+
361
+
362
+ def set_manifest_version(source: str, new_version: str) -> str:
363
+ """Return *source* with the manifest ``"version"`` value replaced, touching nothing else."""
364
+ Semver.parse(new_version)
365
+ old = manifest_version(source)
366
+ block = manifest_blocks(source)[0]
367
+ pattern = re.compile(r'("version"\s*:\s*)"' + re.escape(old) + '"')
368
+ matches = list(pattern.finditer(block.body))
369
+ if len(matches) != 1:
370
+ raise ValueError('Cannot locate a single "version" entry in the manifest to rewrite; edit it by hand.')
371
+ body = (
372
+ block.body[: matches[0].start()]
373
+ + matches[0].group(1)
374
+ + json.dumps(new_version)
375
+ + block.body[matches[0].end() :]
376
+ )
377
+ updated = source[: block.body_start] + body + source[block.body_end :]
378
+ if manifest_version(updated) != new_version: # belt and braces: never write a file we cannot read back
379
+ raise ValueError("Rewriting the manifest version failed verification; edit it by hand.")
380
+ return updated