stilo-cli 0.1.0__tar.gz → 0.2.0__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.
Files changed (42) hide show
  1. {stilo_cli-0.1.0 → stilo_cli-0.2.0}/.gitignore +2 -1
  2. {stilo_cli-0.1.0 → stilo_cli-0.2.0}/PKG-INFO +13 -11
  3. {stilo_cli-0.1.0 → stilo_cli-0.2.0}/README.md +10 -8
  4. {stilo_cli-0.1.0 → stilo_cli-0.2.0}/pyproject.toml +3 -3
  5. {stilo_cli-0.1.0 → stilo_cli-0.2.0}/src/stilo/cli/commands.py +28 -6
  6. stilo_cli-0.2.0/src/stilo/cli/errors.py +155 -0
  7. {stilo_cli-0.1.0 → stilo_cli-0.2.0}/src/stilo/server/app.py +52 -7
  8. stilo_cli-0.2.0/src/stilo/server/storage.py +266 -0
  9. stilo_cli-0.2.0/src/stilo/web/assets/index-BUxoyfxd.js +1712 -0
  10. stilo_cli-0.2.0/src/stilo/web/assets/index-kR4PIGIs.css +1 -0
  11. stilo_cli-0.2.0/src/stilo/web/assets/literata-cyrillic-ext-opsz-italic-5yUt4G_9.woff2 +0 -0
  12. stilo_cli-0.2.0/src/stilo/web/assets/literata-cyrillic-ext-opsz-normal-C5tfwALZ.woff2 +0 -0
  13. stilo_cli-0.2.0/src/stilo/web/assets/literata-cyrillic-opsz-italic-Bj0ndbyp.woff2 +0 -0
  14. stilo_cli-0.2.0/src/stilo/web/assets/literata-cyrillic-opsz-normal-DgmypKXX.woff2 +0 -0
  15. stilo_cli-0.2.0/src/stilo/web/assets/literata-greek-ext-opsz-italic-DFpO5j-Z.woff2 +0 -0
  16. stilo_cli-0.2.0/src/stilo/web/assets/literata-greek-ext-opsz-normal-DGm64vGR.woff2 +0 -0
  17. stilo_cli-0.2.0/src/stilo/web/assets/literata-greek-opsz-italic-CHERNRFq.woff2 +0 -0
  18. stilo_cli-0.2.0/src/stilo/web/assets/literata-greek-opsz-normal-DFglUmAd.woff2 +0 -0
  19. stilo_cli-0.2.0/src/stilo/web/assets/literata-latin-ext-opsz-italic-4y8iAqqs.woff2 +0 -0
  20. stilo_cli-0.2.0/src/stilo/web/assets/literata-latin-ext-opsz-normal-STiTPs0F.woff2 +0 -0
  21. stilo_cli-0.2.0/src/stilo/web/assets/literata-latin-opsz-italic-CJ93D38p.woff2 +0 -0
  22. stilo_cli-0.2.0/src/stilo/web/assets/literata-latin-opsz-normal-BHZsWIlc.woff2 +0 -0
  23. stilo_cli-0.2.0/src/stilo/web/assets/literata-vietnamese-opsz-italic-BdcrZMcO.woff2 +0 -0
  24. stilo_cli-0.2.0/src/stilo/web/assets/literata-vietnamese-opsz-normal-Gqw5JQlq.woff2 +0 -0
  25. stilo_cli-0.2.0/src/stilo/web/assets/source-sans-3-cyrillic-ext-wght-normal-c-5QAGAI.woff2 +0 -0
  26. stilo_cli-0.2.0/src/stilo/web/assets/source-sans-3-cyrillic-wght-normal-BMDVbyM7.woff2 +0 -0
  27. stilo_cli-0.2.0/src/stilo/web/assets/source-sans-3-greek-ext-wght-normal-BXZfsJY4.woff2 +0 -0
  28. stilo_cli-0.2.0/src/stilo/web/assets/source-sans-3-greek-wght-normal-Cc-u-6OI.woff2 +0 -0
  29. stilo_cli-0.2.0/src/stilo/web/assets/source-sans-3-latin-ext-wght-normal-C8iNium2.woff2 +0 -0
  30. stilo_cli-0.2.0/src/stilo/web/assets/source-sans-3-latin-wght-normal-Bo_j9asI.woff2 +0 -0
  31. stilo_cli-0.2.0/src/stilo/web/assets/source-sans-3-vietnamese-wght-normal-BDs68eHQ.woff2 +0 -0
  32. stilo_cli-0.2.0/src/stilo/web/assets/texl_wasm_bg-2_KrrXbk.wasm +0 -0
  33. {stilo_cli-0.1.0 → stilo_cli-0.2.0}/src/stilo/web/index.html +2 -2
  34. stilo_cli-0.1.0/src/stilo/server/storage.py +0 -140
  35. stilo_cli-0.1.0/src/stilo/web/assets/index-4AKEJowe.css +0 -1
  36. stilo_cli-0.1.0/src/stilo/web/assets/index-CM5cmnCe.js +0 -889
  37. stilo_cli-0.1.0/src/stilo/web/assets/texl_wasm_bg-DqOV-p_i.wasm +0 -0
  38. {stilo_cli-0.1.0 → stilo_cli-0.2.0}/LICENSE +0 -0
  39. {stilo_cli-0.1.0 → stilo_cli-0.2.0}/src/stilo/__init__.py +0 -0
  40. {stilo_cli-0.1.0 → stilo_cli-0.2.0}/src/stilo/__main__.py +0 -0
  41. {stilo_cli-0.1.0 → stilo_cli-0.2.0}/src/stilo/cli/__init__.py +0 -0
  42. {stilo_cli-0.1.0 → stilo_cli-0.2.0}/src/stilo/server/__init__.py +0 -0
