stilo-cli 0.4.0__tar.gz → 0.5.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/.gitignore +1 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/PKG-INFO +2 -2
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/pyproject.toml +2 -2
- stilo_cli-0.5.1/src/stilo/cli/__init__.py +65 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/cli/commands.py +6 -3
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/cli/tutor.py +4 -1
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/cli/web.py +10 -6
- stilo_cli-0.5.1/src/stilo/server/__init__.py +31 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/server/app.py +68 -30
- stilo_cli-0.5.1/src/stilo/server/extensions.py +67 -0
- stilo_cli-0.5.1/src/stilo/server/files.py +52 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/server/storage.py +178 -26
- stilo_cli-0.4.0/src/stilo/web/assets/index-CVdAQRVd.js → stilo_cli-0.5.1/src/stilo/web/assets/index-BZH77VUo.js +805 -591
- stilo_cli-0.4.0/src/stilo/web/assets/index-B8RYzswc.css → stilo_cli-0.5.1/src/stilo/web/assets/index-DQjFAUo6.css +1 -1
- stilo_cli-0.5.1/src/stilo/web/assets/texl_wasm_bg-DmpBGblw.wasm +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/index.html +3 -5
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/02-cells.texl +1 -1
- stilo_cli-0.4.0/src/stilo/cli/__init__.py +0 -18
- stilo_cli-0.4.0/src/stilo/server/__init__.py +0 -5
- stilo_cli-0.4.0/src/stilo/web/assets/texl_wasm_bg-CzhWLYga.wasm +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/LICENSE +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/README.md +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/__init__.py +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/__main__.py +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/cli/errors.py +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/cli/project.py +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/server/home.py +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/atkinson-hyperlegible-next-latin-ext-wght-italic-Cigfgs4r.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/atkinson-hyperlegible-next-latin-ext-wght-normal-C6vrW8VD.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/atkinson-hyperlegible-next-latin-wght-italic-DC5MiAaX.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/assets/atkinson-hyperlegible-next-latin-wght-normal-BcXVPD7q.woff2 +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/src/stilo/web/favicon.svg +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/texl-lib/charts.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/texl-lib/dataframe.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/texl-lib/index.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/01-welcome.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/03-rich-text.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/04-formulas.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/05-cell-types.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/06-tables-and-equations.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/07-data-tables.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/08-linking.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/09-errors.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/10-organising.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/11-command-line.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/12-your-first-project.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/13-formula-language.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/14-libraries.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/files/beam-drawing.pdf +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/files/beam.svg +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/files/report.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/index.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/lib/steel/sections.texl +0 -0
- {stilo_cli-0.4.0 → stilo_cli-0.5.1}/tutorial/lib/tutorial/index.texl +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: stilo-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.1
|
|
4
4
|
Summary: Stilo: edit and render a folder of linked Texl documents
|
|
5
5
|
Project-URL: Documentation, https://www.onlabs.org/manual/
|
|
6
6
|
Project-URL: Source, https://github.com/onlabsorg/stilo
|
|
@@ -9,7 +9,7 @@ License-File: LICENSE
|
|
|
9
9
|
Requires-Python: >=3.11
|
|
10
10
|
Requires-Dist: fastapi>=0.115
|
|
11
11
|
Requires-Dist: platformdirs>=4
|
|
12
|
-
Requires-Dist: pytexl>=0.
|
|
12
|
+
Requires-Dist: pytexl>=0.10.0
|
|
13
13
|
Requires-Dist: uvicorn>=0.30
|
|
14
14
|
Description-Content-Type: text/markdown
|
|
15
15
|
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
|
|
19
19
|
[project]
|
|
20
20
|
name = "stilo-cli"
|
|
21
|
-
version = "0.
|
|
21
|
+
version = "0.5.1"
|
|
22
22
|
description = "Stilo: edit and render a folder of linked Texl documents"
|
|
23
23
|
readme = "README.md"
|
|
24
24
|
license = "MIT"
|
|
@@ -27,7 +27,7 @@ requires-python = ">=3.11"
|
|
|
27
27
|
dependencies = [
|
|
28
28
|
"fastapi>=0.115",
|
|
29
29
|
"platformdirs>=4",
|
|
30
|
-
"pytexl>=0.
|
|
30
|
+
"pytexl>=0.10.0",
|
|
31
31
|
"uvicorn>=0.30",
|
|
32
32
|
]
|
|
33
33
|
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""The `stilo` command line: one subcommand per `Command`, Stilo's own in
|
|
2
|
+
`COMMANDS`, then those of other packages (docs/cli.md).
|
|
3
|
+
|
|
4
|
+
The names in `__all__` are the CLI's public API, what a plugin may use;
|
|
5
|
+
`tests/cli/test_plugins.py` pins the list.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import sys
|
|
10
|
+
from importlib.metadata import entry_points
|
|
11
|
+
|
|
12
|
+
from .commands import COMMANDS, Command
|
|
13
|
+
from .project import create_engine
|
|
14
|
+
from .web import WEB_DIST, run_server
|
|
15
|
+
|
|
16
|
+
__all__ = ["Command", "COMMANDS", "main", "create_engine", "WEB_DIST", "run_server"]
|
|
17
|
+
|
|
18
|
+
# The entry-point group through which other packages add commands
|
|
19
|
+
PLUGIN_GROUP = "stilo.commands"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def plugin_commands(taken: set[str]) -> list[Command]:
|
|
23
|
+
"""The commands of installed packages, from the entry-point group
|
|
24
|
+
`stilo.commands`, each entry point a `Command`, sorted by name. One that
|
|
25
|
+
fails to load, is not a `Command`, or takes a name already in `taken`
|
|
26
|
+
(Stilo's own commands, or a plugin's that came first) is skipped with a
|
|
27
|
+
warning on standard error."""
|
|
28
|
+
taken = set(taken)
|
|
29
|
+
found = []
|
|
30
|
+
for point in entry_points(group=PLUGIN_GROUP):
|
|
31
|
+
where = f"{point.name} ({point.dist.name})" if getattr(point, "dist", None) else point.name
|
|
32
|
+
try:
|
|
33
|
+
command = point.load()
|
|
34
|
+
except Exception as e: # a broken plugin must not break stilo
|
|
35
|
+
_skip(where, f"{type(e).__name__}: {e}")
|
|
36
|
+
continue
|
|
37
|
+
if not isinstance(command, Command):
|
|
38
|
+
_skip(where, "not a stilo.cli.Command")
|
|
39
|
+
continue
|
|
40
|
+
found.append((command.name, where, command))
|
|
41
|
+
plugins = []
|
|
42
|
+
for name, where, command in sorted(found, key=lambda entry: (entry[0], entry[1])):
|
|
43
|
+
if name in taken:
|
|
44
|
+
_skip(where, f"the command {name!r} already exists")
|
|
45
|
+
continue
|
|
46
|
+
taken.add(name)
|
|
47
|
+
plugins.append(command)
|
|
48
|
+
return plugins
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _skip(where: str, reason: str) -> None:
|
|
52
|
+
print(f"stilo: plugin {where} skipped: {reason}", file=sys.stderr)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def main(argv=None) -> int:
|
|
56
|
+
parser = argparse.ArgumentParser(
|
|
57
|
+
prog="stilo", description="Edit and render a folder of linked Texl documents.")
|
|
58
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
59
|
+
commands = COMMANDS + plugin_commands({command.name for command in COMMANDS})
|
|
60
|
+
for command in commands:
|
|
61
|
+
sub = subparsers.add_parser(command.name, help=command.help)
|
|
62
|
+
command.add_arguments(sub)
|
|
63
|
+
sub.set_defaults(run=command.run)
|
|
64
|
+
args = parser.parse_args(argv)
|
|
65
|
+
return args.run(args)
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
"""The `stilo` subcommands.
|
|
2
2
|
|
|
3
3
|
Each command is a `Command`: a name, a help line, a function that adds its
|
|
4
|
-
arguments to a parser and a function that runs it. `COMMANDS` lists
|
|
5
|
-
the order `stilo --help` shows them;
|
|
4
|
+
arguments to a parser and a function that runs it. `COMMANDS` lists Stilo's own, in
|
|
5
|
+
the order `stilo --help` shows them; other packages add theirs through the
|
|
6
|
+
entry-point group `stilo.commands` (`__init__.py`, `plugin_commands`).
|
|
6
7
|
"""
|
|
7
8
|
|
|
8
9
|
import asyncio
|
|
@@ -13,6 +14,8 @@ from typing import Callable
|
|
|
13
14
|
|
|
14
15
|
import pytexl
|
|
15
16
|
|
|
17
|
+
from stilo.server import create_app
|
|
18
|
+
|
|
16
19
|
from .errors import count_returned, find_errors, format_report, numbered_text
|
|
17
20
|
from .project import LIB, LIBRARY_NAME, MANIFEST, create_engine, make_project
|
|
18
21
|
from .tutor import tutor, tutor_arguments
|
|
@@ -89,7 +92,7 @@ def serve(args) -> int:
|
|
|
89
92
|
return 1
|
|
90
93
|
print(f"Stilo: serving {args.folder.resolve()} at http://{args.host}:{args.port}/ "
|
|
91
94
|
"(press Ctrl+C here to stop)")
|
|
92
|
-
run_server(args.folder, args.
|
|
95
|
+
run_server(create_app(args.folder, args.web), args.host, args.port)
|
|
93
96
|
return 0
|
|
94
97
|
|
|
95
98
|
|
|
@@ -17,6 +17,8 @@ from pathlib import Path
|
|
|
17
17
|
|
|
18
18
|
import platformdirs
|
|
19
19
|
|
|
20
|
+
from stilo.server import create_app
|
|
21
|
+
|
|
20
22
|
from .project import MANIFEST, PACKAGE, make_project, stilo_version, swan_text
|
|
21
23
|
from .web import WEB_DIST, run_server
|
|
22
24
|
|
|
@@ -148,5 +150,6 @@ def tutor(args) -> int:
|
|
|
148
150
|
url = f"http://{host}:{args.port}/{INDEX}"
|
|
149
151
|
print(f"Stilo: the tutorial is at {url} (press Ctrl+C here to stop)")
|
|
150
152
|
sys.stdout.flush()
|
|
151
|
-
run_server(folder, host, args.port,
|
|
153
|
+
run_server(create_app(folder, WEB_DIST), host, args.port,
|
|
154
|
+
open_url=None if args.no_browser else url)
|
|
152
155
|
return 0
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
"""Serving a folder with the web app, for `stilo serve
|
|
1
|
+
"""Serving a folder with the web app, for `stilo serve`, `stilo tutor` and
|
|
2
|
+
the commands of plugins."""
|
|
2
3
|
|
|
3
4
|
import threading
|
|
4
5
|
import time
|
|
@@ -14,11 +15,14 @@ from stilo.server import create_app
|
|
|
14
15
|
WEB_DIST = Path(__file__).resolve().parents[1] / "web"
|
|
15
16
|
|
|
16
17
|
|
|
17
|
-
def run_server(
|
|
18
|
-
"""Serves `
|
|
19
|
-
it in the browser once the server
|
|
20
|
-
with a goodbye instead of a
|
|
21
|
-
|
|
18
|
+
def run_server(app, host: str, port: int, open_url: str | None = None):
|
|
19
|
+
"""Serves `app` (from `create_app()`, or any ASGI app) until the process
|
|
20
|
+
is stopped. With `open_url`, opens it in the browser once the server
|
|
21
|
+
accepts connections. Ctrl+C stops it with a goodbye instead of a
|
|
22
|
+
traceback. A plugin's command serves a folder with its own server
|
|
23
|
+
extensions as `run_server(create_app(folder, WEB_DIST, extensions=[...]),
|
|
24
|
+
host, port)`."""
|
|
25
|
+
server = uvicorn.Server(uvicorn.Config(app, host=host, port=port))
|
|
22
26
|
if open_url:
|
|
23
27
|
threading.Thread(target=_open_when_started, args=(server, open_url), daemon=True).start()
|
|
24
28
|
try:
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Stilo server: Texl documents over HTTP (docs/server.md).
|
|
2
|
+
|
|
3
|
+
The names below are the server's public API: what a server extension, a
|
|
4
|
+
storage of another kind or another server that speaks the protocol may use.
|
|
5
|
+
`tests/server/test_public_api.py` pins the list; a change to it is
|
|
6
|
+
deliberate.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .app import CAPABILITIES, PROTOCOL, VERSION, create_app
|
|
10
|
+
from .extensions import ServerExtension, get_storage
|
|
11
|
+
from .files import (DOCUMENT_SUFFIX, FILE_TYPES, NO_CACHE, etag, is_document, media_type,
|
|
12
|
+
other_file_response)
|
|
13
|
+
from .home import HOME, MANIFEST, MAX_HOMES, HomeCycle, expand_home, has_home, home_of
|
|
14
|
+
from .storage import (BadRequest, Conflict, FolderStorage, Forbidden, NotFound,
|
|
15
|
+
PreconditionFailed, Storage, StorageError, StorageWrapper)
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
# The app
|
|
19
|
+
"create_app", "PROTOCOL", "VERSION", "CAPABILITIES",
|
|
20
|
+
# Server extensions
|
|
21
|
+
"ServerExtension", "get_storage",
|
|
22
|
+
# Storages
|
|
23
|
+
"Storage", "FolderStorage", "StorageWrapper",
|
|
24
|
+
# Errors a storage raises, with their HTTP status
|
|
25
|
+
"StorageError", "BadRequest", "Forbidden", "NotFound", "Conflict", "PreconditionFailed",
|
|
26
|
+
# Files by their public URL
|
|
27
|
+
"DOCUMENT_SUFFIX", "is_document", "etag", "FILE_TYPES", "media_type",
|
|
28
|
+
"other_file_response", "NO_CACHE",
|
|
29
|
+
# The project home, `~` in paths
|
|
30
|
+
"MANIFEST", "HOME", "MAX_HOMES", "HomeCycle", "home_of", "expand_home", "has_home",
|
|
31
|
+
]
|
|
@@ -1,52 +1,57 @@
|
|
|
1
|
-
"""HTTP layer: protocol
|
|
1
|
+
"""HTTP layer: protocol v1 (docs/protocol.md) and the web app's files."""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
import
|
|
5
|
+
import os
|
|
6
6
|
from pathlib import Path
|
|
7
|
+
from typing import Sequence
|
|
7
8
|
from urllib.parse import quote
|
|
8
9
|
|
|
9
10
|
from fastapi import FastAPI, Query, Request
|
|
10
11
|
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
|
|
11
12
|
from fastapi.staticfiles import StaticFiles
|
|
13
|
+
from starlette.middleware import Middleware
|
|
12
14
|
|
|
15
|
+
from .extensions import ServerExtension, check_extensions
|
|
16
|
+
from .files import NO_CACHE, is_document, other_file_response
|
|
13
17
|
from .home import has_home
|
|
14
|
-
from .storage import BadRequest, Storage, StorageError
|
|
18
|
+
from .storage import BadRequest, FolderStorage, NotFound, Storage, StorageError
|
|
15
19
|
|
|
16
20
|
TEXT = "text/plain; charset=utf-8"
|
|
17
21
|
|
|
18
|
-
#
|
|
19
|
-
|
|
20
|
-
NO_CACHE = {"Cache-Control": "no-cache"}
|
|
22
|
+
# The server's version, as published (bumped with pyproject.toml).
|
|
23
|
+
VERSION = "0.5.1"
|
|
21
24
|
|
|
22
|
-
#
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
FILE_TYPES.add_type("image/webp", ".webp")
|
|
25
|
+
# The version of the protocol it speaks, and what it can do (GET /_api/info).
|
|
26
|
+
PROTOCOL = 1
|
|
27
|
+
CAPABILITIES = ["files", "tree", "folders", "move", "upload", "trash", "home"]
|
|
26
28
|
|
|
27
29
|
NO_BUILD = """<!doctype html><meta charset="utf-8"><title>Stilo</title>
|
|
28
30
|
<p>The web app is not built. Run <code>npm run build</code> in <code>web/</code>
|
|
29
31
|
of the Stilo checkout, or use the Vite dev server (<code>npm run dev</code>).</p>"""
|
|
30
32
|
|
|
31
33
|
|
|
32
|
-
def
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
app = FastAPI(title="Stilo server", version=
|
|
34
|
+
def create_app(storage: Storage | Path | str, web_dist: Path | str | None = None, *,
|
|
35
|
+
extensions: Sequence[ServerExtension] = (),
|
|
36
|
+
middleware: Sequence[Middleware] = ()) -> FastAPI:
|
|
37
|
+
"""The server app for the documents in `storage`: any object with the
|
|
38
|
+
methods of `Storage`, or the path of a folder (a `FolderStorage`).
|
|
39
|
+
`web_dist` is the built web app (`stilo/web` in the CLI); without it, app
|
|
40
|
+
pages show a notice. `extensions` are server extensions, in order: each
|
|
41
|
+
one's storage wrapper wraps the storage (the last outermost), its router
|
|
42
|
+
is mounted under `/_api/x/<id>/`, and `/_api/info` lists it.
|
|
43
|
+
`middleware` (Starlette's `Middleware` entries) wraps the whole app."""
|
|
44
|
+
extensions = list(extensions)
|
|
45
|
+
check_extensions(extensions)
|
|
46
|
+
if isinstance(storage, (str, os.PathLike)):
|
|
47
|
+
storage = FolderStorage(storage)
|
|
48
|
+
for extension in extensions:
|
|
49
|
+
if extension.wrap_storage is not None:
|
|
50
|
+
storage = extension.wrap_storage(storage)
|
|
51
|
+
app = FastAPI(title="Stilo server", version=VERSION, middleware=list(middleware))
|
|
52
|
+
app.state.storage = storage
|
|
53
|
+
app.state.extensions = extensions
|
|
54
|
+
extension_ids = {extension.id for extension in extensions}
|
|
50
55
|
|
|
51
56
|
@app.exception_handler(StorageError)
|
|
52
57
|
async def storage_error(request: Request, error: StorageError):
|
|
@@ -111,6 +116,28 @@ def create_app(root: Path | str, web_dist: Path | str | None = None) -> FastAPI:
|
|
|
111
116
|
async def get_tree(path: str, depth: int | None = Query(None, ge=1)):
|
|
112
117
|
return storage.tree(path, depth)
|
|
113
118
|
|
|
119
|
+
@app.get("/_api/info")
|
|
120
|
+
async def info():
|
|
121
|
+
"""What the server is and can do (docs/protocol.md)."""
|
|
122
|
+
return {"protocol": PROTOCOL, "server": {"name": "stilo", "version": VERSION},
|
|
123
|
+
"capabilities": CAPABILITIES,
|
|
124
|
+
"extensions": [extension.info() for extension in extensions]}
|
|
125
|
+
|
|
126
|
+
# The extensions' endpoints, before the catch-all routes below
|
|
127
|
+
for extension in extensions:
|
|
128
|
+
if extension.router is not None:
|
|
129
|
+
app.include_router(extension.router, prefix=f"/_api/x/{extension.id}")
|
|
130
|
+
|
|
131
|
+
@app.api_route("/_api/x/{extension}/{path:path}", methods=["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"])
|
|
132
|
+
@app.api_route("/_api/x/{extension}", methods=["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"])
|
|
133
|
+
async def no_extension(extension: str, path: str = ""):
|
|
134
|
+
"""The space of server extensions (docs/protocol.md): an extension
|
|
135
|
+
this server does not have, or an endpoint its extension lacks."""
|
|
136
|
+
if extension in extension_ids:
|
|
137
|
+
return JSONResponse({"error": f"unknown endpoint of extension {extension}: /{path}"},
|
|
138
|
+
status_code=404)
|
|
139
|
+
return JSONResponse({"error": f"no extension {extension}"}, status_code=404)
|
|
140
|
+
|
|
114
141
|
@app.api_route("/_api/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
|
|
115
142
|
async def unknown_api(path: str):
|
|
116
143
|
return JSONResponse({"error": f"unknown endpoint: /_api/{path}"}, status_code=404)
|
|
@@ -120,6 +147,17 @@ def create_app(root: Path | str, web_dist: Path | str | None = None) -> FastAPI:
|
|
|
120
147
|
# The bundle is built with base "/_app/" (web/vite.config.js).
|
|
121
148
|
app.mount("/_app", StaticFiles(directory=dist), name="app")
|
|
122
149
|
|
|
150
|
+
def other_file(path: str) -> tuple[bytes, str] | None:
|
|
151
|
+
"""The content and ETag of `path` if it is a file that is not a
|
|
152
|
+
document; None for a document, a folder, a missing file or a path the
|
|
153
|
+
protocol refuses."""
|
|
154
|
+
if is_document(path):
|
|
155
|
+
return None
|
|
156
|
+
try:
|
|
157
|
+
return storage.read(path)
|
|
158
|
+
except (NotFound, BadRequest):
|
|
159
|
+
return None
|
|
160
|
+
|
|
123
161
|
# Every other path is a public URL. A file that is not a document is served
|
|
124
162
|
# as itself to everyone. For the rest, browsers asking for HTML get the web
|
|
125
163
|
# app, which reads the open document from the URL path (and the navigation
|
|
@@ -129,8 +167,8 @@ def create_app(root: Path | str, web_dist: Path | str | None = None) -> FastAPI:
|
|
|
129
167
|
if redirect := home_redirect("/", path, request):
|
|
130
168
|
return redirect
|
|
131
169
|
vary = {"Vary": "Accept"}
|
|
132
|
-
if
|
|
133
|
-
return other_file_response(path, *
|
|
170
|
+
if file := other_file(path):
|
|
171
|
+
return other_file_response(path, *file)
|
|
134
172
|
if "text/html" not in request.headers.get("accept", ""):
|
|
135
173
|
content, tag = storage.read(path)
|
|
136
174
|
return Response(content, media_type=TEXT,
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Server extensions (S17, phase 5): what a package adds to the server.
|
|
2
|
+
|
|
3
|
+
A `ServerExtension` is given to `create_app()`. Its router is mounted under
|
|
4
|
+
`/_api/x/<id>/`, its storage wrapper wraps the storage every route uses, and
|
|
5
|
+
`/_api/info` lists it with its version and capabilities (docs/protocol.md).
|
|
6
|
+
One extension is one value, so that a later loader of installed packages
|
|
7
|
+
(phase 6) can take it from an entry point as it is.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import Callable, Sequence
|
|
15
|
+
|
|
16
|
+
from fastapi import APIRouter, Request
|
|
17
|
+
|
|
18
|
+
from .storage import Storage
|
|
19
|
+
|
|
20
|
+
# Lowercase letters, digits and dashes (docs/protocol.md, Extensions)
|
|
21
|
+
EXTENSION_ID = re.compile(r"[a-z0-9][a-z0-9-]*")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class ServerExtension:
|
|
26
|
+
"""A server extension: `id`, the name of its space `/_api/x/<id>/` and of
|
|
27
|
+
its entry in `/_api/info`; `router`, its endpoints, mounted there;
|
|
28
|
+
`wrap_storage`, given the storage, returns the one to use instead (a
|
|
29
|
+
`StorageWrapper`, say); `capabilities`, what it can do, in names of its
|
|
30
|
+
own; `version`, its own version."""
|
|
31
|
+
|
|
32
|
+
id: str
|
|
33
|
+
router: APIRouter | None = None
|
|
34
|
+
wrap_storage: Callable[[Storage], Storage] | None = None
|
|
35
|
+
capabilities: Sequence[str] = ()
|
|
36
|
+
version: str | None = None
|
|
37
|
+
|
|
38
|
+
def info(self) -> dict:
|
|
39
|
+
"""Its entry in `/_api/info`."""
|
|
40
|
+
entry = {"id": self.id, "capabilities": list(self.capabilities)}
|
|
41
|
+
if self.version is not None:
|
|
42
|
+
entry["version"] = self.version
|
|
43
|
+
return entry
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def check_extensions(extensions: Sequence[ServerExtension]) -> None:
|
|
47
|
+
"""Refuse a list of extensions with a bad or repeated id, or with
|
|
48
|
+
capabilities that are not strings, before anything is mounted."""
|
|
49
|
+
seen = set()
|
|
50
|
+
for extension in extensions:
|
|
51
|
+
if not isinstance(extension, ServerExtension):
|
|
52
|
+
raise TypeError(f"not a ServerExtension: {extension!r}")
|
|
53
|
+
if not isinstance(extension.id, str) or not EXTENSION_ID.fullmatch(extension.id):
|
|
54
|
+
raise ValueError(f"bad extension id {extension.id!r}: use lowercase letters, digits and dashes")
|
|
55
|
+
if extension.id in seen:
|
|
56
|
+
raise ValueError(f"two extensions with the id {extension.id!r}")
|
|
57
|
+
if isinstance(extension.capabilities, str) or not all(
|
|
58
|
+
isinstance(c, str) for c in extension.capabilities):
|
|
59
|
+
raise ValueError(f"extension {extension.id!r}: capabilities must be a list of strings")
|
|
60
|
+
seen.add(extension.id)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def get_storage(request: Request) -> Storage:
|
|
64
|
+
"""The storage of the app, as wrapped by the extensions: a FastAPI
|
|
65
|
+
dependency for an extension's endpoints,
|
|
66
|
+
`storage: Storage = Depends(get_storage)`."""
|
|
67
|
+
return request.app.state.storage
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Files by their public URL: documents, other files, their types and the
|
|
2
|
+
safety headers (docs/protocol.md). Exported, so that another server that
|
|
3
|
+
speaks the protocol answers the same."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
import mimetypes
|
|
9
|
+
from pathlib import PurePosixPath
|
|
10
|
+
|
|
11
|
+
from fastapi.responses import Response
|
|
12
|
+
|
|
13
|
+
DOCUMENT_SUFFIX = ".texl"
|
|
14
|
+
|
|
15
|
+
# Document contents change and the editor fetches imports on every rendering:
|
|
16
|
+
# browsers must not reuse a stored copy without asking the server again.
|
|
17
|
+
NO_CACHE = {"Cache-Control": "no-cache"}
|
|
18
|
+
|
|
19
|
+
# Python's own table of types, not the machine's, so that every installation
|
|
20
|
+
# answers the same. WebP is missing from the table of Python 3.11.
|
|
21
|
+
FILE_TYPES = mimetypes.MimeTypes()
|
|
22
|
+
FILE_TYPES.add_type("image/webp", ".webp")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def etag(content: bytes) -> str:
|
|
26
|
+
"""Strong ETag of a file's content, quoted as HTTP requires."""
|
|
27
|
+
return '"' + hashlib.sha256(content).hexdigest() + '"'
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def is_document(path: str) -> bool:
|
|
31
|
+
"""Whether `path` names a Texl document (by its suffix, `.texl`)."""
|
|
32
|
+
return PurePosixPath(path.strip("/") or "/").suffix == DOCUMENT_SUFFIX
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def media_type(path: str) -> str:
|
|
36
|
+
"""The type a file that is not a document is served with, from its name;
|
|
37
|
+
`application/octet-stream` when unknown or compressed."""
|
|
38
|
+
guessed, encoding = FILE_TYPES.guess_type(path)
|
|
39
|
+
if guessed is None or encoding is not None:
|
|
40
|
+
return "application/octet-stream"
|
|
41
|
+
return guessed
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def other_file_response(path: str, content: bytes, tag: str) -> Response:
|
|
45
|
+
"""A file that is not a Texl document, by its public URL. Files are
|
|
46
|
+
untrusted: one opened by its URL must not run scripts on this origin, which
|
|
47
|
+
can write to every document (docs/protocol.md)."""
|
|
48
|
+
kind = media_type(path)
|
|
49
|
+
headers = {"ETag": tag, "X-Content-Type-Options": "nosniff", **NO_CACHE, "Vary": "Accept"}
|
|
50
|
+
if kind.endswith(("/html", "/xml", "+xml")):
|
|
51
|
+
headers["Content-Security-Policy"] = "sandbox"
|
|
52
|
+
return Response(content, media_type=kind, headers=headers)
|