flask-critiqs 0.4.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.
- flask_critiqs-0.4.0/LICENSE +21 -0
- flask_critiqs-0.4.0/PKG-INFO +123 -0
- flask_critiqs-0.4.0/README.md +104 -0
- flask_critiqs-0.4.0/hatch_build.py +29 -0
- flask_critiqs-0.4.0/package.json +14 -0
- flask_critiqs-0.4.0/pyproject.toml +46 -0
- flask_critiqs-0.4.0/src/flask_critiqs/__init__.py +167 -0
- flask_critiqs-0.4.0/src/flask_critiqs/static/element.js +657 -0
- flask_critiqs-0.4.0/tests/test_critiqs.py +286 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Noah Jung
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: flask-critiqs
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Critiqs for Flask: reviewers comment directly on a running prototype, discuss feedback, and find its context.
|
|
5
|
+
Project-URL: Homepage, https://github.com/noahsjung/critiqs/tree/main/packages/flask#readme
|
|
6
|
+
Project-URL: Issues, https://github.com/noahsjung/critiqs/issues
|
|
7
|
+
Project-URL: Source, https://github.com/noahsjung/critiqs
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: comments,design review,feedback,flask,prototype,review
|
|
11
|
+
Classifier: Framework :: Flask
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Requires-Dist: flask>=3.0
|
|
16
|
+
Provides-Extra: test
|
|
17
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# Critiqs for Flask
|
|
21
|
+
|
|
22
|
+
Reviewers comment directly on a running prototype, discuss feedback, and find
|
|
23
|
+
its original context as the prototype changes. Critiqs brings its own toolbar,
|
|
24
|
+
sidebar, sign-in, and styles; it draws above your pages in its own shadow root
|
|
25
|
+
and needs no JavaScript build. Flask 3.0 or later, Python 3.10 or later.
|
|
26
|
+
|
|
27
|
+
## Set up
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
pip install flask-critiqs
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Add the extension where the app is created:
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from flask import Flask
|
|
37
|
+
from flask_critiqs import Critiqs
|
|
38
|
+
|
|
39
|
+
app = Flask(__name__)
|
|
40
|
+
Critiqs(app)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
In an application factory, call `Critiqs(app)` inside `create_app()`, or
|
|
44
|
+
create `critiqs = Critiqs()` once and call `critiqs.init_app(app)`.
|
|
45
|
+
|
|
46
|
+
Render Critiqs in the template every page extends, usually
|
|
47
|
+
`templates/base.html`, just before `</body>`:
|
|
48
|
+
|
|
49
|
+
```jinja
|
|
50
|
+
<body>
|
|
51
|
+
{% block content %}{% endblock %}
|
|
52
|
+
{{ critiqs() }}
|
|
53
|
+
</body>
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Set the project ID in each deployment's environment:
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
CRITIQS_PROJECT_ID=<project ID>
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Flask reads it on each request. Where it is unset, `critiqs()` renders
|
|
63
|
+
nothing, so production or any copy without a project shows no Critiqs. The
|
|
64
|
+
project ID is public configuration, not a secret. On your computer, put it in
|
|
65
|
+
`.env` instead, which is where `npx critiqs init` writes it. When a page is
|
|
66
|
+
served by Flask's development server (`flask run`, `app.run()`), flask-critiqs
|
|
67
|
+
reads `CRITIQS_PROJECT_ID`, and only that key, from the nearest `.env`, as
|
|
68
|
+
`flask run` finds it. It never puts it or any other key from that file into
|
|
69
|
+
`os.environ`, so the rest of your `.env` stays as your app loads it. A
|
|
70
|
+
production server such as Gunicorn or Waitress never reads it, and a
|
|
71
|
+
`CRITIQS_PROJECT_ID` set in the environment wins. `FLASK_SKIP_DOTENV=1` turns
|
|
72
|
+
the file off, as it does for Flask. flask-critiqs doesn't need python-dotenv;
|
|
73
|
+
`flask run` may suggest installing it because a `.env` file is present, and
|
|
74
|
+
that is your app's choice.
|
|
75
|
+
|
|
76
|
+
The extension serves Critiqs's script at `/_critiqs/element.js`.
|
|
77
|
+
|
|
78
|
+
## Config
|
|
79
|
+
|
|
80
|
+
All optional:
|
|
81
|
+
|
|
82
|
+
| Key | Meaning |
|
|
83
|
+
| --- | --- |
|
|
84
|
+
| `CRITIQS_PROJECT_ID` | The project, instead of the environment variable. |
|
|
85
|
+
| `CRITIQS_REQUIRE_PROJECT_ID` | Default `True`. `False` shows project setup where no ID is set. |
|
|
86
|
+
| `CRITIQS_BACKEND` | Your team's own backend, such as `https://<deployment>.convex.cloud`. |
|
|
87
|
+
| `CRITIQS_VERSION` | Recorded with each message, such as a release or Git commit. |
|
|
88
|
+
|
|
89
|
+
`CRITIQS_PROJECT_ID` set to `None` or `""` means no project, even when the
|
|
90
|
+
`CRITIQS_PROJECT_ID` environment variable is set: the variable applies only
|
|
91
|
+
when the key isn't in the config at all. So
|
|
92
|
+
`app.config["CRITIQS_PROJECT_ID"] = os.environ.get("CRITIQS_PROJECT_ID_WEB")`
|
|
93
|
+
shows no Critiqs where `CRITIQS_PROJECT_ID_WEB` is unset.
|
|
94
|
+
|
|
95
|
+
## Screens and routes
|
|
96
|
+
|
|
97
|
+
Each page tells Critiqs which screen it shows, so a thread left on one user's
|
|
98
|
+
page names the page `users/:id` rather than `/users/42`. By default the screen
|
|
99
|
+
is the matched URL rule with variables as `:name` (`<path:…>` as `:name*`),
|
|
100
|
+
the root is `/`, and the rule's variables become view state, such as
|
|
101
|
+
`route.id = "42"`. Name the screen yourself when the rule isn't the right one:
|
|
102
|
+
|
|
103
|
+
```jinja
|
|
104
|
+
{{ critiqs(screen="user-details") }}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
An empty or undefined `screen` falls back to the rule.
|
|
108
|
+
|
|
109
|
+
Opening a thread on a server-rendered app is a full page load, so there is
|
|
110
|
+
nothing to set up for it. An app that wants the page's path back from a thread
|
|
111
|
+
can build it with `routePath` from the `critiqs` npm package.
|
|
112
|
+
|
|
113
|
+
## Content Security Policy
|
|
114
|
+
|
|
115
|
+
Critiqs's two scripts (its bundle, and the inline one that reports the
|
|
116
|
+
screen) carry the nonce you pass with `{{ critiqs(nonce=...) }}`, or
|
|
117
|
+
Flask-Talisman's request nonce on its own. Without a nonce, a policy that
|
|
118
|
+
blocks inline scripts stops only the screen report: threads then name the URL
|
|
119
|
+
path. Allow `connect-src` to your Critiqs backend.
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# Critiqs for Flask
|
|
2
|
+
|
|
3
|
+
Reviewers comment directly on a running prototype, discuss feedback, and find
|
|
4
|
+
its original context as the prototype changes. Critiqs brings its own toolbar,
|
|
5
|
+
sidebar, sign-in, and styles; it draws above your pages in its own shadow root
|
|
6
|
+
and needs no JavaScript build. Flask 3.0 or later, Python 3.10 or later.
|
|
7
|
+
|
|
8
|
+
## Set up
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
pip install flask-critiqs
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Add the extension where the app is created:
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
from flask import Flask
|
|
18
|
+
from flask_critiqs import Critiqs
|
|
19
|
+
|
|
20
|
+
app = Flask(__name__)
|
|
21
|
+
Critiqs(app)
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
In an application factory, call `Critiqs(app)` inside `create_app()`, or
|
|
25
|
+
create `critiqs = Critiqs()` once and call `critiqs.init_app(app)`.
|
|
26
|
+
|
|
27
|
+
Render Critiqs in the template every page extends, usually
|
|
28
|
+
`templates/base.html`, just before `</body>`:
|
|
29
|
+
|
|
30
|
+
```jinja
|
|
31
|
+
<body>
|
|
32
|
+
{% block content %}{% endblock %}
|
|
33
|
+
{{ critiqs() }}
|
|
34
|
+
</body>
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Set the project ID in each deployment's environment:
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
CRITIQS_PROJECT_ID=<project ID>
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Flask reads it on each request. Where it is unset, `critiqs()` renders
|
|
44
|
+
nothing, so production or any copy without a project shows no Critiqs. The
|
|
45
|
+
project ID is public configuration, not a secret. On your computer, put it in
|
|
46
|
+
`.env` instead, which is where `npx critiqs init` writes it. When a page is
|
|
47
|
+
served by Flask's development server (`flask run`, `app.run()`), flask-critiqs
|
|
48
|
+
reads `CRITIQS_PROJECT_ID`, and only that key, from the nearest `.env`, as
|
|
49
|
+
`flask run` finds it. It never puts it or any other key from that file into
|
|
50
|
+
`os.environ`, so the rest of your `.env` stays as your app loads it. A
|
|
51
|
+
production server such as Gunicorn or Waitress never reads it, and a
|
|
52
|
+
`CRITIQS_PROJECT_ID` set in the environment wins. `FLASK_SKIP_DOTENV=1` turns
|
|
53
|
+
the file off, as it does for Flask. flask-critiqs doesn't need python-dotenv;
|
|
54
|
+
`flask run` may suggest installing it because a `.env` file is present, and
|
|
55
|
+
that is your app's choice.
|
|
56
|
+
|
|
57
|
+
The extension serves Critiqs's script at `/_critiqs/element.js`.
|
|
58
|
+
|
|
59
|
+
## Config
|
|
60
|
+
|
|
61
|
+
All optional:
|
|
62
|
+
|
|
63
|
+
| Key | Meaning |
|
|
64
|
+
| --- | --- |
|
|
65
|
+
| `CRITIQS_PROJECT_ID` | The project, instead of the environment variable. |
|
|
66
|
+
| `CRITIQS_REQUIRE_PROJECT_ID` | Default `True`. `False` shows project setup where no ID is set. |
|
|
67
|
+
| `CRITIQS_BACKEND` | Your team's own backend, such as `https://<deployment>.convex.cloud`. |
|
|
68
|
+
| `CRITIQS_VERSION` | Recorded with each message, such as a release or Git commit. |
|
|
69
|
+
|
|
70
|
+
`CRITIQS_PROJECT_ID` set to `None` or `""` means no project, even when the
|
|
71
|
+
`CRITIQS_PROJECT_ID` environment variable is set: the variable applies only
|
|
72
|
+
when the key isn't in the config at all. So
|
|
73
|
+
`app.config["CRITIQS_PROJECT_ID"] = os.environ.get("CRITIQS_PROJECT_ID_WEB")`
|
|
74
|
+
shows no Critiqs where `CRITIQS_PROJECT_ID_WEB` is unset.
|
|
75
|
+
|
|
76
|
+
## Screens and routes
|
|
77
|
+
|
|
78
|
+
Each page tells Critiqs which screen it shows, so a thread left on one user's
|
|
79
|
+
page names the page `users/:id` rather than `/users/42`. By default the screen
|
|
80
|
+
is the matched URL rule with variables as `:name` (`<path:…>` as `:name*`),
|
|
81
|
+
the root is `/`, and the rule's variables become view state, such as
|
|
82
|
+
`route.id = "42"`. Name the screen yourself when the rule isn't the right one:
|
|
83
|
+
|
|
84
|
+
```jinja
|
|
85
|
+
{{ critiqs(screen="user-details") }}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
An empty or undefined `screen` falls back to the rule.
|
|
89
|
+
|
|
90
|
+
Opening a thread on a server-rendered app is a full page load, so there is
|
|
91
|
+
nothing to set up for it. An app that wants the page's path back from a thread
|
|
92
|
+
can build it with `routePath` from the `critiqs` npm package.
|
|
93
|
+
|
|
94
|
+
## Content Security Policy
|
|
95
|
+
|
|
96
|
+
Critiqs's two scripts (its bundle, and the inline one that reports the
|
|
97
|
+
screen) carry the nonce you pass with `{{ critiqs(nonce=...) }}`, or
|
|
98
|
+
Flask-Talisman's request nonce on its own. Without a nonce, a policy that
|
|
99
|
+
blocks inline scripts stops only the screen report: threads then name the URL
|
|
100
|
+
path. Allow `connect-src` to your Critiqs backend.
|
|
101
|
+
|
|
102
|
+
## License
|
|
103
|
+
|
|
104
|
+
MIT
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Puts Critiqs's browser bundle (element.js from the `critiqs` npm package)
|
|
2
|
+
in the package as a static file. In the repository it comes from
|
|
3
|
+
packages/critiqs/dist, which `bun run build` makes; an sdist already holds it.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
|
|
9
|
+
|
|
10
|
+
BUNDLE = "flask_critiqs/static/element.js"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CustomBuildHook(BuildHookInterface):
|
|
14
|
+
def initialize(self, version, build_data):
|
|
15
|
+
if version == "editable":
|
|
16
|
+
return
|
|
17
|
+
root = Path(self.root)
|
|
18
|
+
# hatchling adds the nearest .gitignore to every sdist; here that is the
|
|
19
|
+
# repository's, which says nothing about this package.
|
|
20
|
+
for path in [path for path in build_data["force_include"] if Path(path).name == ".gitignore" and Path(path).parent != root]:
|
|
21
|
+
del build_data["force_include"][path]
|
|
22
|
+
built = root.parent / "critiqs" / "dist" / "element.js"
|
|
23
|
+
if built.is_file():
|
|
24
|
+
target = BUNDLE if self.target_name == "wheel" else f"src/{BUNDLE}"
|
|
25
|
+
build_data["force_include"][str(built)] = target
|
|
26
|
+
elif not (root / "src" / BUNDLE).is_file():
|
|
27
|
+
raise FileNotFoundError(
|
|
28
|
+
f"Critiqs's browser bundle is missing: build it first with `bun run build` in {root.parent / 'critiqs'}."
|
|
29
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "critiqs-flask",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"description": "Workspace marker for the flask-critiqs Python package: Changesets bumps this version and pyproject.toml reads it.",
|
|
6
|
+
"critiqsRelease": {
|
|
7
|
+
"registry": "pypi"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"test": "bun scripts/tasks.ts test",
|
|
11
|
+
"release:build": "bun scripts/tasks.ts release",
|
|
12
|
+
"check:consumer": "bun scripts/check-consumer.ts"
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "flask-critiqs"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Critiqs for Flask: reviewers comment directly on a running prototype, discuss feedback, and find its context."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
dependencies = ["Flask>=3.0"]
|
|
14
|
+
keywords = ["feedback", "comments", "review", "prototype", "design review", "flask"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Framework :: Flask",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.optional-dependencies]
|
|
22
|
+
test = ["pytest>=8"]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://github.com/noahsjung/critiqs/tree/main/packages/flask#readme"
|
|
26
|
+
Issues = "https://github.com/noahsjung/critiqs/issues"
|
|
27
|
+
Source = "https://github.com/noahsjung/critiqs"
|
|
28
|
+
|
|
29
|
+
# The version lives in package.json, which Changesets bumps with every other
|
|
30
|
+
# Critiqs package; hatchling's built-in regex source reads it.
|
|
31
|
+
[tool.hatch.version]
|
|
32
|
+
path = "package.json"
|
|
33
|
+
pattern = '"version":\s*"(?P<version>[^"]+)"'
|
|
34
|
+
|
|
35
|
+
# hatch_build.py puts Critiqs's browser bundle in the package.
|
|
36
|
+
[tool.hatch.build.hooks.custom]
|
|
37
|
+
|
|
38
|
+
[tool.hatch.build.targets.wheel]
|
|
39
|
+
packages = ["src/flask_critiqs"]
|
|
40
|
+
|
|
41
|
+
[tool.hatch.build.targets.sdist]
|
|
42
|
+
include = ["/src", "/tests", "/hatch_build.py", "/package.json", "/README.md", "/LICENSE"]
|
|
43
|
+
|
|
44
|
+
[tool.pytest.ini_options]
|
|
45
|
+
pythonpath = ["src"]
|
|
46
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Critiqs for Flask: `Critiqs(app)`, then `{{ critiqs() }}` in the base template.
|
|
2
|
+
|
|
3
|
+
Config: CRITIQS_PROJECT_ID (else, when the key is absent, the CRITIQS_PROJECT_ID
|
|
4
|
+
environment variable, else, under Flask's development server only, that one key
|
|
5
|
+
from the nearest .env file; None or "" means no project),
|
|
6
|
+
CRITIQS_REQUIRE_PROJECT_ID (default True), CRITIQS_BACKEND, CRITIQS_VERSION.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
from flask import Blueprint, Flask, current_app, has_request_context, request, url_for
|
|
14
|
+
from flask.helpers import get_load_dotenv
|
|
15
|
+
from jinja2 import Undefined
|
|
16
|
+
from markupsafe import Markup
|
|
17
|
+
|
|
18
|
+
__all__ = ["Critiqs", "critiqs"]
|
|
19
|
+
|
|
20
|
+
ENV_VARIABLE = "CRITIQS_PROJECT_ID"
|
|
21
|
+
# CRITIQS_PROJECT_ID=value in a .env file, optionally after `export`.
|
|
22
|
+
ENV_LINE = re.compile(rf"^[ \t]*(?:export[ \t]+)?{ENV_VARIABLE}[ \t]*=[ \t]*(.*?)[ \t]*$")
|
|
23
|
+
# A rule's variable, such as <int:id>; <path:…> spans segments.
|
|
24
|
+
VARIABLE = re.compile(r"<(?:(\w+)(?:\([^)]*\))?:)?(\w+)>")
|
|
25
|
+
|
|
26
|
+
# Serves Critiqs's browser bundle at /_critiqs/element.js.
|
|
27
|
+
blueprint = Blueprint("critiqs", __name__, static_folder="static", static_url_path="/_critiqs")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Critiqs:
|
|
31
|
+
"""The extension: `Critiqs(app)`, or `Critiqs()` then `init_app(app)` in an app factory."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, app: Flask | None = None):
|
|
34
|
+
if app is not None:
|
|
35
|
+
self.init_app(app)
|
|
36
|
+
|
|
37
|
+
def init_app(self, app: Flask) -> None:
|
|
38
|
+
app.config.setdefault("CRITIQS_REQUIRE_PROJECT_ID", True)
|
|
39
|
+
app.register_blueprint(blueprint)
|
|
40
|
+
app.add_template_global(critiqs, "critiqs")
|
|
41
|
+
app.extensions["critiqs"] = self
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _text(value):
|
|
45
|
+
# None, "" and Jinja's Undefined all mean "not given". Undefined is checked
|
|
46
|
+
# first: StrictUndefined raises when it is turned into a string.
|
|
47
|
+
if value is None or isinstance(value, Undefined) or str(value) == "":
|
|
48
|
+
return None
|
|
49
|
+
return str(value)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _nearest_env_file() -> str | None:
|
|
53
|
+
# Where `flask run` looks for .env: the working directory, then each folder above it.
|
|
54
|
+
try:
|
|
55
|
+
folder = os.getcwd()
|
|
56
|
+
except OSError:
|
|
57
|
+
# The folder the server was started in is gone.
|
|
58
|
+
return None
|
|
59
|
+
while True:
|
|
60
|
+
path = os.path.join(folder, ".env")
|
|
61
|
+
if os.path.isfile(path):
|
|
62
|
+
return path
|
|
63
|
+
parent = os.path.dirname(folder)
|
|
64
|
+
if parent == folder:
|
|
65
|
+
return None
|
|
66
|
+
folder = parent
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _env_file_value(text: str) -> str | None:
|
|
70
|
+
"""The last CRITIQS_PROJECT_ID in a .env file's text, unquoted; None when there is none."""
|
|
71
|
+
value = None
|
|
72
|
+
for line in text.splitlines():
|
|
73
|
+
match = ENV_LINE.match(line)
|
|
74
|
+
if match is None:
|
|
75
|
+
continue
|
|
76
|
+
raw = match.group(1)
|
|
77
|
+
if raw[:1] in ("'", '"') and raw.find(raw[0], 1) != -1:
|
|
78
|
+
value = raw[1 : raw.find(raw[0], 1)]
|
|
79
|
+
else:
|
|
80
|
+
value = re.sub(r"[ \t]+#.*$", "", raw)
|
|
81
|
+
return value
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _development_project_id() -> str | None:
|
|
85
|
+
"""CRITIQS_PROJECT_ID from the nearest .env file, the one `npx critiqs init`
|
|
86
|
+
writes, when this request is served by Werkzeug's development server (`flask
|
|
87
|
+
run`, `app.run()`) and Flask's own FLASK_SKIP_DOTENV doesn't turn .env files
|
|
88
|
+
off. Only that key is read, and nothing is put in os.environ, so the app's
|
|
89
|
+
other .env settings stay as the app loads them. Production servers such as
|
|
90
|
+
Gunicorn and Waitress never read it."""
|
|
91
|
+
if not has_request_context() or not str(request.environ.get("SERVER_SOFTWARE", "")).startswith("Werkzeug/"):
|
|
92
|
+
return None
|
|
93
|
+
if not get_load_dotenv():
|
|
94
|
+
return None
|
|
95
|
+
path = _nearest_env_file()
|
|
96
|
+
if path is None:
|
|
97
|
+
return None
|
|
98
|
+
try:
|
|
99
|
+
with open(path, encoding="utf-8-sig") as file:
|
|
100
|
+
return _env_file_value(file.read())
|
|
101
|
+
except (OSError, UnicodeDecodeError):
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def route_context(screen: str | None = None) -> dict | None:
|
|
106
|
+
"""The view this request shows, in Critiqs's route convention: the screen
|
|
107
|
+
is the matched URL rule in :name form (/users/<int:id> -> users/:id, the
|
|
108
|
+
root -> /), and its variables are view state keys route.<name>. `screen`
|
|
109
|
+
replaces the rule unless it is empty. None when there is neither. Only the
|
|
110
|
+
rule's own URL variables are reported, never its server-side defaults."""
|
|
111
|
+
screen = _text(screen)
|
|
112
|
+
# Outside a request (an app context alone, say) there is no route to report.
|
|
113
|
+
rule = request.url_rule if has_request_context() else None
|
|
114
|
+
params = {}
|
|
115
|
+
if rule is not None:
|
|
116
|
+
# A rule's arguments include the keys of its defaults; those never appear in the URL.
|
|
117
|
+
variables = rule.arguments - set(rule.defaults or ())
|
|
118
|
+
params = {f"route.{name}": str(value) for name, value in (request.view_args or {}).items() if name in variables}
|
|
119
|
+
if screen is None and rule is not None:
|
|
120
|
+
pattern = VARIABLE.sub(lambda m: f":{m.group(2)}{'*' if m.group(1) == 'path' else ''}", rule.rule)
|
|
121
|
+
screen = pattern.strip("/") or "/"
|
|
122
|
+
return None if screen is None else {"screen": screen, "viewState": params}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _json(value):
|
|
126
|
+
# Safe inside <script>: no </script>, <!--, or & can end or change it.
|
|
127
|
+
return json.dumps(value).replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def critiqs(nonce: str | None = None, screen: str | None = None) -> Markup:
|
|
131
|
+
"""<critiqs-app> with the app's settings and the script that defines it,
|
|
132
|
+
then a script that reports this page's screen (the matched URL rule, or
|
|
133
|
+
`screen`); nothing when a project ID is required and none is set. The
|
|
134
|
+
scripts carry `nonce`, or Flask-Talisman's request nonce, for a Content
|
|
135
|
+
Security Policy."""
|
|
136
|
+
config = current_app.config
|
|
137
|
+
# As in Django: the variable applies only when the config doesn't have the key at all.
|
|
138
|
+
# A variable in the environment, even an empty one, wins over .env, as with python-dotenv.
|
|
139
|
+
if "CRITIQS_PROJECT_ID" in config:
|
|
140
|
+
project_id = _text(config["CRITIQS_PROJECT_ID"])
|
|
141
|
+
elif ENV_VARIABLE in os.environ:
|
|
142
|
+
project_id = _text(os.environ[ENV_VARIABLE])
|
|
143
|
+
else:
|
|
144
|
+
project_id = _text(_development_project_id())
|
|
145
|
+
require = bool(config.get("CRITIQS_REQUIRE_PROJECT_ID", True))
|
|
146
|
+
if require and project_id is None:
|
|
147
|
+
return Markup("")
|
|
148
|
+
nonce = _text(nonce)
|
|
149
|
+
if nonce is None and has_request_context():
|
|
150
|
+
nonce = _text(getattr(request, "csp_nonce", None))
|
|
151
|
+
nonce_attribute = Markup(' nonce="{}"').format(nonce) if nonce is not None else ""
|
|
152
|
+
view = route_context(screen)
|
|
153
|
+
report = (
|
|
154
|
+
Markup(
|
|
155
|
+
'<script type="module"{}>customElements.whenDefined("critiqs-app").then(() => document.querySelector("critiqs-app")?.setContext({}));</script>'
|
|
156
|
+
).format(nonce_attribute, Markup(_json(view)))
|
|
157
|
+
if view is not None
|
|
158
|
+
else ""
|
|
159
|
+
)
|
|
160
|
+
attributes = [("project-id", project_id), ("backend", _text(config.get("CRITIQS_BACKEND"))), ("version", _text(config.get("CRITIQS_VERSION")))]
|
|
161
|
+
return Markup('<critiqs-app{}{}></critiqs-app><script type="module" src="{}"{}></script>{}').format(
|
|
162
|
+
Markup("").join(Markup(' {}="{}"').format(name, value) for name, value in attributes if value is not None),
|
|
163
|
+
Markup(" require-project-id") if require else "",
|
|
164
|
+
url_for("critiqs.static", filename="element.js"),
|
|
165
|
+
nonce_attribute,
|
|
166
|
+
report,
|
|
167
|
+
)
|