@@ -16,4 +16,5 @@ src/stilo/web/
16
16
 
17
17
  # Locals
18
18
  local/
19
- target/
19
+ *.todo.md
20
+
@@ -1,14 +1,14 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: stilo-cli
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Stilo: edit and render a folder of linked Texl documents
5
- Project-URL: Homepage, https://www.onlabs.org/stilo/
5
+ Project-URL: Documentation, https://www.onlabs.org/manual/
6
6
  Project-URL: Source, https://github.com/onlabsorg/stilo
7
7
  License-Expression: MIT
8
8
  License-File: LICENSE
9
9
  Requires-Python: >=3.11
10
10
  Requires-Dist: fastapi>=0.115
11
- Requires-Dist: pytexl>=0.4
11
+ Requires-Dist: pytexl>=0.6.0
12
12
  Requires-Dist: uvicorn>=0.30
13
13
  Description-Content-Type: text/markdown
14
14
 
@@ -48,9 +48,7 @@ cd web && npm install && npm run build && cd ..
48
48
  uv run stilo serve examples
49
49
  ```
50
50
 
51
- Open <http://127.0.0.1:8000/projects/beam/beam-check.texl>. See the
52
- [getting started guide](https://www.onlabs.org/stilo/book/getting-started.html)
53
- and the developer guide.
51
+ Open <http://127.0.0.1:8000/projects/beam/beam-check.texl>.
54
52
 
55
53
  ## Parts
56
54
 
@@ -60,15 +58,19 @@ and the developer guide.
60
58
  | `src/stilo/` | The Python package `stilo`: `server/` (FastAPI, one folder of documents), `cli/` (the `stilo` command, `render` and `serve`), `web/` (the built web app) |
61
59
  | `tests/` | The Python tests |
62
60
  | `pyproject.toml` | The package `stilo`, the only one published (on PyPI: `stilo-cli`) |
63
- | `docs/` | The documentation (manual, editor manual, landing page), published on <https://www.onlabs.org/stilo/>; `docs/build.sh` builds it into `target/site` |
61
+ | `docs/` | The developer documentation (plain Markdown) |
64
62
  | `examples/` | Sample documents |
65
63
 
66
64
  ## Documentation
67
65
 
68
- <https://www.onlabs.org/stilo/>: getting started, the `stilo` command, the
69
- web editor (with an interactive editor manual), the protocol, the editor
70
- component and a developer guide. See also [CONTRIBUTING.md](https://github.com/onlabsorg/stilo/blob/main/CONTRIBUTING.md)
71
- and [CHANGELOG.md](https://github.com/onlabsorg/stilo/blob/main/CHANGELOG.md).
66
+ - **Using Stilo:** the [OnLabs.org user manual](https://www.onlabs.org/manual/)
67
+ covers getting started, the web editor, the `stilo` command and the
68
+ document format.
69
+ - **Working on Stilo:** the [developer documentation](https://github.com/onlabsorg/stilo/tree/main/docs)
70
+ covers the architecture, the protocol, the editor component and its API,
71
+ and the development setup. See also
72
+ [CONTRIBUTING.md](https://github.com/onlabsorg/stilo/blob/main/CONTRIBUTING.md)
73
+ and [CHANGELOG.md](https://github.com/onlabsorg/stilo/blob/main/CHANGELOG.md).
72
74
 
73
75
  ## License
74
76
 
@@ -34,9 +34,7 @@ cd web && npm install && npm run build && cd ..
34
34
  uv run stilo serve examples
35
35
  ```
