codis 1.1.1__py3-none-any.whl
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.
- codis-1.1.1.dist-info/METADATA +194 -0
- codis-1.1.1.dist-info/RECORD +329 -0
- codis-1.1.1.dist-info/WHEEL +5 -0
- codis-1.1.1.dist-info/entry_points.txt +5 -0
- codis-1.1.1.dist-info/licenses/LICENSE +21 -0
- codis-1.1.1.dist-info/top_level.txt +2 -0
- run.py +190 -0
- src/__init__.py +1 -0
- src/__main__.py +81 -0
- src/_app_build.py +1507 -0
- src/_app_editor.py +1274 -0
- src/_app_kui.py +825 -0
- src/_app_lsp.py +625 -0
- src/_app_recovery.py +189 -0
- src/_app_settings.py +1385 -0
- src/_app_tools.py +2471 -0
- src/_app_webpreview.py +126 -0
- src/_font_safety.py +127 -0
- src/_shells.py +172 -0
- src/app.py +1488 -0
- src/chat/__init__.py +1 -0
- src/chat/adapters/__init__.py +33 -0
- src/chat/adapters/base.py +209 -0
- src/chat/adapters/discord.py +190 -0
- src/chat/adapters/http.py +78 -0
- src/chat/adapters/irc.py +360 -0
- src/chat/adapters/matrix.py +219 -0
- src/chat/adapters/mattermost.py +178 -0
- src/chat/adapters/mqtt.py +165 -0
- src/chat/adapters/slack.py +204 -0
- src/chat/adapters/telegram.py +117 -0
- src/chat/adapters/ws.py +154 -0
- src/chat/adapters/xmpp.py +337 -0
- src/chat/history.py +76 -0
- src/chat/models.py +207 -0
- src/chat/probe.py +79 -0
- src/chat/session.py +446 -0
- src/chat/util.py +125 -0
- src/collab/__init__.py +1 -0
- src/collab/net.py +411 -0
- src/collab/ot.py +311 -0
- src/collab/session.py +141 -0
- src/collab/tk_adapter.py +134 -0
- src/config.py +335 -0
- src/constants.py +2552 -0
- src/dep_catalog.py +446 -0
- src/diff/__init__.py +1 -0
- src/diff/engine.py +247 -0
- src/dpi.py +30 -0
- src/editor/__init__.py +1 -0
- src/editor/_pane_lsp.py +2937 -0
- src/editor/_pane_utils.py +171 -0
- src/editor/autocomplete.py +607 -0
- src/editor/code_folding.py +836 -0
- src/editor/color_preview.py +382 -0
- src/editor/complexity_lens.py +281 -0
- src/editor/diff_pane.py +623 -0
- src/editor/file_watcher.py +144 -0
- src/editor/focus_block.py +236 -0
- src/editor/heatmap.py +141 -0
- src/editor/inlay_hints.py +366 -0
- src/editor/inline_blame.py +429 -0
- src/editor/kdocs.py +3376 -0
- src/editor/large_file.py +488 -0
- src/editor/ligatures.py +180 -0
- src/editor/line_numbers.py +598 -0
- src/editor/minimap.py +691 -0
- src/editor/multi_cursor.py +269 -0
- src/editor/pane.py +2082 -0
- src/editor/rhythm.py +206 -0
- src/editor/save_hooks.py +43 -0
- src/editor/smart_selection.py +425 -0
- src/editor/smart_tips.py +719 -0
- src/editor/snippets.py +411 -0
- src/editor/sticky_note_gutter.py +410 -0
- src/editor/sticky_scroll.py +385 -0
- src/editor/suggest.py +464 -0
- src/editor/text_transforms.py +310 -0
- src/editor/vim_mode.py +1074 -0
- src/events/__init__.py +84 -0
- src/events/bus.py +427 -0
- src/events/correlator.py +244 -0
- src/events/kinds.py +125 -0
- src/events/pipeline.py +264 -0
- src/events/stream.py +416 -0
- src/events/window.py +204 -0
- src/extcompat/__init__.py +19 -0
- src/extcompat/code/__init__.py +13 -0
- src/extcompat/code/consent.py +162 -0
- src/extcompat/code/host.py +353 -0
- src/extcompat/code/hosts/py_host.py +763 -0
- src/extcompat/code/locate.py +105 -0
- src/extcompat/code/manager.py +325 -0
- src/extcompat/code/permissions.py +154 -0
- src/extcompat/code/sandbox.py +60 -0
- src/extcompat/colors.py +131 -0
- src/extcompat/common.py +184 -0
- src/extcompat/cson.py +269 -0
- src/extcompat/formats/__init__.py +22 -0
- src/extcompat/formats/_tm.py +189 -0
- src/extcompat/formats/_util.py +31 -0
- src/extcompat/formats/base16.py +66 -0
- src/extcompat/formats/brackets.py +172 -0
- src/extcompat/formats/eclipse.py +193 -0
- src/extcompat/formats/emacs.py +361 -0
- src/extcompat/formats/geany.py +147 -0
- src/extcompat/formats/generic.py +184 -0
- src/extcompat/formats/gtksource.py +117 -0
- src/extcompat/formats/helix.py +91 -0
- src/extcompat/formats/jetbrains.py +343 -0
- src/extcompat/formats/kate.py +130 -0
- src/extcompat/formats/micro.py +131 -0
- src/extcompat/formats/nano.py +111 -0
- src/extcompat/formats/notepadpp.py +140 -0
- src/extcompat/formats/pulsar.py +165 -0
- src/extcompat/formats/pyides.py +163 -0
- src/extcompat/formats/sublime.py +340 -0
- src/extcompat/jsonc.py +65 -0
- src/extcompat/lessish.py +128 -0
- src/extcompat/manager.py +122 -0
- src/extcompat/market/__init__.py +63 -0
- src/extcompat/market/sources.py +211 -0
- src/extcompat/model.py +88 -0
- src/extcompat/net.py +228 -0
- src/extcompat/openvsx.py +63 -0
- src/extcompat/readers.py +362 -0
- src/extcompat/registry.py +73 -0
- src/extcompat/safexml.py +63 -0
- src/extcompat/sexp.py +187 -0
- src/extcompat/sources.py +105 -0
- src/extcompat/store.py +276 -0
- src/extcompat/textmate.py +214 -0
- src/extcompat/themes.py +487 -0
- src/extcompat/yamlite.py +294 -0
- src/fileio.py +94 -0
- src/fs_ops.py +106 -0
- src/i18n.py +233 -0
- src/ia/__init__.py +1 -0
- src/ia/actions.py +295 -0
- src/ia/approval_gate.py +672 -0
- src/ia/checkpoints.py +308 -0
- src/ia/context_builder.py +921 -0
- src/ia/dialdiff.py +408 -0
- src/ia/iaspace.py +2078 -0
- src/ia/pair.py +296 -0
- src/ia/providers.py +954 -0
- src/ia/session.py +335 -0
- src/ia/toolbox.py +2524 -0
- src/launcher_actions.py +204 -0
- src/lint/__init__.py +1 -0
- src/lint/manager.py +1058 -0
- src/locales/.translate_manifest.json +64170 -0
- src/locales/de.json +4936 -0
- src/locales/en.json +4936 -0
- src/locales/es.json +4936 -0
- src/locales/fr.json +4936 -0
- src/locales/it.json +4936 -0
- src/locales/ja.json +4936 -0
- src/locales/ko.json +4936 -0
- src/locales/nl.json +4936 -0
- src/locales/pl.json +4936 -0
- src/locales/pt-BR.json +4936 -0
- src/locales/ru.json +4936 -0
- src/locales/tr.json +4936 -0
- src/locales/uk.json +4936 -0
- src/locales/zh-CN.json +4936 -0
- src/lsp/__init__.py +26 -0
- src/lsp/client.py +2300 -0
- src/lsp/dap_client.py +480 -0
- src/lsp/edits.py +84 -0
- src/lsp/framing.py +73 -0
- src/lsp/protocol.py +931 -0
- src/main.py +260 -0
- src/memtrim.py +91 -0
- src/plugins/__init__.py +1 -0
- src/plugins/api.py +1761 -0
- src/plugins/loader.py +571 -0
- src/plugins/process_runner.py +519 -0
- src/plugins/registry.py +342 -0
- src/plugins/safety.py +367 -0
- src/plugins/startup.py +195 -0
- src/plugins/store.py +1178 -0
- src/proc_registry.py +278 -0
- src/pyexec.py +394 -0
- src/recovery.py +259 -0
- src/stall_trace.py +92 -0
- src/standalone.py +1070 -0
- src/startup_profile.py +35 -0
- src/syntax/__init__.py +1 -0
- src/syntax/highlighter.py +776 -0
- src/syntax/patterns.py +584 -0
- src/system_profile.py +430 -0
- src/terminal/backends.py +658 -0
- src/terminal/internal.py +346 -0
- src/terminal/keys.py +138 -0
- src/terminal/palette.py +67 -0
- src/terminal/session.py +283 -0
- src/terminal/shells.py +79 -0
- src/terminal/view.py +489 -0
- src/terminal/vt.py +870 -0
- src/textfmt.py +22 -0
- src/theme/__init__.py +1 -0
- src/theme/base.py +1281 -0
- src/theme/colors.py +49 -0
- src/theme/manager.py +602 -0
- src/theme/utils.py +312 -0
- src/toolbox.py +329 -0
- src/trash_core.py +531 -0
- src/ui/__init__.py +1 -0
- src/ui/_perf_utils.py +285 -0
- src/ui/_persistence_utils.py +93 -0
- src/ui/accessibility.py +843 -0
- src/ui/activity_bar.py +860 -0
- src/ui/app_embed.py +434 -0
- src/ui/archive_panel.py +608 -0
- src/ui/bookmarks.py +314 -0
- src/ui/breadcrumb.py +383 -0
- src/ui/calculator_panel.py +982 -0
- src/ui/calendar_panel.py +1218 -0
- src/ui/chat_panel.py +1271 -0
- src/ui/chat_profile_dialog.py +278 -0
- src/ui/chat_render.py +128 -0
- src/ui/clock_panel.py +810 -0
- src/ui/code_outline.py +364 -0
- src/ui/code_runner.py +729 -0
- src/ui/code_stats.py +546 -0
- src/ui/collab_panel.py +1009 -0
- src/ui/color_picker.py +547 -0
- src/ui/command_palette.py +452 -0
- src/ui/cursor_manager.py +750 -0
- src/ui/custom_keywords_panel.py +413 -0
- src/ui/debug_panel.py +1037 -0
- src/ui/dependency_graph.py +692 -0
- src/ui/diff_panel.py +381 -0
- src/ui/docs_panel.py +514 -0
- src/ui/doom_embed.py +349 -0
- src/ui/dropdown.py +321 -0
- src/ui/easter_eggs.py +979 -0
- src/ui/env_manager.py +666 -0
- src/ui/extcode_bridge.py +215 -0
- src/ui/extcode_dialogs.py +412 -0
- src/ui/extcompat_dialog.py +583 -0
- src/ui/file_timeline.py +319 -0
- src/ui/file_tree.py +1208 -0
- src/ui/find_in_files.py +1355 -0
- src/ui/flowchart_panel.py +727 -0
- src/ui/formatter_panel.py +490 -0
- src/ui/git_auth.py +763 -0
- src/ui/git_clone_dialog.py +487 -0
- src/ui/git_panel.py +1483 -0
- src/ui/grab_safe.py +84 -0
- src/ui/internal_python_dialog.py +98 -0
- src/ui/k_ui/__init__.py +1305 -0
- src/ui/k_ui/_bgrenderer.py +317 -0
- src/ui/k_ui/_colors.py +213 -0
- src/ui/k_ui/_dock.py +545 -0
- src/ui/k_ui/_easter.py +290 -0
- src/ui/k_ui/_engine.py +5448 -0
- src/ui/k_ui/_perf.py +333 -0
- src/ui/k_ui/_tkutil.py +7 -0
- src/ui/k_ui/_tooltip.py +365 -0
- src/ui/k_ui/_widgets.py +1204 -0
- src/ui/k_ui/_world.py +837 -0
- src/ui/key_remapper.py +856 -0
- src/ui/launcher.py +1252 -0
- src/ui/lazy_panel.py +73 -0
- src/ui/macro_recorder.py +610 -0
- src/ui/menu_bar.py +898 -0
- src/ui/output_panel.py +321 -0
- src/ui/paint_canvas.py +1000 -0
- src/ui/paint_engine.py +535 -0
- src/ui/paint_panel.py +888 -0
- src/ui/panel_detach.py +112 -0
- src/ui/performance_panel.py +861 -0
- src/ui/pip_manager.py +1758 -0
- src/ui/plugin_panel.py +1586 -0
- src/ui/pomodoro_panel.py +447 -0
- src/ui/problems.py +566 -0
- src/ui/process_manager.py +1657 -0
- src/ui/project_templates.py +775 -0
- src/ui/recovery_dialog.py +122 -0
- src/ui/regex_playground.py +304 -0
- src/ui/remote_adapters.py +1398 -0
- src/ui/remote_browser.py +1224 -0
- src/ui/remote_profile_dialog.py +342 -0
- src/ui/render_panel.py +1293 -0
- src/ui/rest_client.py +549 -0
- src/ui/scratchpad.py +548 -0
- src/ui/search_bar.py +1274 -0
- src/ui/settings_editor.py +3349 -0
- src/ui/settings_window.py +1554 -0
- src/ui/snippets_panel.py +597 -0
- src/ui/sql_studio.py +1815 -0
- src/ui/status_bar.py +438 -0
- src/ui/tab_bar.py +654 -0
- src/ui/task_manager.py +1773 -0
- src/ui/terminal.py +525 -0
- src/ui/theme_preview_panel.py +851 -0
- src/ui/thread_safe_tk.py +152 -0
- src/ui/time_tracker.py +574 -0
- src/ui/tkbind.py +43 -0
- src/ui/todo_panel.py +358 -0
- src/ui/toolbox_panels.py +658 -0
- src/ui/trash_manager.py +657 -0
- src/ui/ui_scale.py +294 -0
- src/ui/ux_enhancements.py +41 -0
- src/ui/web_preview.py +397 -0
- src/ui/webdev.py +630 -0
- src/ui/welcome.py +567 -0
- src/ui/window_embed.py +1500 -0
- src/ui/wizard.py +1550 -0
- src/ui/workspace_switcher.py +418 -0
- src/ui/workspace_trust.py +370 -0
- src/ui/zen_audio.py +354 -0
- src/ui/zen_media.py +2271 -0
- src/ui/zen_media_client.py +303 -0
- src/ui/zen_media_host.py +329 -0
- src/ui/zen_player.py +907 -0
- src/ui/zen_player_widgets.py +700 -0
- src/updater/__init__.py +11 -0
- src/updater/assets.py +145 -0
- src/updater/backup.py +101 -0
- src/updater/channel.py +221 -0
- src/updater/dialog.py +492 -0
- src/updater/integrity.py +111 -0
- src/updater/manager.py +727 -0
- src/updater/result.py +114 -0
- src/venv_runtime.py +531 -0
- src/workspace_state.py +25 -0
src/ui/webdev.py
ADDED
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
"""Codis - infraestrutura do Preview Web (sem API key, sem serviços externos).
|
|
2
|
+
|
|
3
|
+
Três peças independentes de Tk (testáveis sozinhas):
|
|
4
|
+
|
|
5
|
+
* :func:`find_browser` - localiza um navegador Chromium instalado
|
|
6
|
+
(Edge, Chrome, Chromium, Brave...). No Windows o Edge já vem no sistema.
|
|
7
|
+
* :class:`DevServer` - servidor HTTP **local (127.0.0.1)** para a pasta do
|
|
8
|
+
projeto, com *live reload* (troca CSS sem recarregar a página), preview de
|
|
9
|
+
Markdown, MIME correto para ``.js``/``.mjs``/``.wasm`` e **buffers não
|
|
10
|
+
salvos** do editor (você vê o que digita antes de salvar).
|
|
11
|
+
* :class:`CdpClient` - cliente mínimo do *Chrome DevTools Protocol*: navegar,
|
|
12
|
+
recarregar, emular dispositivo e receber console/erros/requisições
|
|
13
|
+
falhas para mostrar no Codis.
|
|
14
|
+
|
|
15
|
+
O navegador roda como processo próprio e sua janela é incorporada ao editor
|
|
16
|
+
por :mod:`src.ui.window_embed`; por isso HTML, CSS e JavaScript têm o suporte
|
|
17
|
+
**completo** de um navegador de verdade (flexbox, grid, módulos ES, fetch,
|
|
18
|
+
WebGL, DevTools com F12...), e não de um renderizador parcial.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import contextlib
|
|
24
|
+
import json
|
|
25
|
+
import logging
|
|
26
|
+
import os
|
|
27
|
+
import shutil
|
|
28
|
+
import sys
|
|
29
|
+
import threading
|
|
30
|
+
import time
|
|
31
|
+
import urllib.request
|
|
32
|
+
from collections.abc import Callable, Mapping
|
|
33
|
+
from dataclasses import dataclass, field
|
|
34
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
from typing import Any
|
|
37
|
+
from urllib.parse import parse_qs, unquote, urlsplit
|
|
38
|
+
|
|
39
|
+
logger = logging.getLogger("Codis.Web")
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"CdpClient",
|
|
43
|
+
"ConsoleEntry",
|
|
44
|
+
"DevServer",
|
|
45
|
+
"DEVICE_PRESETS",
|
|
46
|
+
"find_browser",
|
|
47
|
+
"is_previewable",
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
PREVIEW_EXTS = frozenset({".html", ".htm", ".xhtml", ".md", ".markdown", ".svg"})
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def is_previewable(path: str | os.PathLike[str] | None) -> bool:
|
|
54
|
+
"""True se ``path`` é HTML/Markdown/SVG."""
|
|
55
|
+
return bool(path) and Path(str(path)).suffix.lower() in PREVIEW_EXTS
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
_WIN_CANDIDATES = (
|
|
59
|
+
(r"Microsoft\Edge\Application\msedge.exe", "edge"),
|
|
60
|
+
(r"Google\Chrome\Application\chrome.exe", "chrome"),
|
|
61
|
+
(r"BraveSoftware\Brave-Browser\Application\brave.exe", "brave"),
|
|
62
|
+
(r"Chromium\Application\chrome.exe", "chromium"),
|
|
63
|
+
(r"Vivaldi\Application\vivaldi.exe", "vivaldi"),
|
|
64
|
+
)
|
|
65
|
+
_POSIX_NAMES = (
|
|
66
|
+
"google-chrome-stable", "google-chrome", "chromium", "chromium-browser",
|
|
67
|
+
"microsoft-edge-stable", "microsoft-edge", "brave-browser", "brave", "vivaldi",
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def find_browser(
|
|
72
|
+
configured: str | None = None,
|
|
73
|
+
env: Mapping[str, str] | None = None,
|
|
74
|
+
which: Callable[[str], str | None] = shutil.which,
|
|
75
|
+
platform: str | None = None,
|
|
76
|
+
) -> Path | None:
|
|
77
|
+
"""Localiza um navegador baseado em Chromium (necessário para ``--app`` e CDP).
|
|
78
|
+
|
|
79
|
+
Ordem: caminho configurado (``web_browser_path`` / ``CODIS_WEB_BROWSER``)
|
|
80
|
+
-> instalações padrão (Windows) -> PATH. Firefox/Safari não servem aqui
|
|
81
|
+
(não falam CDP nem têm modo ``--app``).
|
|
82
|
+
"""
|
|
83
|
+
env = os.environ if env is None else env
|
|
84
|
+
platform = sys.platform if platform is None else platform
|
|
85
|
+
for explicit in (configured, env.get("CODIS_WEB_BROWSER")):
|
|
86
|
+
if explicit and Path(explicit).expanduser().is_file():
|
|
87
|
+
return Path(explicit).expanduser()
|
|
88
|
+
if platform == "win32":
|
|
89
|
+
bases = [env.get(k) for k in ("ProgramFiles(x86)", "ProgramFiles", "LOCALAPPDATA")]
|
|
90
|
+
for rel, _name in _WIN_CANDIDATES:
|
|
91
|
+
for base in filter(None, bases):
|
|
92
|
+
cand = Path(base, *rel.split("\\"))
|
|
93
|
+
if cand.is_file():
|
|
94
|
+
return cand
|
|
95
|
+
for exe in ("msedge", "chrome", "brave"):
|
|
96
|
+
found = which(exe)
|
|
97
|
+
if found:
|
|
98
|
+
return Path(found)
|
|
99
|
+
return None
|
|
100
|
+
if platform == "darwin":
|
|
101
|
+
return None
|
|
102
|
+
for name in _POSIX_NAMES:
|
|
103
|
+
found = which(name)
|
|
104
|
+
if found:
|
|
105
|
+
return Path(found)
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
_MIME = {
|
|
110
|
+
".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8",
|
|
111
|
+
".cjs": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8",
|
|
112
|
+
".html": "text/html; charset=utf-8", ".htm": "text/html; charset=utf-8",
|
|
113
|
+
".xhtml": "application/xhtml+xml", ".svg": "image/svg+xml", ".json": "application/json",
|
|
114
|
+
".map": "application/json", ".wasm": "application/wasm", ".webmanifest": "application/manifest+json",
|
|
115
|
+
".md": "text/markdown; charset=utf-8", ".txt": "text/plain; charset=utf-8",
|
|
116
|
+
".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif",
|
|
117
|
+
".webp": "image/webp", ".avif": "image/avif", ".ico": "image/x-icon",
|
|
118
|
+
".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf", ".otf": "font/otf",
|
|
119
|
+
".mp4": "video/mp4", ".webm": "video/webm", ".mp3": "audio/mpeg", ".ogg": "audio/ogg",
|
|
120
|
+
".wav": "audio/wav", ".pdf": "application/pdf", ".xml": "application/xml",
|
|
121
|
+
}
|
|
122
|
+
_WATCH_EXTS = frozenset(
|
|
123
|
+
{".html", ".htm", ".css", ".js", ".mjs", ".cjs", ".json", ".svg", ".md", ".markdown",
|
|
124
|
+
".xhtml", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".woff", ".woff2", ".wasm"}
|
|
125
|
+
)
|
|
126
|
+
_SKIP_DIRS = frozenset({".git", "node_modules", "__pycache__", ".venv", "venv", ".idea", ".vscode", "dist-cache"})
|
|
127
|
+
_MAX_WATCH_FILES = 4000
|
|
128
|
+
|
|
129
|
+
_RELOAD_JS = r"""(function(){
|
|
130
|
+
var v=null, busy=false;
|
|
131
|
+
function swapCss(){
|
|
132
|
+
var links=document.querySelectorAll('link[rel~="stylesheet"]'), t=Date.now();
|
|
133
|
+
links.forEach(function(l){
|
|
134
|
+
try{var u=new URL(l.href,location.href); if(u.origin!==location.origin) return;
|
|
135
|
+
u.searchParams.set('__codis',t);
|
|
136
|
+
var n=l.cloneNode(); n.href=u.toString();
|
|
137
|
+
n.onload=function(){l.remove()}; n.onerror=function(){n.remove()}; l.after(n);}catch(e){}
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
function tick(){
|
|
141
|
+
if(busy) return; busy=true;
|
|
142
|
+
fetch('/__codis/poll?v='+(v===null?'':v),{cache:'no-store'}).then(function(r){return r.json()})
|
|
143
|
+
.then(function(d){
|
|
144
|
+
if(v!==null && d.v!==v){
|
|
145
|
+
var onlyCss=d.changed.length>0 && d.changed.every(function(p){return /\.css$/i.test(p)});
|
|
146
|
+
if(onlyCss) swapCss(); else location.reload();
|
|
147
|
+
}
|
|
148
|
+
v=d.v;
|
|
149
|
+
}).catch(function(){}).then(function(){busy=false});
|
|
150
|
+
}
|
|
151
|
+
setInterval(tick,500); tick();
|
|
152
|
+
})();"""
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class DevServer:
|
|
156
|
+
"""Servidor local de preview para uma pasta (``root``).
|
|
157
|
+
|
|
158
|
+
Args:
|
|
159
|
+
root: Pasta servida (nada fora dela é acessível).
|
|
160
|
+
md_renderer: ``(markdown_text, title) -> html`` para arquivos ``.md``.
|
|
161
|
+
live_reload: Injeta o script de recarga automática em páginas HTML.
|
|
162
|
+
watch_interval: Segundos entre varreduras de mtime.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
def __init__(
|
|
166
|
+
self,
|
|
167
|
+
root: str | os.PathLike[str],
|
|
168
|
+
*,
|
|
169
|
+
md_renderer: Callable[[str, str], str] | None = None,
|
|
170
|
+
live_reload: bool = True,
|
|
171
|
+
watch_interval: float = 0.4,
|
|
172
|
+
) -> None:
|
|
173
|
+
"""Prepara o servidor (use :meth:`start`)."""
|
|
174
|
+
self.root = Path(root).resolve()
|
|
175
|
+
self._md = md_renderer
|
|
176
|
+
self._live = live_reload
|
|
177
|
+
self._interval = watch_interval
|
|
178
|
+
self._overlay: dict[Path, str] = {}
|
|
179
|
+
self._lock = threading.Lock()
|
|
180
|
+
self._version = 0
|
|
181
|
+
self._changed: list[str] = []
|
|
182
|
+
self._mtimes: dict[Path, float] = {}
|
|
183
|
+
self._httpd: ThreadingHTTPServer | None = None
|
|
184
|
+
self._stop = threading.Event()
|
|
185
|
+
self.port = 0
|
|
186
|
+
|
|
187
|
+
def start(self) -> int:
|
|
188
|
+
"""Inicia o servidor em ``127.0.0.1:<porta livre>``; devolve a porta."""
|
|
189
|
+
if self._httpd is not None:
|
|
190
|
+
return self.port
|
|
191
|
+
server = self
|
|
192
|
+
|
|
193
|
+
class Handler(_Handler):
|
|
194
|
+
dev = server
|
|
195
|
+
|
|
196
|
+
self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
197
|
+
self._httpd.daemon_threads = True
|
|
198
|
+
self.port = int(self._httpd.server_address[1])
|
|
199
|
+
self._scan(initial=True)
|
|
200
|
+
threading.Thread(target=self._httpd.serve_forever, name="CodisDevHTTP", daemon=True).start()
|
|
201
|
+
threading.Thread(target=self._watch, name="CodisDevWatch", daemon=True).start()
|
|
202
|
+
return self.port
|
|
203
|
+
|
|
204
|
+
def stop(self) -> None:
|
|
205
|
+
"""Encerra o servidor e a varredura."""
|
|
206
|
+
self._stop.set()
|
|
207
|
+
httpd, self._httpd = self._httpd, None
|
|
208
|
+
if httpd is not None:
|
|
209
|
+
with contextlib.suppress(OSError):
|
|
210
|
+
httpd.shutdown()
|
|
211
|
+
httpd.server_close()
|
|
212
|
+
|
|
213
|
+
def url_for(self, path: str | os.PathLike[str]) -> str | None:
|
|
214
|
+
"""URL http do arquivo (``None`` se estiver fora de ``root``)."""
|
|
215
|
+
try:
|
|
216
|
+
rel = Path(path).resolve().relative_to(self.root)
|
|
217
|
+
except (ValueError, OSError):
|
|
218
|
+
return None
|
|
219
|
+
from urllib.parse import quote
|
|
220
|
+
|
|
221
|
+
return f"http://127.0.0.1:{self.port}/{quote(rel.as_posix())}"
|
|
222
|
+
|
|
223
|
+
def path_for_url(self, url: str) -> Path | None:
|
|
224
|
+
"""Arquivo local correspondente a uma URL deste servidor (para "ir ao erro")."""
|
|
225
|
+
parts = urlsplit(url)
|
|
226
|
+
if parts.hostname not in ("127.0.0.1", "localhost") or parts.port != self.port:
|
|
227
|
+
return None
|
|
228
|
+
return self._safe_path(parts.path)
|
|
229
|
+
|
|
230
|
+
def _safe_path(self, url_path: str) -> Path | None:
|
|
231
|
+
rel = unquote(url_path).lstrip("/")
|
|
232
|
+
try:
|
|
233
|
+
target = (self.root / rel).resolve()
|
|
234
|
+
target.relative_to(self.root)
|
|
235
|
+
except (ValueError, OSError):
|
|
236
|
+
return None
|
|
237
|
+
return target
|
|
238
|
+
|
|
239
|
+
def set_overlay(self, path: str | os.PathLike[str], text: str | None) -> None:
|
|
240
|
+
"""Serve ``text`` no lugar do arquivo em disco (``None`` remove o overlay)."""
|
|
241
|
+
p = Path(path).resolve()
|
|
242
|
+
with self._lock:
|
|
243
|
+
if text is None:
|
|
244
|
+
if self._overlay.pop(p, None) is None:
|
|
245
|
+
return
|
|
246
|
+
elif self._overlay.get(p) == text:
|
|
247
|
+
return
|
|
248
|
+
else:
|
|
249
|
+
self._overlay[p] = text
|
|
250
|
+
self._bump([self._rel(p)])
|
|
251
|
+
|
|
252
|
+
def _rel(self, p: Path) -> str:
|
|
253
|
+
try:
|
|
254
|
+
return p.relative_to(self.root).as_posix()
|
|
255
|
+
except ValueError:
|
|
256
|
+
return p.name
|
|
257
|
+
|
|
258
|
+
def overlay_for(self, p: Path) -> str | None:
|
|
259
|
+
"""Texto em memória para ``p`` (ou ``None``)."""
|
|
260
|
+
with self._lock:
|
|
261
|
+
return self._overlay.get(p)
|
|
262
|
+
|
|
263
|
+
@property
|
|
264
|
+
def version(self) -> int:
|
|
265
|
+
"""Contador incrementado a cada mudança observada."""
|
|
266
|
+
return self._version
|
|
267
|
+
|
|
268
|
+
def state(self) -> dict[str, Any]:
|
|
269
|
+
"""Estado enviado ao script de recarga."""
|
|
270
|
+
with self._lock:
|
|
271
|
+
return {"v": self._version, "changed": list(self._changed)}
|
|
272
|
+
|
|
273
|
+
def _bump(self, changed: list[str]) -> None:
|
|
274
|
+
self._version += 1
|
|
275
|
+
self._changed = changed[:50]
|
|
276
|
+
|
|
277
|
+
def _scan(self, *, initial: bool = False) -> None:
|
|
278
|
+
seen: dict[Path, float] = {}
|
|
279
|
+
count = 0
|
|
280
|
+
for dirpath, dirnames, filenames in os.walk(self.root):
|
|
281
|
+
dirnames[:] = [d for d in dirnames if d not in _SKIP_DIRS and not d.startswith(".")]
|
|
282
|
+
for name in filenames:
|
|
283
|
+
if os.path.splitext(name)[1].lower() not in _WATCH_EXTS:
|
|
284
|
+
continue
|
|
285
|
+
full = Path(dirpath, name)
|
|
286
|
+
try:
|
|
287
|
+
seen[full] = full.stat().st_mtime
|
|
288
|
+
except OSError:
|
|
289
|
+
continue
|
|
290
|
+
count += 1
|
|
291
|
+
if count >= _MAX_WATCH_FILES:
|
|
292
|
+
break
|
|
293
|
+
if count >= _MAX_WATCH_FILES:
|
|
294
|
+
break
|
|
295
|
+
if not initial:
|
|
296
|
+
changed = [self._rel(p) for p, m in seen.items() if self._mtimes.get(p) != m]
|
|
297
|
+
changed += [self._rel(p) for p in self._mtimes if p not in seen]
|
|
298
|
+
if changed:
|
|
299
|
+
with self._lock:
|
|
300
|
+
self._bump(changed)
|
|
301
|
+
self._mtimes = seen
|
|
302
|
+
|
|
303
|
+
def _watch(self) -> None:
|
|
304
|
+
while not self._stop.wait(self._interval):
|
|
305
|
+
try:
|
|
306
|
+
self._scan()
|
|
307
|
+
except Exception as exc:
|
|
308
|
+
logger.debug("varredura falhou: %s", exc)
|
|
309
|
+
|
|
310
|
+
def render(self, path: Path) -> tuple[bytes, str] | None:
|
|
311
|
+
"""Corpo e Content-Type de ``path`` (overlay > disco; Markdown -> HTML)."""
|
|
312
|
+
suffix = path.suffix.lower()
|
|
313
|
+
text = self.overlay_for(path)
|
|
314
|
+
if text is None:
|
|
315
|
+
if not path.is_file():
|
|
316
|
+
return None
|
|
317
|
+
if suffix not in (".md", ".markdown", ".html", ".htm", ".xhtml"):
|
|
318
|
+
return path.read_bytes(), _MIME.get(suffix, "application/octet-stream")
|
|
319
|
+
text = path.read_text(encoding="utf-8", errors="replace")
|
|
320
|
+
if suffix in (".md", ".markdown"):
|
|
321
|
+
html = self._md(text, path.stem) if self._md else f"<pre>{_esc(text)}</pre>"
|
|
322
|
+
return self._inject(html).encode("utf-8"), _MIME[".html"]
|
|
323
|
+
if suffix in (".html", ".htm", ".xhtml"):
|
|
324
|
+
return self._inject(text).encode("utf-8"), _MIME[suffix]
|
|
325
|
+
return text.encode("utf-8"), _MIME.get(suffix, "text/plain; charset=utf-8")
|
|
326
|
+
|
|
327
|
+
def _inject(self, html: str) -> str:
|
|
328
|
+
if not self._live:
|
|
329
|
+
return html
|
|
330
|
+
tag = '<script src="/__codis/reload.js"></script>'
|
|
331
|
+
low = html.lower()
|
|
332
|
+
i = low.rfind("</body>")
|
|
333
|
+
return html[:i] + tag + html[i:] if i != -1 else html + tag
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _esc(text: str) -> str:
|
|
337
|
+
return text.replace("&", "&").replace("<", "<").replace(">", ">")
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
class _Handler(BaseHTTPRequestHandler):
|
|
341
|
+
"""Handler GET/HEAD: somente leitura, somente loopback."""
|
|
342
|
+
|
|
343
|
+
dev: DevServer
|
|
344
|
+
server_version = "CodisDev/1.0"
|
|
345
|
+
protocol_version = "HTTP/1.1"
|
|
346
|
+
|
|
347
|
+
def log_message(self, *_: Any) -> None:
|
|
348
|
+
"""Sem logs no console."""
|
|
349
|
+
|
|
350
|
+
def _host_ok(self) -> bool:
|
|
351
|
+
host = (self.headers.get("Host") or "").split(":")[0].lower()
|
|
352
|
+
return host in ("127.0.0.1", "localhost", "[::1]")
|
|
353
|
+
|
|
354
|
+
def _send(self, code: int, body: bytes, ctype: str, head: bool = False) -> None:
|
|
355
|
+
self.send_response(code)
|
|
356
|
+
self.send_header("Content-Type", ctype)
|
|
357
|
+
self.send_header("Content-Length", str(len(body)))
|
|
358
|
+
self.send_header("Cache-Control", "no-store")
|
|
359
|
+
self.send_header("X-Content-Type-Options", "nosniff")
|
|
360
|
+
self.end_headers()
|
|
361
|
+
if not head:
|
|
362
|
+
self.wfile.write(body)
|
|
363
|
+
|
|
364
|
+
def do_HEAD(self) -> None:
|
|
365
|
+
"""HEAD = GET sem corpo."""
|
|
366
|
+
self._serve(head=True)
|
|
367
|
+
|
|
368
|
+
def do_GET(self) -> None:
|
|
369
|
+
"""Serve arquivos, o script de recarga e o estado de versão."""
|
|
370
|
+
self._serve(head=False)
|
|
371
|
+
|
|
372
|
+
def _serve(self, *, head: bool) -> None:
|
|
373
|
+
if not self._host_ok():
|
|
374
|
+
self._send(403, b"forbidden", "text/plain", head)
|
|
375
|
+
return
|
|
376
|
+
parts = urlsplit(self.path)
|
|
377
|
+
if parts.path == "/__codis/reload.js":
|
|
378
|
+
self._send(200, _RELOAD_JS.encode(), "text/javascript; charset=utf-8", head)
|
|
379
|
+
return
|
|
380
|
+
if parts.path == "/__codis/poll":
|
|
381
|
+
parse_qs(parts.query)
|
|
382
|
+
self._send(200, json.dumps(self.dev.state()).encode(), "application/json", head)
|
|
383
|
+
return
|
|
384
|
+
target = self.dev._safe_path(parts.path)
|
|
385
|
+
if target is None:
|
|
386
|
+
self._send(403, b"forbidden", "text/plain", head)
|
|
387
|
+
return
|
|
388
|
+
if target.is_dir():
|
|
389
|
+
idx = next((target / n for n in ("index.html", "index.htm") if (target / n).is_file()), None)
|
|
390
|
+
if idx is None:
|
|
391
|
+
self._send(200, _listing(self.dev, target).encode(), _MIME[".html"], head)
|
|
392
|
+
return
|
|
393
|
+
target = idx
|
|
394
|
+
try:
|
|
395
|
+
out = self.dev.render(target)
|
|
396
|
+
except OSError:
|
|
397
|
+
out = None
|
|
398
|
+
if out is None:
|
|
399
|
+
self._send(404, b"404 - nao encontrado", "text/plain; charset=utf-8", head)
|
|
400
|
+
return
|
|
401
|
+
self._send(200, out[0], out[1], head)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _listing(dev: DevServer, folder: Path) -> str:
|
|
405
|
+
from urllib.parse import quote
|
|
406
|
+
|
|
407
|
+
rel = folder.relative_to(dev.root).as_posix()
|
|
408
|
+
rows = []
|
|
409
|
+
try:
|
|
410
|
+
entries = sorted(folder.iterdir(), key=lambda p: (not p.is_dir(), p.name.lower()))
|
|
411
|
+
except OSError:
|
|
412
|
+
entries = []
|
|
413
|
+
for p in entries:
|
|
414
|
+
if p.name.startswith("."):
|
|
415
|
+
continue
|
|
416
|
+
href = quote((Path(rel) / p.name).as_posix() if rel != "." else p.name) + ("/" if p.is_dir() else "")
|
|
417
|
+
rows.append(f'<li><a href="/{href}">{_esc(p.name)}{"/" if p.is_dir() else ""}</a></li>')
|
|
418
|
+
title = _esc("/" + rel if rel != "." else "/")
|
|
419
|
+
return (
|
|
420
|
+
f"<!doctype html><meta charset=utf-8><title>{title}</title>"
|
|
421
|
+
"<style>body{font:15px system-ui;margin:2rem}li{line-height:1.8}</style>"
|
|
422
|
+
f"<h3>{title}</h3><ul>{''.join(rows)}</ul>"
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
DEVICE_PRESETS: dict[str, tuple[int, int, float, bool] | None] = {
|
|
427
|
+
"Responsivo (janela)": None,
|
|
428
|
+
"Desktop 1440": (1440, 900, 1.0, False),
|
|
429
|
+
"Laptop 1280": (1280, 720, 1.0, False),
|
|
430
|
+
"Tablet 820": (820, 1180, 2.0, True),
|
|
431
|
+
"Mobile 390": (390, 844, 3.0, True),
|
|
432
|
+
"Mobile pequeno 320": (320, 568, 2.0, True),
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
@dataclass
|
|
437
|
+
class ConsoleEntry:
|
|
438
|
+
"""Mensagem de console/erro vinda do navegador."""
|
|
439
|
+
|
|
440
|
+
level: str
|
|
441
|
+
text: str
|
|
442
|
+
url: str = ""
|
|
443
|
+
line: int = 0
|
|
444
|
+
col: int = 0
|
|
445
|
+
ts: float = field(default_factory=time.time)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
class CdpClient:
|
|
449
|
+
"""Cliente CDP mínimo sobre WebSocket (biblioteca ``websockets``, já dependência do Codis).
|
|
450
|
+
|
|
451
|
+
Todos os callbacks são chamados em **thread de fundo**: quem usa Tk deve
|
|
452
|
+
repassar à thread principal (o painel faz isso com uma fila + ``after``).
|
|
453
|
+
|
|
454
|
+
Args:
|
|
455
|
+
profile_dir: ``--user-data-dir`` usado no lançamento (contém ``DevToolsActivePort``).
|
|
456
|
+
on_console: callback de :class:`ConsoleEntry`.
|
|
457
|
+
on_navigated: callback ``(url)`` quando o frame principal navega.
|
|
458
|
+
"""
|
|
459
|
+
|
|
460
|
+
def __init__(
|
|
461
|
+
self,
|
|
462
|
+
profile_dir: Path,
|
|
463
|
+
on_console: Callable[[ConsoleEntry], None] | None = None,
|
|
464
|
+
on_navigated: Callable[[str], None] | None = None,
|
|
465
|
+
) -> None:
|
|
466
|
+
"""Cria o cliente (use :meth:`connect_async`)."""
|
|
467
|
+
self.profile_dir = Path(profile_dir)
|
|
468
|
+
self._on_console = on_console
|
|
469
|
+
self._on_navigated = on_navigated
|
|
470
|
+
self._ws: Any = None
|
|
471
|
+
self._next_id = 0
|
|
472
|
+
self._pending: dict[int, tuple[threading.Event, list[Any]]] = {}
|
|
473
|
+
self._lock = threading.Lock()
|
|
474
|
+
self._stop = threading.Event()
|
|
475
|
+
self._connected = threading.Event()
|
|
476
|
+
self.port = 0
|
|
477
|
+
|
|
478
|
+
@property
|
|
479
|
+
def connected(self) -> bool:
|
|
480
|
+
"""True com o WebSocket aberto."""
|
|
481
|
+
return self._connected.is_set()
|
|
482
|
+
|
|
483
|
+
def connect_async(self, timeout: float = 20.0) -> None:
|
|
484
|
+
"""Aguarda o navegador publicar a porta e conecta (em thread de fundo)."""
|
|
485
|
+
threading.Thread(target=self._run, args=(timeout,), name="CodisCDP", daemon=True).start()
|
|
486
|
+
|
|
487
|
+
def close(self) -> None:
|
|
488
|
+
"""Fecha a conexão."""
|
|
489
|
+
self._stop.set()
|
|
490
|
+
ws, self._ws = self._ws, None
|
|
491
|
+
if ws is not None:
|
|
492
|
+
with contextlib.suppress(Exception):
|
|
493
|
+
ws.close()
|
|
494
|
+
self._connected.clear()
|
|
495
|
+
|
|
496
|
+
def navigate(self, url: str) -> None:
|
|
497
|
+
"""Navega a aba."""
|
|
498
|
+
self.send("Page.navigate", {"url": url})
|
|
499
|
+
|
|
500
|
+
def reload(self, *, ignore_cache: bool = True) -> None:
|
|
501
|
+
"""Recarrega a página."""
|
|
502
|
+
self.send("Page.reload", {"ignoreCache": ignore_cache})
|
|
503
|
+
|
|
504
|
+
def back(self) -> None:
|
|
505
|
+
"""Voltar no histórico."""
|
|
506
|
+
self.send("Runtime.evaluate", {"expression": "history.back()"})
|
|
507
|
+
|
|
508
|
+
def forward(self) -> None:
|
|
509
|
+
"""Avançar no histórico."""
|
|
510
|
+
self.send("Runtime.evaluate", {"expression": "history.forward()"})
|
|
511
|
+
|
|
512
|
+
def evaluate(self, expression: str) -> None:
|
|
513
|
+
"""Executa JavaScript na página."""
|
|
514
|
+
self.send("Runtime.evaluate", {"expression": expression, "userGesture": True})
|
|
515
|
+
|
|
516
|
+
def emulate(self, preset: tuple[int, int, float, bool] | None) -> None:
|
|
517
|
+
"""Aplica (ou remove, com ``None``) a emulação de dispositivo."""
|
|
518
|
+
if preset is None:
|
|
519
|
+
self.send("Emulation.clearDeviceMetricsOverride", {})
|
|
520
|
+
self.send("Emulation.setTouchEmulationEnabled", {"enabled": False})
|
|
521
|
+
return
|
|
522
|
+
w, h, scale, mobile = preset
|
|
523
|
+
self.send("Emulation.setDeviceMetricsOverride",
|
|
524
|
+
{"width": w, "height": h, "deviceScaleFactor": scale, "mobile": mobile})
|
|
525
|
+
self.send("Emulation.setTouchEmulationEnabled", {"enabled": mobile})
|
|
526
|
+
|
|
527
|
+
def send(self, method: str, params: dict[str, Any] | None = None) -> None:
|
|
528
|
+
"""Envia comando sem esperar resposta (ignora se desconectado)."""
|
|
529
|
+
ws = self._ws
|
|
530
|
+
if ws is None:
|
|
531
|
+
return
|
|
532
|
+
with self._lock:
|
|
533
|
+
self._next_id += 1
|
|
534
|
+
msg = {"id": self._next_id, "method": method, "params": params or {}}
|
|
535
|
+
with contextlib.suppress(Exception):
|
|
536
|
+
ws.send(json.dumps(msg))
|
|
537
|
+
|
|
538
|
+
def call(self, method: str, params: dict[str, Any] | None = None, timeout: float = 5.0) -> Any:
|
|
539
|
+
"""Envia e espera a resposta (``None`` em erro/timeout)."""
|
|
540
|
+
ws = self._ws
|
|
541
|
+
if ws is None:
|
|
542
|
+
return None
|
|
543
|
+
ev, box = threading.Event(), []
|
|
544
|
+
with self._lock:
|
|
545
|
+
self._next_id += 1
|
|
546
|
+
mid = self._next_id
|
|
547
|
+
self._pending[mid] = (ev, box)
|
|
548
|
+
try:
|
|
549
|
+
ws.send(json.dumps({"id": mid, "method": method, "params": params or {}}))
|
|
550
|
+
except Exception:
|
|
551
|
+
self._pending.pop(mid, None)
|
|
552
|
+
return None
|
|
553
|
+
ev.wait(timeout)
|
|
554
|
+
self._pending.pop(mid, None)
|
|
555
|
+
return box[0] if box else None
|
|
556
|
+
|
|
557
|
+
def _discover_ws_url(self, deadline: float) -> str | None:
|
|
558
|
+
port_file = self.profile_dir / "DevToolsActivePort"
|
|
559
|
+
while time.monotonic() < deadline and not self._stop.is_set():
|
|
560
|
+
with contextlib.suppress(OSError, ValueError, IndexError):
|
|
561
|
+
self.port = int(port_file.read_text().splitlines()[0])
|
|
562
|
+
with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/json/list", timeout=2) as r:
|
|
563
|
+
targets = json.loads(r.read().decode("utf-8"))
|
|
564
|
+
for tgt in targets:
|
|
565
|
+
if tgt.get("type") == "page" and tgt.get("webSocketDebuggerUrl"):
|
|
566
|
+
return str(tgt["webSocketDebuggerUrl"])
|
|
567
|
+
time.sleep(0.25)
|
|
568
|
+
return None
|
|
569
|
+
|
|
570
|
+
def _run(self, timeout: float) -> None:
|
|
571
|
+
try:
|
|
572
|
+
from websockets.sync.client import connect
|
|
573
|
+
except ImportError:
|
|
574
|
+
logger.warning("websockets>=11 ausente: console/navegação do preview indisponíveis")
|
|
575
|
+
return
|
|
576
|
+
url = self._discover_ws_url(time.monotonic() + timeout)
|
|
577
|
+
if url is None:
|
|
578
|
+
logger.info("CDP: porta de depuração não apareceu")
|
|
579
|
+
return
|
|
580
|
+
try:
|
|
581
|
+
with connect(url, max_size=None, open_timeout=5, ping_interval=None) as ws:
|
|
582
|
+
self._ws = ws
|
|
583
|
+
self._connected.set()
|
|
584
|
+
for m in ("Runtime.enable", "Log.enable", "Page.enable", "Network.enable"):
|
|
585
|
+
self.send(m)
|
|
586
|
+
while not self._stop.is_set():
|
|
587
|
+
self._dispatch(json.loads(ws.recv()))
|
|
588
|
+
except Exception as exc:
|
|
589
|
+
logger.debug("CDP encerrado: %s", exc)
|
|
590
|
+
finally:
|
|
591
|
+
self._ws = None
|
|
592
|
+
self._connected.clear()
|
|
593
|
+
|
|
594
|
+
def _dispatch(self, msg: dict[str, Any]) -> None:
|
|
595
|
+
mid = msg.get("id")
|
|
596
|
+
if mid is not None:
|
|
597
|
+
pend = self._pending.get(mid)
|
|
598
|
+
if pend:
|
|
599
|
+
pend[1].append(msg.get("result"))
|
|
600
|
+
pend[0].set()
|
|
601
|
+
return
|
|
602
|
+
method, p = msg.get("method", ""), msg.get("params", {})
|
|
603
|
+
if method == "Runtime.consoleAPICalled" and self._on_console:
|
|
604
|
+
level = {"warning": "warn", "assert": "error", "trace": "debug"}.get(p.get("type", "log"), p.get("type", "log"))
|
|
605
|
+
text = " ".join(_remote_str(a) for a in p.get("args", []))
|
|
606
|
+
frame = (p.get("stackTrace", {}).get("callFrames") or [{}])[0]
|
|
607
|
+
self._on_console(ConsoleEntry(level, text, frame.get("url", ""), frame.get("lineNumber", 0) + 1,
|
|
608
|
+
frame.get("columnNumber", 0) + 1))
|
|
609
|
+
elif method == "Runtime.exceptionThrown" and self._on_console:
|
|
610
|
+
d = p.get("exceptionDetails", {})
|
|
611
|
+
text = (d.get("exception", {}) or {}).get("description") or d.get("text", "Erro")
|
|
612
|
+
self._on_console(ConsoleEntry("error", text.split("\n")[0], d.get("url", ""),
|
|
613
|
+
d.get("lineNumber", 0) + 1, d.get("columnNumber", 0) + 1))
|
|
614
|
+
elif method == "Log.entryAdded" and self._on_console:
|
|
615
|
+
e = p.get("entry", {})
|
|
616
|
+
lvl = {"warning": "warn", "verbose": "debug"}.get(e.get("level", "info"), e.get("level", "info"))
|
|
617
|
+
self._on_console(ConsoleEntry(lvl, e.get("text", ""), e.get("url", ""), e.get("lineNumber", 0)))
|
|
618
|
+
elif method == "Network.loadingFailed" and self._on_console and not p.get("canceled"):
|
|
619
|
+
self._on_console(ConsoleEntry("error", f"Falha ao carregar recurso: {p.get('errorText', '')}"))
|
|
620
|
+
elif method == "Page.frameNavigated" and self._on_navigated:
|
|
621
|
+
fr = p.get("frame", {})
|
|
622
|
+
if not fr.get("parentId"):
|
|
623
|
+
self._on_navigated(fr.get("url", ""))
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def _remote_str(arg: dict[str, Any]) -> str:
|
|
627
|
+
if "value" in arg:
|
|
628
|
+
v = arg["value"]
|
|
629
|
+
return v if isinstance(v, str) else json.dumps(v, ensure_ascii=False)
|
|
630
|
+
return str(arg.get("description") or arg.get("unserializableValue") or arg.get("type", ""))
|