mkdocs-ai-chatbot 1.0.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Asyntai
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,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: mkdocs-ai-chatbot
3
+ Version: 1.0.0
4
+ Summary: Add the Asyntai AI chat assistant to your MkDocs site. It answers visitor questions from your own documentation.
5
+ Author-email: Asyntai <hello@asyntai.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://asyntai.com/documentation/integrations/mkdocs/
8
+ Project-URL: Documentation, https://asyntai.com/documentation/integrations/mkdocs/
9
+ Project-URL: Source, https://github.com/asyntai/mkdocs-ai-chatbot
10
+ Project-URL: Issues, https://github.com/asyntai/mkdocs-ai-chatbot/issues
11
+ Keywords: mkdocs,mkdocs-plugin,chatbot,ai,chat,support,documentation,asyntai
12
+ Classifier: Framework :: MkDocs
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Documentation
15
+ Classifier: Topic :: Communications :: Chat
16
+ Requires-Python: >=3.8
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: mkdocs>=1.4
20
+ Dynamic: license-file
21
+
22
+ # mkdocs-ai-chatbot
23
+
24
+ Add the [Asyntai](https://asyntai.com) AI chat assistant to your MkDocs site.
25
+ It answers visitor questions from your own documentation, day and night.
26
+
27
+ Works with every MkDocs theme, including Material for MkDocs and Read the Docs.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install mkdocs-ai-chatbot
33
+ ```
34
+
35
+ Then add the plugin in `mkdocs.yml`:
36
+
37
+ ```yaml
38
+ plugins:
39
+ - search
40
+ - asyntai:
41
+ widget_id: asyntai_1a2b3c4d5e6f
42
+ ```
43
+
44
+ Build the site. The chat bubble is on every page.
45
+
46
+ Keep `search` in the list if you use it. When `mkdocs.yml` has a `plugins`
47
+ section, MkDocs only loads the plugins named there.
48
+
49
+ ## Where the widget ID comes from
50
+
51
+ Open the Install page in your [Asyntai dashboard](https://asyntai.com/dashboard).
52
+ The widget ID is the value of `data-asyntai-id` in the snippet shown there. It
53
+ starts with `asyntai_`.
54
+
55
+ Creating an account is free, and the Free plan is enough to try the widget.
56
+
57
+ ## Options
58
+
59
+ | Option | Type | Default | What it does |
60
+ | --- | --- | --- | --- |
61
+ | `widget_id` | string | required | Your Asyntai widget ID |
62
+ | `enable_on_serve` | boolean | `true` | Set to `false` to keep the widget off the site during `mkdocs serve` |
63
+ | `script_url` | string | the Asyntai CDN | Advanced. Load the widget from another URL |
64
+
65
+ A missing or malformed `widget_id` stops the build with a message that says how
66
+ to fix it.
67
+
68
+ ## What the plugin does
69
+
70
+ - It adds one `<script>` tag in front of the closing body tag of every page.
71
+ - It marks the tag `async`, so your documentation renders first.
72
+ - It changes nothing else. No theme files are overridden and no CSS is added.
73
+ - If a page already has the Asyntai snippet, for example from a theme
74
+ override, the plugin leaves that page alone.
75
+
76
+ ## Answering from your documentation
77
+
78
+ Asyntai reads your published pages. Add your site URL in the dashboard, and the
79
+ assistant answers from the same documentation the widget sits on. You can also
80
+ add documents, and question and answer pairs.
81
+
82
+ ## Removing it
83
+
84
+ Delete the `asyntai` entry from `mkdocs.yml` and build again. The widget is
85
+ gone.
86
+
87
+ ## Support
88
+
89
+ Email [hello@asyntai.com](mailto:hello@asyntai.com), or read the
90
+ [MkDocs guide](https://asyntai.com/documentation/integrations/mkdocs/).
91
+
92
+ ## Licence
93
+
94
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,73 @@
1
+ # mkdocs-ai-chatbot
2
+
3
+ Add the [Asyntai](https://asyntai.com) AI chat assistant to your MkDocs site.
4
+ It answers visitor questions from your own documentation, day and night.
5
+
6
+ Works with every MkDocs theme, including Material for MkDocs and Read the Docs.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pip install mkdocs-ai-chatbot
12
+ ```
13
+
14
+ Then add the plugin in `mkdocs.yml`:
15
+
16
+ ```yaml
17
+ plugins:
18
+ - search
19
+ - asyntai:
20
+ widget_id: asyntai_1a2b3c4d5e6f
21
+ ```
22
+
23
+ Build the site. The chat bubble is on every page.
24
+
25
+ Keep `search` in the list if you use it. When `mkdocs.yml` has a `plugins`
26
+ section, MkDocs only loads the plugins named there.
27
+
28
+ ## Where the widget ID comes from
29
+
30
+ Open the Install page in your [Asyntai dashboard](https://asyntai.com/dashboard).
31
+ The widget ID is the value of `data-asyntai-id` in the snippet shown there. It
32
+ starts with `asyntai_`.
33
+
34
+ Creating an account is free, and the Free plan is enough to try the widget.
35
+
36
+ ## Options
37
+
38
+ | Option | Type | Default | What it does |
39
+ | --- | --- | --- | --- |
40
+ | `widget_id` | string | required | Your Asyntai widget ID |
41
+ | `enable_on_serve` | boolean | `true` | Set to `false` to keep the widget off the site during `mkdocs serve` |
42
+ | `script_url` | string | the Asyntai CDN | Advanced. Load the widget from another URL |
43
+
44
+ A missing or malformed `widget_id` stops the build with a message that says how
45
+ to fix it.
46
+
47
+ ## What the plugin does
48
+
49
+ - It adds one `<script>` tag in front of the closing body tag of every page.
50
+ - It marks the tag `async`, so your documentation renders first.
51
+ - It changes nothing else. No theme files are overridden and no CSS is added.
52
+ - If a page already has the Asyntai snippet, for example from a theme
53
+ override, the plugin leaves that page alone.
54
+
55
+ ## Answering from your documentation
56
+
57
+ Asyntai reads your published pages. Add your site URL in the dashboard, and the
58
+ assistant answers from the same documentation the widget sits on. You can also
59
+ add documents, and question and answer pairs.
60
+
61
+ ## Removing it
62
+
63
+ Delete the `asyntai` entry from `mkdocs.yml` and build again. The widget is
64
+ gone.
65
+
66
+ ## Support
67
+
68
+ Email [hello@asyntai.com](mailto:hello@asyntai.com), or read the
69
+ [MkDocs guide](https://asyntai.com/documentation/integrations/mkdocs/).
70
+
71
+ ## Licence
72
+
73
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,4 @@
1
+ from .plugin import AsyntaiPlugin, DEFAULT_SCRIPT_URL
2
+
3
+ __all__ = ["AsyntaiPlugin", "DEFAULT_SCRIPT_URL"]
4
+ __version__ = "1.0.0"
@@ -0,0 +1,102 @@
1
+ """
2
+ Asyntai AI chatbot for MkDocs.
3
+
4
+ Adds the Asyntai chat widget to every page that MkDocs builds. The plugin
5
+ writes the ordinary embed snippet in front of the closing body tag of each
6
+ page. Nothing else about the site changes: no theme files are overridden and
7
+ no CSS is added.
8
+ """
9
+
10
+ import re
11
+
12
+ from mkdocs.config import config_options
13
+ from mkdocs.exceptions import PluginError
14
+ from mkdocs.plugins import BasePlugin
15
+
16
+ DEFAULT_SCRIPT_URL = "https://widget.asyntai.com/static/js/chat-widget.js"
17
+ WIDGET_ID_PATTERN = re.compile(r"^asyntai_[A-Za-z0-9]+$")
18
+
19
+ # The last closing body tag of the page. A page can quote "</body>" inside a
20
+ # code block, so only the final one is the real end of the document.
21
+ _BODY_END = re.compile(r"</body\s*>", re.IGNORECASE)
22
+
23
+
24
+ def build_tag(widget_id, script_url):
25
+ return (
26
+ '<script async src="{src}" data-asyntai-id="{wid}"></script>'.format(
27
+ src=script_url.replace('"', "&quot;"),
28
+ wid=widget_id,
29
+ )
30
+ )
31
+
32
+
33
+ def insert_tag(html, tag):
34
+ """Put the tag in front of the last </body>, or at the end if there is none."""
35
+ matches = list(_BODY_END.finditer(html))
36
+ if not matches:
37
+ return html + tag
38
+ end = matches[-1].start()
39
+ return html[:end] + tag + "\n" + html[end:]
40
+
41
+
42
+ class AsyntaiPlugin(BasePlugin):
43
+ config_scheme = (
44
+ ("widget_id", config_options.Type(str, default="")),
45
+ # Set to false to keep the widget off the site during `mkdocs serve`.
46
+ ("enable_on_serve", config_options.Type(bool, default=True)),
47
+ # Advanced. Load the widget from another URL.
48
+ ("script_url", config_options.Type(str, default=DEFAULT_SCRIPT_URL)),
49
+ )
50
+
51
+ def __init__(self):
52
+ super().__init__()
53
+ self._command = "build"
54
+ self._tag = ""
55
+
56
+ def on_startup(self, *, command, dirty):
57
+ self._command = command
58
+
59
+ def on_config(self, config):
60
+ widget_id = (self.config.get("widget_id") or "").strip()
61
+ if not widget_id:
62
+ raise PluginError(
63
+ 'mkdocs-ai-chatbot: "widget_id" is required. Copy it from the '
64
+ "Install page of your Asyntai dashboard, for example "
65
+ "asyntai_1a2b3c4d5e6f."
66
+ )
67
+ if not WIDGET_ID_PATTERN.match(widget_id):
68
+ raise PluginError(
69
+ 'mkdocs-ai-chatbot: "{0}" does not look like a widget ID. It '
70
+ "starts with asyntai_, for example asyntai_1a2b3c4d5e6f.".format(
71
+ widget_id
72
+ )
73
+ )
74
+ script_url = (self.config.get("script_url") or "").strip() or DEFAULT_SCRIPT_URL
75
+ self._tag = build_tag(widget_id, script_url)
76
+ return config
77
+
78
+ def _active(self):
79
+ if self._command == "serve" and not self.config.get("enable_on_serve"):
80
+ return False
81
+ return bool(self._tag)
82
+
83
+ def _add(self, html):
84
+ if not self._active():
85
+ return html
86
+ # The site owner already pasted the snippet in a theme override. Two
87
+ # loaders would only fight over one chat bubble, so keep theirs.
88
+ if "data-asyntai-id" in html:
89
+ return html
90
+ return insert_tag(html, self._tag)
91
+
92
+ def on_post_page(self, output, *, page, config):
93
+ return self._add(output)
94
+
95
+ def on_post_template(self, output_content, *, template_name, config):
96
+ # Static templates such as 404.html, and search.html in the Read the
97
+ # Docs theme, are not pages, so on_post_page never sees them. A
98
+ # visitor on a dead link or a failed search needs the chat most.
99
+ # sitemap.xml and other non-HTML templates stay as they are.
100
+ if template_name.lower().endswith((".html", ".htm")):
101
+ return self._add(output_content)
102
+ return output_content
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: mkdocs-ai-chatbot
3
+ Version: 1.0.0
4
+ Summary: Add the Asyntai AI chat assistant to your MkDocs site. It answers visitor questions from your own documentation.
5
+ Author-email: Asyntai <hello@asyntai.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://asyntai.com/documentation/integrations/mkdocs/
8
+ Project-URL: Documentation, https://asyntai.com/documentation/integrations/mkdocs/
9
+ Project-URL: Source, https://github.com/asyntai/mkdocs-ai-chatbot
10
+ Project-URL: Issues, https://github.com/asyntai/mkdocs-ai-chatbot/issues
11
+ Keywords: mkdocs,mkdocs-plugin,chatbot,ai,chat,support,documentation,asyntai
12
+ Classifier: Framework :: MkDocs
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Documentation
15
+ Classifier: Topic :: Communications :: Chat
16
+ Requires-Python: >=3.8
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: mkdocs>=1.4
20
+ Dynamic: license-file
21
+
22
+ # mkdocs-ai-chatbot
23
+
24
+ Add the [Asyntai](https://asyntai.com) AI chat assistant to your MkDocs site.
25
+ It answers visitor questions from your own documentation, day and night.
26
+
27
+ Works with every MkDocs theme, including Material for MkDocs and Read the Docs.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install mkdocs-ai-chatbot
33
+ ```
34
+
35
+ Then add the plugin in `mkdocs.yml`:
36
+
37
+ ```yaml
38
+ plugins:
39
+ - search
40
+ - asyntai:
41
+ widget_id: asyntai_1a2b3c4d5e6f
42
+ ```
43
+
44
+ Build the site. The chat bubble is on every page.
45
+
46
+ Keep `search` in the list if you use it. When `mkdocs.yml` has a `plugins`
47
+ section, MkDocs only loads the plugins named there.
48
+
49
+ ## Where the widget ID comes from
50
+
51
+ Open the Install page in your [Asyntai dashboard](https://asyntai.com/dashboard).
52
+ The widget ID is the value of `data-asyntai-id` in the snippet shown there. It
53
+ starts with `asyntai_`.
54
+
55
+ Creating an account is free, and the Free plan is enough to try the widget.
56
+
57
+ ## Options
58
+
59
+ | Option | Type | Default | What it does |
60
+ | --- | --- | --- | --- |
61
+ | `widget_id` | string | required | Your Asyntai widget ID |
62
+ | `enable_on_serve` | boolean | `true` | Set to `false` to keep the widget off the site during `mkdocs serve` |
63
+ | `script_url` | string | the Asyntai CDN | Advanced. Load the widget from another URL |
64
+
65
+ A missing or malformed `widget_id` stops the build with a message that says how
66
+ to fix it.
67
+
68
+ ## What the plugin does
69
+
70
+ - It adds one `<script>` tag in front of the closing body tag of every page.
71
+ - It marks the tag `async`, so your documentation renders first.
72
+ - It changes nothing else. No theme files are overridden and no CSS is added.
73
+ - If a page already has the Asyntai snippet, for example from a theme
74
+ override, the plugin leaves that page alone.
75
+
76
+ ## Answering from your documentation
77
+
78
+ Asyntai reads your published pages. Add your site URL in the dashboard, and the
79
+ assistant answers from the same documentation the widget sits on. You can also
80
+ add documents, and question and answer pairs.
81
+
82
+ ## Removing it
83
+
84
+ Delete the `asyntai` entry from `mkdocs.yml` and build again. The widget is
85
+ gone.
86
+
87
+ ## Support
88
+
89
+ Email [hello@asyntai.com](mailto:hello@asyntai.com), or read the
90
+ [MkDocs guide](https://asyntai.com/documentation/integrations/mkdocs/).
91
+
92
+ ## Licence
93
+
94
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ mkdocs_ai_chatbot/__init__.py
5
+ mkdocs_ai_chatbot/plugin.py
6
+ mkdocs_ai_chatbot.egg-info/PKG-INFO
7
+ mkdocs_ai_chatbot.egg-info/SOURCES.txt
8
+ mkdocs_ai_chatbot.egg-info/dependency_links.txt
9
+ mkdocs_ai_chatbot.egg-info/entry_points.txt
10
+ mkdocs_ai_chatbot.egg-info/requires.txt
11
+ mkdocs_ai_chatbot.egg-info/top_level.txt
12
+ tests/test_plugin.py
@@ -0,0 +1,2 @@
1
+ [mkdocs.plugins]
2
+ asyntai = mkdocs_ai_chatbot.plugin:AsyntaiPlugin
@@ -0,0 +1 @@
1
+ mkdocs_ai_chatbot
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mkdocs-ai-chatbot"
7
+ version = "1.0.0"
8
+ description = "Add the Asyntai AI chat assistant to your MkDocs site. It answers visitor questions from your own documentation."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{name = "Asyntai", email = "hello@asyntai.com"}]
13
+ requires-python = ">=3.8"
14
+ dependencies = ["mkdocs>=1.4"]
15
+ keywords = ["mkdocs", "mkdocs-plugin", "chatbot", "ai", "chat", "support", "documentation", "asyntai"]
16
+ classifiers = [
17
+ "Framework :: MkDocs",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Documentation",
20
+ "Topic :: Communications :: Chat",
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://asyntai.com/documentation/integrations/mkdocs/"
25
+ Documentation = "https://asyntai.com/documentation/integrations/mkdocs/"
26
+ Source = "https://github.com/asyntai/mkdocs-ai-chatbot"
27
+ Issues = "https://github.com/asyntai/mkdocs-ai-chatbot/issues"
28
+
29
+ [project.entry-points."mkdocs.plugins"]
30
+ asyntai = "mkdocs_ai_chatbot.plugin:AsyntaiPlugin"
31
+
32
+ [tool.setuptools]
33
+ packages = ["mkdocs_ai_chatbot"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,379 @@
1
+ """
2
+ Tests for mkdocs-ai-chatbot.
3
+
4
+ Most checks run a real `mkdocs build` (and one real `mkdocs serve`) on small
5
+ sites made in a temporary folder, so they test what a user gets, not a mock.
6
+ Needs mkdocs and the plugin installed in the same Python; Material for MkDocs
7
+ is used when it is installed.
8
+
9
+ Run: python plugins/mkdocs/tests/test_plugin.py
10
+ """
11
+
12
+ import os
13
+ import re
14
+ import shutil
15
+ import socket
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ import time
20
+ import urllib.request
21
+
22
+ HERE = os.path.dirname(os.path.abspath(__file__))
23
+ sys.path.insert(0, os.path.dirname(HERE))
24
+
25
+ from mkdocs_ai_chatbot.plugin import ( # noqa: E402
26
+ DEFAULT_SCRIPT_URL,
27
+ AsyntaiPlugin,
28
+ insert_tag,
29
+ )
30
+
31
+ WIDGET_ID = "asyntai_1a2b3c4d5e6f"
32
+ TAG_RE = re.compile(r"<script[^>]*data-asyntai-id=\"([^\"]+)\"[^>]*></script>")
33
+
34
+ passed = []
35
+ failed = []
36
+
37
+
38
+ def check(name, fn):
39
+ try:
40
+ fn()
41
+ passed.append(name)
42
+ print(" PASS " + name)
43
+ except Exception as err: # noqa: BLE001
44
+ failed.append(name)
45
+ print(" FAIL " + name + " -> " + repr(err))
46
+
47
+
48
+ def has_material():
49
+ try:
50
+ import material # noqa: F401
51
+ return True
52
+ except ImportError:
53
+ return False
54
+
55
+
56
+ def make_site(plugin_yaml, theme="mkdocs", extra_yaml="", pages=None, overrides=None):
57
+ root = tempfile.mkdtemp(prefix="mkdocs_asyntai_")
58
+ docs = os.path.join(root, "docs")
59
+ os.makedirs(docs)
60
+ pages = pages or {
61
+ "index.md": "# Home\n\nWelcome. Příliš žluťoučký kůň.\n",
62
+ "guide/setup.md": "# Setup\n\nInstall it.\n",
63
+ }
64
+ for rel, text in pages.items():
65
+ path = os.path.join(docs, rel)
66
+ os.makedirs(os.path.dirname(path), exist_ok=True)
67
+ with open(path, "w", encoding="utf-8") as f:
68
+ f.write(text)
69
+ theme_block = "theme:\n name: {0}\n".format(theme)
70
+ if overrides:
71
+ over = os.path.join(root, "overrides")
72
+ os.makedirs(over)
73
+ for rel, text in overrides.items():
74
+ with open(os.path.join(over, rel), "w", encoding="utf-8") as f:
75
+ f.write(text)
76
+ theme_block += " custom_dir: overrides\n"
77
+ with open(os.path.join(root, "mkdocs.yml"), "w", encoding="utf-8") as f:
78
+ f.write(
79
+ "site_name: Test Docs\nsite_url: https://docs.example.com/\n"
80
+ + theme_block
81
+ + extra_yaml
82
+ + "plugins:\n - search\n"
83
+ + plugin_yaml
84
+ )
85
+ return root
86
+
87
+
88
+ def build(root):
89
+ return subprocess.run(
90
+ [sys.executable, "-m", "mkdocs", "build", "--strict"],
91
+ cwd=root,
92
+ capture_output=True,
93
+ text=True,
94
+ encoding="utf-8",
95
+ errors="replace",
96
+ )
97
+
98
+
99
+ def html_files(root):
100
+ site = os.path.join(root, "site")
101
+ for dirpath, _, files in os.walk(site):
102
+ for name in files:
103
+ if name.endswith(".html"):
104
+ yield os.path.join(dirpath, name)
105
+
106
+
107
+ def read(path):
108
+ with open(path, encoding="utf-8") as f:
109
+ return f.read()
110
+
111
+
112
+ def assert_every_page_has_one_tag(root, widget_id=WIDGET_ID, script_url=DEFAULT_SCRIPT_URL):
113
+ files = list(html_files(root))
114
+ assert len(files) >= 3, "expected index, guide page and 404, got %d" % len(files)
115
+ for path in files:
116
+ html = read(path)
117
+ tags = TAG_RE.findall(html)
118
+ assert tags == [widget_id], "%s has tags %r" % (os.path.basename(path), tags)
119
+ tag = TAG_RE.search(html).group(0)
120
+ assert "async" in tag, "tag is not async"
121
+ assert 'src="%s"' % script_url in tag, "wrong src in " + tag
122
+ after = html[html.index(tag) + len(tag):]
123
+ assert re.match(r"\s*</body>", after, re.I), "tag is not right before </body>"
124
+ return files
125
+
126
+
127
+ def run_theme(theme, extra_yaml=""):
128
+ root = make_site(" - asyntai:\n widget_id: %s\n" % WIDGET_ID, theme=theme, extra_yaml=extra_yaml)
129
+ try:
130
+ result = build(root)
131
+ assert result.returncode == 0, result.stderr[-800:]
132
+ files = assert_every_page_has_one_tag(root)
133
+ assert any(f.endswith("404.html") for f in files), "no 404.html"
134
+ index = read(os.path.join(root, "site", "index.html"))
135
+ assert "Příliš žluťoučký kůň" in index, "non-ASCII text changed"
136
+ sitemap = os.path.join(root, "site", "sitemap.xml")
137
+ if os.path.exists(sitemap):
138
+ assert "asyntai" not in read(sitemap), "sitemap was touched"
139
+ finally:
140
+ shutil.rmtree(root, ignore_errors=True)
141
+
142
+
143
+ # --- insert_tag, the only string surgery -----------------------------------
144
+
145
+ def t_insert_last_body():
146
+ html = "<html><body><pre>&lt;/body&gt; </body></pre></body></html>"
147
+ out = insert_tag(html, "<X>")
148
+ assert out.endswith("<X>\n</body></html>"), out
149
+
150
+
151
+ def t_insert_uppercase():
152
+ out = insert_tag("<HTML><BODY>a</BODY ></HTML>", "<X>")
153
+ assert out == "<HTML><BODY>a<X>\n</BODY ></HTML>", out
154
+
155
+
156
+ def t_insert_no_body():
157
+ assert insert_tag("<p>fragment</p>", "<X>") == "<p>fragment</p><X>"
158
+
159
+
160
+ # --- real builds -------------------------------------------------------------
161
+
162
+ def t_theme_mkdocs():
163
+ run_theme("mkdocs")
164
+
165
+
166
+ def t_theme_readthedocs():
167
+ run_theme("readthedocs")
168
+
169
+
170
+ def t_theme_material():
171
+ if not has_material():
172
+ raise RuntimeError("mkdocs-material is not installed")
173
+ run_theme("material")
174
+
175
+
176
+ def t_theme_material_instant():
177
+ if not has_material():
178
+ raise RuntimeError("mkdocs-material is not installed")
179
+ root = make_site(
180
+ " - asyntai:\n widget_id: %s\n" % WIDGET_ID,
181
+ theme="material\n features:\n - navigation.instant",
182
+ )
183
+ try:
184
+ result = build(root)
185
+ assert result.returncode == 0, result.stderr[-800:]
186
+ assert_every_page_has_one_tag(root)
187
+ finally:
188
+ shutil.rmtree(root, ignore_errors=True)
189
+
190
+
191
+ def expect_failure(plugin_yaml, needle):
192
+ root = make_site(plugin_yaml)
193
+ try:
194
+ result = build(root)
195
+ assert result.returncode != 0, "build passed but should fail"
196
+ out = result.stdout + result.stderr
197
+ assert needle in out, "message not shown, got: " + out[-600:]
198
+ assert not os.path.exists(os.path.join(root, "site", "index.html")), "site was written"
199
+ finally:
200
+ shutil.rmtree(root, ignore_errors=True)
201
+
202
+
203
+ def t_missing_id():
204
+ expect_failure(" - asyntai\n", '"widget_id" is required')
205
+
206
+
207
+ def t_empty_id():
208
+ expect_failure(" - asyntai:\n widget_id: ' '\n", '"widget_id" is required')
209
+
210
+
211
+ def t_bad_id():
212
+ expect_failure(" - asyntai:\n widget_id: 1a2b3c\n", "does not look like a widget ID")
213
+
214
+
215
+ def t_wrong_type():
216
+ expect_failure(" - asyntai:\n widget_id: [a, b]\n", "widget_id")
217
+
218
+
219
+ def t_trimmed_id():
220
+ root = make_site(" - asyntai:\n widget_id: ' %s '\n" % WIDGET_ID)
221
+ try:
222
+ assert build(root).returncode == 0
223
+ assert_every_page_has_one_tag(root)
224
+ finally:
225
+ shutil.rmtree(root, ignore_errors=True)
226
+
227
+
228
+ def t_custom_script_url():
229
+ url = "https://cdn.example.com/w.js"
230
+ root = make_site(" - asyntai:\n widget_id: %s\n script_url: %s\n" % (WIDGET_ID, url))
231
+ try:
232
+ assert build(root).returncode == 0
233
+ assert_every_page_has_one_tag(root, script_url=url)
234
+ finally:
235
+ shutil.rmtree(root, ignore_errors=True)
236
+
237
+
238
+ def t_existing_snippet_kept():
239
+ main = (
240
+ '{% extends "base.html" %}\n{% block scripts %}{{ super() }}'
241
+ '<script async src="https://widget.asyntai.com/static/js/chat-widget.js" '
242
+ 'data-asyntai-id="asyntai_ownsnippet1"></script>{% endblock %}\n'
243
+ )
244
+ root = make_site(
245
+ " - asyntai:\n widget_id: %s\n" % WIDGET_ID,
246
+ overrides={"main.html": main},
247
+ )
248
+ try:
249
+ assert build(root).returncode == 0
250
+ index = read(os.path.join(root, "site", "index.html"))
251
+ assert TAG_RE.findall(index) == ["asyntai_ownsnippet1"], TAG_RE.findall(index)
252
+ finally:
253
+ shutil.rmtree(root, ignore_errors=True)
254
+
255
+
256
+ def t_body_in_code_block():
257
+ pages = {
258
+ "index.md": "# Home\n\n```html\n<html><body>x</body></html>\n```\n",
259
+ "guide/setup.md": "# Setup\n",
260
+ }
261
+ root = make_site(" - asyntai:\n widget_id: %s\n" % WIDGET_ID, pages=pages)
262
+ try:
263
+ assert build(root).returncode == 0
264
+ assert_every_page_has_one_tag(root)
265
+ index = read(os.path.join(root, "site", "index.html"))
266
+ assert index.count("&lt;/body&gt;") == 1, "code block changed"
267
+ finally:
268
+ shutil.rmtree(root, ignore_errors=True)
269
+
270
+
271
+ def t_no_plugin_no_tag():
272
+ root = make_site("")
273
+ try:
274
+ assert build(root).returncode == 0
275
+ for path in html_files(root):
276
+ assert "data-asyntai-id" not in read(path)
277
+ finally:
278
+ shutil.rmtree(root, ignore_errors=True)
279
+
280
+
281
+ # --- serve -------------------------------------------------------------------
282
+
283
+ def free_port():
284
+ s = socket.socket()
285
+ s.bind(("127.0.0.1", 0))
286
+ port = s.getsockname()[1]
287
+ s.close()
288
+ return port
289
+
290
+
291
+ def serve_and_fetch(plugin_yaml):
292
+ root = make_site(plugin_yaml)
293
+ port = free_port()
294
+ proc = subprocess.Popen(
295
+ [sys.executable, "-m", "mkdocs", "serve", "-a", "127.0.0.1:%d" % port, "--no-livereload"],
296
+ cwd=root,
297
+ stdout=subprocess.DEVNULL,
298
+ stderr=subprocess.DEVNULL,
299
+ )
300
+ try:
301
+ deadline = time.time() + 30
302
+ while True:
303
+ try:
304
+ with urllib.request.urlopen("http://127.0.0.1:%d/guide/setup/" % port, timeout=2) as r:
305
+ return r.read().decode("utf-8")
306
+ except Exception: # noqa: BLE001
307
+ if time.time() > deadline:
308
+ raise
309
+ time.sleep(0.5)
310
+ finally:
311
+ proc.terminate()
312
+ proc.wait(timeout=10)
313
+ shutil.rmtree(root, ignore_errors=True)
314
+
315
+
316
+ def t_serve_default_on():
317
+ html = serve_and_fetch(" - asyntai:\n widget_id: %s\n" % WIDGET_ID)
318
+ assert TAG_RE.findall(html) == [WIDGET_ID], "serve page has no widget"
319
+
320
+
321
+ def t_serve_off():
322
+ html = serve_and_fetch(" - asyntai:\n widget_id: %s\n enable_on_serve: false\n" % WIDGET_ID)
323
+ assert "data-asyntai-id" not in html, "widget is on during serve"
324
+ assert "<h1" in html, "page did not render"
325
+
326
+
327
+ # --- in-process hook calls -----------------------------------------------------
328
+
329
+ def t_hooks_in_process():
330
+ plugin = AsyntaiPlugin()
331
+ errors, warnings = plugin.load_config({"widget_id": WIDGET_ID, "enable_on_serve": False})
332
+ assert not errors, errors
333
+ plugin.on_startup(command="build", dirty=False)
334
+ plugin.on_config({})
335
+ page = "<html><body>a</body></html>"
336
+ assert WIDGET_ID in plugin.on_post_page(page, page=None, config={})
337
+ assert plugin.on_post_template("x", template_name="sitemap.xml", config={}) == "x"
338
+ assert WIDGET_ID in plugin.on_post_template(page, template_name="search.html", config={})
339
+ plugin.on_startup(command="serve", dirty=False)
340
+ assert plugin.on_post_page(page, page=None, config={}) == page
341
+
342
+
343
+ def t_entry_point():
344
+ from importlib.metadata import entry_points
345
+
346
+ eps = entry_points()
347
+ group = eps.select(group="mkdocs.plugins") if hasattr(eps, "select") else eps.get("mkdocs.plugins", [])
348
+ match = [ep for ep in group if ep.name == "asyntai"]
349
+ assert match, "entry point asyntai is not registered"
350
+ assert match[0].load() is not None
351
+
352
+
353
+ if __name__ == "__main__":
354
+ print("mkdocs-ai-chatbot tests")
355
+ for name, fn in [
356
+ ("insert before the LAST </body>", t_insert_last_body),
357
+ ("insert works with upper case </BODY >", t_insert_uppercase),
358
+ ("insert appends when there is no body", t_insert_no_body),
359
+ ("build: mkdocs theme, every page + 404 has one tag", t_theme_mkdocs),
360
+ ("build: readthedocs theme", t_theme_readthedocs),
361
+ ("build: Material for MkDocs", t_theme_material),
362
+ ("build: Material with navigation.instant", t_theme_material_instant),
363
+ ("missing widget_id stops the build", t_missing_id),
364
+ ("blank widget_id stops the build", t_empty_id),
365
+ ("malformed widget_id stops the build", t_bad_id),
366
+ ("widget_id of wrong type stops the build", t_wrong_type),
367
+ ("widget_id with spaces is trimmed", t_trimmed_id),
368
+ ("custom script_url is used", t_custom_script_url),
369
+ ("existing snippet in a theme override is kept, no second tag", t_existing_snippet_kept),
370
+ ("</body> inside a code block is left alone", t_body_in_code_block),
371
+ ("site without the plugin has no tag", t_no_plugin_no_tag),
372
+ ("mkdocs serve: widget is on by default", t_serve_default_on),
373
+ ("mkdocs serve: enable_on_serve false keeps it off", t_serve_off),
374
+ ("hooks in process: build vs serve, sitemap untouched", t_hooks_in_process),
375
+ ("entry point 'asyntai' resolves", t_entry_point),
376
+ ]:
377
+ check(name, fn)
378
+ print("\n%d passed, %d failed" % (len(passed), len(failed)))
379
+ sys.exit(1 if failed else 0)