36
36
 
37
- Open <http://127.0.0.1:8000/projects/beam/beam-check.texl>. See the
38
- [getting started guide](https://www.onlabs.org/stilo/book/getting-started.html)
39
- and the developer guide.
37
+ Open <http://127.0.0.1:8000/projects/beam/beam-check.texl>.
40
38
 
41
39
  ## Parts
42
40
 
@@ -46,15 +44,19 @@ and the developer guide.
46
44
  | `src/stilo/` | The Python package `stilo`: `server/` (FastAPI, one folder of documents), `cli/` (the `stilo` command, `render` and `serve`), `web/` (the built web app) |
47
45
  | `tests/` | The Python tests |
48
46
  | `pyproject.toml` | The package `stilo`, the only one published (on PyPI: `stilo-cli`) |
49
- | `docs/` | The documentation (manual, editor manual, landing page), published on <https://www.onlabs.org/stilo/>; `docs/build.sh` builds it into `target/site` |
47
+ | `docs/` | The developer documentation (plain Markdown) |
50
48
  | `examples/` | Sample documents |
51
49
 
52
50
  ## Documentation
53
51
 
54
- <https://www.onlabs.org/stilo/>: getting started, the `stilo` command, the
55
- web editor (with an interactive editor manual), the protocol, the editor
56
- component and a developer guide. See also [CONTRIBUTING.md](https://github.com/onlabsorg/stilo/blob/main/CONTRIBUTING.md)
57
- and [CHANGELOG.md](https://github.com/onlabsorg/stilo/blob/main/CHANGELOG.md).
52
+ - **Using Stilo:** the [OnLabs.org user manual](https://www.onlabs.org/manual/)
53
+ covers getting started, the web editor, the `stilo` command and the
54
+ document format.
55
+ - **Working on Stilo:** the [developer documentation](https://github.com/onlabsorg/stilo/tree/main/docs)
56
+ covers the architecture, the protocol, the editor component and its API,
57
+ and the development setup. See also
58
+ [CONTRIBUTING.md](https://github.com/onlabsorg/stilo/blob/main/CONTRIBUTING.md)
59
+ and [CHANGELOG.md](https://github.com/onlabsorg/stilo/blob/main/CHANGELOG.md).
58
60
 
59
61
  ## License
60
62
 
@@ -14,7 +14,7 @@
14
14
 
15
15
  [project]
16
16
  name = "stilo-cli"
17
- version = "0.1.0"
17
+ version = "0.2.0"
18
18
  description = "Stilo: edit and render a folder of linked Texl documents"
19
19
  readme = "README.md"
20
20
  license = "MIT"
@@ -22,7 +22,7 @@ license-files = ["LICENSE"]
22
22
  requires-python = ">=3.11"
23
23
  dependencies = [
24
24
  "fastapi>=0.115",
25
- "pytexl>=0.4",
25
+ "pytexl>=0.6.0",
26
26
  "uvicorn>=0.30",
27
27
  ]
28
28
 
@@ -30,7 +30,7 @@ dependencies = [
30
30
  stilo = "stilo.cli:main"
31
31
 
32
32
  [project.urls]
33
- Homepage = "https://www.onlabs.org/stilo/"
33
+ Documentation = "https://www.onlabs.org/manual/"
34
34
  Source = "https://github.com/onlabsorg/stilo"
35
35
 
36
36
  [dependency-groups]
@@ -16,6 +16,8 @@ import uvicorn
16
16
 
17
17
  from stilo.server import create_app
18
18
 
19
+ from .errors import count_returned, find_errors, format_report, numbered_text
20
+
19
21
  # The built web app, `stilo/web`: written there by `npm run build` in a
20
22
  # checkout, shipped there in the package
21
23
  WEB_DIST = Path(__file__).resolve().parents[1] / "web"
@@ -34,24 +36,44 @@ def render_arguments(parser):
34
36
  help="document to render; relative imports resolve from its folder")
35
37
  parser.add_argument("-o", "--output", type=Path,
36
38
  help="output file (default: standard output)")
39
+ parser.add_argument("-d", "--debug", action="store_true",
40
+ help="number the undefined values in the output and explain each one on standard error")
41
+ parser.add_argument("--strict", action="store_true",
42
+ help="exit with status 1 if the document returned an undefined value")
37
43
 
38
44
 
39
45
  def render(args) -> int:
40
46
  """Renders a document to standard output or a file, like `texl`."""
41
47
  path = args.file.resolve()
42
- doc = asyncio.run(pytexl.Engine().load(path.as_uri()))
43
- if doc is None:
44
- print(f"stilo: {args.file}: could not be loaded", file=sys.stderr)
48
+ try:
49
+ doc = asyncio.run(pytexl.Engine().load(path.as_uri()))
50
+ except pytexl.LoadError as e:
51
+ print(f"stilo: {args.file}: could not be loaded: {e.reason}", file=sys.stderr)
45
52
  return 1
53
+ errors = find_errors(doc)
54
+ text = numbered_text(doc, errors) if args.debug else doc.text
46
55
  if args.output:
47
56
  try:
48
- args.output.write_text(doc.rendering, encoding="utf-8")
57
+ args.output.write_text(text, encoding="utf-8")
49
58
  except OSError as e:
50
59
  print(f"stilo: {args.output}: {e}", file=sys.stderr)
51
60
  return 1
52
61
  else:
53
- sys.stdout.write(doc.rendering)
54
- return 0
62
+ sys.stdout.write(text)
63
+ sys.stdout.flush() # the document comes before the report on a terminal
64
+ if errors:
65
+ report_errors(args, doc, errors)
66
+ return 1 if errors and args.strict else 0
67
+
68
+
69
+ def report_errors(args, doc, errors):
70
+ """Says on standard error how many undefined values `doc` returned, and, with `--debug`, why."""
71
+ count = count_returned(errors)
72
+ summary = f"stilo: {args.file}: {count} undefined value{'' if count == 1 else 's'}"
73
+ if args.debug:
74
+ print(f"{summary}\n\n{format_report(doc, errors)}", file=sys.stderr)
75
+ else:
76
+ print(f"{summary} (use --debug to list them)", file=sys.stderr)
55
77
 
56
78
 
57
79
  def serve_arguments(parser):
@@ -0,0 +1,155 @@
1
+ """The errors of a rendered document, and how `stilo render` reports them.
2
+
3
+ An error is an undefined value that a tag returned, directly or as an item of
4
+ a returned tuple: the Swan counterpart of an exception that was thrown. An
5
+ undefined value that was only assigned, or that sits inside a list or a
6
+ namespace, is not one, and neither is `Nothing`.
7
+ """
8
+
9
+ import os
10
+ from dataclasses import dataclass, field
11
+ from urllib.parse import urlparse
12
+ from urllib.request import url2pathname
13
+
14
+ import pytexl
15
+
16
+ # How Texl renders an undefined value
17
+ UNDEFINED_TEXT = "[[Undefined]]"
18
+
19
+ # The longest source line shown in a report; longer ones are cut around the error
20
+ MAX_EXCERPT = 100
21
+
22
+
23
+ @dataclass
24
+ class Place:
25
+ """Where a document returned an error: the tag, and the span of its text."""
26
+
27
+ tag: pytexl.Tag
28
+ out_start: int
29
+ out_end: int
30
+
31
+
32
+ @dataclass
33
+ class DocumentError:
34
+ """One error, with every place where the document returned it."""
35
+
36
+ number: int
37
+ value: pytexl.Undefined
38
+ places: list[Place] = field(default_factory=list)
39
+
40
+
41
+ def find_errors(doc: pytexl.Document) -> list[DocumentError]:
42
+ """The errors of `doc`, numbered in order of first appearance.
43
+
44
+ The same value returned by several tags is one error with several places.
45
+ """
46
+ errors: dict[tuple, DocumentError] = {}
47
+ for tag in doc.tags:
48
+ for value, out_start, out_end in _returned(doc, tag):
49
+ # A value with no position can only be told apart by its tag
50
+ where = (value.uri, value.pos) if value.pos is not None else tag.start
51
+ key = (where, value.description)
52
+ if key not in errors:
53
+ errors[key] = DocumentError(len(errors) + 1, value)
54
+ errors[key].places.append(Place(tag, out_start, out_end))
55
+ return list(errors.values())
56
+
57
+
58
+ def _returned(doc, tag):
59
+ """The undefined values `tag` returned, each with the span of its text."""
60
+ if isinstance(tag.value, pytexl.Undefined):
61
+ yield tag.value, tag.out_start, tag.out_end
62
+ elif isinstance(tag.value, tuple):
63
+ # A tuple shows its items in order. A text item may itself read
64
+ # "[[Undefined]]", so the search moves past each text item too.
65
+ cursor = tag.out_start
66
+ for item in tag.value:
67
+ if isinstance(item, pytexl.Undefined):
68
+ start = doc.text.index(UNDEFINED_TEXT, cursor, tag.out_end)
69
+ cursor = start + len(UNDEFINED_TEXT)
70
+ yield item, start, cursor
71
+ elif isinstance(item, str):
72
+ found = doc.text.find(item, cursor, tag.out_end)
73
+ cursor = found + len(item) if found >= 0 else cursor
74
+
75
+
76
+ def count_returned(errors: list[DocumentError]) -> int:
77
+ """How many undefined values the document returned, repeats included."""
78
+ return sum(len(error.places) for error in errors)
79
+
80
+
81
+ def numbered_text(doc: pytexl.Document, errors: list[DocumentError]) -> str:
82
+ """The text of `doc`, with each error shown as `[[Undefined #n]]`."""
83
+ spans = [(place.out_start, place.out_end, error.number)
84
+ for error in errors for place in error.places]
85
+ text = doc.text
86
+ for start, end, number in sorted(spans, reverse=True):
87
+ text = f"{text[:start]}[[Undefined #{number}]]{text[end:]}"
88
+ return text
89
+
90
+
91
+ def format_report(doc: pytexl.Document, errors: list[DocumentError]) -> str:
92
+ """The errors of `doc` in plain words: where, what, and what caused them."""
93
+ return "\n\n".join(_format_error(doc, error) for error in errors)
94
+
95
+
96
+ def _format_error(doc, error):
97
+ value = error.value
98
+ if value.pos is not None:
99
+ uri, source, pos = value.uri, value.source, value.pos
100
+ else:
101
+ # No position of its own: point at the tag that returned it
102
+ uri, source, pos = doc.uri, doc.source, error.places[0].tag.start
103
+ lines = [f"#{error.number} {_location(uri, source, pos)} {value.description}"]
104
+ lines += [f" {line}" for line in _excerpt(source, pos)]
105
+
106
+ cause = value.cause
107
+ while cause is not None: # not `while cause`: an undefined value is falsy
108
+ where = f" {_location(cause.uri, cause.source, cause.pos)}:" if cause.pos is not None else ":"
109
+ lines.append(f" caused by{where} {cause.description}")
110
+ cause = cause.cause
111
+
112
+ shown = sorted({_line_number(doc.source, place.tag.start) for place in error.places})
113
+ if shown != [_line_number(source, pos)] or uri != doc.uri:
114
+ label = "line" if len(shown) == 1 else "lines"
115
+ numbers = ", ".join(str(n) for n in shown)
116
+ lines.append(f" shown at {_document_name(doc.uri)} {label} {numbers}")
117
+ return "\n".join(lines)
118
+
119
+
120
+ def _location(uri, source, pos):
121
+ """`file:line:column`, counted from 1."""
122
+ start = source.rfind("\n", 0, pos) + 1
123
+ return f"{_document_name(uri)}:{_line_number(source, pos)}:{pos - start + 1}"
124
+
125
+
126
+ def _line_number(source, pos):
127
+ return source.count("\n", 0, pos) + 1
128
+
129
+
130
+ def _document_name(uri):
131
+ """A file's path relative to the current folder; any other URI as it is."""
132
+ if uri is None:
133
+ return "(parsed code)" # code run by Swan's `parse` has no document
134
+ parsed = urlparse(uri)
135
+ if parsed.scheme != "file":
136
+ return uri
137
+ path = url2pathname(parsed.path)
138
+ try:
139
+ return os.path.relpath(path)
140
+ except ValueError: # another drive, on Windows
141
+ return path
142
+
143
+
144
+ def _excerpt(source, pos):
145
+ """The source line holding `pos`, and a caret under `pos`."""
146
+ start = source.rfind("\n", 0, pos) + 1
147
+ end = source.find("\n", pos)
148
+ line = source[start:end if end >= 0 else len(source)].rstrip("\r")
149
+ column = pos - start
150
+ if len(line) > MAX_EXCERPT:
151
+ first = max(0, min(column - MAX_EXCERPT // 2, len(line) - MAX_EXCERPT))
152
+ line, column = line[first:first + MAX_EXCERPT], column - first
153
+ # Tabs stay tabs, so the caret lines up however wide they are
154
+ padding = "".join("\t" if c == "\t" else " " for c in line[:column])
155
+ return [line, f"{padding}^"]
@@ -1,14 +1,15 @@
1
- """HTTP layer: protocol v0 (docs/src/protocol.md) and the web app's files."""
1
+ """HTTP layer: protocol v0 (docs/protocol.md) and the web app's files."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import mimetypes
5
6
  from pathlib import Path
6
7
 
7
8
  from fastapi import FastAPI, Query, Request
8
9
  from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
9
10
  from fastapi.staticfiles import StaticFiles
10
11
 
11
- from .storage import Storage, StorageError
12
+ from .storage import BadRequest, Storage, StorageError
12
13
 
13
14
  TEXT = "text/plain; charset=utf-8"
14
15
 
@@ -16,16 +17,34 @@ TEXT = "text/plain; charset=utf-8"
16
17
  # browsers must not reuse a stored copy without asking the server again.
17
18
  NO_CACHE = {"Cache-Control": "no-cache"}
18
19
 
20
+ # Python's own table of types, not the machine's, so that every installation
21
+ # answers the same. WebP is missing from the table of Python 3.11.
22
+ FILE_TYPES = mimetypes.MimeTypes()
23
+ FILE_TYPES.add_type("image/webp", ".webp")
24
+
19
25
  NO_BUILD = """<!doctype html><meta charset="utf-8"><title>Stilo</title>
20
26
  <p>The web app is not built. Run <code>npm run build</code> in <code>web/</code>
21
27
  of the Stilo checkout, or use the Vite dev server (<code>npm run dev</code>).</p>"""
22
28
 
23
29
 
30
+ def other_file_response(path: str, content: bytes, tag: str) -> Response:
31
+ """A file that is not a Texl document, by its public URL. Files are
32
+ untrusted: one opened by its URL must not run scripts on this origin, which
33
+ can write to every document (docs/protocol.md)."""
34
+ media_type, encoding = FILE_TYPES.guess_type(path)
35
+ if media_type is None or encoding is not None:
36
+ media_type = "application/octet-stream"
37
+ headers = {"ETag": tag, "X-Content-Type-Options": "nosniff", **NO_CACHE, "Vary": "Accept"}
38
+ if media_type.endswith(("/html", "/xml", "+xml")):
39
+ headers["Content-Security-Policy"] = "sandbox"
40
+ return Response(content, media_type=media_type, headers=headers)
41
+
42
+
24
43
  def create_app(root: Path | str, web_dist: Path | str | None = None) -> FastAPI:
25
44
  """The server app for the documents under `root`. `web_dist` is the built
26
45
  web app (`stilo/web` in the CLI); without it, app pages show a notice."""
27
46
  storage = Storage(root)
28
- app = FastAPI(title="Stilo server", version="0.1.0")
47
+ app = FastAPI(title="Stilo server", version="0.2.0")
29
48
 
30
49
  @app.exception_handler(StorageError)
31
50
  async def storage_error(request: Request, error: StorageError):
@@ -47,6 +66,30 @@ def create_app(root: Path | str, web_dist: Path | str | None = None) -> FastAPI:
47
66
  tag = storage.update(path, await request.body(), request.headers.get("if-match"))
48
67
  return Response(status_code=200, headers={"ETag": tag})
49
68
 
69
+ @app.delete("/_api/files/{path:path}", status_code=204)
70
+ async def delete_file(path: str):
71
+ storage.delete_file(path)
72
+ return Response(status_code=204)
73
+
74
+ @app.post("/_api/move/{path:path}")
75
+ async def move(path: str, request: Request):
76
+ try:
77
+ to = (await request.json())["to"]
78
+ except (ValueError, KeyError, TypeError):
79
+ raise BadRequest('expected a JSON body {"to": "<new path>"}') from None
80
+ if not isinstance(to, str):
81
+ raise BadRequest('expected a JSON body {"to": "<new path>"}')
82
+ return {"path": storage.move(path, to)}
83
+
84
+ @app.post("/_api/tree/{path:path}", status_code=201)
85
+ async def create_folder(path: str):
86
+ storage.create_folder(path)
87
+ return Response(status_code=201, headers={"Location": f"/_api/tree/{path}"})
88
+
89
+ @app.delete("/_api/tree/{path:path}")
90
+ async def delete_folder(path: str):
91
+ return storage.delete_folder(path)
92
+
50
93
  @app.get("/_api/tree/{path:path}")
51
94
  async def get_tree(path: str, depth: int | None = Query(None, ge=1)):
52
95
  return storage.tree(path, depth)
@@ -60,13 +103,15 @@ def create_app(root: Path | str, web_dist: Path | str | None = None) -> FastAPI:
60
103
  # The bundle is built with base "/_app/" (web/vite.config.js).
61
104
  app.mount("/_app", StaticFiles(directory=dist), name="app")
62
105
 
63
- # Every other path is a document's public URL. Browsers asking for HTML
64
- # get the web app, which reads the open document from the URL path (and
65
- # the navigation root from ?root=); any other client (texl.import) gets
66
- # the file itself.
106
+ # Every other path is a public URL. A file that is not a document is served
107
+ # as itself to everyone. For the rest, browsers asking for HTML get the web
108
+ # app, which reads the open document from the URL path (and the navigation
109
+ # root from ?root=); any other client (texl.import) gets the file itself.
67
110
  @app.api_route("/{path:path}", methods=["GET", "HEAD"], include_in_schema=False)
68
111
  async def page(path: str, request: Request):
69
112
  vary = {"Vary": "Accept"}
113
+ if storage.is_other_file(path):
114
+ return other_file_response(path, *storage.read(path))
70
115
  if "text/html" not in request.headers.get("accept", ""):
71
116
  content, tag = storage.read(path)
72
117
  return Response(content, media_type=TEXT,