diff --git a/README.md b/README.md index 953efd0..c6ddc8f 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ **sysmod-sysmlv2-api-mcp** connects to a SysML v2 repository server and provides: +- 📄 **Single-page SYSMOD Viewer** (`web/`) — the recommended viewer: one web page, no Flask server, no Python packages. See [Single-page viewer](#single-page-viewer-web) - 🔌 **REST API + Web UI** — interactive browser-based viewer and wizard for SYSMOD models - 🤖 **MCP Server** — exposes all SYSMOD artifacts as tools for AI agents (Claude, Cursor, GitHub Copilot, etc.) - 🧠 **SYSMOD AI Agent** — an LLM can autonomously query problem statements, contexts, stakeholders, requirements, feature trees, and more directly from the SysML v2 model @@ -38,9 +39,38 @@ --- +## Single-page viewer (`web/`) + +The SYSMOD Viewer as **one web page**: it reads the model with the SysML v2 API directly from the browser. No Flask server, no `pip install`. + +```bash +python web/serve.py # then open http://localhost:8080/ + +# other SysML v2 servers: name them, as for the Flask server +ALLOWED_SYSML_SERVER_ORIGINS=http://localhost:9000,http://sysml2.intercax.com:9000 python web/serve.py +``` + +`serve.py` uses only the Python standard library. It serves the page and **relays** its requests, read-only, to the SysML v2 API servers in `ALLOWED_SYSML_SERVER_ORIGINS` (as for the Flask server; default `http://localhost:9000`): a page alone can only read servers that allow requests from it (CORS), and a page on https may not call an http server. With the relay every allowed server works, e.g. `http://sysml2.intercax.com:9000` or Open-MBEE Flexo. The relay listens on localhost only, allows only GET of the read endpoints (`/projects`, `…/branches`, `…/commits`, `…/commits/{id}/elements`) with the paging query, follows no redirects and passes the token on without storing it. Any other static web server works too; then only servers that allow CORS can be read. + +What it shows: the project cover (purpose, owner, description, the SYSMOD version from `@SYSMOD { version = … }`, the cover view), the SYSMOD Atlas, completeness checks, problem statement, system idea and objectives, stakeholders, needs, system requirements, system use cases and the context diagram of all six contexts, from the brownfield to the product architecture: actors, the system of interest with its white box parts, and the interfaces with the ports they connect. It reads **SYSMOD v5** (the project is an `occurrence def` with `#project`; the roles are found by their direct redefinition of the features of `SYSMOD::Project`). It loads a commit once (paged) and reads it in the browser. Also a `.json` file with the elements of a commit can be opened. + +| File | What | +|---|---| +| `web/index.html`, `web/sysmod-viewer.css` | the page | +| `web/sysmod-viewer-core.js` | reads the SYSMOD project from the elements (pure ES module, no dependencies) | +| `web/sysmod-viewer-api.js` | the requests to the SysML v2 API server, paging, relay | +| `web/sysmod-viewer.js` | the interface; the context diagrams are SVG drawn by the page (no CDN) | +| `web/serve.py` | serves the page and relays the requests | + +The same JavaScript runs on [mbse4u.com/tools/sysmod-viewer](https://mbse4u.com/tools/sysmod-viewer/), which in addition opens the Delivery Drone example and `.sysml` files with a SysML v2 engine in the browser, and reaches servers without CORS through a relay with an allowlist. Changes to the viewer belong here; the site copies them. + +Read-only. Editing the problem statement, AI suggestions and the creation wizard are in the Flask server (below). Tests of `serve.py`: `python -m pytest tests/test_web_serve.py` (part of `python -m pytest`, no extra packages). The viewer's JavaScript is tested on mbse4u.com with the Delivery Drone model and `tests/test_sysmod.sysml` of this repository. + +--- + ## Features -### SYSMOD Viewer (`project.html`) +### SYSMOD Viewer (`project.html`, Flask; for the single-page viewer see above) | Feature | Description | |---|---| @@ -211,7 +241,7 @@ ALLOWED_SYSML_SERVER_ORIGINS=http://localhost:9000,http://127.0.0.1:9000,http:// python sysmod_api_server.py ``` -Runs on `http://localhost:5000`. Open in browser to use the web UI. +Runs on `http://localhost:5000`. Open in browser to use the web UI (viewer with editing and AI, wizard). For viewing only, the [single-page viewer](#single-page-viewer-web) needs no server packages. --- diff --git a/tests/test_web_serve.py b/tests/test_web_serve.py new file mode 100644 index 0000000..af0ee51 --- /dev/null +++ b/tests/test_web_serve.py @@ -0,0 +1,163 @@ +"""Tests of web/serve.py: the rules of the relay and real HTTP requests against a fake SysML v2 API server. +Standard library only: python -m unittest tests/test_web_serve.py (pytest runs it too)""" +import json +import sys +import threading +import unittest +import urllib.error +import urllib.parse +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "web")) +import serve # noqa: E402 + + +class FakeSysml(BaseHTTPRequestHandler): + """A tiny SysML v2 API server: echoes what it received, pages elements with a Link header.""" + def log_message(self, *a): + pass + + def send(self, code, body, headers=None): + b = json.dumps(body).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.end_headers() + self.wfile.write(b) + + def do_GET(self): + u = urllib.parse.urlsplit(self.path) + if u.path == "/projects": + return self.send(200, [{"@id": "p-1", "name": "P", "auth": self.headers.get("Authorization", ""), "query": u.query}]) + if u.path == "/projects/p-1/commits/c/elements": + return self.send(200, [{"@id": "e-1"}], {"Link": f"; rel=\"next\""}) + if u.path == "/projects/redirect": + self.send_response(302); self.send_header("Location", "https://example.org/"); self.end_headers(); return + if u.path == "/projects/html": + b = b"oops" + self.send_response(200); self.send_header("Content-Type", "text/html"); self.end_headers(); self.wfile.write(b); return + if u.path == "/projects/secret": + return self.send(401, {"error": "unauthorized"}) + return self.send(404, {"error": "not found"}) + + +def start(handler): + srv = ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + return srv + + +ALLOWED = "https://h.org,http://sysml2.intercax.com:9000" + + +class Rules(unittest.TestCase): + def setUp(self): + import os + os.environ["ALLOWED_SYSML_SERVER_ORIGINS"] = ALLOWED + + def tearDown(self): + import os + os.environ.pop("ALLOWED_SYSML_SERVER_ORIGINS", None) + def ok(self, url, expected=None): + target, error = serve.check_url(url) + self.assertEqual(error, "", url) + if expected: + self.assertEqual(target, expected) + + def refused(self, url, reason): + self.assertEqual(serve.check_url(url), (None, reason), url) + + def test_allowed(self): + self.ok("https://h.org/projects") + self.ok("http://sysml2.intercax.com:9000/projects?page%5Bsize%5D=1000", "http://sysml2.intercax.com:9000/projects?page%5Bsize%5D=1000") + self.ok("https://h.org/projects?page[size]=10", "https://h.org/projects?page%5Bsize%5D=10") + self.ok("https://h.org/api/v1/projects/p/commits/c/elements?page%5Bafter%5D=x") + self.ok("https://h.org/projects/p/branches/b") + self.ok("https://H.org/projects", "https://h.org/projects") + + def test_allowed_origins(self): + import os + self.refused("https://other.org/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") + self.refused("http://h.org/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") + self.refused("http://sysml2.intercax.com:9001/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") + os.environ.pop("ALLOWED_SYSML_SERVER_ORIGINS") + self.ok("http://localhost:9000/projects") # the default, as for the Flask server + self.refused("https://h.org/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") + + def test_refused(self): + self.refused("", "invalid address") + self.refused("file:///etc/passwd", "only http and https") + self.refused("https://h.org@evil.org/projects", "invalid address") + self.refused("https://u:p@h.org/projects", "invalid address") + self.refused("https://h.org/projects#x", "invalid address") + self.refused("https://h.org/admin", "not a read endpoint of the SysML v2 API") + self.refused("https://h.org/projects/p/query-results", "not a read endpoint of the SysML v2 API") + self.refused("https://h.org/projects/../admin", "invalid path") + self.refused("https://h.org/projects/%2e%2e", "invalid path") + self.refused("https://h.org//projects", "invalid path") + self.refused("https://h.org/projects?x=1", "query not allowed") + self.refused("https://h.org/projects?page%5Bsize%5D=1&page%5Bsize%5D=2", "query not allowed") + self.refused("https://h.org/projects?page%5Bsize%5D=x", "query not allowed") + + +class Relay(unittest.TestCase): + @classmethod + def setUpClass(cls): + import os + cls.up = start(FakeSysml) + os.environ["ALLOWED_SYSML_SERVER_ORIGINS"] = f"http://127.0.0.1:{cls.up.server_address[1]}" + cls.viewer = start(serve.Handler) + cls.U = f"http://127.0.0.1:{cls.up.server_address[1]}" + cls.R = f"http://127.0.0.1:{cls.viewer.server_address[1]}" + + @classmethod + def tearDownClass(cls): + import os + os.environ.pop("ALLOWED_SYSML_SERVER_ORIGINS", None) + cls.up.shutdown(); cls.viewer.shutdown() + + def get(self, path, headers=None): + req = urllib.request.Request(self.R + path, headers=headers or {}) + try: + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, r.headers, r.read() + except urllib.error.HTTPError as e: + return e.code, e.headers, e.read() + + def relay(self, url, headers=None): + return self.get("/relay?url=" + urllib.parse.quote(url, safe=""), headers) + + def test_page_and_config(self): + status, _, body = self.get("/") + self.assertEqual(status, 200) + self.assertIn(b'id="sysmod-viewer"', body) + status, _, body = self.get("/viewer-config.json") + self.assertEqual(json.loads(body)["relay"]["servers"], [self.U]) + self.assertEqual(self.get("/serve.py")[0], 404) + + def test_relayed_with_token_and_paging(self): + status, _, body = self.relay(self.U + "/projects?page%5Bsize%5D=1000", {"X-Relay-Authorization": "Bearer t"}) + data = json.loads(body)[0] + self.assertEqual((status, data["auth"], data["query"]), (200, "Bearer t", "page%5Bsize%5D=1000")) + status, headers, _ = self.relay(self.U + "/projects/p-1/commits/c/elements") + self.assertEqual(headers["Link"], f"<{self.U}/projects/p-1/commits/c/elements?page%5Bafter%5D=e-1>; rel=\"next\"") + self.assertIsNone(headers.get("Access-Control-Allow-Origin")) + + def test_errors(self): + self.assertEqual(self.relay(self.U + "/projects/secret")[0], 401) + self.assertEqual(self.relay(self.U + "/projects/nothing")[0], 404) + self.assertEqual(self.relay(self.U + "/projects/redirect")[0], 502) + self.assertIn(b"did not answer with JSON", self.relay(self.U + "/projects/html")[2]) + self.assertEqual(self.relay(self.U + "/admin")[0], 400) + self.assertEqual(self.relay("http://127.0.0.1:1/projects")[0], 400) # not on the list + self.assertEqual(self.relay("https://example.org/projects")[0], 400) + self.assertEqual(self.relay(self.U + "/projects", {"Sec-Fetch-Site": "cross-site"})[0], 403) + status, headers, _ = self.relay(self.U + "/admin") + self.assertEqual(headers["X-Relay-Error"], "1") + + +if __name__ == "__main__": + unittest.main() diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..e369ff0 --- /dev/null +++ b/web/index.html @@ -0,0 +1,109 @@ + + + + + + + SYSMOD Viewer + + + + +
+
+

tool

+

SYSMOD Viewer

+

+ Shows a SYSMOD project of a SysML v2 model the way the method structures it: the SYSMOD Atlas, the problem statement, + the system idea and its objectives, stakeholders, needs, system requirements, system use cases and the system context of every architecture. + It reads the model with the SysML v2 API (OMG Systems Modeling API). A single page, no server of its own: everything runs in your browser. +

+
+ +
+ + + + +
+
+ +
+

Good to know

+
    +
  • Run it: python web/serve.py, then open http://localhost:8080/. The script needs only Python 3, no packages. Browsers do not run the page from a file:// address.
  • +
  • CORS and http: a page can only read servers that allow requests from it. serve.py also relays the requests (read-only) to the servers in ALLOWED_SYSML_SERVER_ORIGINS (default http://localhost:9000), including plain http:// ones and servers without CORS.
  • +
  • Token: optional, passed on as header Authorization; it stays in the page and is never stored. The page address records server, project and commit (not the token).
  • +
  • SYSMOD v5: the project is an occurrence def with #project or a specialization of SYSMOD::Project; the SYSMOD library must be in the same project.
  • +
  • Read-only. Editing, the AI suggestions and the creation wizard are in the Flask server of this repository (sysmod_api_server.py).
  • +
+
+
+ + + diff --git a/web/serve.py b/web/serve.py new file mode 100644 index 0000000..ea7f89f --- /dev/null +++ b/web/serve.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python3 +""" +Serves the single-page SYSMOD viewer (this folder) and relays its requests to SysML v2 API servers. + + python web/serve.py # http://localhost:8080/ + python web/serve.py --port 9090 + +Only the Python standard library, no packages. + +Why a relay: a web page may only read servers that allow requests from it (CORS), and a page may not call +plain-http servers from https. The relay asks the server on behalf of the page, so every allowed SysML v2 API server +works, also e.g. http://sysml2.intercax.com:9000 or a server without CORS such as Flexo: + + ALLOWED_SYSML_SERVER_ORIGINS=http://localhost:9000,http://sysml2.intercax.com:9000 python web/serve.py + +The relay is narrow: + - it listens on localhost only (unless --host says otherwise); + - only GET of the read endpoints of the SysML v2 API (/projects, /projects/{id}, .../branches, .../commits, + .../commits/{id}/elements[/{id}], optionally behind a path prefix such as /api/v1) and only the paging query + page[size], page[after], page[before]; http and https; no redirects followed; JSON only; + - the token (header X-Relay-Authorization) is passed on as Authorization and never stored or logged. + - only the servers in ALLOWED_SYSML_SERVER_ORIGINS (comma-separated origins, as for the Flask server; default + http://localhost:9000, http://127.0.0.1:9000, http://[::1]:9000); +The same rules as relay.php of mbse4u.com/tools/sysmod-viewer/, which in addition has an allowlist of servers. +""" +import argparse +import json +import os +import re +import sys +import urllib.error +import urllib.parse +import urllib.request +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +HERE = Path(__file__).resolve().parent +TIMEOUT = 60 +MAX_BYTES = 64 * 1024 * 1024 +QUERY_KEYS = ("page[size]", "page[after]", "page[before]") +SEGMENT_CHARS = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._~%-") +PREFIX_CHARS = SEGMENT_CHARS - {"%"} +# what may follow /projects: {id}, {id}/branches[/{id}], {id}/commits[/{id}[/elements[/{id}]]] +READ_ENDPOINTS = {(), ("*",), ("*", "branches"), ("*", "branches", "*"), ("*", "commits"), ("*", "commits", "*"), + ("*", "commits", "*", "elements"), ("*", "commits", "*", "elements", "*")} + + +def _is_segment(seg: str, chars=SEGMENT_CHARS, longest=200) -> bool: + return 0 < len(seg) <= longest and set(seg) <= chars + + +def _is_read_path(path: str) -> bool: + """/projects…: a read endpoint of the SysML v2 API, optionally behind up to three prefix segments (e.g. /api/v1).""" + segments = path.split("/")[1:] if path.startswith("/") else [] + if "projects" not in segments: + return False + i = segments.index("projects") + if i > 3 or not all(_is_segment(x, PREFIX_CHARS, 60) for x in segments[:i]): + return False + rest = segments[i + 1:] + shape = tuple("*" if k % 2 == 0 else x for k, x in enumerate(rest)) + ids_ok = all(_is_segment(x) for x in rest[0::2]) + return shape in READ_ENDPOINTS and ids_ok + + +DEFAULT_ORIGINS = "http://localhost:9000,http://127.0.0.1:9000,http://[::1]:9000" # as sysmod_api_server.py + + +def allowed_origins(): + """The servers the relay may ask: ALLOWED_SYSML_SERVER_ORIGINS, as for the Flask server.""" + raw = os.environ.get("ALLOWED_SYSML_SERVER_ORIGINS", DEFAULT_ORIGINS) + return [o.strip().rstrip("/").lower() for o in raw.split(",") if o.strip()] + + +def viewer_config(): + return {"relay": {"url": "relay", "servers": allowed_origins(), "label": "the local relay (serve.py)", + "contact": "the variable ALLOWED_SYSML_SERVER_ORIGINS of serve.py"}} + + +def _check_form(p): + """The parts of the address: scheme, host, no user info or fragment. '' if fine, else the reason.""" + if p.scheme.lower() not in ("http", "https") or not p.hostname: + return "only http and https" + if p.username or p.password or p.fragment: + return "invalid address" + return "" + + +def _check_path(path: str): + """A read endpoint of the SysML v2 API, without traversal. '' if fine, else the reason.""" + if "//" in path: + return "invalid path" + for segment in path.split("/"): + d = urllib.parse.unquote(segment) + if d in (".", "..") or any(c in d for c in "/\\\0"): + return "invalid path" + if not _is_read_path(path): + return "not a read endpoint of the SysML v2 API" + return "" + + +def _paging_query(query: str): + """The paging parameters, each once, re-encoded; None if anything else is in the query.""" + pairs = {} + for pair in filter(None, (query or "").split("&")): + k, _, v = pair.partition("=") + k, v = urllib.parse.unquote(k), urllib.parse.unquote(v) + valid = k in QUERY_KEYS and k not in pairs and len(v) <= 200 and not re.search(r"[\x00-\x1f\x7f]", v) + if not valid or (k == "page[size]" and not re.fullmatch(r"\d{1,5}", v)): + return None + pairs[k] = v + return "&".join(urllib.parse.quote(k, safe="") + "=" + urllib.parse.quote(v, safe="") for k, v in pairs.items()) + + +def _allowed_base(p): + """The entry of ALLOWED_SYSML_SERVER_ORIGINS for the server of the address, or None.""" + host = p.hostname.lower() + origin = f"{p.scheme.lower()}://" + (f"[{host}]" if ":" in host else host) + (f":{p.port}" if p.port else "") + return next((allowed for allowed in allowed_origins() if allowed == origin), None) + + +def check_url(url: str): + """The address to request, or (None, reason). Same rules as relay.php of mbse4u.com.""" + if not url or len(url) > 2048 or re.search(r"[\x00-\x20\x7f\\]", url): + return None, "invalid address" + p = urllib.parse.urlsplit(url) + reason = _check_form(p) or _check_path(p.path or "") + if reason: + return None, reason + query = _paging_query(p.query) + if query is None: + return None, "query not allowed" + # the server part of the request is taken from the allowlist, never from the address the page sent + base = _allowed_base(p) + if base is None: + return None, "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)" + return base + (p.path or "") + ("?" + query if query else ""), "" + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None # a redirect is answered as an HTTP error, never followed + + +OPENER = urllib.request.build_opener(NoRedirect) + + +class Handler(SimpleHTTPRequestHandler): + def __init__(self, *args, **kwargs): + super().__init__(*args, directory=str(HERE), **kwargs) + + def log_message(self, fmt, *args): # no query strings in the log (they may name projects) + sys.stderr.write("%s %s\n" % (self.command, self.path.split("?")[0])) + + def end_headers(self): + self.send_header("Cache-Control", "no-store") + self.send_header("X-Content-Type-Options", "nosniff") + super().end_headers() + + def answer(self, status, body: bytes, headers=None): + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.end_headers() + self.wfile.write(body) + + def fail(self, status, message): + self.answer(status, json.dumps({"error": message}).encode(), {"X-Relay-Error": "1"}) + + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + if path == "/viewer-config.json": + return self.answer(200, json.dumps(viewer_config()).encode()) + if path == "/relay": + return self.relay() + if path.endswith(".py"): + return self.send_error(404) + return super().do_GET() + + def do_POST(self): + self.fail(405, "only GET") + + def relay(self): + site = self.headers.get("Sec-Fetch-Site", "") + if site not in ("", "same-origin", "none"): + return self.fail(403, "only for the SYSMOD viewer of this server") + params = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query) + target, error = check_url((params.get("url") or [""])[0]) + if not target: + return self.fail(400, error) + try: + status, body, headers = fetch(target, self.headers.get("X-Relay-Authorization") or self.headers.get("Authorization")) + except RelayError as e: + return self.fail(e.status, str(e)) + extra = {} + link = headers.get("Link") + if link and "\r" not in link and "\n" not in link: + extra["Link"] = link # unchanged: the viewer resolves the next page against the server's address + self.answer(status, json_or_error(body, status), extra) + + +class RelayError(Exception): + def __init__(self, status, message): + super().__init__(message) + self.status = status + + +def fetch(target, auth): + """GET of the target, without following redirects. (status, body, headers); RelayError if the relay cannot answer.""" + headers = {"Accept": "application/json", "User-Agent": "SYSMOD-viewer-relay/1"} + if auth and len(auth) < 8192 and "\r" not in auth and "\n" not in auth: + headers["Authorization"] = auth + try: + with OPENER.open(urllib.request.Request(target, headers=headers), timeout=TIMEOUT) as r: + status, body, rh = r.status, r.read(MAX_BYTES + 1), r.headers + except urllib.error.HTTPError as e: + if 300 <= e.code < 400: + raise RelayError(502, "the server answered with a redirect, which the relay does not follow") from None + status, body, rh = e.code, e.read(MAX_BYTES + 1), e.headers + except OSError as e: # URLError and TimeoutError are OSErrors + if "timed out" in str(e).lower(): + raise RelayError(504, "the server did not answer in time") from None + raise RelayError(502, "the server could not be reached") from None + if len(body) > MAX_BYTES: + raise RelayError(502, "the answer of the server is too large for the relay") + return status, body, rh + + +def json_or_error(body: bytes, status: int) -> bytes: + """The body if it is JSON, else a JSON error (an HTML error page of the server is not passed on).""" + try: + json.loads(body or b"null") + return body + except ValueError: + return json.dumps({"error": "the server did not answer with JSON", "status": status}).encode() + + +def main(): + ap = argparse.ArgumentParser(description="Serves the SYSMOD viewer and relays its requests to SysML v2 API servers.") + ap.add_argument("--port", type=int, default=8080) + ap.add_argument("--host", default="127.0.0.1", help="default 127.0.0.1: only this computer can use the relay") + a = ap.parse_args() + server = ThreadingHTTPServer((a.host, a.port), Handler) + print(f"SYSMOD viewer on port {a.port} of {a.host}: open localhost:{a.port} in the browser (Ctrl+C to stop)") + print("Servers it may read (ALLOWED_SYSML_SERVER_ORIGINS): " + ", ".join(allowed_origins())) + try: + # Plain HTTP on purpose: a local development server (127.0.0.1 by default). + server.serve_forever() # NOSONAR + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/web/sysmod-viewer-api.js b/web/sysmod-viewer-api.js new file mode 100644 index 0000000..59479d9 --- /dev/null +++ b/web/sysmod-viewer-api.js @@ -0,0 +1,231 @@ +/* sysmod-viewer-api.js: the requests of the SYSMOD viewer to a SysML v2 REST API server (OMG Systems Modeling API, + e.g. the SysML v2 Pilot Implementation's API services or Open-MBEE Flexo). Pure ES module; runs in the browser and in Node. + + Used by the single-page SYSMOD viewer of github.com/Open-MBEE/sysmod-sysmlv2-api (web/) and by mbse4u.com/tools/sysmod-viewer/. + + The browser talks to the server DIRECTLY: there is no server of the viewer in between. That needs + - CORS: the server must allow requests from the page's origin (Access-Control-Allow-Origin), with a token also the + header Authorization (Access-Control-Allow-Headers); for paging it should expose the header Link. + - HTTPS: a page on https:// may not call an http:// server. Exception: http://localhost and http://127.0.0.1. + + Servers that do not allow it (or have no https) can be reached through a relay on the origin of the page: + createClient({ baseUrl, relay: { url: '/relay', servers: ['https://flexo.systemsmodeling.com'], label: 'the relay of mbse4u.com', contact: 'info@mbse4u.com' } }) + Then every request to such a server goes to ?url=
, the token as header X-Relay-Authorization. + servers: ['*'] sends every server through the relay (web/serve.py, the local relay of the repository). + Relays: web/serve.py (local, any server), mbse4u.com/tools/sysmod-viewer/relay.php (allowlist relay-servers.json). + + const api = createClient({ baseUrl: 'https://sysml.example.org', token: 'Bearer …' }); + await api.projects(); // [{ '@id', name, description, created, defaultBranch }] + await api.commits(projectId); // newest first + await api.elements(projectId, commitId, { onProgress: (n) => … , signal }); // all elements of the commit +*/ + +export class ApiError extends Error { + constructor(message, { status = 0, url = '', hint = '' } = {}) { + super(message); + this.name = 'ApiError'; + this.status = status; + this.url = url; + this.hint = hint; + } +} + +/** Removes trailing slashes, in linear time (no regular expression anchored at the end). */ +function trimSlashes(s) { + let e = s.length; + while (e > 0 && s[e - 1] === '/') e--; + return s.slice(0, e); +} + +const LOCAL_HOSTS = ['localhost', '127.0.0.1', '[::1]']; +const isLocal = (u) => LOCAL_HOSTS.includes(u.hostname); +const hasScheme = (s) => /^[a-z][a-z0-9+.-]*:\/\//i.test(s); +const startsWithLocalHost = (s) => LOCAL_HOSTS.some((h) => s.toLowerCase().startsWith(h) && [undefined, ':', '/'].includes(s[h.length])); + +/** The base path of the API: the path in front of /projects (a pasted address may contain /projects/…). */ +function basePath(pathname) { + const i = pathname.indexOf('/projects'); + const end = i + '/projects'.length; + const isSegment = i >= 0 && (pathname.length === end || pathname[end] === '/'); + return trimSlashes(isSegment ? pathname.slice(0, i) : pathname); +} + +/** Normalizes what a user pastes: no trailing slash, no /projects…, scheme added if missing. */ +export function normalizeBaseUrl(input) { + let s = String(input || '').trim(); + if (!s) return ''; + if (!hasScheme(s)) { + const scheme = startsWithLocalHost(s) ? 'http://' : 'https://'; + s = scheme + s; + } + const u = new URL(s); + if (u.protocol !== 'https:' && u.protocol !== 'http:') throw new ApiError('The address must start with https:// (or http:// for a server on this computer).'); + u.hash = ''; + u.search = ''; + u.pathname = basePath(u.pathname); + return trimSlashes(u.href); +} + +const LOCAL_RELAY = 'Or run the viewer locally with its relay (python web/serve.py of github.com/Open-MBEE/sysmod-sysmlv2-api).'; +const relayOffer = (contact, problem) => (contact ? 'If the server ' + problem + ', it can be added to the relay of this page: write to ' + contact + '.' : LOCAL_RELAY); + +/** A reason why the browser will not even send the request (mixed content), or '' */ +export function blockedReason(baseUrl, pageProtocol = globalThis.location?.protocol, contact = '') { + const u = new URL(baseUrl); + if (pageProtocol !== 'https:' || u.protocol !== 'http:' || isLocal(u)) return ''; + return 'This page is loaded over HTTPS, so your browser does not allow it to call a server over plain HTTP. Use the https:// address of the server. ' + + 'A server on your own computer (http://localhost) is the exception. ' + relayOffer(contact, 'has no https address'); +} + +/** The next page from a Link header: ; rel="next" (parsed without regular expressions) */ +export function nextFromLink(header) { + if (!header) return null; + for (const part of header.split(',')) { + const open = part.indexOf('<'), close = part.indexOf('>', open + 1); + if (open < 0 || close < 0) continue; + const params = part.slice(close + 1).split(';').map((x) => x.trim().toLowerCase().replaceAll('"', '')); + if (params.includes('rel=next')) return part.slice(open + 1, close).trim(); + } + return null; +} + +/** Is this address on a server that the relay serves? relay.servers are origins (https://host[:port]), or '*'. */ +export function usesRelay(url, relay) { + if (!relay?.url || !Array.isArray(relay.servers)) return false; + if (relay.servers.includes('*')) return true; + try { + const origin = new URL(url).origin.toLowerCase(); + return relay.servers.some((s) => trimSlashes(String(s)).toLowerCase() === origin); + } catch { + return false; + } +} + +const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1); +/** The header Authorization from what the user enters: "Bearer …", "Basic …" or the bare token */ +function authorization(token) { + const t = String(token || '').trim(); + if (!t) return ''; + return /^(bearer|basic)\s/i.test(t) ? t : 'Bearer ' + t; +} +/** The list of items in an answer: an array, or { elements: [...] } */ +function itemsOf(body) { + if (Array.isArray(body)) return body; + return Array.isArray(body?.elements) ? body.elements : null; +} + +/** The address of the next page, or null: from the Link header, else page[after]= if the page was full */ +function nextUrl({ link, url, items, fresh, size, first }) { + if (!fresh) return null; + const next = nextFromLink(link); + if (next) return new URL(next, url).href; + const last = items.at(-1)?.['@id']; + return items.length >= size && last ? first + '&page%5Bafter%5D=' + encodeURIComponent(last) : null; +} + +export function createClient({ baseUrl, token = '', relay = null, fetch: fetchFn = globalThis.fetch.bind(globalThis), pageSize = 256 } = {}) { + // 256 per page: some servers take too long for larger pages (e.g. sysml2.intercax.com) + const base = normalizeBaseUrl(baseUrl); + if (!base) throw new ApiError('Enter the address of a SysML v2 API server.'); + const auth = authorization(token); + const viaRelay = usesRelay(base, relay); + const relayLabel = relay?.label || 'the relay'; + const contact = relay?.contact || ''; + + /** The request as the browser sends it: to the server, or to the relay with the address as parameter */ + function request(url, relayed, signal) { + const headers = { Accept: 'application/json' }; + if (auth) headers[relayed ? 'X-Relay-Authorization' : 'Authorization'] = auth; + const target = relayed ? relay.url + '?url=' + encodeURIComponent(url) : url; + return fetchFn(target, { headers, signal, credentials: 'omit', mode: 'cors' }); + } + + function unreachable(url, relayed) { + if (relayed) return new ApiError(capitalize(relayLabel) + ' could not be reached.', { url, hint: 'Check your connection and try again.' }); + const tokenHint = auth ? 'With a token the server must also allow the header Authorization in its CORS settings. ' : ''; + return new ApiError('The server could not be reached.', { + url, + hint: 'Most likely the server does not allow requests from this page (CORS); otherwise the address is wrong or the server is down. ' + + 'The developer console of your browser (F12) shows the exact reason. ' + tokenHint + relayOffer(contact, 'cannot allow it'), + }); + } + + /** An error for an answer that is not OK, or null */ + async function answerError(r, url, relayed) { + if (relayed && r.headers.get('X-Relay-Error')) { + let msg = ''; + try { msg = (await r.json()).error || ''; } catch { /* not JSON */ } + return new ApiError(capitalize(relayLabel) + ': ' + (msg || 'HTTP ' + r.status) + '.', { status: r.status, url }); + } + if (r.status === 401 || r.status === 403) { + const hint = auth ? 'Check the token.' : 'The server needs a token: enter it under "Token".'; + return new ApiError('The server refused access (HTTP ' + r.status + ').', { status: r.status, url, hint }); + } + if (r.status === 404) return new ApiError('Not found (HTTP 404).', { status: 404, url, hint: 'Is this the base address of the API? It is the address in front of /projects.' }); + if (!r.ok) return new ApiError('The server answered with HTTP ' + r.status + '.', { status: r.status, url }); + return null; + } + + async function readJson(r, url, relayed) { + try { + return await r.json(); + } catch { + if (relayed) throw new ApiError('The relay did not answer with JSON.', { url, hint: 'Is ' + relayLabel + ' running? (It is a server-side script; a static development server does not run it.)' }); + throw new ApiError('The server did not answer with JSON.', { url, hint: 'Is this the address of a SysML v2 API server?' }); + } + } + + async function get(url, signal) { + const relayed = usesRelay(url, relay); + const blocked = relayed ? '' : blockedReason(url, globalThis.location?.protocol, contact); + if (blocked) throw new ApiError('The browser blocks this address.', { url, hint: blocked }); + let r; + try { + r = await request(url, relayed, signal); + } catch (e) { + if (e?.name === 'AbortError') throw e; + throw unreachable(url, relayed); + } + const error = await answerError(r, url, relayed); + if (error) throw error; + const body = await readJson(r, url, relayed); + return { body, link: r.headers.get('Link') || r.headers.get('link') }; + } + + /** All pages of a list resource. Follows the Link header; without it (not exposed by CORS) page[after]=. */ + async function list(path, { signal, onProgress, size = pageSize } = {}) { + const sep = path.includes('?') ? '&' : '?'; + const first = base + path + sep + 'page%5Bsize%5D=' + size; + const paging = { first, size, signal, onProgress, out: [], seen: new Set() }; + await readPages(first, paging, 0); + return paging.out; + } + + /** Reads the page at url and, one after the other, the pages after it (at most 10000) */ + async function readPages(url, paging, page) { + if (!url || page >= 10000) return; + const { body, link } = await get(url, paging.signal); + const items = itemsOf(body); + if (!items) throw new ApiError('The server did not answer with a list.', { url, hint: 'Is this the address of a SysML v2 API server?' }); + const fresh = items.filter((it) => !paging.seen.has(it?.['@id'])); + for (const it of fresh) { + if (it?.['@id']) paging.seen.add(it['@id']); + } + paging.out.push(...fresh); + paging.onProgress?.(paging.out.length); + await readPages(nextUrl({ link, url, items, fresh: fresh.length, size: paging.size, first: paging.first }), paging, page + 1); + } + + const time = (c) => Date.parse(c.created || c.timestamp || '') || 0; + const byName = (a, b) => String(a.name || '').localeCompare(String(b.name || '')); + + return { + base, + viaRelay, + projects: async (opts) => (await list('/projects', opts)).toSorted(byName), + project: async (id, opts) => (await get(base + '/projects/' + encodeURIComponent(id), opts?.signal)).body, + branches: (id, opts) => list('/projects/' + encodeURIComponent(id) + '/branches', opts), + commits: async (id, opts) => (await list('/projects/' + encodeURIComponent(id) + '/commits', opts)).toSorted((a, b) => time(b) - time(a)), + elements: (id, commit, opts) => list('/projects/' + encodeURIComponent(id) + '/commits/' + encodeURIComponent(commit) + '/elements', opts), + }; +} diff --git a/web/sysmod-viewer-core.js b/web/sysmod-viewer-core.js new file mode 100644 index 0000000..52b16d4 --- /dev/null +++ b/web/sysmod-viewer-core.js @@ -0,0 +1,675 @@ +/* sysmod-viewer-core.js: reads a SYSMOD project from the elements of a SysML v2 model, as the SysML v2 REST API delivers them. + Pure ES module without dependencies: runs in the browser (page /tools/sysmod-viewer/) and in Node (scripts/test-sysmod-viewer.mjs). + + Port of the reading part of github.com/Open-MBEE/sysmod-sysmlv2-api (sysmod_api_helpers.py) and + github.com/MBSE4U/mbse4u_sysmlv2_helpers (Apache License 2.0, Tim Weilkiens and contributors), adapted to SYSMOD v5 + (SYSMOD::Project with brownfieldContext, systemIdeaContext, specificationContext, functionalContext, logicalContext, + productContext and their *Impl white box variants). Differences to the Python original: + - The whole commit is loaded once (paged), then everything is read locally. No request per element. + - Roles of the project are found by their DIRECT redefinition/subsetting of the library feature (:>> problemStatement), + not by any specialization: specificationContext also specializes systemIdeaContext, the direct relation tells them apart. + - Read-only. No AI, no writing commits. + + const model = createModel(elements); // elements: array of SysML v2 API element objects (with derived properties) + const projects = findProjects(model); // [{ id, name, qualifiedName }] + const view = readProject(model, projects[0].id); // everything the viewer shows, plain data, see readProject() +*/ + +export const SYSMOD = { + project: 'SYSMOD::Project', + soi: 'SYSMOD::SystemContext::systemOfInterest', + actors: 'SYSMOD::SystemContext::actors', + useCases: 'SYSMOD::SystemContext::useCases', +}; + +/** The contexts of a SYSMOD v5 project, in the order of the SYSMOD Atlas. key = atlas id, role = feature of SYSMOD::Project. */ +export const CONTEXTS = [ + { key: 'BFAC', role: 'brownfieldContext', title: 'Brownfield Architecture', space: 'solution' }, + { key: 'SIC', role: 'systemIdeaContext', title: 'System Idea Architecture', space: 'solution' }, + { key: 'SC', role: 'specificationContext', title: 'System Specification', space: 'problem' }, + { key: 'FUC', role: 'functionalContext', title: 'Functional Architecture', space: 'solution' }, + { key: 'LAC', role: 'logicalContext', title: 'Logical Architecture', space: 'solution' }, + { key: 'PAC', role: 'productContext', title: 'Product Architecture', space: 'solution' }, +]; + +const ref = (r) => (r && typeof r === 'object' ? r['@id'] : r) || null; +const asList = (v) => { + if (Array.isArray(v)) return v; + return v ? [v] : []; +}; +const refs = (v) => asList(v).map(ref).filter(Boolean); +/** Adds a value to the list of a key in a Map of lists. */ +const addTo = (map, key, value) => { + const list = map.get(key); + if (list) list.push(value); + else map.set(key, [value]); +}; +/** The definition of a MetadataUsage */ +const metadataDefOf = (M, mu) => M.get(mu.metadataDefinition) || M.all(mu.definition)[0]; +/** Does the type of an element match a type or one of a list of types? */ +const isOfType = (el, type) => (Array.isArray(type) ? type.includes(el['@type']) : el['@type'] === type); + +/** Element access over an array of elements. Unknown ids (e.g. the standard library, not part of the project) give null. */ +export function createModel(elements) { + const byId = new Map(); + for (const e of elements) { + if (e?.['@id']) byId.set(e['@id'], e); + } + let byQName = null, byType = null, annotations = null; + const M = { + size: byId.size, + get: (r) => byId.get(ref(r)) ?? null, + all: (rs) => refs(rs).map((id) => byId.get(id)).filter(Boolean), + /** first element with this qualified name; library elements are preferred over model elements with the same name */ + byQName(qn) { + if (!byQName) { + byQName = new Map(); + for (const e of byId.values()) { + if (e.qualifiedName && !byQName.has(e.qualifiedName)) byQName.set(e.qualifiedName, e); + } + } + return byQName.get(qn) ?? null; + }, + ofType(t) { + if (!byType) { + byType = new Map(); + for (const e of byId.values()) addTo(byType, e['@type'], e); + } + return byType.get(t) ?? []; + }, + /** ids of the metadata definitions applied to an element (#user, #system, ...), from the MetadataUsages */ + metadataOf(el) { + if (!annotations) { + annotations = new Map(); + for (const mu of M.ofType('MetadataUsage')) { + const def = metadataDefOf(M, mu); + if (!def) continue; + for (const a of refs(mu.annotatedElement)) addTo(annotations, a, def); + } + } + return annotations.get(ref(el)) ?? []; + }, + }; + return M; +} + +/** An element of the SYSMOD library itself (SYSMOD, SYSMOD15288, SYSMOD4AI, SYSMODViews …) or of another library */ +export const isLibrary = (el) => !!el && (el.isLibraryElement === true || /^SYSMOD\w*::/.test(el.qualifiedName || '')); + +export const nameOf = (el) => (el && (el.name ?? el.declaredName ?? el.shortName ?? el.declaredShortName)) || ''; + +/** The general elements of an element: what it redefines, subsets, is typed by, specializes. */ +function generals(M, el) { + const out = []; + for (const s of M.all(el.ownedSpecialization)) { + const g = ref(s.general); + if (g) out.push(g); + } + // some servers omit ownedSpecialization on usages: typing and redefinition are specializations as well + for (const t of refs(el.type)) out.push(t); + return out; +} + +/** Does el specialize target (transitively, also over typing)? el === target counts. */ +export function specializes(M, el, target) { + const goal = ref(target); + if (!el || !goal) return false; + const seen = new Set(), todo = [ref(el)]; + while (todo.length) { + const id = todo.pop(); + if (id === goal) return true; + if (seen.has(id)) continue; + seen.add(id); + const e = M.get(id); + if (e) todo.push(...generals(M, e)); + } + return false; +} + +/** Does el redefine or subset target directly (:>> target, :> target)? */ +export function directlySpecializes(M, el, target) { + const goal = ref(target); + return M.all(el.ownedSpecialization).some((s) => ref(s.general) === goal); +} + +/** Documentation text of an element; with viaDefinition the documentation of its definition if it has none of its own. */ +export function docOf(M, el, viaDefinition = true) { + if (!el) return ''; + const own = M.all(el.documentation).map((d) => cleanDoc(d.body)).filter(Boolean); + if (own.length) return own.join('\n\n'); + // the text of the definition, but not the generic text of a SYSMOD library definition ("Base element for concerns.") + if (!viaDefinition) return ''; + for (const d of definitionsOf(M, el)) { + const t = isLibrary(d) ? '' : docOf(M, d, false); + if (t) return t; + } + return ''; +} + +/** The most specific definitions of a usage: a definition that another one of the list specializes is left out. */ +export function definitionsOf(M, el) { + const defs = M.all(el?.definition ?? el?.type); + return defs.filter((d) => !defs.some((o) => o !== d && specializes(M, o, d))); +} + +/** Removes the comment layout that some servers keep in the body (leading asterisks of continued lines). */ +export function cleanDoc(body) { + if (typeof body !== 'string') return ''; + // without regular expressions anchored at the end (linear time also for long texts) + let t = body.trim(); + if (t.startsWith('/*')) { + let i = 1; + while (i < t.length && t[i] === '*') i++; + t = t.slice(i); + } + if (t.endsWith('*/')) { + let e = t.length - 1; + while (e > 0 && t[e - 1] === '*') e--; + t = t.slice(0, e); + } + const lines = t.split('\n').map((l) => { + const s = l.trimStart(); + return (s.startsWith('*') ? s.slice(1) : s).trim(); + }); + const out = []; + for (const l of lines) { + if (l || (out.length && out.at(-1) !== '')) out.push(l); // at most one blank line + } + return out.join('\n').trim(); +} + +/** + * All features of an element, effective: its own and the inherited ones, a redefined feature replaced by its redefinition. + * Computed here over the generalizations (typing, subclassification, subsetting, redefinition), because not every server + * delivers the derived inheritedFeature; what the server delivers in feature/inheritedFeature is added. + */ +export function featuresOf(M, el, type) { + if (!el) return []; + const all = M.effective ? M.effective(el) : effectiveFeatures(M, el); + return type ? all.filter((f) => isOfType(f, type)) : all; +} +function effectiveFeatures(M, el) { + const cache = (M._eff ||= new Map()); + const hit = cache.get(el['@id']); + if (hit) return hit; + cache.set(el['@id'], []); // guards against cycles + const out = [], seen = new Set(), redefined = new Set(); + const add = (f) => { + if (!f || seen.has(f['@id']) || redefined.has(f['@id'])) return; + seen.add(f['@id']); + out.push(f); + for (const g of redefinedBy(M, f)) redefined.add(g); + }; + M.all(el.ownedFeature).forEach(add); + for (const g of generals(M, el)) { + const ge = M.get(g); + if (ge && ge !== el) effectiveFeatures(M, ge).forEach(add); + } + M.all(el.feature).forEach(add); + M.all(el.inheritedFeature).forEach(add); + // the nearest feature of a name wins (several paths of inheritance can bring redefinitions of the same feature) + const names = new Set(); + const result = out.filter((f) => { + if (redefined.has(f['@id'])) return false; + const n = nameOf(f); + if (!n) return true; + if (names.has(n)) return false; + names.add(n); + return true; + }); + cache.set(el['@id'], result); + return result; +} +/** The ids of the features a feature redefines */ +const redefinedBy = (M, f) => M.all(f.ownedSpecialization) + .filter((r) => r['@type'] === 'Redefinition') + .map((r) => ref(r.redefinedFeature ?? r.general)) + .filter(Boolean); + +/** Only the owned features (no inherited ones) */ +export const ownedFeaturesOf = (M, el, type) => M.all(el?.ownedFeature).filter((f) => !type || isOfType(f, type)); + +/** The feature of an element with this name (effective, inherited included) */ +export const featureNamed = (M, el, name, type) => featuresOf(M, el, type).find((f) => nameOf(f) === name) || null; + +/** Text of the value of an attribute (literal, enumeration literal, quantity, feature chain); '' if it has none. */ +export function valueOf(M, feature) { + if (!feature) return ''; + for (const r of M.all(feature.ownedRelationship)) { + if (r['@type'] !== 'FeatureValue') continue; + const t = exprText(M, M.get(r.value), 0); + if (t !== '') return t; + } + return ''; +} + +/** A readable text of an expression. Keeps to the common cases of SYSMOD attribute values. */ +export function exprText(M, e, depth = 0) { + if (!e || depth > 8) return ''; + const t = e['@type']; + if (t === 'LiteralInfinity') return '*'; + if ('value' in e && t.startsWith('Literal')) return String(e.value); + const text = EXPRESSIONS[t]; + return text ? text(M, e, depth) : ''; +} +const argTexts = (M, e, depth) => argsOf(M, e).map((a) => exprText(M, a, depth + 1)); +/** The texts of the kinds of expressions, by metaclass */ +const EXPRESSIONS = { + NullExpression: () => '', + FeatureReferenceExpression: (M, e) => nameOf(M.get(e.referent)), + FeatureChainExpression: (M, e, depth) => { + const target = M.get(e.targetFeature); + const chain = refs(target?.chainingFeature).length ? M.all(target.chainingFeature).map(nameOf) : [nameOf(target)]; + const src = argTexts(M, e, depth).find(Boolean); + return [src, ...chain].filter(Boolean).join('.'); + }, + OperatorExpression: (M, e, depth) => operatorText(e.operator, argTexts(M, e, depth)), + InvocationExpression: (M, e, depth) => { + const type = nameOf(M.all(e.instantiatedType ?? e.type)[0]); + return type + '(' + argTexts(M, e, depth).join(', ') + ')'; + }, +}; +function operatorText(op, args) { + if (op === '[') return (args[0] ?? '') + ' [' + (args[1] ?? '') + ']'; + if (op === ',') return args.filter(Boolean).join(', '); + if (op === '-' && args.length === 1) return '-' + args[0]; + if (args.length === 2 && op) return args[0] + ' ' + op + ' ' + args[1]; + return args.filter(Boolean).join(' '); +} +/** Arguments of an invocation: the values of its input parameters, in order. */ +function argsOf(M, e) { + const direct = M.all(e.argument); + if (direct.length) return direct; + return M.all(e.ownedFeature) + .filter((p) => !p.direction || p.direction === 'in') + .flatMap((p) => M.all(p.ownedRelationship).filter((r) => r['@type'] === 'FeatureValue').map((r) => M.get(r.value))) + .filter(Boolean); +} + +const valueNamed = (M, el, name) => valueOf(M, featureNamed(M, el, name, 'AttributeUsage')); + +/** The SYSMOD projects of the model: elements with #project, otherwise definitions that specialize SYSMOD::Project. */ +export function findProjects(M) { + const lib = M.byQName(SYSMOD.project); + const found = new Map(); + const isProjectMetadata = (def) => def?.declaredShortName === 'project' || def?.qualifiedName === 'SYSMOD::ProjectMetadata'; + for (const mu of M.ofType('MetadataUsage').filter((x) => isProjectMetadata(metadataDefOf(M, x)))) { + for (const a of M.all(mu.annotatedElement)) { + if (a !== lib) found.set(a['@id'], a); + } + } + if (!found.size && lib) { + const specialized = M.ofType('OccurrenceDefinition').filter((d) => d !== lib && !d.isLibraryElement && specializes(M, d, lib)); + for (const d of specialized) found.set(d['@id'], d); + } + const list = [...found.values()].map((p) => ({ id: p['@id'], name: nameOf(p) || '(unnamed project)', qualifiedName: p.qualifiedName || '' })); + list.sort((a, b) => a.name.localeCompare(b.name)); + return list; +} + +/** The features of the project that play a role of SYSMOD::Project (e.g. 'problemStatement'). */ +function roleOf(M, project, role, { transitive = false } = {}) { + const lib = M.byQName(`${SYSMOD.project}::${role}`); + if (!lib) return []; + const own = ownedFeaturesOf(M, project); + const direct = own.filter((f) => f !== lib && directlySpecializes(M, f, lib)); + if (direct.length || !transitive) return direct; + return own.filter((f) => f !== lib && specializes(M, f, lib)); +} + +/** Stereotype-like labels from the SYSMOD metadata on an element and the elements it redefines (#user, #system ...). */ +function stereotypesOf(M, el) { + const names = new Set(); + const seen = new Set(), todo = [el['@id']]; + while (todo.length && seen.size < 40) { + const id = todo.pop(); + if (seen.has(id)) continue; + seen.add(id); + for (const d of M.metadataOf(id)) names.add(d.declaredShortName || nameOf(d)); + todo.push(...redefinedOrSubsetted(M, M.get(id))); + } + names.delete(''); + return [...names]; +} +/** What a feature redefines or subsets (not its types) */ +function redefinedOrSubsetted(M, e) { + if (!e) return []; + return M.all(e.ownedSpecialization).filter((s) => s['@type'] !== 'FeatureTyping').map((s) => ref(s.general)).filter(Boolean); +} + +const brief = (M, el) => (el ? { id: el['@id'], name: nameOf(el), type: el['@type'], doc: docOf(M, el) } : null); +const typeNames = (M, el) => definitionsOf(M, el).map(nameOf).filter(Boolean); + +/** System of interest, actors, connections and (white box) internal parts of a context. */ +export function readContext(M, project, def) { + const ctx = roleOf(M, project, def.role)[0]; + if (!ctx) return null; + const impl = roleOf(M, project, `${def.role}Impl`)[0] || null; + const soiLib = M.byQName(SYSMOD.soi), actorsLib = M.byQName(SYSMOD.actors); + const parts = featuresOf(M, ctx, 'PartUsage'); + const soi = parts.find((p) => p !== soiLib && specializes(M, p, soiLib)) || null; + const actors = parts.filter((p) => p !== actorsLib && p !== soi && specializes(M, p, actorsLib)); + const links = contextLinks(M, ctx, { soi, actors, soiLib, actorsLib }); + // white box: the system of interest of the Impl context, its parts + const soiImpl = impl ? featuresOf(M, impl, 'PartUsage').find((p) => p !== soiLib && specializes(M, p, soiLib)) || null : null; + const inner = featuresOf(M, soiImpl || soi, 'PartUsage').filter((p) => !p.isLibraryElement && !specializes(M, p, actorsLib)); + return { + key: def.key, role: def.role, title: def.title, + context: { ...brief(M, ctx), types: typeNames(M, ctx) }, + impl: impl ? brief(M, impl) : null, + system: soi ? { ...brief(M, soi), types: typeNames(M, soi), stereotypes: stereotypesOf(M, soi), ports: portsOf(M, soi) } : null, + systemImpl: soiImpl ? { ...brief(M, soiImpl), types: typeNames(M, soiImpl) } : null, + actors: actors.map((a) => ({ ...brief(M, a), types: typeNames(M, a), stereotypes: stereotypesOf(M, a).filter((x) => x !== 'system'), ports: portsOf(M, a) })), + links, + parts: inner.map((p) => ({ ...brief(M, p), types: typeNames(M, p), multiplicity: multiplicityOf(M, p), ports: portsOf(M, p) })), + }; +} + +const CONNECTIONS = ['InterfaceUsage', 'ConnectionUsage', 'FlowUsage', 'SuccessionFlowUsage']; + +/** The ends of a connection: the owned ones (the inherited ends of the library point to the generic actors and soi) */ +function endsOf(M, c) { + for (const list of [c.ownedEndFeature, c.connectorEnd, c.relatedFeature]) { + const ends = M.all(list); + if (ends.length) return ends; + } + return []; +} + +/** The connections between the actors and the system of interest, with the ports they connect */ +function contextLinks(M, ctx, roles) { + const links = []; + for (const c of featuresOf(M, ctx, CONNECTIONS)) { + const hits = endsOf(M, c).map((end) => partOfEnd(M, end, roles)).filter(Boolean); + const ps = [...new Set(hits.map((x) => x.part))]; + if (ps.length !== 2 || !ps.includes(roles.soi)) continue; + const actor = ps.find((p) => p !== roles.soi); + const portOf = (part) => nameOf(hits.find((x) => x.part === part)?.port) || ''; + links.push({ id: c['@id'], name: nameOf(c), kind: c['@type'], actor: actor['@id'], actorPort: portOf(actor), systemPort: portOf(roles.soi) }); + } + return links; +} + +/** The soi or the actor a feature stands for: the part itself or one it redefines (e.g. the part of the context definition) */ +function matchRole(M, x, { soi, actors, soiLib, actorsLib }) { + if (!x || x === soiLib || x === actorsLib) return null; + if (soi && (x === soi || specializes(M, soi, x))) return soi; + return actors.find((a) => a === x || specializes(M, a, x)) || null; +} + +/** The feature an end refers to: by its reference subsetting (end :: operator.controlPort) */ +function referencedBy(M, e) { + const rs = M.all(e.ownedSpecialization).find((x) => x['@type'] === 'ReferenceSubsetting') || M.all(e.ownedReferenceSubsetting)[0]; + return rs ? M.get(rs.referencedFeature ?? rs.general) : null; +} + +/** One step from an end towards the part it connects: through a feature chain or a reference subsetting. + { next, port }: next = the next feature (null at the end of the way), port = a port met on the way */ +function stepOf(M, e) { + const chain = M.all(e.chainingFeature); + if (chain.length) { + const last = chain.at(-1); + return { next: chain[0], port: last['@type'] === 'PortUsage' ? last : null }; + } + return { next: referencedBy(M, e), port: null }; +} + +/** The part (soi or actor) an end connects, and the port it connects at (operator.controlPort -> operator, controlPort) */ +function partOfEnd(M, end, roles) { + let e = end, port = null; + for (let i = 0; e && i < 6; i++) { + const hit = matchRole(M, e, roles); + if (hit) return { part: hit, port }; + if (e['@type'] === 'PortUsage') port ||= e; + const step = stepOf(M, e); + if (step.port) port = step.port; + if (!step.next) { + // a port of the soi (or of a part that redefines it) also stands for the soi + const owner = matchRole(M, M.get(e.owningType ?? e.owner), roles); + return owner ? { part: owner, port } : null; + } + e = step.next; + } + return null; +} + +/** The ports of a part (effective, without the generic ports of the SYSMOD library such as actorPorts, systemPorts) */ +const portsOf = (M, el) => featuresOf(M, el, 'PortUsage').filter((p) => !isLibrary(p) && nameOf(p)).map((p) => ({ id: p['@id'], name: nameOf(p), types: typeNames(M, p) })); + +/** "1..*", "0..1", "" from the multiplicity of a feature */ +export function multiplicityOf(M, f) { + const m = M.get(f?.multiplicity); + if (!m) return ''; + const lo = exprText(M, M.get(m.lowerBound)), hi = exprText(M, M.get(m.upperBound)); + if (!lo && !hi) { + const bounds = M.all(m.ownedFeature).map((b) => valueOf(M, b) || exprText(M, b)); + if (bounds.length === 2) return `${bounds[0]}..${bounds[1]}`; + if (bounds.length === 1) return bounds[0]; + return ''; + } + return lo && hi && lo !== hi ? `${lo}..${hi}` : hi || lo; +} + +function readStakeholders(M, project) { + const ownerLib = M.byQName(`${SYSMOD.project}::projectOwner`); + const lib = M.byQName(`${SYSMOD.project}::projectStakeholders`); + // all owned features that are stakeholders, also the project owner (:>> projectOwner, which :> projectStakeholders) + const all = lib ? ownedFeaturesOf(M, project).filter((f) => f !== lib && f !== ownerLib && specializes(M, f, lib)) : []; + const isOwner = (f) => (ownerLib && specializes(M, f, ownerLib) ? 1 : 0); + const sorted = [...all]; + sorted.sort((a, b) => isOwner(b) - isOwner(a)); + return sorted.map((p) => ({ + id: p['@id'], + name: valueNamed(M, p, 'name') || nameOf(p), + element: nameOf(p), + types: typeNames(M, p), + owner: !!ownerLib && specializes(M, p, ownerLib), + doc: docOf(M, p), + contact: valueNamed(M, p, 'contact'), + risk: valueNamed(M, p, 'risk'), + effort: valueNamed(M, p, 'effort'), + categories: valueNamed(M, p, 'categories'), + })); +} + +/** Nested concerns/requirements of a root (the needs under stakeholderNeeds, the requirements under the specification) */ +function nestedOf(M, root, types, depth = 0, seen = new Set()) { + if (!root || depth > 6) return []; + const out = []; + for (const f of featuresOf(M, root, types)) { + if (seen.has(f['@id']) || f.isLibraryElement || !nameOf(f)) continue; + if (M.get(f.owningMembership)?.['@type'] === 'FramedConcernMembership') continue; // frame x: a reference, not a nested need + seen.add(f['@id']); + out.push({ el: f, depth }, ...nestedOf(M, f, types, depth + 1, seen)); + } + return out; +} + +const subjectStakeholders = (M, el) => featuresOf(M, el) + .filter((f) => f['@type'] === 'PartUsage' && M.get(f.owningMembership)?.['@type'] === 'StakeholderMembership') + .map((f) => { + const v = valueOf(M, f); + return v && v !== nameOf(f) ? v.split('.').pop() : nameOf(f); + }) + .filter(Boolean); + +function readNeeds(M, project) { + const root = roleOf(M, project, 'stakeholderNeeds')[0]; + return nestedOf(M, root, 'ConcernUsage').map(({ el, depth }) => ({ + id: el['@id'], depth, + name: nameOf(el), shortName: el.shortName || el.declaredShortName || '', + types: typeNames(M, el), + doc: docOf(M, el), + stakeholders: subjectStakeholders(M, el).join(', '), + priority: valueNamed(M, el, 'priority'), + })); +} + +function readRequirements(M, project) { + const root = roleOf(M, project, 'systemRequirementSpecification')[0]; + return { + specification: root ? { ...brief(M, root), types: typeNames(M, root) } : null, + requirements: nestedOf(M, root, ['RequirementUsage', 'ConcernUsage']).filter(({ el }) => el['@type'] === 'RequirementUsage').map(({ el, depth }) => ({ + id: el['@id'], depth, + shortName: el.shortName || el.declaredShortName || M.all(el.definition).map((d) => d.shortName || d.declaredShortName).find(Boolean) || '', + name: nameOf(el), + types: typeNames(M, el), + doc: docOf(M, el), + motivation: valueNamed(M, el, 'motivation'), + priority: valueNamed(M, el, 'priority'), + obligation: valueNamed(M, el, 'obligation'), + stability: valueNamed(M, el, 'stability'), + stakeholders: subjectStakeholders(M, el).join(', '), + })), + }; +} + +function readUseCases(M, ctx) { + if (!ctx) return []; + const lib = M.byQName(SYSMOD.useCases); + const el = M.get(ctx.context.id); + return featuresOf(M, el, 'UseCaseUsage').filter((u) => u !== lib && !u.isLibraryElement).map((u) => { + const objective = M.all(u.objectiveRequirement)[0] + || featuresOf(M, u, 'RequirementUsage').find((r) => M.get(r.owningMembership)?.['@type'] === 'ObjectiveMembership'); + const subject = M.get(u.subjectParameter) || featuresOf(M, u).find((f) => M.get(f.owningMembership)?.['@type'] === 'SubjectMembership'); + const steps = useCaseSteps(M, u); + const actors = M.all(u.actorParameter).map((a) => nameOf(a)).filter(Boolean); + return { + id: u['@id'], + name: nameOf(u), + types: typeNames(M, u), + doc: docOf(M, objective) || docOf(M, u), + subject: subject ? nameOf(subject) : '', + actors: actors.join(', '), + trigger: valueNamed(M, u, 'ucTrigger'), + result: valueNamed(M, u, 'ucResult'), + motivation: valueNamed(M, u, 'ucMotivation'), + precondition: modelDoc(M, featureNamed(M, u, 'precondition')), + postcondition: modelDoc(M, featureNamed(M, u, 'postcondition')), + steps, + }; + }); +} + +const ACTIONS = ['PerformActionUsage', 'ActionUsage', 'AcceptActionUsage', 'SendActionUsage']; +const LIBRARY_ACTIONS = new Set(['start', 'done', 'subactions', 'actions']); + +/** The steps of a use case: the actions the use case (or its definition) owns and the actions its subject performs for it */ +function useCaseSteps(M, u) { + const steps = new Set(); + for (const s of [u, ...definitionsOf(M, u)]) { + const subj = M.get(s.subjectParameter) || ownedFeaturesOf(M, s).find((f) => M.get(f.owningMembership)?.['@type'] === 'SubjectMembership'); + const actions = [subj, s].filter(Boolean).flatMap((owner) => ownedFeaturesOf(M, owner, ACTIONS)); + for (const a of actions) { + const n = nameOf(a); + if (n && !a.isLibraryElement && !LIBRARY_ACTIONS.has(n)) steps.add(n); + } + } + return [...steps]; +} + +/** Documentation of a feature of the model; '' for the inherited feature of the SYSMOD library with its generic text */ +const modelDoc = (M, f) => (f && !isLibrary(f) ? docOf(M, f) : ''); + +function readObjectives(M, project) { + const root = roleOf(M, project, 'systemObjectives')[0]; + return { + doc: docOf(M, root, false), + items: nestedOf(M, root, 'ConcernUsage').map(({ el, depth }) => ({ id: el['@id'], depth, name: nameOf(el), types: typeNames(M, el), doc: docOf(M, el) })), + }; +} + +/** UVL text of a feature tree (PLEML): element with #featureTree and a textual representation */ +function readFeatureTree(M) { + for (const mu of M.ofType('MetadataUsage')) { + if (metadataDefOf(M, mu)?.declaredShortName !== 'featureTree') continue; + for (const a of M.all(mu.annotatedElement)) { + const rep = M.all(a.textualRepresentation)[0] || M.all(a.ownedElement).find((e) => e['@type'] === 'TextualRepresentation'); + if (rep?.body) return { name: nameOf(a), language: rep.language || '', body: cleanDoc(rep.body) }; + } + } + return null; +} + +/** The version of the SYSMOD library in the model: @SYSMOD { version = "5.1.4"; } on the SYSMOD package; '' if not stated */ +export function sysmodVersionOf(M) { + for (const mu of M.ofType('MetadataUsage')) { + const def = metadataDefOf(M, mu); + if (nameOf(def) !== 'SYSMOD' || !(def.qualifiedName || 'SYSMOD::').startsWith('SYSMOD::')) continue; + const v = valueOf(M, featureNamed(M, mu, 'version')); + if (v) return v; + } + return ''; +} + +/** Everything the viewer shows for one SYSMOD project. Plain data: strings, arrays, objects. */ +export function readProject(M, projectId) { + const project = M.get(projectId); + if (!project) throw new Error('The SYSMOD project is not in the loaded model.'); + const ps = roleOf(M, project, 'problemStatement')[0]; + const contexts = CONTEXTS.map((def) => readContext(M, project, def)); + const byKey = Object.fromEntries(CONTEXTS.map((d, i) => [d.key, contexts[i]])); + const owner = roleOf(M, project, 'projectOwner')[0]; + const sic = byKey.SIC; + const sicImpl = M.get(sic?.systemImpl?.id), sicSoi = M.get(sic?.system?.id); + const cover = featureNamed(M, project, 'projectCoverView', 'ViewUsage') || featureNamed(M, project, 'projectCover', 'ViewUsage'); + const view = { + sysmodVersion: sysmodVersionOf(M), + coverView: cover ? nameOf(cover) : '', + id: project['@id'], + name: nameOf(project), + qualifiedName: project.qualifiedName || '', + doc: docOf(M, project, false), + purpose: valueNamed(M, project, 'purpose'), + owner: owner ? valueNamed(M, owner, 'name') || nameOf(owner) : '', + problemStatement: ps ? { id: ps['@id'], name: nameOf(ps), doc: docOf(M, ps, false) } : null, + // the system idea: the white box system of interest of the system idea context (its own text, else its definition's) + systemIdea: sic?.system ? { + name: sic.system.name, + types: (sicImpl ? typeNames(M, sicImpl) : sic.system.types), + doc: docOf(M, sicImpl) || docOf(M, sicSoi), + blackBox: sicImpl ? docOf(M, sicSoi) : '', + } : null, + objectives: readObjectives(M, project), + stakeholders: readStakeholders(M, project), + needs: readNeeds(M, project), + ...readRequirements(M, project), + useCases: readUseCases(M, byKey.SC), + contexts, + featureTree: readFeatureTree(M), + }; + view.atlas = atlasOf(view); + view.checks = checksOf(view); + return view; +} + +/** Which SYSMOD artifacts the project has: the status of the SYSMOD Atlas. */ +export function atlasOf(v) { + const ctx = Object.fromEntries(v.contexts.map((c, i) => [CONTEXTS[i].key, !!c])); + return { + FEATURE: !!v.featureTree, + STAKE: v.stakeholders.length > 0, + PS: !!v.problemStatement?.doc, + NE: v.needs.length > 0, + RE: v.requirements.length > 0, + UC: v.useCases.length > 0, + ...ctx, + }; +} + +/** Simple completeness checks (the "quality checks" of the original viewer, extended to SYSMOD v5). */ +export function checksOf(v) { + const c = (id, ok, title, okText, failText) => ({ id, status: ok ? 'passed' : 'failed', title, text: ok ? okText : failText }); + const owner = v.stakeholders.find((s) => s.owner); + return [ + c('SYSMOD-001', !!v.problemStatement?.doc, 'Problem statement', 'The project has a problem statement with text.', 'The project has no problem statement with text (concern :>> problemStatement with a doc).'), + c('SYSMOD-002', !!owner, 'Project owner', `The project owner is ${owner?.name}.`, 'No stakeholder redefines projectOwner.'), + c('SYSMOD-003', v.stakeholders.length > 1, 'Stakeholders', `${v.stakeholders.length} stakeholders.`, 'Besides the project owner, no stakeholders are modeled (:> projectStakeholders).'), + c('SYSMOD-004', !!v.systemIdea, 'System idea', 'The system idea context has a system of interest.', 'No system idea context with a system of interest (:>> systemIdeaContext).'), + c('SYSMOD-005', v.contexts.some((x) => x?.key === 'SC'), 'System context', 'The project has a specification context.', 'No specification context (:>> specificationContext).'), + c('SYSMOD-006', v.contexts.filter(Boolean).every((x) => x.actors.length > 0), 'Actors', 'Every context has actors.', `Contexts without actors: ${v.contexts.filter((x) => x && !x.actors.length).map((x) => x.title).join(', ')}.`), + c('SYSMOD-007', v.useCases.length > 0, 'Use cases', `${v.useCases.length} system use cases.`, 'The specification context has no system use cases.'), + c('SYSMOD-008', v.requirements.length > 0, 'Requirements', `${v.requirements.length} requirements.`, 'No requirements under the system requirement specification (:>> systemRequirementSpecification).'), + c('SYSMOD-009', v.requirements.every((r) => r.doc), 'Requirement texts', 'Every requirement has a text.', `Requirements without text: ${v.requirements.filter((r) => !r.doc).map((r) => r.name).join(', ')}.`), + ]; +} diff --git a/web/sysmod-viewer.css b/web/sysmod-viewer.css new file mode 100644 index 0000000..ddcbad5 --- /dev/null +++ b/web/sysmod-viewer.css @@ -0,0 +1,123 @@ +/* SYSMOD viewer (single page): styles. The same class names as on mbse4u.com/tools/sysmod-viewer/, without the site's framework. */ +:root { + --sheet: #f6f7f9; --surface: #ffffff; --ink: #1d2330; --muted: #5f6878; --line: #2457c5; --mark: #ffe14d; --on-mark: #1d2330; + --c-methods: #2e7d32; --c-books: #c62828; --c-info: #b26a00; --sec: #2457c5; + --font-ui: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; --font-display: var(--font-ui); + --font-notation: ui-monospace, "Cascadia Code", Consolas, monospace; --font-mono: var(--font-notation); + color-scheme: light dark; +} +@media (prefers-color-scheme: dark) { + :root { --sheet: #14171c; --surface: #1b1f26; --ink: #e3e7ee; --muted: #9aa3b2; --line: #6e9cff; --sec: #6e9cff; --c-methods: #66bb6a; --c-books: #ff6b6b; --c-info: #f0b45a; } +} +* { box-sizing: border-box; } +body { margin: 0; background: var(--sheet); color: var(--ink); font-family: var(--font-ui); line-height: 1.5; } +main { max-width: 72rem; margin: 0 auto; padding: 2rem clamp(1rem, 4vw, 2.5rem) 4rem; } +a { color: var(--line); } +h1 { font-size: clamp(1.75rem, 3vw, 2.25rem); margin: 0 0 0.25rem; } +code { font-family: var(--font-notation); font-size: 0.9em; } +.lead { max-width: 46rem; margin: 0.5rem 0 0; } +.btn { display: inline-flex; align-items: center; gap: 0.45rem; font: 600 0.9375rem var(--font-ui); padding: 0.55rem 1rem; border: 1.5px solid var(--ink); background: var(--ink); color: var(--sheet); border-radius: 3px; cursor: pointer; text-decoration: none; } +.btn:hover { background: var(--mark); color: var(--on-mark); } +.prose { max-width: 46rem; } .prose li + li { margin-top: 0.4rem; } +.ui { font-family: var(--font-ui); } .text-muted { color: var(--muted); } .font-semibold { font-weight: 600; } .font-normal { font-weight: 400; } +.m-0 { margin: 0; } .mb-2 { margin-bottom: 0.5rem; } .mb-3 { margin-bottom: 0.75rem; } .mb-4 { margin-bottom: 1rem; } .mt-4 { margin-top: 1rem; } .mt-6 { margin-top: 1.5rem; } .mt-10 { margin-top: 2.5rem; } .mt-16 { margin-top: 4rem; } .ml-3 { margin-left: 0.75rem; } +.max-w-\[46rem\] { max-width: 46rem; } .overflow-x-auto { overflow-x: auto; } +.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } +[hidden] { display: none !important; } + +.display { font-family: var(--font-display); font-weight: 700; letter-spacing: -0.01em; line-height: 1.1; } +.display-md { font-size: clamp(1.625rem, 2.6vw, 2.125rem); } +.notation { font-family: var(--font-notation); font-size: 0.8125rem; line-height: 1.7; } +.stereo { font-family: var(--font-ui); font-size: 0.8125rem; font-weight: 500; color: var(--sec, var(--muted)); line-height: 1.3; } +.stereo::before { content: "«" / ""; } +.stereo::after { content: "»" / ""; } +.bk { border: 1.5px solid var(--line); background: var(--surface); } +.bk-usage { border-radius: 10px; overflow: hidden; } +.bk-head { padding: calc(0.7rem + 6px) 1rem 0.8rem; font-family: var(--font-ui); box-shadow: inset 0 6px 0 var(--sec, var(--line)); background: color-mix(in oklab, var(--sec, var(--surface)) 9%, var(--surface)); } +.bk-comp { border-top: 1.5px solid var(--line); padding: 0.65rem 1rem; } +.bk-comp.text { font-size: 1rem; line-height: 1.6; } +.bk-link { display: block; color: inherit; text-decoration: none; height: 100%; } +.bk-link:hover .bk { background: color-mix(in oklab, var(--mark) 22%, var(--surface)); } +.bk-link:hover .bk-title { background: var(--mark); color: var(--on-mark); } +.bk-title { font-family: var(--font-ui); font-stretch: 82%; font-weight: 700; font-size: 1.5rem; line-height: 1.1; letter-spacing: -0.005em; } +.mc-result { border: 1.5px solid var(--line); border-left-width: 6px; border-radius: 10px; padding: 1rem 1.25rem; background: color-mix(in oklab, var(--surface) 70%, transparent); max-width: 52rem; } +.mc-result.mc-ok { border-left-color: var(--c-methods); } +.mc-result.mc-bad { border-left-color: var(--c-books); } +.mc-result.mc-meh { border-left-color: var(--c-info); } +.mc-verdict { margin: 0 0 0.35rem; font-family: var(--font-display); font-weight: 700; font-size: 1.5rem; } +.mc-ok .mc-verdict { color: var(--c-methods); } .mc-bad .mc-verdict { color: var(--c-books); } .mc-meh .mc-verdict { color: var(--c-info); } +.mc-facts { margin: 0.25rem 0; font-family: var(--font-ui); font-size: 0.9375rem; color: var(--muted); } +.mc-src { margin: 0.5rem 0 0; padding: 0.4rem 0.6rem; border: 1px solid var(--line); border-radius: 6px; overflow-x: auto; font-size: 0.8125rem; background: var(--surface); max-width: 100%; } +.mc-files { border-collapse: collapse; font-family: var(--font-ui); font-size: 0.9375rem; min-width: 34rem; } +.mc-files th, .mc-files td { text-align: left; padding: 0.4rem 1rem 0.4rem 0; border-bottom: 1px solid var(--line); } +.mc-files .num { text-align: right; font-variant-numeric: tabular-nums; } +.mc-result, .mc-diag-body { overflow-wrap: anywhere; } + +/* SYSMOD viewer (/tools/sysmod-viewer/, script public/tools/sysmod-viewer/sysmod-viewer.js) */ +.sv-tabs { display: flex; flex-wrap: wrap; gap: 0.25rem 1.25rem; border-bottom: 1.5px solid var(--line); margin-bottom: 1.25rem; } +.sv-tabs [role="tab"] { font-weight: 600; font-size: 0.9375rem; color: var(--ink); background: none; border: 0; border-bottom: 3px solid transparent; padding: 0.4rem 0.1rem; margin-bottom: -1.5px; cursor: pointer; } +.sv-tabs [role="tab"]:hover { background: var(--mark); color: var(--on-mark); } +.sv-tabs [role="tab"][aria-selected="true"] { border-bottom-color: var(--sec, var(--line)); } +.sv-form { display: grid; grid-template-columns: max-content minmax(0, 34rem); gap: 0.6rem 1rem; align-items: center; } +@media (max-width: 40rem) { .sv-form { grid-template-columns: minmax(0, 1fr); } .sv-form > span:empty { display: none; } } +.sv-input { width: 100%; box-sizing: border-box; font-family: var(--font-ui); font-size: 0.9375rem; padding: 0.5rem 0.65rem; border: 1.5px solid var(--line); border-radius: 4px; background: var(--surface); color: var(--ink); } +.sv-input:focus-visible, .sv-file-btn:has(+ input:focus-visible) { outline: 3px solid var(--mark); outline-offset: 1px; } +.btn:disabled { opacity: 0.55; cursor: progress; } +.sv-file-btn { cursor: pointer; } +.sv-status[data-kind="ok"] { color: var(--c-methods); font-weight: 600; } +.sv-status[data-kind="bad"] { color: var(--c-books); font-weight: 600; } +.sv-out { scroll-margin-top: 5rem; } +.sv-head { border-top: 1.5px solid var(--line); padding-top: 1.5rem; display: grid; gap: 0.35rem; } +.sv-origin { font-size: 0.875rem; margin: 0.25rem 0 0.5rem; } +.sv-purpose { margin: 0; max-width: 46rem; } +.sv-sec { margin-top: 3rem; scroll-margin-top: 5rem; } +.sv-h { font-size: 1.625rem; margin: 0 0 1rem; } +.sv-h4 { font-weight: 700; font-size: 1.0625rem; margin: 1.5rem 0 0.5rem; } +.sv-empty { margin: 0; font-style: italic; } +.sv-details { margin-top: 1rem; } +.sv-details > summary { cursor: pointer; font-weight: 600; } +.sv-atlas { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1.25rem; max-width: 52rem; } +@media (max-width: 40rem) { .sv-atlas { grid-template-columns: minmax(0, 1fr); } } +.sv-space { border: 1.5px solid var(--line); border-radius: 10px; padding: 0.75rem; display: grid; gap: 0.6rem; align-content: start; background: var(--surface); } +.sv-space-h { margin: 0; } +.sv-row { display: flex; flex-wrap: wrap; gap: 0.5rem; } +.sv-cell { flex: 1 1 9rem; display: flex; gap: 0.45rem; align-items: baseline; font-family: var(--font-ui); font-size: 0.9375rem; padding: 0.55rem 0.7rem; border: 1.5px dashed color-mix(in oklab, var(--line) 50%, transparent); border-radius: 6px; color: var(--muted); text-decoration: none; } +.sv-cell.on { border-style: solid; border-color: var(--c-methods); color: var(--ink); font-weight: 600; background: color-mix(in oklab, var(--c-methods) 9%, var(--surface)); } +.sv-cell.on:hover { background: var(--mark); color: var(--on-mark); } +.sv-cell-mark { color: var(--c-methods); font-size: 0.75rem; } +.sv-checks { list-style: none; margin: 0.75rem 0 0; padding: 0; display: grid; gap: 0.4rem; max-width: 52rem; font-family: var(--font-ui); font-size: 0.9375rem; } +.sv-check { display: flex; gap: 0.6rem; align-items: baseline; } +.sv-check-mark { flex: none; width: 1.25rem; text-align: center; font-weight: 700; } +.sv-check.passed .sv-check-mark { color: var(--c-methods); } +.sv-check.failed .sv-check-mark { color: var(--c-info); } +.sv-quote { margin: 0; max-width: 46rem; border-left: 6px solid var(--sec, var(--line)); background: color-mix(in oklab, var(--sec, var(--line)) 8%, transparent); padding: 0.75rem 1rem; border-radius: 0 10px 10px 0; font-size: 1.125rem; line-height: 1.6; } +.sv-quote p { margin: 0; } .sv-quote p + p { margin-top: 0.6rem; } +.sv-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.75rem; max-width: 46rem; } +.sv-list p { margin: 0.15rem 0 0; } +.sv-table { min-width: 44rem; } +.sv-table td { vertical-align: top; } +.sv-table .sv-text { min-width: 16rem; max-width: 28rem; } +.sv-table .sv-text p + p { margin-top: 0.4rem; } +.sv-tag { display: inline-block; font-family: var(--font-ui); font-size: 0.75rem; font-weight: 600; padding: 0 0.4rem; border-radius: 3px; background: var(--mark); color: var(--on-mark); } +.sv-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 22rem), 1fr)); gap: 1.25rem; } +.sv-card-title { font-size: 1.25rem; margin: 0.1rem 0; overflow-wrap: anywhere; } +.sv-dl { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 0.3rem 0.75rem; margin: 0.75rem 0; font-size: 0.9375rem; } +.sv-dl dt { font-family: var(--font-ui); font-weight: 600; color: var(--muted); } +.sv-dl dd { margin: 0; } +.sv-steps { margin: 0.4rem 0 0; padding-left: 1.5rem; } +.sv-pre { max-height: 28rem; white-space: pre; } +.sv-fig { margin: 0; max-width: 60rem; border: 1.5px solid var(--line); border-radius: 10px; background: var(--surface); padding: 0.5rem; overflow-x: auto; } +.sv-svg { display: block; width: 100%; min-width: 34rem; height: auto; font-family: var(--font-ui); } +.sv-svg text { fill: var(--ink); font-size: 13px; } +.sv-svg .sv-name { font-weight: 650; font-size: 14px; } +.sv-svg .sv-st { fill: var(--muted); font-size: 12px; } +.sv-svg .sv-ifc { fill: var(--muted); font-size: 11.5px; font-family: var(--font-notation); } +.sv-sys > rect { fill: color-mix(in oklab, var(--sec, var(--line)) 8%, var(--surface)); stroke: var(--sec, var(--line)); stroke-width: 2; } +.sv-part rect { fill: var(--surface); stroke: var(--line); stroke-width: 1.25; } +.sv-part text { font-size: 12.5px; font-family: var(--font-notation); } +.sv-actor rect { fill: var(--surface); stroke: var(--line); stroke-width: 1.5; } +.sv-actor circle, .sv-actor path { fill: none; stroke: var(--ink); stroke-width: 1.5; stroke-linecap: round; } +.sv-lines line { stroke: var(--line); stroke-width: 1.5; } +.sv-port { fill: var(--surface); stroke: var(--line); stroke-width: 1.5; } +.sv-svg .sv-portname { fill: var(--muted); font-size: 10.5px; font-family: var(--font-notation); } +.sv-lines line.sv-nolink { stroke-dasharray: 4 4; opacity: 0.6; } diff --git a/web/sysmod-viewer.js b/web/sysmod-viewer.js new file mode 100644 index 0000000..37e8970 --- /dev/null +++ b/web/sysmod-viewer.js @@ -0,0 +1,663 @@ +/* sysmod-viewer.js: the interface of the SYSMOD viewer. Shows a SYSMOD project of a SysML v2 model: + the SYSMOD Atlas, problem statement, system idea and objectives, stakeholders, needs, requirements, use cases and the + system context diagrams. The model comes from + - a SysML v2 API server (the browser asks the server directly, or through a relay; see sysmod-viewer-api.js), + - the Delivery Drone example (a SysML v2 engine reads the SYSMOD files in the browser; only where cfg.engine is set), + - files of the visitor: .json (elements as the API delivers them) or, with cfg.engine, .sysml. + Nothing is sent anywhere else. All texts from the model are inserted with textContent, never as HTML. + The same file runs in github.com/Open-MBEE/sysmod-sysmlv2-api (web/index.html) and on mbse4u.com/tools/sysmod-viewer/: + without cfg.engine there is no example and no .sysml files (only .json), without cfg.relay no relay. */ + +// ---------- small DOM and text helpers ---------- + +const SVGNS = 'http://www.w3.org/2000/svg'; +const isContent = (k) => k != null && k !== false && k !== ''; +const toNode = (k) => (k.nodeType ? k : document.createTextNode(String(k))); + +function setAttribute(e, k, v) { + if (v == null || v === false) return; + if (k === 'class') e.className = v; + else if (k.startsWith('on')) e.addEventListener(k.slice(2), v); + else e.setAttribute(k, v === true ? '' : v); +} + +/** An HTML element with attributes and children (strings become text nodes) */ +function h(tag, attrs = {}, ...kids) { + const e = document.createElement(tag); + for (const [k, v] of Object.entries(attrs || {})) setAttribute(e, k, v); + e.append(...kids.flat(Infinity).filter(isContent).map(toNode)); + return e; +} + +/** An SVG element with attributes and children */ +function s(tag, attrs = {}, ...kids) { + const e = document.createElementNS(SVGNS, tag); + for (const [k, v] of Object.entries(attrs)) { + if (v != null) e.setAttribute(k, v); + } + e.append(...kids.flat(Infinity).filter(isContent).map(toNode)); + return e; +} + +/** text if the condition holds, else '' (keeps template literals flat) */ +const when = (cond, text) => (cond ? text : ''); +const clip = (text, n) => (text.length > n ? text.slice(0, n - 1) + '…' : text); +const nf = new Intl.NumberFormat('en'); + +/** Doc text as paragraphs: blank lines separate paragraphs, single line breaks are the line breaks of the source. */ +function paras(text, cls = '') { + return String(text || '') + .split(/\n{2,}/) + .map((p) => p.split('\n').map((l) => l.trim()).filter(Boolean).join(' ')) + .filter(Boolean) + .map((p) => h('p', { class: cls }, p)); +} + +function setStatus(el, text, kind = '') { + el.textContent = text; + el.dataset.kind = kind; +} + +function errorBox(e) { + return h('div', { class: 'mc-result mc-bad' }, + h('p', { class: 'mc-verdict' }, e?.message || String(e)), + e?.hint ? h('p', { class: 'm-0' }, e.hint) : null, + e?.url ? h('p', { class: 'mc-facts' }, h('code', {}, e.url)) : null); +} + +const withHint = (message, hint) => Object.assign(new Error(message), { hint }); + +// ---------- the SysML v2 engine in the browser (example and .sysml files; only where cfg.engine is set) ---------- + +async function fetchBytes(url) { + const r = await fetch(url); + if (!r.ok) throw new Error(url + ' could not be loaded (HTTP ' + r.status + ')'); + const raw = new Uint8Array(await r.arrayBuffer()); + if (raw[0] !== 0x1f || raw[1] !== 0x8b) return raw; // the server already decompressed it + if (typeof DecompressionStream === 'undefined') throw new Error('This browser cannot decompress the engine. Use a current Chrome, Edge, Firefox or Safari.'); + return new Uint8Array(await new Response(new Blob([raw]).stream().pipeThrough(new DecompressionStream('gzip'))).arrayBuffer()); +} + +let kernelPromise = null; +function loadKernel(engine) { + kernelPromise ||= (async () => { + const at = (name) => engine.base + name; + const [k, wasm, bundle, snapshot] = await Promise.all([ + import(at(engine.kernel)), fetchBytes(at(engine.wasm)), fetchBytes(at(engine.bundle)), fetchBytes(at(engine.snapshot)), + ]); + await k.default({ module_or_path: wasm }); + return { k, lib: new k.PreparedLibrary(new TextDecoder().decode(bundle), snapshot) }; + })().catch((err) => { + kernelPromise = null; // a failed start can be retried + throw err; + }); + return kernelPromise; +} + +/** SysML v2 text files -> elements (SysML v2 API JSON), by the engine. Parse errors stop with a message. */ +async function elementsFromSources(engine, files, statusEl) { + setStatus(statusEl, 'Loading the SysML v2 engine (about 5 MB, once) …'); + const { k, lib } = await loadKernel(engine); + setStatus(statusEl, 'Reading ' + files.length + ' files …'); + await new Promise((r) => setTimeout(r, 30)); // let the browser paint the status + const json = JSON.stringify(files); + const syntax = JSON.parse(k.checkSyntax(json)).filter((x) => x.stage === 'parse'); + if (syntax.length) { + const errors = syntax.length + ' syntax error' + when(syntax.length > 1, 's'); + throw withHint(errors + ', the model cannot be read.', syntax.slice(0, 3).map((x) => x.unit + ', line ' + x.line + ': ' + x.message).join(' · ')); + } + const session = k.Session.fromSourcesWithPreparedLibrary(json, lib); + try { + return JSON.parse(session.toFullJson(false, 'passthrough')); + } finally { + session.free(); + } +} + +/** The elements of .json files (arrays of elements, or { elements: [...] }) */ +async function elementsFromJsonFiles(files) { + const texts = await Promise.all([...files].map((file) => file.text())); + return texts.flatMap((text, i) => { + const data = JSON.parse(text); + const list = Array.isArray(data) ? data : data?.elements; + if (!Array.isArray(list)) throw withHint(files[i].name + ' is not a list of elements.', 'Expected: a JSON array of elements as GET …/commits/{commit}/elements returns it.'); + return list; + }); +} + +// ---------- rendering of a SYSMOD project ---------- + +const ATLAS = { + problem: [['FEATURE'], ['STAKE', 'PS'], ['NE', 'RE', 'UC', 'SC']], + solution: [['BFAC'], ['SIC'], ['FUC', 'LAC', 'PAC']], +}; +const LABEL = { + FEATURE: 'Features', STAKE: 'Stakeholders', PS: 'Problem Statement', NE: 'Needs', RE: 'Requirements', UC: 'Use Cases', + SC: 'System Specification', BFAC: 'Brownfield Architecture', SIC: 'System Idea Architecture', FUC: 'Functional Architecture', LAC: 'Logical Architecture', PAC: 'Product Architecture', +}; +const TARGET = { FEATURE: 'sv-features', STAKE: 'sv-stakeholders', PS: 'sv-problem', NE: 'sv-needs', RE: 'sv-requirements', UC: 'sv-usecases' }; +const targetOf = (k) => TARGET[k] || 'sv-ctx-' + k; + +const section = (id, title, ...kids) => h('section', { class: 'sv-sec', id, 'aria-labelledby': id + '-h' }, h('h3', { id: id + '-h', class: 'display sv-h' }, title), ...kids); +const empty = (text) => h('p', { class: 'ui text-muted sv-empty' }, text); +const tag = (text) => (text ? h('span', { class: 'sv-tag' }, text) : null); +const typesText = (types) => when(types?.length, ' : ' + (types || []).join(', ')); +const typesLine = (types) => (types?.length ? h('span', { class: 'notation text-muted' }, ': ' + types.join(', ')) : null); +const indent = (depth, prop) => (depth ? prop + ':' + depth * 1.25 + 'rem' : null); +const table = (cols, rows) => h('div', { class: 'overflow-x-auto' }, h('table', { class: 'mc-files sv-table' }, + h('thead', {}, h('tr', {}, cols.map((c) => h('th', { scope: 'col' }, c)))), + h('tbody', {}, rows))); + +function atlasCell(v, k) { + const on = v.atlas[k]; + if (!on) { + return h('span', { class: 'sv-cell', title: LABEL[k] + ': not in the model' }, + h('span', { class: 'sv-cell-mark', 'aria-hidden': 'true' }, '□'), LABEL[k], h('span', { class: 'sr-only' }, ' (not in the model)')); + } + return h('a', { class: 'sv-cell on', href: '#' + targetOf(k), title: 'Go to ' + LABEL[k] }, + h('span', { class: 'sv-cell-mark', 'aria-hidden': 'true' }, '■'), LABEL[k], h('span', { class: 'sr-only' }, ' (in the model)')); +} + +function atlasSection(v) { + const atlas = h('div', { class: 'sv-atlas' }, + ['problem', 'solution'].map((side) => h('div', { class: 'sv-space sv-' + side }, + h('p', { class: 'stereo sv-space-h' }, side + ' space'), + ATLAS[side].map((row) => h('div', { class: 'sv-row' }, row.map((k) => atlasCell(v, k))))))); + const passed = (c) => c.status === 'passed'; + const checks = h('ul', { class: 'sv-checks' }, v.checks.map((c) => h('li', { class: 'sv-check ' + c.status }, + h('span', { class: 'sv-check-mark', 'aria-hidden': 'true' }, passed(c) ? '✓' : '!'), + h('span', {}, h('strong', {}, c.title), ' ', h('span', { class: 'sr-only' }, passed(c) ? '(passed) ' : '(open) '), c.text)))); + return section('sv-atlas', 'SYSMOD Atlas', h('p', { class: 'ui text-muted m-0 mb-3' }, 'Which SYSMOD artifacts the project has. Click one to go there.'), atlas, + h('details', { class: 'sv-details', open: true }, h('summary', { class: 'ui' }, 'Completeness: ' + v.checks.filter(passed).length + ' of ' + v.checks.length), checks)); +} + +function projectHead(v, sourceLabel, size, ms) { + const facts = [when(v.sysmodVersion, 'SYSMOD ' + v.sysmodVersion), when(v.coverView, 'cover view: ' + v.coverView)].filter(Boolean).join(' · '); + const origin = 'Source: ' + sourceLabel + ' · ' + nf.format(size) + ' elements' + when(ms, ' · read in ' + Math.round(ms) + ' ms'); + return h('header', { class: 'sv-head' }, + h('p', { class: 'stereo m-0' }, 'project'), + h('h2', { class: 'display display-md m-0' }, v.name), + v.qualifiedName ? h('p', { class: 'notation text-muted m-0' }, v.qualifiedName) : null, + facts ? h('p', { class: 'ui text-muted m-0 sv-origin' }, facts) : null, + h('p', { class: 'ui text-muted sv-origin' }, origin), + v.purpose ? h('p', { class: 'sv-purpose' }, h('span', { class: 'ui font-semibold' }, 'Purpose: '), v.purpose) : null, + v.owner ? h('p', { class: 'ui m-0' }, h('span', { class: 'font-semibold' }, 'Project owner: '), v.owner) : null, + v.doc ? h('details', { class: 'sv-details' }, h('summary', { class: 'ui' }, 'Project description'), h('div', { class: 'prose max-w-[46rem]' }, paras(v.doc))) : null); +} + +function problemSection(v) { + const ps = v.problemStatement?.doc; + return section('sv-problem', 'Problem statement', ps ? h('blockquote', { class: 'sv-quote' }, paras(ps)) : empty('No problem statement in the model.')); +} + +function ideaSection(v) { + const idea = v.systemIdea + ? [h('p', { class: 'ui m-0 mb-2' }, h('strong', {}, v.systemIdea.name), typesLine(v.systemIdea.types)), h('div', { class: 'prose max-w-[46rem]' }, paras(v.systemIdea.doc))] + : empty('No system idea context in the model.'); + const items = v.objectives.items; + const objectives = items.length ? [ + h('h4', { class: 'ui sv-h4' }, 'System objectives'), + v.objectives.doc ? h('div', { class: 'prose max-w-[46rem] text-muted' }, paras(v.objectives.doc)) : null, + h('ul', { class: 'sv-list' }, items.map((o) => h('li', { style: indent(o.depth, 'margin-left') }, h('strong', { class: 'ui' }, o.name), typesLine(o.types), paras(o.doc, 'm-0')))), + ] : null; + return section('sv-idea', 'System idea', idea, objectives); +} + +function stakeholderSection(v) { + if (!v.stakeholders.length) return section('sv-stakeholders', 'Stakeholders', empty('No stakeholders in the model.')); + const row = (x) => h('tr', {}, + h('td', {}, h('strong', {}, x.name), x.owner ? [' ', tag('project owner')] : null, h('br'), h('span', { class: 'notation text-muted' }, x.element + typesText(x.types))), + h('td', { class: 'sv-text' }, paras(x.doc, 'm-0')), h('td', {}, x.risk), h('td', {}, x.effort), h('td', {}, x.categories), h('td', {}, x.contact)); + return section('sv-stakeholders', 'Stakeholders', table(['Stakeholder', 'Description', 'Risk', 'Effort', 'Categories', 'Contact'], v.stakeholders.map(row))); +} + +function needsSection(v) { + if (!v.needs.length) return section('sv-needs', 'Stakeholder needs', empty('No stakeholder needs in the model.')); + const row = (x) => h('tr', {}, + h('td', { style: indent(x.depth, 'padding-left') }, h('strong', {}, x.name), h('br'), typesLine(x.types)), + h('td', { class: 'sv-text' }, paras(x.doc, 'm-0')), h('td', {}, x.stakeholders), h('td', {}, x.priority)); + return section('sv-needs', 'Stakeholder needs', table(['Need', 'Text', 'Stakeholders', 'Priority'], v.needs.map(row))); +} + +function requirementsSection(v) { + const spec = v.specification; + const specLine = spec ? h('p', { class: 'ui text-muted m-0 mb-3' }, h('span', { class: 'notation' }, spec.name + when(spec.types.length, ' : ' + spec.types[0]))) : null; + if (!v.requirements.length) return section('sv-requirements', 'System requirements', specLine, empty('No system requirements in the model.')); + const row = (x) => h('tr', {}, + h('td', { style: indent(x.depth, 'padding-left') }, x.shortName ? h('span', { class: 'notation' }, '<' + x.shortName + '> ') : null, h('strong', {}, x.name), h('br'), typesLine(x.types)), + h('td', { class: 'sv-text' }, paras(x.doc, 'm-0')), h('td', {}, x.obligation), h('td', {}, x.stability), h('td', { class: 'sv-text' }, x.motivation), h('td', {}, x.stakeholders)); + return section('sv-requirements', 'System requirements', specLine, + table(['Requirement', 'Text', 'Obligation', 'Stability', 'Motivation', 'Stakeholders'], v.requirements.map(row))); +} + +function useCaseCard(u) { + const facts = [['Trigger', u.trigger], ['Result', u.result], ['Precondition', u.precondition], ['Postcondition', u.postcondition], ['Motivation', u.motivation], ['Actors', u.actors], ['Subject', u.subject]] + .filter(([, val]) => val); + const steps = u.steps.length + ? h('details', {}, h('summary', { class: 'ui' }, u.steps.length + ' steps'), h('ol', { class: 'sv-steps notation' }, u.steps.map((st) => h('li', {}, st)))) + : null; + return h('article', { class: 'bk bk-usage sv-card' }, + h('div', { class: 'bk-head' }, h('p', { class: 'stereo m-0' }, 'use case'), h('h4', { class: 'bk-title sv-card-title' }, u.name), typesLine(u.types)), + h('div', { class: 'bk-comp' }, paras(u.doc, 'm-0'), h('dl', { class: 'sv-dl' }, facts.map(([k, val]) => [h('dt', {}, k), h('dd', {}, val)])), steps)); +} + +function useCaseSection(v) { + const content = v.useCases.length ? h('div', { class: 'sv-cards' }, v.useCases.map(useCaseCard)) : empty('No system use cases in the specification context.'); + return section('sv-usecases', 'System use cases', content); +} + +function featureSection(v) { + const ft = v.featureTree; + if (!ft) return null; + return section('sv-features', 'Feature tree', h('p', { class: 'ui text-muted m-0 mb-2' }, ft.name + when(ft.language, ' (' + ft.language + ')')), h('pre', { class: 'mc-src sv-pre' }, ft.body)); +} + +// ---------- context diagram (SVG) ---------- + +function contextView(c) { + const counts = ' · ' + c.actors.length + ' actors · ' + c.links.length + ' interfaces · ' + (c.system?.ports?.length || 0) + ' system ports · ' + + c.parts.length + ' parts' + when(c.systemImpl, ' (white box)'); + const facts = h('p', { class: 'ui text-muted m-0 mb-3' }, h('span', { class: 'notation' }, c.context.name + when(c.context.types.length, ' : ' + c.context.types[0])), counts); + return [facts, h('figure', { class: 'sv-fig' }, diagram(c), h('figcaption', { class: 'sr-only' }, describe(c))), + c.context.doc ? h('details', { class: 'sv-details' }, h('summary', { class: 'ui' }, 'Description'), h('div', { class: 'prose max-w-[46rem]' }, paras(c.context.doc))) : null]; +} + +/** The diagram in words, for screen readers */ +function describe(c) { + const actor = (a) => a.name + when(a.stereotypes.length, ' (' + a.stereotypes.join(', ') + ')'); + const ports = (l) => when(l.actorPort || l.systemPort, ' (' + (l.actorPort || '?') + ' to ' + (l.systemPort || '?') + ')'); + const link = (l) => (l.name || 'interface') + ports(l); + return 'System context ' + c.context.name + ': system of interest ' + (c.system?.name || 'missing') + + when(c.parts.length, ' with the parts ' + c.parts.map((p) => p.name).join(', ')) + + '; actors ' + (c.actors.map(actor).join(', ') || 'none') + + when(c.links.length, '; interfaces ' + c.links.map(link).join(', ')) + '.'; +} + +const D = { W: 960, ACT_W: 180, ACT_H: 62, GAP: 26, PAD: 20, LANE: 140, PART_H: 40 }; + +/** Positions of the diagram: the system box in the middle, its parts in one or two columns */ +function layout(c) { + const rows = Math.max(Math.ceil(c.actors.length / 2), 1); + const sysX = D.PAD + D.ACT_W + D.LANE, sysW = D.W - 2 * sysX; + const partCols = sysW > 300 ? 2 : 1; + const partW = (sysW - 36 - (partCols - 1) * 14) / partCols; + const partRows = Math.ceil(c.parts.length / partCols); + const sysInner = 64 + (partRows ? partRows * (D.PART_H + 12) + 6 : 10); + const H = Math.max(rows * D.ACT_H + (rows - 1) * D.GAP, sysInner) + 2 * D.PAD; + const sysY = D.PAD + Math.max(0, (H - 2 * D.PAD - sysInner) / 2); + const sysH = Math.max(sysInner, Math.min(H - 2 * D.PAD, sysInner + 40)); + return { H, sysX, sysW, sysY, sysH, partCols, partW }; +} + +function systemBox(c, L) { + const name = c.system?.name || ''; + const sys = s('g', { class: 'sv-sys' }, + s('rect', { x: L.sysX, y: L.sysY, width: L.sysW, height: L.sysH, rx: 10 }), + s('text', { x: L.sysX + L.sysW / 2, y: L.sysY + 22, class: 'sv-st', 'text-anchor': 'middle' }, '«' + (c.system?.stereotypes?.[0] || 'system') + '»'), + s('text', { x: L.sysX + L.sysW / 2, y: L.sysY + 42, class: 'sv-name', 'text-anchor': 'middle' }, s('title', {}, name), clip(name || '(no system of interest)', 40))); + c.parts.forEach((p, i) => { + const x = L.sysX + 18 + (i % L.partCols) * (L.partW + 14), y = L.sysY + 60 + Math.floor(i / L.partCols) * (D.PART_H + 12); + const label = p.name + when(p.types[0], ' : ' + p.types[0]) + when(p.multiplicity, ' [' + p.multiplicity + ']'); + sys.append(s('g', { class: 'sv-part' }, s('title', {}, label), s('rect', { x, y, width: L.partW, height: D.PART_H, rx: 4 }), + s('text', { x: x + L.partW / 2, y: y + 25, 'text-anchor': 'middle' }, clip(label, Math.floor(L.partW / 7.2))))); + }); + return sys; +} + +/** Long interface names on two lines, broken at a word boundary of the camelCase name (operator|Interface) */ +function splitLabel(label) { + if (label.length <= 18) return [label]; + const cuts = [...label.matchAll(/(?<=[a-z0-9])(?=[A-Z])|(?<=[,_ -])/g)].map((m) => m.index).filter((i) => i > 2 && i < label.length - 2); + if (!cuts.length) return [label]; + const middle = label.length / 2; + const cut = cuts.reduce((best, i) => (Math.abs(i - middle) < Math.abs(best - middle) ? i : best), cuts[0]); + return [label.slice(0, cut).trim(), label.slice(cut).trim()]; +} + +const unique = (list) => [...new Set(list.filter(Boolean))].join(', '); + +/** The interface label above the line, the ports below it, and the port squares on the borders */ +function drawLink(g, links, a, ends) { + const { ax, cy, sx, sy, side, systemName } = ends; + const mx = (ax + sx) / 2; + const label = links.map((l) => l.name || 'interface').join(', '); + const parts = splitLabel(label); + g.lines.append(s('text', { x: mx, y: cy - 8 - (parts.length - 1) * 13, 'text-anchor': 'middle', class: 'sv-ifc' }, s('title', {}, label), + parts.map((t, i) => s('tspan', { x: mx, dy: i ? 13 : 0 }, clip(t, 19))))); + const ap = unique(links.map((l) => l.actorPort)), sp = unique(links.map((l) => l.systemPort)); + if (ap) g.ports.append(s('rect', { x: ax - 4, y: cy - 4, width: 8, height: 8, class: 'sv-port' }, s('title', {}, a.name + '.' + ap))); + if (sp) g.ports.append(s('rect', { x: sx - 4, y: sy - 4, width: 8, height: 8, class: 'sv-port' }, s('title', {}, systemName + '.' + sp))); + if (!ap && !sp) return; + // two lines, left port above the right one, so that long names fit into the lane between the boxes + const [l, r] = side === 'left' ? [ap || '·', sp || '·'] : [sp || '·', ap || '·']; + const my = (cy + sy) / 2 + 15; + g.lines.append(s('text', { x: mx, y: my, 'text-anchor': 'middle', class: 'sv-portname' }, s('title', {}, 'ports: ' + l + ' ↔ ' + r), + s('tspan', { x: mx, dy: 0 }, clip(l, 19) + ' ↔'), s('tspan', { x: mx, dy: 12 }, clip(r, 19)))); +} + +/** An actor box; a «user» gets a small stick figure in it */ +function actorBox(a, x, y) { + const st = a.stereotypes[0] || 'actor'; + const title = a.name + typesText(a.types) + when(a.doc, '\n' + a.doc); + const g = s('g', { class: 'sv-actor sv-' + st }, s('title', {}, title)); + const fig = st === 'user' ? 22 : 0, tx = x + fig + (D.ACT_W - fig) / 2; + g.append(s('rect', { x, y, width: D.ACT_W, height: D.ACT_H, rx: st === 'environmentalEffect' ? 28 : 4 })); + if (fig) { + const fx = x + 18, fy = y + 13; + const figure = 'M' + fx + ' ' + (fy + 5) + 'v15M' + (fx - 8) + ' ' + (fy + 11) + 'h16M' + fx + ' ' + (fy + 20) + 'l-7 12M' + fx + ' ' + (fy + 20) + 'l7 12'; + g.append(s('circle', { cx: fx, cy: fy, r: 5 }), s('path', { class: 'sv-fig-line', d: figure })); + } + g.append(s('text', { x: tx, y: y + 24, 'text-anchor': 'middle', class: 'sv-st' }, '«' + st + '»'), + s('text', { x: tx, y: y + 44, 'text-anchor': 'middle', class: 'sv-name' }, clip(a.name, fig ? 18 : 21))); + return g; +} + +/** The actors of one side, with the lines to the system box */ +function placeActors(g, c, L, list, side) { + const linksOf = (a) => c.links.filter((l) => l.actor === a.id); + const off = (L.H - 2 * D.PAD - (list.length * D.ACT_H + (list.length - 1) * D.GAP)) / 2; + const left = side === 'left'; + list.forEach((a, i) => { + const x = left ? D.PAD : D.W - D.PAD - D.ACT_W, y = D.PAD + off + i * (D.ACT_H + D.GAP); + const cy = y + D.ACT_H / 2, ax = left ? x + D.ACT_W : x, sx = left ? L.sysX : L.sysX + L.sysW; + const sy = Math.min(Math.max(cy, L.sysY + 14), L.sysY + L.sysH - 14); + const links = linksOf(a); + g.lines.append(s('line', { x1: ax, y1: cy, x2: sx, y2: sy, class: links.length ? '' : 'sv-nolink' })); + if (links.length) drawLink(g, links, a, { ax, cy, sx, sy, side, systemName: c.system?.name || 'system' }); + g.actors.append(actorBox(a, x, y)); + }); +} + +function diagram(c) { + const L = layout(c); + const svg = s('svg', { viewBox: '0 0 ' + D.W + ' ' + L.H, class: 'sv-svg', role: 'img', 'aria-label': 'Context diagram of ' + c.context.name }); + const g = { lines: s('g', { class: 'sv-lines' }), actors: s('g', {}), ports: s('g', {}) }; + placeActors(g, c, L, c.actors.filter((_, i) => i % 2 === 0), 'left'); + placeActors(g, c, L, c.actors.filter((_, i) => i % 2 === 1), 'right'); + svg.append(g.lines, systemBox(c, L), g.actors, g.ports); + if (!c.actors.length) svg.append(s('text', { x: D.PAD, y: D.PAD + 14, class: 'sv-st' }, 'no actors')); + return svg; +} + +/** All sections of a project */ +function projectSections(v, contexts) { + return [ + atlasSection(v), problemSection(v), ideaSection(v), stakeholderSection(v), needsSection(v), requirementsSection(v), useCaseSection(v), + ...v.contexts.map((c, i) => section('sv-ctx-' + contexts[i].key, contexts[i].title, c ? contextView(c) : empty('No ' + contexts[i].role + ' in the model.'))), + featureSection(v), + ].filter(Boolean); +} + +// ---------- the page ---------- + +/** The commit to preselect: the one in the address, else the head of the default branch, else the newest */ +function preselectedCommit(commits, wanted, head) { + const has = (id) => id && commits.some((c) => c['@id'] === id); + if (has(wanted)) return wanted; + if (has(head)) return head; + return commits[0]?.['@id'] || ''; +} + +function commitLabel(c, head) { + const d = Date.parse(c.created || ''); + const date = d ? new Date(d).toLocaleString('en', { dateStyle: 'medium', timeStyle: 'short' }) : c['@id'].slice(0, 8); + return date + when(c.description, ' · ' + String(c.description).slice(0, 60)) + when(c['@id'] === head, ' (head of the default branch)'); +} + +async function start(root, cfg) { + const core = await import(cfg.core); + const apiMod = await import(cfg.api); + const $ = (sel) => root.querySelector(sel); + + // ---------- state in the address (never the token) ---------- + const params = new URLSearchParams(location.search); + const setParams = (obj) => { + const p = new URLSearchParams(); + for (const [k, v] of Object.entries(obj)) { + if (v) p.set(k, v); + } + const q = p.toString(); + history.replaceState(null, '', location.pathname + when(q, '?' + q) + location.hash); + }; + + // ---------- source tabs ---------- + const tabs = [...root.querySelectorAll('[data-src-tab]')]; + const panels = [...root.querySelectorAll('[data-src-panel]')]; + const showTab = (name) => { + for (const t of tabs) t.setAttribute('aria-selected', String(t.dataset.srcTab === name)); + for (const p of panels) p.hidden = p.dataset.srcPanel !== name; + }; + tabs.forEach((t) => t.addEventListener('click', () => showTab(t.dataset.srcTab))); + root.querySelector('[data-js-only]')?.removeAttribute('hidden'); + + // ---------- the model ---------- + let model = null, source = null; // source: { kind: 'server'|'example'|'files', label, server?, project?, commit? } + const out = $('[data-out]'); + const pick = $('[data-pick]'), pickSel = $('[data-pick-select]'); + + function render(projectId, ms) { + const v = core.readProject(model, projectId); + if (source?.kind === 'server') setParams({ server: source.server, project: source.project, commit: source.commit, sysmod: projectId }); + out.replaceChildren(projectHead(v, source?.label || '', model.size, ms), ...projectSections(v, core.CONTEXTS)); + out.querySelector('h2')?.setAttribute('tabindex', '-1'); + out.scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', block: 'start' }); + } + + function useElements(elements, src) { + const t0 = performance.now(); + model = core.createModel(elements); + source = src; + const projects = core.findProjects(model); + out.replaceChildren(); + if (!projects.length) { + pick.hidden = true; + out.append(h('div', { class: 'mc-result mc-bad' }, + h('p', { class: 'mc-verdict' }, 'No SYSMOD project found'), + h('p', { class: 'm-0' }, 'The model has ' + nf.format(model.size) + ' elements, but none of them is a SYSMOD project (#project, or a specialization of SYSMOD::Project). ' + + 'The SYSMOD library must be part of the same model.'))); + return; + } + const label = (p) => (p.qualifiedName && p.qualifiedName !== p.name ? p.name + ' (' + p.qualifiedName + ')' : p.name); + pickSel.replaceChildren(...projects.map((p) => h('option', { value: p.id }, label(p)))); + pick.hidden = projects.length < 2; + const first = projects.find((p) => p.id === params.get('sysmod')) || projects[0]; + pickSel.value = first.id; + render(first.id, performance.now() - t0); + } + pickSel.addEventListener('change', () => render(pickSel.value)); + + // ---------- 1. SysML v2 API server ---------- + const f = { + url: $('[data-url]'), token: $('[data-token]'), connect: $('[data-connect]'), st: $('[data-status-server]'), + projRow: $('[data-proj-row]'), proj: $('[data-proj]'), projFilter: $('[data-proj-filter]'), + commit: $('[data-commit]'), load: $('[data-load]'), err: $('[data-err-server]'), + }; + let client = null, projectList = [], abort = null; + if (params.get('server')) { + f.url.value = params.get('server'); + showTab('server'); + } + // the servers of the relay as suggestions for the address field + $('[data-relay-list]')?.replaceChildren(...(cfg.relay?.servers || []).filter((u) => u !== '*').map((u) => h('option', { value: u }))); + + const showError = (box, e) => { + if (e?.name !== 'AbortError') box.replaceChildren(errorBox(e)); + }; + + async function connect() { + f.err.replaceChildren(); + f.projRow.hidden = true; + try { + client = apiMod.createClient({ baseUrl: f.url.value, token: f.token.value, relay: cfg.relay }); + f.url.value = client.base; + const via = when(client.viaRelay, ' via ' + (cfg.relay?.label || 'the relay')); + setStatus(f.st, 'Connecting' + via + ' …'); + projectList = await client.projects(); + if (!projectList.length) { + setStatus(f.st, 'The server has no projects.', 'bad'); + return; + } + setStatus(f.st, nf.format(projectList.length) + ' projects' + via, 'ok'); + f.proj.replaceChildren(); // a new server: no selection carried over from the previous one + fillProjects(); + f.projRow.hidden = false; + const want = params.get('project'); + if (want && projectList.some((p) => p['@id'] === want)) f.proj.value = want; + await loadCommits(); + } catch (e) { + setStatus(f.st, ''); + showError(f.err, e); + } + } + f.connect.addEventListener('click', () => void connect()); + f.url.addEventListener('keydown', (e) => { + if (e.key === 'Enter') f.connect.click(); + }); + + function fillProjects() { + const q = f.projFilter.value.trim().toLowerCase(); + const keep = f.proj.value; + const list = projectList.filter((p) => !q || String(p.name || '').toLowerCase().includes(q) || p['@id'].includes(q)); + f.proj.replaceChildren(...list.map((p) => h('option', { value: p['@id'] }, p.name || p['@id']))); + if (list.some((p) => p['@id'] === keep)) f.proj.value = keep; + } + f.projFilter.addEventListener('input', () => { + const before = f.proj.value; + fillProjects(); + if (f.proj.value !== before) void loadCommits(); + }); + f.proj.addEventListener('change', () => void loadCommits()); + + async function defaultHead(pid) { + try { + const p = await client.project(pid); + const bid = p?.defaultBranch?.['@id']; + if (!bid) return null; + const b = (await client.branches(pid)).find((x) => x['@id'] === bid); + return b?.head?.['@id'] || null; + } catch { + return null; + } + } + + async function loadCommits() { + f.commit.replaceChildren(h('option', {}, 'Loading commits …')); + f.load.disabled = true; + const pid = f.proj.value; + if (!pid) return; + try { + const [commits, head] = await Promise.all([client.commits(pid), defaultHead(pid)]); + if (pid !== f.proj.value) return; // the visitor chose another project meanwhile + if (!commits.length) { + f.commit.replaceChildren(h('option', {}, 'This project has no commits.')); + return; + } + f.commit.replaceChildren(...commits.map((c) => h('option', { value: c['@id'] }, commitLabel(c, head)))); + f.commit.value = preselectedCommit(commits, params.get('commit'), head); + f.load.disabled = false; + } catch (e) { + f.commit.replaceChildren(); + showError(f.err, e); + } + } + + async function loadModel() { + f.err.replaceChildren(); + abort?.abort(); + abort = new AbortController(); + const pid = f.proj.value, cid = f.commit.value; + const pname = f.proj.selectedOptions[0]?.textContent || pid; + f.load.disabled = true; + try { + setStatus(f.st, 'Loading the model …'); + const onProgress = (n) => setStatus(f.st, 'Loading the model … ' + nf.format(n) + ' elements'); + const elements = await client.elements(pid, cid, { signal: abort.signal, onProgress }); + setStatus(f.st, nf.format(elements.length) + ' elements loaded', 'ok'); + setParams({ server: client.base, project: pid, commit: cid }); + useElements(elements, { kind: 'server', label: pname + ' on ' + new URL(client.base).host, server: client.base, project: pid, commit: cid }); + } catch (e) { + setStatus(f.st, ''); + showError(f.err, e); + } finally { + f.load.disabled = false; + } + } + f.load.addEventListener('click', () => void loadModel()); + + // ---------- 2. + 3. The example and files ---------- + let manifestPromise = null; + const manifest = () => { + manifestPromise ||= fetch(cfg.example.manifest).then((r) => { + if (!r.ok) throw new Error('The SYSMOD files could not be loaded.'); + return r.json(); + }); + return manifestPromise; + }; + const sysmodFiles = async (roles) => { + const m = await manifest(); + const files = m.files.filter((x) => roles.includes(x.role)); + return Promise.all(files.map(async (x) => ({ name: x.name, text: await (await fetch(cfg.example.dir + x.name)).text() }))); + }; + + const ex = { btn: $('[data-example]'), st: $('[data-status-example]'), err: $('[data-err-example]') }; + async function openExample() { + ex.err.replaceChildren(); + ex.btn.disabled = true; + try { + const elements = await elementsFromSources(cfg.engine, await sysmodFiles(['library', 'example']), ex.st); + setStatus(ex.st, nf.format(elements.length) + ' elements', 'ok'); + setParams({ example: 'drone' }); + useElements(elements, { kind: 'example', label: 'SYSMOD Delivery Drone example' }); + } catch (e) { + setStatus(ex.st, ''); + showError(ex.err, e); + } finally { + ex.btn.disabled = false; + } + } + ex.btn?.addEventListener('click', () => void openExample()); + + /** .sysml files, read together with the SYSMOD library (unless the visitor brings it along) */ + async function elementsFromSysmlFiles(files, statusEl) { + if (!cfg.engine) throw withHint('.sysml files need the SysML v2 engine, which this page does not have.', 'Open a .json file with the elements of a commit, or use mbse4u.com/tools/sysmod-viewer/, which reads .sysml files.'); + const own = await Promise.all(files.map(async (x) => ({ name: x.name, text: await x.text() }))); + const have = new Set(own.map((x) => x.name)); + const lib = (await sysmodFiles(['library'])).filter((x) => !have.has(x.name)); + return elementsFromSources(cfg.engine, [...lib, ...own], statusEl); + } + + const fl = { input: $('[data-files]'), st: $('[data-status-files]'), err: $('[data-err-files]') }; + async function openFiles() { + fl.err.replaceChildren(); + const picked = [...fl.input.files]; + if (!picked.length) return; + const ofKind = (...ext) => picked.filter((x) => ext.some((e) => x.name.toLowerCase().endsWith(e))); + const jsons = ofKind('.json'), texts = ofKind('.sysml', '.kerml'); + try { + if (!jsons.length && !texts.length) throw new Error('Choose .sysml files or a .json file.'); + setStatus(fl.st, 'Reading …'); + const elements = jsons.length ? await elementsFromJsonFiles(jsons) : await elementsFromSysmlFiles(texts, fl.st); + setStatus(fl.st, nf.format(elements.length) + ' elements', 'ok'); + setParams({}); + useElements(elements, { kind: 'files', label: picked.map((x) => x.name).join(', ') }); + } catch (e) { + setStatus(fl.st, ''); + showError(fl.err, e); + } + } + fl.input.addEventListener('change', () => void openFiles()); + + // ---------- start ---------- + if (params.get('example') === 'drone' && ex.btn && cfg.engine) { + showTab('example'); + await openExample(); + } +} + +const viewerRoot = document.getElementById('sysmod-viewer'); +if (viewerRoot) { + start(viewerRoot, JSON.parse(viewerRoot.dataset.config)).catch((e) => { + viewerRoot.querySelector('[data-out]')?.replaceChildren(errorBox(e)); + console.error(e); + }); +}