pygpt-net 2.6.54__py3-none-any.whl → 2.6.56__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.
- pygpt_net/CHANGELOG.txt +11 -0
- pygpt_net/__init__.py +3 -3
- pygpt_net/app.py +26 -22
- pygpt_net/controller/audio/audio.py +0 -0
- pygpt_net/controller/calendar/calendar.py +0 -0
- pygpt_net/controller/calendar/note.py +0 -0
- pygpt_net/controller/chat/chat.py +0 -0
- pygpt_net/controller/chat/handler/openai_stream.py +2 -1
- pygpt_net/controller/chat/handler/worker.py +0 -0
- pygpt_net/controller/chat/remote_tools.py +0 -0
- pygpt_net/controller/chat/render.py +0 -0
- pygpt_net/controller/chat/text.py +0 -0
- pygpt_net/controller/ctx/common.py +0 -0
- pygpt_net/controller/debug/debug.py +26 -2
- pygpt_net/controller/debug/fixtures.py +1 -1
- pygpt_net/controller/dialogs/confirm.py +15 -1
- pygpt_net/controller/dialogs/debug.py +2 -0
- pygpt_net/controller/lang/mapping.py +0 -0
- pygpt_net/controller/launcher/launcher.py +0 -0
- pygpt_net/controller/mode/mode.py +0 -0
- pygpt_net/controller/presets/presets.py +0 -0
- pygpt_net/controller/realtime/realtime.py +0 -0
- pygpt_net/controller/theme/theme.py +0 -0
- pygpt_net/controller/ui/mode.py +0 -0
- pygpt_net/controller/ui/tabs.py +0 -0
- pygpt_net/core/agents/agents.py +3 -1
- pygpt_net/core/agents/custom.py +150 -0
- pygpt_net/core/agents/provider.py +0 -0
- pygpt_net/core/builder/__init__.py +12 -0
- pygpt_net/core/builder/graph.py +478 -0
- pygpt_net/core/calendar/calendar.py +0 -0
- pygpt_net/core/ctx/ctx.py +2 -1
- pygpt_net/core/ctx/output.py +0 -0
- pygpt_net/core/debug/agent.py +0 -0
- pygpt_net/core/debug/agent_builder.py +29 -0
- pygpt_net/core/debug/console/console.py +0 -0
- pygpt_net/core/debug/db.py +0 -0
- pygpt_net/core/debug/debug.py +0 -0
- pygpt_net/core/debug/events.py +0 -0
- pygpt_net/core/debug/indexes.py +0 -0
- pygpt_net/core/debug/kernel.py +0 -0
- pygpt_net/core/debug/tabs.py +0 -0
- pygpt_net/core/filesystem/filesystem.py +0 -0
- pygpt_net/core/fixtures/__init__ +0 -0
- pygpt_net/core/fixtures/stream/__init__.py +0 -0
- pygpt_net/core/fixtures/stream/generator.py +0 -0
- pygpt_net/core/models/models.py +0 -0
- pygpt_net/core/render/plain/pid.py +0 -0
- pygpt_net/core/render/plain/renderer.py +26 -4
- pygpt_net/core/render/web/body.py +46 -4
- pygpt_net/core/render/web/debug.py +0 -0
- pygpt_net/core/render/web/helpers.py +0 -0
- pygpt_net/core/render/web/pid.py +0 -0
- pygpt_net/core/render/web/renderer.py +15 -20
- pygpt_net/core/tabs/tab.py +0 -0
- pygpt_net/core/tabs/tabs.py +0 -0
- pygpt_net/core/text/utils.py +0 -0
- pygpt_net/css.qrc +0 -0
- pygpt_net/css_rc.py +0 -0
- pygpt_net/data/config/config.json +7 -7
- pygpt_net/data/config/models.json +3 -3
- pygpt_net/data/css/web-blocks.css +9 -0
- pygpt_net/data/css/web-blocks.dark.css +6 -0
- pygpt_net/data/css/web-blocks.darkest.css +6 -0
- pygpt_net/data/css/web-chatgpt.css +14 -6
- pygpt_net/data/css/web-chatgpt.dark.css +6 -0
- pygpt_net/data/css/web-chatgpt.darkest.css +6 -0
- pygpt_net/data/css/web-chatgpt.light.css +6 -0
- pygpt_net/data/css/web-chatgpt_wide.css +14 -6
- pygpt_net/data/css/web-chatgpt_wide.dark.css +6 -0
- pygpt_net/data/css/web-chatgpt_wide.darkest.css +6 -0
- pygpt_net/data/css/web-chatgpt_wide.light.css +6 -0
- pygpt_net/data/fixtures/fake_stream.txt +14 -1
- pygpt_net/data/icons/case.svg +0 -0
- pygpt_net/data/icons/chat1.svg +0 -0
- pygpt_net/data/icons/chat2.svg +0 -0
- pygpt_net/data/icons/chat3.svg +0 -0
- pygpt_net/data/icons/chat4.svg +0 -0
- pygpt_net/data/icons/fit.svg +0 -0
- pygpt_net/data/icons/note1.svg +0 -0
- pygpt_net/data/icons/note2.svg +0 -0
- pygpt_net/data/icons/note3.svg +0 -0
- pygpt_net/data/icons/stt.svg +0 -0
- pygpt_net/data/icons/translate.svg +0 -0
- pygpt_net/data/icons/tts.svg +0 -0
- pygpt_net/data/icons/url.svg +0 -0
- pygpt_net/data/icons/vision.svg +0 -0
- pygpt_net/data/icons/web_off.svg +0 -0
- pygpt_net/data/icons/web_on.svg +0 -0
- pygpt_net/data/js/app/async.js +166 -0
- pygpt_net/data/js/app/bridge.js +88 -0
- pygpt_net/data/js/app/common.js +212 -0
- pygpt_net/data/js/app/config.js +223 -0
- pygpt_net/data/js/app/custom.js +961 -0
- pygpt_net/data/js/app/data.js +84 -0
- pygpt_net/data/js/app/dom.js +322 -0
- pygpt_net/data/js/app/events.js +400 -0
- pygpt_net/data/js/app/highlight.js +542 -0
- pygpt_net/data/js/app/logger.js +305 -0
- pygpt_net/data/js/app/markdown.js +1137 -0
- pygpt_net/data/js/app/math.js +167 -0
- pygpt_net/data/js/app/nodes.js +395 -0
- pygpt_net/data/js/app/queue.js +260 -0
- pygpt_net/data/js/app/raf.js +250 -0
- pygpt_net/data/js/app/runtime.js +582 -0
- pygpt_net/data/js/app/scroll.js +433 -0
- pygpt_net/data/js/app/stream.js +2708 -0
- pygpt_net/data/js/app/template.js +287 -0
- pygpt_net/data/js/app/tool.js +87 -0
- pygpt_net/data/js/app/ui.js +86 -0
- pygpt_net/data/js/app/user.js +380 -0
- pygpt_net/data/js/app/utils.js +64 -0
- pygpt_net/data/js/app.min.js +880 -0
- pygpt_net/data/js/markdown-it/markdown-it-katex.min.js +1 -1
- pygpt_net/data/js/markdown-it/markdown-it.min.js +0 -0
- pygpt_net/data/locale/locale.de.ini +0 -0
- pygpt_net/data/locale/locale.en.ini +7 -0
- pygpt_net/data/locale/locale.es.ini +0 -0
- pygpt_net/data/locale/locale.fr.ini +0 -0
- pygpt_net/data/locale/locale.it.ini +0 -0
- pygpt_net/data/locale/locale.pl.ini +0 -0
- pygpt_net/data/locale/locale.uk.ini +0 -0
- pygpt_net/data/locale/locale.zh.ini +0 -0
- pygpt_net/data/locale/plugin.agent.de.ini +0 -0
- pygpt_net/data/locale/plugin.agent.en.ini +0 -0
- pygpt_net/data/locale/plugin.agent.es.ini +0 -0
- pygpt_net/data/locale/plugin.agent.fr.ini +0 -0
- pygpt_net/data/locale/plugin.agent.it.ini +0 -0
- pygpt_net/data/locale/plugin.agent.pl.ini +0 -0
- pygpt_net/data/locale/plugin.agent.uk.ini +0 -0
- pygpt_net/data/locale/plugin.agent.zh.ini +0 -0
- pygpt_net/data/locale/plugin.audio_input.de.ini +0 -0
- pygpt_net/data/locale/plugin.audio_input.en.ini +0 -0
- pygpt_net/data/locale/plugin.audio_input.es.ini +0 -0
- pygpt_net/data/locale/plugin.audio_input.fr.ini +0 -0
- pygpt_net/data/locale/plugin.audio_input.it.ini +0 -0
- pygpt_net/data/locale/plugin.audio_input.pl.ini +0 -0
- pygpt_net/data/locale/plugin.audio_input.uk.ini +0 -0
- pygpt_net/data/locale/plugin.audio_input.zh.ini +0 -0
- pygpt_net/data/locale/plugin.audio_output.de.ini +0 -0
- pygpt_net/data/locale/plugin.audio_output.en.ini +0 -0
- pygpt_net/data/locale/plugin.audio_output.es.ini +0 -0
- pygpt_net/data/locale/plugin.audio_output.fr.ini +0 -0
- pygpt_net/data/locale/plugin.audio_output.it.ini +0 -0
- pygpt_net/data/locale/plugin.audio_output.pl.ini +0 -0
- pygpt_net/data/locale/plugin.audio_output.uk.ini +0 -0
- pygpt_net/data/locale/plugin.audio_output.zh.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_api.de.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_api.en.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_api.es.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_api.fr.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_api.it.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_api.pl.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_api.uk.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_api.zh.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_code_interpreter.de.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_code_interpreter.en.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_code_interpreter.es.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_code_interpreter.fr.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_code_interpreter.it.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_code_interpreter.pl.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_code_interpreter.uk.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_code_interpreter.zh.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_custom.de.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_custom.en.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_custom.es.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_custom.fr.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_custom.it.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_custom.pl.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_custom.uk.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_custom.zh.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_files.de.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_files.en.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_files.es.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_files.fr.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_files.it.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_files.pl.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_files.uk.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_files.zh.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_history.de.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_history.en.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_history.es.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_history.fr.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_history.it.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_history.pl.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_history.uk.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_history.zh.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_mouse_control.de.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_mouse_control.en.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_mouse_control.es.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_mouse_control.fr.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_mouse_control.it.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_mouse_control.pl.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_mouse_control.uk.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_mouse_control.zh.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_serial.de.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_serial.en.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_serial.es.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_serial.fr.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_serial.it.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_serial.pl.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_serial.uk.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_serial.zh.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_system.de.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_system.en.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_system.es.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_system.fr.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_system.it.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_system.pl.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_system.uk.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_system.zh.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_web.de.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_web.en.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_web.es.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_web.fr.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_web.it.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_web.pl.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_web.uk.ini +0 -0
- pygpt_net/data/locale/plugin.cmd_web.zh.ini +0 -0
- pygpt_net/data/locale/plugin.crontab.de.ini +0 -0
- pygpt_net/data/locale/plugin.crontab.en.ini +0 -0
- pygpt_net/data/locale/plugin.crontab.es.ini +0 -0
- pygpt_net/data/locale/plugin.crontab.fr.ini +0 -0
- pygpt_net/data/locale/plugin.crontab.it.ini +0 -0
- pygpt_net/data/locale/plugin.crontab.pl.ini +0 -0
- pygpt_net/data/locale/plugin.crontab.uk.ini +0 -0
- pygpt_net/data/locale/plugin.crontab.zh.ini +0 -0
- pygpt_net/data/locale/plugin.experts.de.ini +0 -0
- pygpt_net/data/locale/plugin.experts.en.ini +0 -0
- pygpt_net/data/locale/plugin.experts.es.ini +0 -0
- pygpt_net/data/locale/plugin.experts.fr.ini +0 -0
- pygpt_net/data/locale/plugin.experts.it.ini +0 -0
- pygpt_net/data/locale/plugin.experts.pl.ini +0 -0
- pygpt_net/data/locale/plugin.experts.uk.ini +0 -0
- pygpt_net/data/locale/plugin.experts.zh.ini +0 -0
- pygpt_net/data/locale/plugin.extra_prompt.de.ini +0 -0
- pygpt_net/data/locale/plugin.extra_prompt.en.ini +0 -0
- pygpt_net/data/locale/plugin.extra_prompt.es.ini +0 -0
- pygpt_net/data/locale/plugin.extra_prompt.fr.ini +0 -0
- pygpt_net/data/locale/plugin.extra_prompt.it.ini +0 -0
- pygpt_net/data/locale/plugin.extra_prompt.pl.ini +0 -0
- pygpt_net/data/locale/plugin.extra_prompt.uk.ini +0 -0
- pygpt_net/data/locale/plugin.extra_prompt.zh.ini +0 -0
- pygpt_net/data/locale/plugin.idx_llama_index.de.ini +0 -0
- pygpt_net/data/locale/plugin.idx_llama_index.en.ini +0 -0
- pygpt_net/data/locale/plugin.idx_llama_index.es.ini +0 -0
- pygpt_net/data/locale/plugin.idx_llama_index.fr.ini +0 -0
- pygpt_net/data/locale/plugin.idx_llama_index.it.ini +0 -0
- pygpt_net/data/locale/plugin.idx_llama_index.pl.ini +0 -0
- pygpt_net/data/locale/plugin.idx_llama_index.uk.ini +0 -0
- pygpt_net/data/locale/plugin.idx_llama_index.zh.ini +0 -0
- pygpt_net/data/locale/plugin.mailer.en.ini +0 -0
- pygpt_net/data/locale/plugin.mcp.en.ini +0 -0
- pygpt_net/data/locale/plugin.openai_dalle.de.ini +0 -0
- pygpt_net/data/locale/plugin.openai_dalle.en.ini +0 -0
- pygpt_net/data/locale/plugin.openai_dalle.es.ini +0 -0
- pygpt_net/data/locale/plugin.openai_dalle.fr.ini +0 -0
- pygpt_net/data/locale/plugin.openai_dalle.it.ini +0 -0
- pygpt_net/data/locale/plugin.openai_dalle.pl.ini +0 -0
- pygpt_net/data/locale/plugin.openai_dalle.uk.ini +0 -0
- pygpt_net/data/locale/plugin.openai_dalle.zh.ini +0 -0
- pygpt_net/data/locale/plugin.openai_vision.de.ini +0 -0
- pygpt_net/data/locale/plugin.openai_vision.en.ini +0 -0
- pygpt_net/data/locale/plugin.openai_vision.es.ini +0 -0
- pygpt_net/data/locale/plugin.openai_vision.fr.ini +0 -0
- pygpt_net/data/locale/plugin.openai_vision.it.ini +0 -0
- pygpt_net/data/locale/plugin.openai_vision.pl.ini +0 -0
- pygpt_net/data/locale/plugin.openai_vision.uk.ini +0 -0
- pygpt_net/data/locale/plugin.openai_vision.zh.ini +0 -0
- pygpt_net/data/locale/plugin.osm.en.ini +0 -0
- pygpt_net/data/locale/plugin.real_time.de.ini +0 -0
- pygpt_net/data/locale/plugin.real_time.en.ini +0 -0
- pygpt_net/data/locale/plugin.real_time.es.ini +0 -0
- pygpt_net/data/locale/plugin.real_time.fr.ini +0 -0
- pygpt_net/data/locale/plugin.real_time.it.ini +0 -0
- pygpt_net/data/locale/plugin.real_time.pl.ini +0 -0
- pygpt_net/data/locale/plugin.real_time.uk.ini +0 -0
- pygpt_net/data/locale/plugin.real_time.zh.ini +0 -0
- pygpt_net/data/locale/plugin.voice_control.de.ini +0 -0
- pygpt_net/data/locale/plugin.voice_control.en.ini +0 -0
- pygpt_net/data/locale/plugin.voice_control.es.ini +0 -0
- pygpt_net/data/locale/plugin.voice_control.fr.ini +0 -0
- pygpt_net/data/locale/plugin.voice_control.it.ini +0 -0
- pygpt_net/data/locale/plugin.voice_control.pl.ini +0 -0
- pygpt_net/data/locale/plugin.voice_control.uk.ini +0 -0
- pygpt_net/data/locale/plugin.voice_control.zh.ini +0 -0
- pygpt_net/data/locale/plugin.wolfram.en.ini +0 -0
- pygpt_net/fonts.qrc +0 -0
- pygpt_net/fonts_rc.py +0 -0
- pygpt_net/icons.qrc +0 -0
- pygpt_net/icons_rc.py +0 -0
- pygpt_net/item/agent.py +62 -0
- pygpt_net/item/builder_layout.py +62 -0
- pygpt_net/js.qrc +24 -1
- pygpt_net/js_rc.py +51394 -33687
- pygpt_net/plugin/base/worker.py +0 -0
- pygpt_net/plugin/mcp/__init__.py +0 -0
- pygpt_net/plugin/mcp/config.py +0 -0
- pygpt_net/plugin/mcp/plugin.py +0 -0
- pygpt_net/plugin/mcp/worker.py +0 -0
- pygpt_net/plugin/osm/__init__.py +0 -0
- pygpt_net/plugin/osm/config.py +0 -0
- pygpt_net/plugin/osm/plugin.py +0 -0
- pygpt_net/plugin/osm/worker.py +0 -0
- pygpt_net/plugin/wolfram/__init__.py +0 -0
- pygpt_net/plugin/wolfram/config.py +0 -0
- pygpt_net/plugin/wolfram/plugin.py +0 -0
- pygpt_net/plugin/wolfram/worker.py +0 -0
- pygpt_net/provider/api/anthropic/tools.py +0 -0
- pygpt_net/provider/api/google/__init__.py +0 -0
- pygpt_net/provider/api/google/video.py +0 -0
- pygpt_net/provider/api/openai/agents/experts.py +0 -0
- pygpt_net/provider/api/openai/agents/remote_tools.py +0 -0
- pygpt_net/provider/api/openai/remote_tools.py +0 -0
- pygpt_net/provider/api/openai/responses.py +0 -0
- pygpt_net/provider/api/x_ai/__init__.py +0 -0
- pygpt_net/provider/api/x_ai/remote.py +0 -0
- pygpt_net/provider/core/agent/__init__.py +10 -0
- pygpt_net/provider/core/agent/base.py +51 -0
- pygpt_net/provider/core/agent/json_file.py +200 -0
- pygpt_net/provider/core/config/patch.py +18 -0
- pygpt_net/provider/core/config/patches/__init__.py +0 -0
- pygpt_net/provider/core/config/patches/patch_before_2_6_42.py +0 -0
- pygpt_net/provider/core/ctx/db_sqlite/storage.py +0 -0
- pygpt_net/provider/core/model/patches/__init__.py +0 -0
- pygpt_net/provider/core/model/patches/patch_before_2_6_42.py +0 -0
- pygpt_net/provider/core/preset/patch.py +0 -0
- pygpt_net/provider/core/preset/patches/__init__.py +0 -0
- pygpt_net/provider/core/preset/patches/patch_before_2_6_42.py +0 -0
- pygpt_net/provider/llms/base.py +0 -0
- pygpt_net/provider/llms/deepseek_api.py +0 -0
- pygpt_net/provider/llms/google.py +0 -0
- pygpt_net/provider/llms/hugging_face_api.py +0 -0
- pygpt_net/provider/llms/hugging_face_embedding.py +0 -0
- pygpt_net/provider/llms/hugging_face_router.py +0 -0
- pygpt_net/provider/llms/local.py +0 -0
- pygpt_net/provider/llms/mistral.py +0 -0
- pygpt_net/provider/llms/open_router.py +0 -0
- pygpt_net/provider/llms/perplexity.py +0 -0
- pygpt_net/provider/llms/utils.py +0 -0
- pygpt_net/provider/llms/voyage.py +0 -0
- pygpt_net/provider/llms/x_ai.py +0 -0
- pygpt_net/tools/agent_builder/__init__.py +12 -0
- pygpt_net/tools/agent_builder/tool.py +292 -0
- pygpt_net/tools/agent_builder/ui/__init__.py +0 -0
- pygpt_net/tools/agent_builder/ui/dialogs.py +152 -0
- pygpt_net/tools/agent_builder/ui/list.py +228 -0
- pygpt_net/tools/code_interpreter/ui/html.py +0 -0
- pygpt_net/tools/code_interpreter/ui/widgets.py +0 -0
- pygpt_net/tools/html_canvas/tool.py +23 -6
- pygpt_net/tools/html_canvas/ui/widgets.py +224 -2
- pygpt_net/ui/layout/chat/chat.py +0 -0
- pygpt_net/ui/main.py +10 -9
- pygpt_net/ui/menu/debug.py +39 -1
- pygpt_net/ui/widget/builder/__init__.py +12 -0
- pygpt_net/ui/widget/builder/editor.py +2001 -0
- pygpt_net/ui/widget/draw/painter.py +0 -0
- pygpt_net/ui/widget/element/labels.py +9 -4
- pygpt_net/ui/widget/lists/db.py +0 -0
- pygpt_net/ui/widget/lists/debug.py +0 -0
- pygpt_net/ui/widget/tabs/body.py +0 -0
- pygpt_net/ui/widget/textarea/input.py +17 -8
- pygpt_net/ui/widget/textarea/output.py +21 -1
- pygpt_net/ui/widget/textarea/web.py +29 -2
- pygpt_net/utils.py +40 -0
- {pygpt_net-2.6.54.dist-info → pygpt_net-2.6.56.dist-info}/METADATA +13 -2
- {pygpt_net-2.6.54.dist-info → pygpt_net-2.6.56.dist-info}/RECORD +86 -47
- pygpt_net/data/js/app.js +0 -5869
- {pygpt_net-2.6.54.dist-info → pygpt_net-2.6.56.dist-info}/LICENSE +0 -0
- {pygpt_net-2.6.54.dist-info → pygpt_net-2.6.56.dist-info}/WHEEL +0 -0
- {pygpt_net-2.6.54.dist-info → pygpt_net-2.6.56.dist-info}/entry_points.txt +0 -0
|
@@ -0,0 +1,880 @@
|
|
|
1
|
+
/* app.min.js — generated on 2025-09-22 09:05:08 by bin/minify_js.py using rjsmin */
|
|
2
|
+
|
|
3
|
+
/* data/js/app/async.js */
|
|
4
|
+
class AsyncRunner{constructor(cfg,raf){this.cfg=cfg||{};this.raf=raf||null;const A=this.cfg.ASYNC||{};this.SLICE_MS=Utils.g('ASYNC_SLICE_MS',A.SLICE_MS??12);this.SLICE_HIDDEN_MS=Utils.g('ASYNC_SLICE_HIDDEN_MS',A.SLICE_HIDDEN_MS??Math.min(this.SLICE_MS,6));this.MIN_YIELD_MS=Utils.g('ASYNC_MIN_YIELD_MS',A.MIN_YIELD_MS??0);this._opGen=new Map();}
|
|
5
|
+
shouldYield(startTs){try{const s=navigator&&navigator.scheduling;if(s&&s.isInputPending&&s.isInputPending({includeContinuous:true}))return true;}catch(_){}
|
|
6
|
+
const now=Utils.now();const hidden=(typeof document!=='undefined'&&document.visibilityState==='hidden');const budget=hidden?this.SLICE_HIDDEN_MS:this.SLICE_MS;return(now-startTs)>=budget;}
|
|
7
|
+
async yield(){if(this.raf&&typeof this.raf.nextFrame==='function'){await this.raf.nextFrame();return;}
|
|
8
|
+
if(typeof requestAnimationFrame==='function'){await new Promise(res=>{try{requestAnimationFrame(()=>res());}
|
|
9
|
+
catch(_){setTimeout(res,16);}});return;}
|
|
10
|
+
await new Promise(res=>setTimeout(res,16));}
|
|
11
|
+
async yieldIdle(timeoutMs=100){if(typeof requestIdleCallback==='function'){await new Promise(res=>{try{requestIdleCallback(()=>res(),{timeout:timeoutMs});}
|
|
12
|
+
catch(_){res();}});return;}
|
|
13
|
+
await this.yield();}
|
|
14
|
+
_beginOp(label){if(!label)return 0;const g=(this._opGen.get(label)||0)+1;this._opGen.set(label,g);return g;}
|
|
15
|
+
_isLatest(label,gen){if(!label)return true;return(this._opGen.get(label)===gen);}
|
|
16
|
+
cancel(label){if(!label)return;const g=(this._opGen.get(label)||0)+1;this._opGen.set(label,g);}
|
|
17
|
+
async forEachChunk(arr,fn,labelOrOpts){if(!arr||!arr.length)return;let label=(typeof labelOrOpts==='string')?labelOrOpts:(labelOrOpts&&labelOrOpts.label)||undefined;const opts=(label&&typeof labelOrOpts==='object')?{...labelOrOpts,label}:(typeof labelOrOpts==='object'?labelOrOpts:{});const batch=Math.max(1,opts.batch|0||1);const release=!!opts.release;const signal=opts.signal;const onProgress=(typeof opts.onProgress==='function')?opts.onProgress:null;const gen=this._beginOp(label);const total=arr.length;let start=Utils.now();let processedInBatch=0;for(let i=0;i<total;i++){if((signal&&signal.aborted)||!this._isLatest(label,gen))break;await fn(arr[i],i);if(release){try{arr[i]=undefined;}catch(_){}}
|
|
18
|
+
processedInBatch++;if(onProgress){try{onProgress({index:i+1,total});}catch(_){}}
|
|
19
|
+
if(processedInBatch>=batch||this.shouldYield(start)){processedInBatch=0;await this.yield();start=Utils.now();}}}
|
|
20
|
+
async mapChunked(arr,mapper,labelOrOpts){if(!arr||!arr.length)return[];const out=new Array(arr.length);let idx=0;await this.forEachChunk(arr,async(v,i)=>{out[i]=await mapper(v,i);idx=i;},labelOrOpts);return out;}
|
|
21
|
+
async reduceChunked(arr,reducer,initial,labelOrOpts){let acc=initial;await this.forEachChunk(arr,async(v,i)=>{acc=await reducer(acc,v,i);},labelOrOpts);return acc;}};
|
|
22
|
+
|
|
23
|
+
/* data/js/app/bridge.js */
|
|
24
|
+
class BridgeManager{constructor(cfg,logger){this.cfg=cfg;this.logger=logger||new Logger(cfg);this.bridge=null;this.connected=false;}
|
|
25
|
+
log(text){try{if(this.bridge&&this.bridge.log)this.bridge.log(text);}catch(_){}}
|
|
26
|
+
connect(onChunk,onNode,onNodeReplace,onNodeInput){if(!this.bridge)return false;if(this.connected)return true;try{if(this.bridge.chunk)this.bridge.chunk.connect((name,chunk,type)=>onChunk(name,chunk,type));if(this.bridge.node)this.bridge.node.connect(onNode);if(this.bridge.nodeReplace)this.bridge.nodeReplace.connect(onNodeReplace);if(this.bridge.nodeInput)this.bridge.nodeInput.connect(onNodeInput);this.connected=true;return true;}catch(e){this.log(e);return false;}}
|
|
27
|
+
disconnect(){if(!this.bridge)return false;if(!this.connected)return true;try{if(this.bridge.chunk)this.bridge.chunk.disconnect();if(this.bridge.node)this.bridge.node.disconnect();if(this.bridge.nodeReplace)this.bridge.nodeReplace.disconnect();if(this.bridge.nodeInput)this.bridge.nodeInput.disconnect();}catch(_){}
|
|
28
|
+
this.connected=false;return true;}
|
|
29
|
+
initQWebChannel(pid,onReady){try{new QWebChannel(qt.webChannelTransport,(channel)=>{this.bridge=channel.objects.bridge;try{this.logger.bindBridge(this.bridge);}catch(_){}
|
|
30
|
+
onReady&&onReady(this.bridge);if(this.bridge&&this.bridge.js_ready)this.bridge.js_ready(pid);});}catch(e){}}
|
|
31
|
+
copyCode(text){if(this.bridge&&this.bridge.copy_text)this.bridge.copy_text(text);}
|
|
32
|
+
previewCode(text){if(this.bridge&&this.bridge.preview_text)this.bridge.preview_text(text);}
|
|
33
|
+
runCode(text){if(this.bridge&&this.bridge.run_text)this.bridge.run_text(text);}
|
|
34
|
+
updateScrollPosition(pos){if(this.bridge&&this.bridge.update_scroll_position)this.bridge.update_scroll_position(pos);}};
|
|
35
|
+
|
|
36
|
+
/* data/js/app/common.js */
|
|
37
|
+
class Loading{constructor(dom){this.dom=dom;}
|
|
38
|
+
show(){if(typeof window.hideTips==='function'){window.hideTips();}
|
|
39
|
+
const el=this.dom.get('_loader_');if(!el)return;if(el.classList.contains('hidden'))el.classList.remove('hidden');el.classList.add('visible');}
|
|
40
|
+
hide(){const el=this.dom.get('_loader_');if(!el)return;if(el.classList.contains('visible'))el.classList.remove('visible');el.classList.add('hidden');}}
|
|
41
|
+
class TipsManager{constructor(dom){this.dom=dom;this.hidden=false;this._timers=[];this._running=false;this._idx=0;}
|
|
42
|
+
_getList(){const upper=(typeof window!=='undefined')?window.TIPS:undefined;if(Array.isArray(upper)&&upper.length)return upper;const lower=(typeof window!=='undefined')?window.tips:undefined;if(Array.isArray(lower)&&lower.length)return lower;if(typeof lower==='string'&&lower.trim().length){try{const arr=JSON.parse(lower);if(Array.isArray(arr))return arr;}catch(_){}}
|
|
43
|
+
const host=this._host();if(host&&host.dataset&&typeof host.dataset.tips==='string'){try{const arr=JSON.parse(host.dataset.tips);if(Array.isArray(arr))return arr;}catch(_){}}
|
|
44
|
+
return[];}
|
|
45
|
+
_host(){return this.dom.get('tips')||document.getElementById('tips');}
|
|
46
|
+
_clearTimers(){for(const t of this._timers){try{clearTimeout(t);}catch(_){}}
|
|
47
|
+
this._timers.length=0;}
|
|
48
|
+
stopTimers(){this._clearTimers();this._running=false;}
|
|
49
|
+
_applyBaseStyle(el){if(!el)return;const z=(typeof window!=='undefined'&&typeof window.TIPS_ZINDEX!=='undefined')?String(window.TIPS_ZINDEX):'2147483000';el.style.zIndex=z;}
|
|
50
|
+
hide(){if(this.hidden)return;this.stopTimers();const el=this._host();if(el){el.classList.remove('visible');el.classList.remove('hidden');el.style.display='none';}
|
|
51
|
+
this.hidden=true;}
|
|
52
|
+
show(){const list=this._getList();if(!list.length)return;const el=this._host();if(!el)return;this.hidden=false;this._applyBaseStyle(el);el.classList.remove('hidden');el.style.display='block';}
|
|
53
|
+
_showOne(idx){const list=this._getList();if(!list.length)return;const el=this._host();if(!el||this.hidden)return;this._applyBaseStyle(el);el.innerHTML=list[idx%list.length];try{if(typeof runtime!=='undefined'&&runtime.raf&&typeof runtime.raf.schedule==='function'){const key={t:'Tips:show',el,i:Math.random()};runtime.raf.schedule(key,()=>{if(this.hidden||!el.isConnected)return;el.classList.add('visible');},'Tips',2);}else{el.classList.add('visible');}}catch(_){el.classList.add('visible');}}
|
|
54
|
+
_cycleLoop(){if(this.hidden)return;const el=this._host();if(!el)return;const VISIBLE_MS=(typeof window!=='undefined'&&window.TIPS_VISIBLE_MS)?window.TIPS_VISIBLE_MS:15000;const FADE_MS=(typeof window!=='undefined'&&window.TIPS_FADE_MS)?window.TIPS_FADE_MS:1000;this._showOne(this._idx);this._timers.push(setTimeout(()=>{if(this.hidden)return;el.classList.remove('visible');this._timers.push(setTimeout(()=>{if(this.hidden)return;const list=this._getList();if(!list.length)return;this._idx=(this._idx+1)%list.length;this._cycleLoop();},FADE_MS));},VISIBLE_MS));}
|
|
55
|
+
cycle(){const list=this._getList();if(!list.length||this._running)return;this._running=true;this._idx=0;this.show();const INIT_DELAY=(typeof window!=='undefined'&&window.TIPS_INIT_DELAY_MS)?window.TIPS_INIT_DELAY_MS:10000;this._timers.push(setTimeout(()=>{if(this.hidden)return;this._cycleLoop();},Math.max(0,INIT_DELAY)));}
|
|
56
|
+
cleanup(){this.stopTimers();const el=this._host();if(el)el.classList.remove('visible');}};
|
|
57
|
+
|
|
58
|
+
/* data/js/app/config.js */
|
|
59
|
+
class Config{constructor(){this.PID=Utils.g('PID',0);this.UI={AUTO_FOLLOW_REENABLE_PX:Utils.g('AUTO_FOLLOW_REENABLE_PX',8),SCROLL_NEAR_MARGIN_PX:Utils.g('SCROLL_NEAR_MARGIN_PX',450),INTERACTION_BUSY_MS:Utils.g('UI_INTERACTION_BUSY_MS',140),ZOOM_BUSY_MS:Utils.g('UI_ZOOM_BUSY_MS',300)};this.FAB={SHOW_DOWN_THRESHOLD_PX:Utils.g('SHOW_DOWN_THRESHOLD_PX',0),TOGGLE_DEBOUNCE_MS:Utils.g('FAB_TOGGLE_DEBOUNCE_MS',100)};this.HL={PER_FRAME:Utils.g('HL_PER_FRAME',2),DISABLE_ALL:Utils.g('DISABLE_SYNTAX_HIGHLIGHT',false)};this.OBSERVER={CODE_ROOT_MARGIN:Utils.g('CODE_ROOT_MARGIN','1000px 0px 1000px 0px'),BOX_ROOT_MARGIN:Utils.g('BOX_ROOT_MARGIN','1500px 0px 1500px 0px'),CODE_THRESHOLD:[0,0.001],BOX_THRESHOLD:0};this.SCAN={PRELOAD_PX:Utils.g('SCAN_PRELOAD_PX',1000)};this.CODE_SCROLL={AUTO_FOLLOW_REENABLE_PX:Utils.g('CODE_AUTO_FOLLOW_REENABLE_PX',8),NEAR_MARGIN_PX:Utils.g('CODE_SCROLL_NEAR_MARGIN_PX',48)};this.STREAM={MAX_PER_FRAME:Utils.g('STREAM_MAX_PER_FRAME',8),EMERGENCY_COALESCE_LEN:Utils.g('STREAM_EMERGENCY_COALESCE_LEN',300),COALESCE_MODE:Utils.g('STREAM_COALESCE_MODE','fixed'),SNAPSHOT_MAX_STEP:Utils.g('STREAM_SNAPSHOT_MAX_STEP',8000),QUEUE_MAX_ITEMS:Utils.g('STREAM_QUEUE_MAX_ITEMS',1200),PRESERVE_CODES_MAX:Utils.g('STREAM_PRESERVE_CODES_MAX',120),PLAIN_ACTIVATE_AFTER_LINES:Utils.g('STREAM_PLAIN_ACTIVATE_AFTER_LINES',80),};this.MATH={IDLE_TIMEOUT_MS:Utils.g('MATH_IDLE_TIMEOUT_MS',800),BATCH_HINT:Utils.g('MATH_BATCH_HINT',24)};this.ICONS={EXPAND:Utils.g('ICON_EXPAND',''),COLLAPSE:Utils.g('ICON_COLLAPSE',''),CODE_MENU:Utils.g('ICON_CODE_MENU',''),CODE_COPY:Utils.g('ICON_CODE_COPY',''),CODE_RUN:Utils.g('ICON_CODE_RUN',''),CODE_PREVIEW:Utils.g('ICON_CODE_PREVIEW','')};this.LOCALE={PREVIEW:Utils.g('LOCALE_PREVIEW','Preview'),RUN:Utils.g('LOCALE_RUN','Run'),COLLAPSE:Utils.g('LOCALE_COLLAPSE','Collapse'),EXPAND:Utils.g('LOCALE_EXPAND','Expand'),COPY:Utils.g('LOCALE_COPY','Copy'),COPIED:Utils.g('LOCALE_COPIED','Copied')};this.CODE_STYLE=Utils.g('CODE_SYNTAX_STYLE','default');this.PROFILE_TEXT={base:Utils.g('PROFILE_TEXT_BASE',4),growth:Utils.g('PROFILE_TEXT_GROWTH',1.28),minInterval:Utils.g('PROFILE_TEXT_MIN_INTERVAL',4),softLatency:Utils.g('PROFILE_TEXT_SOFT_LATENCY',60),adaptiveStep:Utils.g('PROFILE_TEXT_ADAPTIVE_STEP',false)};this.PROFILE_CODE={base:2048,growth:2.6,minInterval:500,softLatency:1200,minLinesForHL:Utils.g('PROFILE_CODE_HL_N_LINE',25),minCharsForHL:Utils.g('PROFILE_CODE_HL_N_CHARS',5000),promoteMinInterval:300,promoteMaxLatency:800,promoteMinLines:Utils.g('PROFILE_CODE_HL_N_LINE',25),adaptiveStep:Utils.g('PROFILE_CODE_ADAPTIVE_STEP',false),stopAfterLines:Utils.g('PROFILE_CODE_STOP_HL_AFTER_LINES',300),streamPlainAfterLines:0,streamPlainAfterChars:0,maxFrozenChars:32000,finalHighlightMaxLines:Utils.g('PROFILE_CODE_FINAL_HL_MAX_LINES',1500),finalHighlightMaxChars:Utils.g('PROFILE_CODE_FINAL_HL_MAX_CHARS',350000)};this.RESET={HEAVY_DEBOUNCE_MS:Utils.g('RESET_HEAVY_DEBOUNCE_MS',24)};this.LOG={MAX_QUEUE:Utils.g('LOG_MAX_QUEUE',400),MAX_BYTES:Utils.g('LOG_MAX_BYTES',256*1024),BATCH_MAX:Utils.g('LOG_BATCH_MAX',64),RATE_LIMIT_PER_SEC:Utils.g('LOG_RATE_LIMIT_PER_SEC',0)};this.ASYNC={SLICE_MS:Utils.g('ASYNC_SLICE_MS',12),MIN_YIELD_MS:Utils.g('ASYNC_MIN_YIELD_MS',0),MD_NODES_PER_SLICE:Utils.g('ASYNC_MD_NODES_PER_SLICE',12)};this.RAF={FLUSH_BUDGET_MS:Utils.g('RAF_FLUSH_BUDGET_MS',7),MAX_TASKS_PER_FLUSH:Utils.g('RAF_MAX_TASKS_PER_FLUSH',120)};this.MD={ALLOW_INDENTED_CODE:Utils.g('MD_ALLOW_INDENTED_CODE',false)};this.CUSTOM_MARKUP_RULES=Utils.g('CUSTOM_MARKUP_RULES',[{name:'cmd',open:'[!cmd]',close:'[/!cmd]',tag:'div',className:'cmd',innerMode:'text'},{name:'think_md',open:'[!think]',close:'[/!think]',tag:'think',className:'',innerMode:'text',nl2br:true,allowBr:true},{name:'think_html',open:'<think>',close:'</think>',tag:'think',className:'',innerMode:'text',stream:true,nl2br:true,allowBr:true},{name:'tool',open:'<tool>',close:'</tool>',tag:'div',className:'cmd',innerMode:'text',stream:true},{name:'exec_md',open:'[!exec]',close:'[/!exec]',innerMode:'text',stream:true,openReplace:'```python\n',closeReplace:'\n```',phase:'source'},{name:'exec_html',open:'<execute>',close:'</execute>',innerMode:'text',stream:true,openReplace:'```python\n',closeReplace:'\n```',phase:'source'}]);}};
|
|
60
|
+
|
|
61
|
+
/* data/js/app/custom.js */
|
|
62
|
+
class CustomMarkup{constructor(cfg,logger){this.cfg=cfg||{CUSTOM_MARKUP_RULES:[]};this.logger=logger||new Logger(cfg);this.__compiled=null;this.__streamRules=null;this.__streamWrapRules=null;this.__hasStreamRules=false;this.__openReAll=null;this.__openReStream=null;}
|
|
63
|
+
_d(tag,data){try{const lg=this.logger||(this.cfg&&this.cfg.logger)||(window.runtime&&runtime.logger)||null;if(!lg||typeof lg.debug!=='function')return;lg.debug_obj("CM",tag,data);}catch(_){}}
|
|
64
|
+
decodeEntitiesOnce(s){if(!s||!s.indexOf||s.indexOf('&')===-1)return String(s||'');const ta=CustomMarkup._decTA||(CustomMarkup._decTA=document.createElement('textarea'));ta.innerHTML=s;return ta.value;}
|
|
65
|
+
_escHtml(s){try{return Utils.escapeHtml(s);}catch(_){return String(s||'').replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));}}
|
|
66
|
+
_escapeHtmlAllowBr(text,{convertNewlines=true}={}){const PLACEHOLDER='\u0001__BR__\u0001';let s=String(text||'');s=s.replace(/<br\s*\/?>/gi,PLACEHOLDER);s=this._escHtml(s);if(convertNewlines)s=s.replace(/\r\n|\r|\n/g,'<br>');s=s.replaceAll(PLACEHOLDER,'<br>');return s;}
|
|
67
|
+
hasAnyOpenToken(text,rules){if(!text||!rules||!rules.length)return false;if(rules===this.__compiled&&this.__openReAll){return this.__openReAll.test(text);}
|
|
68
|
+
if(rules===this.__streamRules&&this.__openReStream){return this.__openReStream.test(text);}
|
|
69
|
+
for(let i=0;i<rules.length;i++){const r=rules[i];if(!r||!r.open)continue;if(text.indexOf(r.open)!==-1)return true;}
|
|
70
|
+
return false;}
|
|
71
|
+
hasAnyStreamOpenToken(text){this.ensureCompiled();if(!this.__hasStreamRules)return false;const t=String(text||'');if(this.__openReStream)return this.__openReStream.test(t);const rules=this.__streamRules||[];return this.hasAnyOpenToken(t,rules);}
|
|
72
|
+
_materializeInnerHTML(rule,text,MD){let payload=String(text||'');const wantsBr=!!(rule&&(rule.nl2br||rule.allowBr));if(rule&&rule.decodeEntities&&payload&&payload.indexOf('&')!==-1){try{payload=this.decodeEntitiesOnce(payload);}catch(_){}}
|
|
73
|
+
if(wantsBr){try{return this._escapeHtmlAllowBr(payload,{convertNewlines:!!rule.nl2br});}catch(_){return this._escHtml(payload);}}
|
|
74
|
+
if(rule&&rule.innerMode==='markdown-inline'&&MD&&typeof MD.renderInline==='function'){try{return MD.renderInline(payload);}catch(_){return this._escHtml(payload);}}
|
|
75
|
+
return this._escHtml(payload);}
|
|
76
|
+
_fragmentFromHTML(html){const tpl=document.createElement('template');tpl.innerHTML=String(html||'');return tpl.content;}
|
|
77
|
+
_replaceElementWithHTML(el,html){if(!el||!el.parentNode)return;const parent=el.parentNode;const frag=this._fragmentFromHTML(html);parent.insertBefore(frag,el);parent.removeChild(el);}
|
|
78
|
+
_buildOpenRegex(rules){if(!rules||!rules.length)return null;const tokens=[];let patternLen=0;const LIMIT_TOKENS=200;const LIMIT_PATTERN_LEN=4000;for(const r of rules){if(!r||!r.open)continue;const esc=Utils.reEscape(r.open);tokens.push(esc);patternLen+=esc.length+1;if(tokens.length>LIMIT_TOKENS||patternLen>LIMIT_PATTERN_LEN)return null;}
|
|
79
|
+
if(!tokens.length)return null;tokens.sort((a,b)=>b.length-a.length);try{return new RegExp('(?:'+tokens.join('|')+')');}catch(_){return null;}}
|
|
80
|
+
compile(rules){const src=Array.isArray(rules)?rules:(window.CUSTOM_MARKUP_RULES||this.cfg.CUSTOM_MARKUP_RULES||[]);const compiled=[];let hasStream=false;for(const r of src){if(!r||typeof r.open!=='string'||typeof r.close!=='string')continue;const tag=(r.tag||'span').toLowerCase();const className=(r.className||r.class||'').trim();const innerMode=(r.innerMode==='markdown-inline'||r.innerMode==='text')?r.innerMode:'text';const stream=!!(r.stream===true);const openReplace=String((r.openReplace!=null?r.openReplace:(r.openReplace||''))||'');const closeReplace=String((r.closeReplace!=null?r.closeReplace:(r.closeReplace||''))||'');const decodeEntities=(typeof r.decodeEntities==='boolean')?r.decodeEntities:((r.name||'').toLowerCase()==='cmd'||className==='cmd');let phaseRaw=(typeof r.phase==='string')?r.phase.toLowerCase():'';if(phaseRaw!=='source'&&phaseRaw!=='html'&&phaseRaw!=='both')phaseRaw='';const looksLikeFence=(openReplace.indexOf('```')!==-1)||(closeReplace.indexOf('```')!==-1);const phase=phaseRaw||(looksLikeFence?'source':'html');const re=new RegExp(Utils.reEscape(r.open)+'([\\s\\S]*?)'+Utils.reEscape(r.close),'g');const reFull=new RegExp('^'+Utils.reEscape(r.open)+'([\\s\\S]*?)'+Utils.reEscape(r.close)+'$');const reFullTrim=new RegExp('^\\s*'+Utils.reEscape(r.open)+'([\\s\\S]*?)'+Utils.reEscape(r.close)+'\\s*$');const nl2br=!!r.nl2br;const allowBr=!!r.allowBr;const item={name:r.name||tag,tag,className,innerMode,open:r.open,close:r.close,decodeEntities,re,reFull,reFullTrim,stream,openReplace,closeReplace,phase,isSourceFence:looksLikeFence,nl2br,allowBr};compiled.push(item);if(stream)hasStream=true;}
|
|
81
|
+
if(compiled.length===0){const open='[!cmd]',close='[/!cmd]';const item={name:'cmd',tag:'p',className:'cmd',innerMode:'text',open,close,decodeEntities:true,re:new RegExp(Utils.reEscape(open)+'([\\s\\S]*?)'+Utils.reEscape(close),'g'),reFull:new RegExp('^'+Utils.reEscape(open)+'([\\s\\S]*?)'+Utils.reEscape(close)+'$'),reFullTrim:new RegExp('^\\s*'+Utils.reEscape(open)+'([\\s\\S]*?)'+Utils.reEscape(close)+'\\s*$'),stream:false,openReplace:'',closeReplace:'',phase:'html',isSourceFence:false,nl2br:false,allowBr:false};compiled.push(item);}
|
|
82
|
+
this.__compiled=compiled;this.__hasStreamRules=hasStream;this.__streamRules=compiled.filter(r=>!!r.stream);this.__streamWrapRules=this.__streamRules.filter(r=>(r.phase==='html'||r.phase==='both')&&!(r.openReplace||r.closeReplace)&&r.open&&r.close);const htmlPhaseAll=compiled.filter(r=>(r.phase==='html'||r.phase==='both'));const htmlPhaseStream=this.__streamRules.filter(r=>(r.phase==='html'||r.phase==='both'));this.__openReAll=this._buildOpenRegex(htmlPhaseAll);this.__openReStream=this._buildOpenRegex(htmlPhaseStream);this._d('cm.compile',{rules:compiled.length,streamRules:this.__streamRules.length});return compiled;}
|
|
83
|
+
transformSource(src,opts){let s=String(src||'');this.ensureCompiled();const rules=this.__compiled;if(!rules||!rules.length)return s;const candidates=[];for(let i=0;i<rules.length;i++){const r=rules[i];if(!r)continue;if((r.phase==='source'||r.phase==='both')&&(r.openReplace||r.closeReplace))candidates.push(r);}
|
|
84
|
+
if(!candidates.length)return s;const fences=this._findFenceRanges(s);let result='';if(!fences.length){result=this._applySourceReplacementsInChunk(s,s,0,candidates);}else{let out='',last=0;for(let k=0;k<fences.length;k++){const[a,b]=fences[k];if(a>last){const chunk=s.slice(last,a);out+=this._applySourceReplacementsInChunk(s,chunk,last,candidates);}
|
|
85
|
+
out+=s.slice(a,b);last=b;}
|
|
86
|
+
if(last<s.length){const tail=s.slice(last);out+=this._applySourceReplacementsInChunk(s,tail,last,candidates);}
|
|
87
|
+
result=out;}
|
|
88
|
+
if(opts&&opts.streaming===true){const fenceRules=candidates.filter(r=>!!r.isSourceFence);if(fenceRules.length)result=this._injectUnmatchedSourceOpeners(result,fenceRules);}
|
|
89
|
+
if(result!==src)this._d('cm.transformSource',{streaming:!!(opts&&opts.streaming),delta:result.length-String(src||'').length});return result;}
|
|
90
|
+
getSourceFenceSpecs(){this.ensureCompiled();const rules=this.__compiled||[];const out=[];for(let i=0;i<rules.length;i++){const r=rules[i];if(!r||!r.isSourceFence)continue;if(r.phase!=='source'&&r.phase!=='both')continue;out.push({open:r.open,close:r.close});}
|
|
91
|
+
return out;}
|
|
92
|
+
ensureCompiled(){if(!this.__compiled){this.compile(window.CUSTOM_MARKUP_RULES||this.cfg.CUSTOM_MARKUP_RULES);}
|
|
93
|
+
return this.__compiled;}
|
|
94
|
+
setRules(rules){this.compile(rules);window.CUSTOM_MARKUP_RULES=Array.isArray(rules)?rules.slice():(this.cfg.CUSTOM_MARKUP_RULES||[]).slice();this._d('cm.setRules',{count:(window.CUSTOM_MARKUP_RULES||[]).length});}
|
|
95
|
+
getRules(){const list=(window.CUSTOM_MARKUP_RULES?window.CUSTOM_MARKUP_RULES.slice():(this.cfg.CUSTOM_MARKUP_RULES||[]).slice());return list;}
|
|
96
|
+
hasStreamRules(){this.ensureCompiled();return!!this.__hasStreamRules;}
|
|
97
|
+
hasStreamOpenerAtStart(text){if(!text)return false;this.ensureCompiled();if(!this.__hasStreamRules)return false;const rules=this.__streamRules||[];if(!rules.length)return false;const t=String(text).trimStart();for(let i=0;i<rules.length;i++){const r=rules[i];if(!r||!r.open)continue;if(t.startsWith(r.open))return true;}
|
|
98
|
+
return false;}
|
|
99
|
+
maybeApplyStreamOnDelta(root,deltaText,MD){try{this.ensureCompiled();if(!this.__hasStreamRules)return;const t=String(deltaText||'');if(t&&this.hasAnyStreamOpenToken(t)){this._d('cm.stream.delta',{len:t.length,head:t.slice(0,64)});this.applyStream(root,MD);return;}
|
|
100
|
+
if(root&&root.querySelector&&root.querySelector('[data-cm-pending="1"]')){if(t.indexOf('>')!==-1||t.indexOf(']')!==-1){this.applyStreamFinalizeClosers(root,this.__streamRules);this._d('cm.stream.delta.finalize',{});}}}catch(_){return;}}
|
|
101
|
+
applyStream(root,MD){this.ensureCompiled();if(!this.__hasStreamRules)return;const rules=this.__streamRules;if(!rules||!rules.length)return;this.applyRules(root,MD,rules);try{this.applyStreamPartialOpeners(root,MD,this.__streamWrapRules);}catch(_){}
|
|
102
|
+
try{this.applyStreamFinalizeClosers(root,rules);}catch(_){}}
|
|
103
|
+
isInsideForbiddenContext(node){const p=node.parentElement;if(!p)return true;return!!p.closest('pre, code, kbd, samp, var, script, style, textarea, .math-pending, .hljs, .code-wrapper, ul, ol, li, dl, dt, dd');}
|
|
104
|
+
isInsideForbiddenElement(el){if(!el)return true;return!!el.closest('pre, code, kbd, samp, var, script, style, textarea, .math-pending, .hljs, .code-wrapper, ul, ol, li, dl, dt, dd');}
|
|
105
|
+
findNextMatch(text,from,rules){let best=null;for(const rule of rules){rule.re.lastIndex=from;const m=rule.re.exec(text);if(m){const start=m.index,end=rule.re.lastIndex;if(!best||start<best.start)best={rule,start,end,inner:m[1]||''};}}
|
|
106
|
+
return best;}
|
|
107
|
+
findFullMatch(text,rules){for(const rule of rules){if(rule.reFull){const m=rule.reFull.exec(text);if(m)return{rule,inner:m[1]||''};}else{rule.re.lastIndex=0;const m=rule.re.exec(text);if(m&&m.index===0&&(rule.re.lastIndex===text.length)){const m2=rule.re.exec(text);if(!m2)return{rule,inner:m[1]||''};}}}
|
|
108
|
+
return null;}
|
|
109
|
+
setInnerByMode(el,mode,text,MD,decodeEntities=false,rule=null){let payload=String(text||'');const wantsBr=!!(rule&&(rule.nl2br||rule.allowBr));if(decodeEntities&&payload&&payload.indexOf('&')!==-1){try{payload=this.decodeEntitiesOnce(payload);}catch(_){}}
|
|
110
|
+
if(wantsBr){el.innerHTML=this._escapeHtmlAllowBr(payload,{convertNewlines:!!(rule&&rule.nl2br)});return;}
|
|
111
|
+
if(mode==='markdown-inline'&&MD&&typeof MD.renderInline==='function'){try{el.innerHTML=MD.renderInline(payload);return;}catch(_){}}
|
|
112
|
+
el.textContent=payload;}
|
|
113
|
+
_tryReplaceFullParagraph(el,rules,MD){if(!el||el.tagName!=='P')return false;if(this.isInsideForbiddenElement(el)){return false;}
|
|
114
|
+
const t=el.textContent||'';if(!this.hasAnyOpenToken(t,rules))return false;for(const rule of rules){if(!rule)continue;const m=rule.reFullTrim?rule.reFullTrim.exec(t):null;if(!m)continue;const innerText=m[1]||'';if(rule.phase!=='html'&&rule.phase!=='both')continue;if(rule.openReplace||rule.closeReplace){const innerHTML=this._materializeInnerHTML(rule,innerText,MD);const html=String(rule.openReplace||'')+innerHTML+String(rule.closeReplace||'');this._replaceElementWithHTML(el,html);this._d('cm.replace.full',{name:rule.name});return true;}
|
|
115
|
+
const outTag=(rule.tag&&typeof rule.tag==='string')?rule.tag.toLowerCase():'span';const out=document.createElement(outTag==='p'?'p':outTag);if(rule.className)out.className=rule.className;out.setAttribute('data-cm',rule.name);this.setInnerByMode(out,rule.innerMode,innerText,MD,!!rule.decodeEntities,rule);try{el.replaceWith(out);}catch(_){const par=el.parentNode;if(par)par.replaceChild(out,el);}
|
|
116
|
+
this._d('cm.wrap.full',{name:rule.name});return true;}
|
|
117
|
+
return false;}
|
|
118
|
+
applyRules(root,MD,rules){if(!root||!rules||!rules.length)return;const scope=(root.nodeType===1||root.nodeType===11)?root:document;try{const paragraphs=(typeof scope.querySelectorAll==='function')?scope.querySelectorAll('p'):[];if(paragraphs&¶graphs.length){for(let i=0;i<paragraphs.length;i++){const p=paragraphs[i];if(p&&p.getAttribute&&p.getAttribute('data-cm'))continue;const tc=p&&(p.textContent||'');if(!tc||!this.hasAnyOpenToken(tc,rules))continue;if(this.isInsideForbiddenElement(p))continue;this._tryReplaceFullParagraph(p,rules,MD);}}}catch(e){}
|
|
119
|
+
const self=this;const walker=document.createTreeWalker(root,NodeFilter.SHOW_TEXT,{acceptNode:(node)=>{const val=node&&node.nodeValue?node.nodeValue:'';if(!val||!self.hasAnyOpenToken(val,rules))return NodeFilter.FILTER_SKIP;if(self.isInsideForbiddenContext(node))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT;}});let node;while((node=walker.nextNode())){const text=node.nodeValue;if(!text||!this.hasAnyOpenToken(text,rules))continue;const parent=node.parentElement;if(parent&&parent.tagName==='P'&&parent.childNodes.length===1){const fm=this.findFullMatch(text,rules);if(fm){if((fm.rule.phase==='html'||fm.rule.phase==='both')&&(fm.rule.openReplace||fm.rule.closeReplace)){const innerHTML=this._materializeInnerHTML(fm.rule,fm.inner,MD);const html=String(fm.rule.openReplace||'')+innerHTML+String(fm.rule.closeReplace||'');this._replaceElementWithHTML(parent,html);this._d('cm.replace.inlineFull',{name:fm.rule.name});continue;}
|
|
120
|
+
if(fm.rule.tag==='p'){const out=document.createElement('p');if(fm.rule.className)out.className=fm.rule.className;out.setAttribute('data-cm',fm.rule.name);this.setInnerByMode(out,fm.rule.innerMode,fm.inner,MD,!!fm.rule.decodeEntities,fm.rule);try{parent.replaceWith(out);}catch(_){const par=parent.parentNode;if(par)par.replaceChild(out,parent);}
|
|
121
|
+
this._d('cm.wrap.paragraph',{name:fm.rule.name});continue;}}}
|
|
122
|
+
let i=0;let didReplace=false;const frag=document.createDocumentFragment();while(i<text.length){const m=this.findNextMatch(text,i,rules);if(!m)break;if(m.start>i){frag.appendChild(document.createTextNode(text.slice(i,m.start)));}
|
|
123
|
+
if((m.rule.openReplace||m.rule.closeReplace)&&(m.rule.phase==='html'||m.rule.phase==='both')){const innerHTML=this._materializeInnerHTML(m.rule,m.inner,MD);const html=String(m.rule.openReplace||'')+innerHTML+String(m.rule.closeReplace||'');const part=this._fragmentFromHTML(html);frag.appendChild(part);i=m.end;didReplace=true;this._d('cm.replace.inline',{name:m.rule.name});continue;}
|
|
124
|
+
if(m.rule.openReplace||m.rule.closeReplace){frag.appendChild(document.createTextNode(text.slice(m.start,m.end)));i=m.end;didReplace=true;continue;}
|
|
125
|
+
const tag=(m.rule.tag==='p')?'span':m.rule.tag;const el=document.createElement(tag);if(m.rule.className)el.className=m.rule.className;el.setAttribute('data-cm',m.rule.name);this.setInnerByMode(el,m.rule.innerMode,m.inner,MD,!!m.rule.decodeEntities,m.rule);frag.appendChild(el);this._d('cm.wrap.inline',{name:m.rule.name});i=m.end;didReplace=true;}
|
|
126
|
+
if(!didReplace)continue;if(i<text.length)frag.appendChild(document.createTextNode(text.slice(i)));const parentNode=node.parentNode;if(parentNode){parentNode.replaceChild(frag,node);}}}
|
|
127
|
+
apply(root,MD){this.ensureCompiled();this.applyRules(root,MD,this.__compiled);}
|
|
128
|
+
applyStreamPartialOpeners(root,MD,rules){if(!root)return;rules=(rules||this.__streamWrapRules||[]).slice();if(!rules.length)return;const scope=(root.nodeType===1||root.nodeType===11)?root:document;const self=this;const walker=document.createTreeWalker(scope,NodeFilter.SHOW_TEXT,{acceptNode(node){const val=node&&node.nodeValue?node.nodeValue:'';if(!val||!self.hasAnyOpenToken(val,rules))return NodeFilter.FILTER_SKIP;if(self.isInsideForbiddenContext(node))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT;}});let node;while((node=walker.nextNode())){const text=node.nodeValue||'';if(!text)continue;let best=null;for(let i=0;i<rules.length;i++){const r=rules[i];if(!r||!r.open||!r.close)continue;const idx=text.lastIndexOf(r.open);if(idx===-1)continue;const after=text.indexOf(r.close,idx+r.open.length);if(after!==-1)continue;if(!best||idx>best.start)best={rule:r,start:idx};}
|
|
129
|
+
if(!best)continue;const r=best.rule;const start=best.start;const openLen=r.open.length;const prefixText=text.slice(0,start);const fromOffset=start+openLen;try{const range=document.createRange();range.setStart(node,Math.min(fromOffset,node.nodeValue.length));let endNode=root;try{endNode=(root.nodeType===11||root.nodeType===1)?root:node.parentNode;while(endNode&&endNode.lastChild)endNode=endNode.lastChild;}catch(_){}
|
|
130
|
+
if(endNode&&endNode.nodeType===3)range.setEnd(endNode,endNode.nodeValue.length);else if(endNode)range.setEndAfter(endNode);else range.setEndAfter(node);const remainder=range.extractContents();const outTag=(r.tag&&typeof r.tag==='string')?r.tag.toLowerCase():'span';const hostTag=(outTag==='p')?'span':outTag;const el=document.createElement(hostTag);if(r.className)el.className=r.className;el.setAttribute('data-cm',r.name);el.setAttribute('data-cm-pending','1');el.appendChild(remainder);range.insertNode(el);range.detach();try{node.nodeValue=prefixText;}catch(_){}
|
|
131
|
+
this._d('cm.stream.open.pending',{name:r.name});return;}catch(err){try{const tail=text.slice(start+r.open.length);const frag=document.createDocumentFragment();if(prefixText)frag.appendChild(document.createTextNode(prefixText));const el=document.createElement((r.tag==='p')?'span':r.tag);if(r.className)el.className=r.className;el.setAttribute('data-cm',r.name);el.setAttribute('data-cm-pending','1');this.setInnerByMode(el,r.innerMode,tail,MD,!!r.decodeEntities,r);frag.appendChild(el);node.parentNode.replaceChild(frag,node);this._d('cm.stream.open.pending.fallback',{name:r.name});return;}catch(_){}}}}
|
|
132
|
+
applyStreamFinalizeClosers(root,rulesAll){if(!root)return;const scope=(root.nodeType===1||root.nodeType===11)?root:document;const pending=scope.querySelectorAll('[data-cm][data-cm-pending="1"]');if(!pending||!pending.length)return;const rulesByName=new Map();(rulesAll||[]).forEach(r=>{if(r&&r.name)rulesByName.set(r.name,r);});for(let i=0;i<pending.length;i++){const el=pending[i];const name=el.getAttribute('data-cm')||'';const rule=rulesByName.get(name);if(!rule||!rule.close)continue;const self=this;const walker=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,{acceptNode(node){const val=node&&node.nodeValue?node.nodeValue:'';if(!val||val.indexOf(rule.close)===-1)return NodeFilter.FILTER_SKIP;if(self.isInsideForbiddenContext(node))return NodeFilter.FILTER_REJECT;return NodeFilter.FILTER_ACCEPT;}});let nodeWithClose=null;let idxInNode=-1;let tn;while((tn=walker.nextNode())){const idx=tn.nodeValue.indexOf(rule.close);if(idx!==-1){nodeWithClose=tn;idxInNode=idx;break;}}
|
|
133
|
+
if(!nodeWithClose)continue;try{const tokenLen=rule.close.length;const afterRange=document.createRange();afterRange.setStart(nodeWithClose,idxInNode+tokenLen);let endNode=el;while(endNode&&endNode.lastChild)endNode=endNode.lastChild;if(endNode&&endNode.nodeType===3)afterRange.setEnd(endNode,endNode.nodeValue.length);else afterRange.setEndAfter(el.lastChild||el);const tail=afterRange.extractContents();afterRange.detach();const tok=document.createRange();tok.setStart(nodeWithClose,idxInNode);tok.setEnd(nodeWithClose,idxInNode+tokenLen);tok.deleteContents();tok.detach();if(el.parentNode&&tail&&tail.childNodes.length){el.parentNode.insertBefore(tail,el.nextSibling);}
|
|
134
|
+
el.removeAttribute('data-cm-pending');this._d('cm.stream.close.finalize',{name});}catch(err){}}}
|
|
135
|
+
_findFenceRanges(s){const ranges=[];const n=s.length;let i=0;let inFence=false;let fenceMark='';let fenceLen=0;let startLineStart=0;while(i<n){const lineStart=i;let j=lineStart;while(j<n&&s.charCodeAt(j)!==10&&s.charCodeAt(j)!==13)j++;const lineEnd=j;let nl=0;if(j<n){if(s.charCodeAt(j)===13&&j+1<n&&s.charCodeAt(j+1)===10)nl=2;else nl=1;}
|
|
136
|
+
let k=lineStart;let indent=0;while(k<lineEnd){const c=s.charCodeAt(k);if(c===32){indent++;if(indent>3)break;k++;}else if(c===9){indent++;if(indent>3)break;k++;}else break;}
|
|
137
|
+
if(!inFence){if(indent<=3&&k<lineEnd){const ch=s.charCodeAt(k);if(ch===0x60||ch===0x7E){const mark=String.fromCharCode(ch);let m=k;while(m<lineEnd&&s.charCodeAt(m)===ch)m++;const run=m-k;if(run>=3){inFence=true;fenceMark=mark;fenceLen=run;startLineStart=lineStart;}}}}else{if(indent<=3&&k<lineEnd&&s.charCodeAt(k)===fenceMark.charCodeAt(0)){let m=k;while(m<lineEnd&&s.charCodeAt(m)===fenceMark.charCodeAt(0))m++;const run=m-k;if(run>=fenceLen){let onlyWS=true;for(let t=m;t<lineEnd;t++){const cc=s.charCodeAt(t);if(cc!==32&&cc!==9){onlyWS=false;break;}}
|
|
138
|
+
if(onlyWS){const endIdx=lineEnd+nl;ranges.push([startLineStart,endIdx]);inFence=false;fenceMark='';fenceLen=0;startLineStart=0;}}}}
|
|
139
|
+
i=lineEnd+nl;}
|
|
140
|
+
if(inFence)ranges.push([startLineStart,n]);return ranges;}
|
|
141
|
+
_isTopLevelLineInSource(s,absIdx){let ls=absIdx;while(ls>0){const ch=s.charCodeAt(ls-1);if(ch===10||ch===13)break;ls--;}
|
|
142
|
+
const prefix=s.slice(ls,absIdx);let i=0,indent=0;while(i<prefix.length){const c=prefix.charCodeAt(i);if(c===32){indent++;if(indent>3)break;i++;}
|
|
143
|
+
else if(c===9){indent++;if(indent>3)break;i++;}
|
|
144
|
+
else break;}
|
|
145
|
+
if(indent>3)return false;const rest=prefix.slice(i);if(/^>\s?/.test(rest))return false;if(/^[-+*]\s/.test(rest))return false;if(/^\d+[.)]\s/.test(rest))return false;if(rest.trim().length>0)return false;return true;}
|
|
146
|
+
_applySourceReplacementsInChunk(full,chunk,baseOffset,rules){let t=chunk;for(let i=0;i<rules.length;i++){const r=rules[i];if(!r||!(r.openReplace||r.closeReplace))continue;try{r.re.lastIndex=0;t=t.replace(r.re,(match,inner,offset)=>{const abs=baseOffset+(offset|0);if(!this._isTopLevelLineInSource(full,abs))return match;const open=r.openReplace||'';const close=r.closeReplace||'';return open+(inner||'')+close;});}catch(_){}}
|
|
147
|
+
return t;}
|
|
148
|
+
_injectUnmatchedSourceOpeners(text,fenceRules){let s=String(text||'');if(!s||!fenceRules||!fenceRules.length)return s;let best=null;for(let i=0;i<fenceRules.length;i++){const r=fenceRules[i];if(!r||!r.open||!r.close||!r.openReplace)continue;const idx=s.lastIndexOf(r.open);if(idx===-1)continue;if(!this._isTopLevelLineInSource(s,idx))continue;const after=s.indexOf(r.close,idx+r.open.length);if(after!==-1)continue;if(!best||idx>best.idx)best={r,idx};}
|
|
149
|
+
if(!best)return s;const r=best.r,i=best.idx;const before=s.slice(0,i);const after=s.slice(i+r.open.length);const injected=String(r.openReplace||'');this._d('cm.inject.open',{name:r.name});return before+injected+after;}};
|
|
150
|
+
|
|
151
|
+
/* data/js/app/data.js */
|
|
152
|
+
class DataReceiver{constructor(cfg,templates,nodes,scrollMgr){this.cfg=cfg||{};this.templates=templates;this.nodes=nodes;this.scrollMgr=scrollMgr;}
|
|
153
|
+
_tryParseJSON(s){if(typeof s!=='string')return s;const t=s.trim();if(!t)return null;if(t[0]==='<')return null;try{return JSON.parse(t);}catch(_){return null;}}
|
|
154
|
+
_normalizeToBlocks(obj){if(!obj)return[];if(Array.isArray(obj))return obj;if(obj.node)return[obj.node];if(obj.nodes)return(Array.isArray(obj.nodes)?obj.nodes:[]);if(typeof obj==='object'&&(obj.input||obj.output||obj.id))return[obj];return[];}
|
|
155
|
+
append(payload){if(typeof payload==='string'&&payload.trim().startsWith('<')){this.nodes.appendNode(payload,this.scrollMgr);return;}
|
|
156
|
+
const obj=this._tryParseJSON(payload);if(!obj){this.nodes.appendNode(String(payload),this.scrollMgr);return;}
|
|
157
|
+
const blocks=this._normalizeToBlocks(obj);if(!blocks.length){this.nodes.appendNode('',this.scrollMgr);return;}
|
|
158
|
+
const html=this.templates.renderNodes(blocks);this.nodes.appendNode(html,this.scrollMgr);}
|
|
159
|
+
replace(payload){if(typeof payload==='string'&&payload.trim().startsWith('<')){this.nodes.replaceNodes(payload,this.scrollMgr);return;}
|
|
160
|
+
const obj=this._tryParseJSON(payload);if(!obj){this.nodes.replaceNodes(String(payload),this.scrollMgr);return;}
|
|
161
|
+
const blocks=this._normalizeToBlocks(obj);if(!blocks.length){this.nodes.replaceNodes('',this.scrollMgr);return;}
|
|
162
|
+
const html=this.templates.renderNodes(blocks);this.nodes.replaceNodes(html,this.scrollMgr);}};
|
|
163
|
+
|
|
164
|
+
/* data/js/app/dom.js */
|
|
165
|
+
class DOMRefs{constructor(){this.els=Object.create(null);this._domOutputStreamRef=null;this._domStreamMsgRef=null;this._domStreamBoxRef=null;}
|
|
166
|
+
init(){const ids=['container','_nodes_','_append_input_','_append_output_before_','_append_output_','_append_live_','_footer_','_loader_','tips','scrollFab','scrollFabIcon'];for(let i=0;i<ids.length;i++){const id=ids[i];const el=document.getElementById(id);if(el)this.els[id]=el;}}
|
|
167
|
+
get(id){let el=this.els[id];if(el&&el.isConnected)return el;el=document.getElementById(id);if(el)this.els[id]=el;return el||null;}
|
|
168
|
+
resetEphemeral(){this._domStreamMsgRef=null;this._domStreamBoxRef=null;}
|
|
169
|
+
cleanup(){this.resetEphemeral();this._domOutputStreamRef=null;this.els=Object.create(null);try{history.scrollRestoration="auto";}catch(_){}}
|
|
170
|
+
_deref(ref){if(!ref||typeof ref.deref!=='function')return null;try{const el=ref.deref();return(el&&el.isConnected)?el:null;}catch(_){return null;}}
|
|
171
|
+
fastClear(id){const el=this.get(id);if(!el)return null;if(el.firstChild){if(typeof el.replaceChildren==='function')el.replaceChildren();else el.textContent='';}
|
|
172
|
+
return el;}
|
|
173
|
+
async fastClearAndPaint(id){const el=this.fastClear(id);if(!el)return null;try{if(typeof runtime!=='undefined'&&runtime.raf&&typeof runtime.raf.nextFrame==='function'){await runtime.raf.nextFrame();}else if(typeof requestAnimationFrame==='function'){await new Promise(res=>requestAnimationFrame(()=>res()));}else{await new Promise(res=>setTimeout(res,16));}}catch(_){}
|
|
174
|
+
return el;}
|
|
175
|
+
fastClearHidden(id){const el=this.get(id);if(!el)return null;const prevDisplay=el.style.display;el.style.display='none';if(typeof el.replaceChildren==='function')el.replaceChildren();else el.textContent='';el.style.display=prevDisplay;return el;}
|
|
176
|
+
hardReplaceByClone(id){const el=this.get(id);if(!el||!el.parentNode)return null;const clone=el.cloneNode(false);try{el.replaceWith(clone);}catch(_){el.textContent='';return el;}
|
|
177
|
+
this.els[id]=clone;if(id==='_append_output_'){this._domOutputStreamRef=(typeof WeakRef!=='undefined')?new WeakRef(clone):null;}
|
|
178
|
+
return clone;}
|
|
179
|
+
hardResetStreamContainers(){this.resetEphemeral();this._domOutputStreamRef=null;this.fastClearHidden('_append_output_before_');this.fastClearHidden('_append_output_');}
|
|
180
|
+
getStreamContainer(){let el=this._deref(this._domOutputStreamRef);if(el)return el;el=this.get('_append_output_');if(el)this._domOutputStreamRef=(typeof WeakRef!=='undefined')?new WeakRef(el):null;return el;}
|
|
181
|
+
_sanitizeHeaderFragment(root){const ALLOWED=new Set(['IMG','SPAN','STRONG','EM']);const ALLOWED_ATTR={IMG:new Set(['src','alt','class','width','height','loading','decoding']),SPAN:new Set(['class']),STRONG:new Set([]),EM:new Set([])};const isAllowedSrc=(src)=>{if(!src||typeof src!=='string')return false;const s=src.trim().toLowerCase();if(s.startsWith('file:'))return true;if(s.startsWith('qrc:'))return true;if(s.startsWith('bridge:'))return true;if(s.startsWith('blob:'))return true;if(s.startsWith('data:image/'))return true;if(s.startsWith('http:'))return true;if(s.startsWith('https:'))return true;if(!/^[a-z0-9.+-]+:/.test(s))return true;return false;};const walker=document.createTreeWalker(root,NodeFilter.SHOW_ELEMENT,null);const toRemove=[];while(walker.nextNode()){const el=walker.currentNode;const tag=el.tagName;if(!ALLOWED.has(tag)){toRemove.push(el);continue;}
|
|
182
|
+
const allowAttrs=ALLOWED_ATTR[tag];for(let i=el.attributes.length-1;i>=0;i--){const a=el.attributes[i];if(!allowAttrs.has(a.name))el.removeAttribute(a.name);}
|
|
183
|
+
if(tag==='IMG'){const src=el.getAttribute('src')||'';if(!isAllowedSrc(src)){toRemove.push(el);continue;}
|
|
184
|
+
if(!el.hasAttribute('loading'))el.setAttribute('loading','lazy');if(!el.hasAttribute('decoding'))el.setAttribute('decoding','async');}}
|
|
185
|
+
for(const el of toRemove){const txt=el.textContent||'';const tn=document.createTextNode(txt);try{el.replaceWith(tn);}catch(_){}}}
|
|
186
|
+
_setHeaderHTML(container,html){if(!container)return;const s=String(html||'');if(s.indexOf('<')===-1&&s.indexOf('&')===-1){container.textContent=s;return;}
|
|
187
|
+
const tpl=document.createElement('template');tpl.innerHTML=s;const frag=tpl.content;try{this._sanitizeHeaderFragment(frag);container.replaceChildren(frag);}catch(_){container.textContent=s.replace(/<[^>]*>/g,'');}}
|
|
188
|
+
getStreamMsg(create,name_header){const container=this.getStreamContainer();if(!container)return null;let msg=this._deref(this._domStreamMsgRef);if(msg)return msg;let box=this._deref(this._domStreamBoxRef);if(!box){try{box=container.querySelector('.msg-box');}catch(_){box=null;}}
|
|
189
|
+
if(!box&&create){const frag=document.createDocumentFragment();const newBox=document.createElement('div');newBox.classList.add('msg-box','msg-bot');if(name_header){const name=document.createElement('div');name.classList.add('name-header','name-bot');this._setHeaderHTML(name,name_header);newBox.appendChild(name);}
|
|
190
|
+
const newMsg=document.createElement('div');newMsg.classList.add('msg');const snap=document.createElement('div');snap.className='md-snapshot-root';newMsg.appendChild(snap);newBox.appendChild(newMsg);frag.appendChild(newBox);container.appendChild(frag);this._domStreamBoxRef=(typeof WeakRef!=='undefined')?new WeakRef(newBox):null;this._domStreamMsgRef=(typeof WeakRef!=='undefined')?new WeakRef(newMsg):null;return newMsg;}
|
|
191
|
+
if(box){try{msg=box.querySelector('.msg');}catch(_){msg=null;}
|
|
192
|
+
if(!msg){msg=document.createElement('div');msg.classList.add('msg');box.appendChild(msg);}
|
|
193
|
+
if(!msg.querySelector('.md-snapshot-root')){const snap=document.createElement('div');snap.className='md-snapshot-root';msg.appendChild(snap);}
|
|
194
|
+
this._domStreamBoxRef=(typeof WeakRef!=='undefined')?new WeakRef(box):null;this._domStreamMsgRef=(typeof WeakRef!=='undefined')?new WeakRef(msg):null;}
|
|
195
|
+
return msg||null;}
|
|
196
|
+
clearStreamBefore(){try{if(typeof window.hideTips==='function')window.hideTips();}catch(_){}
|
|
197
|
+
this.fastClearHidden('_append_output_before_');}
|
|
198
|
+
clearOutput(){this.hardResetStreamContainers();}
|
|
199
|
+
clearNodes(){this.clearStreamBefore();const el=this.fastClearHidden('_nodes_');if(el)el.classList.add('empty_list');this.resetEphemeral();}
|
|
200
|
+
clearInput(){this.fastClearHidden('_append_input_');}
|
|
201
|
+
clearLive(){const el=this.fastClearHidden('_append_live_');if(!el)return;el.classList.remove('visible');el.classList.add('hidden');this.resetEphemeral();}};
|
|
202
|
+
|
|
203
|
+
/* data/js/app/events.js */
|
|
204
|
+
class EventManager{constructor(cfg,dom,scrollMgr,highlighter,codeScroll,toolOutput,bridge){this.cfg=cfg;this.dom=dom;this.scrollMgr=scrollMgr;this.highlighter=highlighter;this.codeScroll=codeScroll;this.toolOutput=toolOutput;this.bridge=bridge;this.handlers={wheel:null,scroll:null,resize:null,fabClick:null,mouseover:null,mouseout:null,click:null,keydown:null,docClickFocus:null,visibility:null,focus:null,pageshow:null};}
|
|
205
|
+
_findWrapper(target){if(!target||typeof target.closest!=='function')return null;return target.closest('.code-wrapper');}
|
|
206
|
+
_getCodeEl(wrapper){if(!wrapper)return null;return wrapper.querySelector('pre > code');}
|
|
207
|
+
_collectCodeText(codeEl){if(!codeEl)return'';const frozen=codeEl.querySelector('.hl-frozen');const tail=codeEl.querySelector('.hl-tail');if(frozen||tail)return(frozen?.textContent||'')+(tail?.textContent||'');return codeEl.textContent||'';}
|
|
208
|
+
_collectUserText(msgBox){if(!msgBox)return'';const msg=msgBox.querySelector('.msg');if(!msg)return'';const root=msg.querySelector('.uc-content')||msg;let out='';const walker=document.createTreeWalker(root,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:(node)=>{if(node.nodeType===Node.ELEMENT_NODE){const el=node;if(el.matches('.uc-ellipsis,[data-copy-ignore="1"],.msg-copy-btn,.uc-toggle')){return NodeFilter.FILTER_REJECT;}
|
|
209
|
+
if(el.tagName==='BR'){out+='\n';return NodeFilter.FILTER_SKIP;}}
|
|
210
|
+
if(node.nodeType===Node.TEXT_NODE){return NodeFilter.FILTER_ACCEPT;}
|
|
211
|
+
return NodeFilter.FILTER_SKIP;}},false);let n;while((n=walker.nextNode())){out+=n.nodeValue;}
|
|
212
|
+
return String(out||'').replace(/\r\n?/g,'\n');}
|
|
213
|
+
async _copyTextRobust(text){try{if(this.bridge&&typeof this.bridge.copyCode==='function'){this.bridge.copyCode(text);return true;}}catch(_){}
|
|
214
|
+
try{if(navigator&&navigator.clipboard&&navigator.clipboard.writeText){await navigator.clipboard.writeText(text);return true;}}catch(_){}
|
|
215
|
+
try{const ta=document.createElement('textarea');ta.value=text;ta.setAttribute('readonly','');ta.style.position='fixed';ta.style.top='-9999px';ta.style.opacity='0';document.body.appendChild(ta);ta.select();const ok=document.execCommand&&document.execCommand('copy');document.body.removeChild(ta);return!!ok;}catch(_){return false;}}
|
|
216
|
+
_flashCopied(btn,wrapper){if(!btn)return;const DUR=1200;const img=btn.querySelector('img.copy-img')||btn.querySelector('img.action-img')||btn.querySelector('img');try{if(btn.__copyTimer){clearTimeout(btn.__copyTimer);btn.__copyTimer=0;}}catch(_){}
|
|
217
|
+
try{if(btn.__iconTimer){clearTimeout(btn.__iconTimer);btn.__iconTimer=0;}}catch(_){}
|
|
218
|
+
if(typeof window!=='undefined'&&window.ICON_DONE&&img){if(!btn.__origIconSrc){try{btn.__origIconSrc=img.getAttribute('src')||'';}catch(_){btn.__origIconSrc='';}}
|
|
219
|
+
try{img.setAttribute('src',String(window.ICON_DONE));}catch(_){}
|
|
220
|
+
btn.__iconTimer=setTimeout(()=>{try{const orig=btn.__origIconSrc||'';if(orig)img.setAttribute('src',orig);}catch(_){}
|
|
221
|
+
btn.__iconTimer=0;},DUR);}
|
|
222
|
+
const span=btn.querySelector('span');if(!span){btn.classList.add('copied');btn.__copyTimer=setTimeout(()=>{try{btn.classList.remove('copied');}catch(_){}
|
|
223
|
+
btn.__copyTimer=0;},DUR);return;}
|
|
224
|
+
const L_COPY=(wrapper&&wrapper.getAttribute('data-locale-copy'))||'Copy';const L_COPIED=(wrapper&&wrapper.getAttribute('data-locale-copied'))||'Copied';span.textContent=L_COPIED;btn.classList.add('copied');btn.__copyTimer=setTimeout(()=>{try{span.textContent=L_COPY;btn.classList.remove('copied');}catch(_){}
|
|
225
|
+
btn.__copyTimer=0;},DUR);}
|
|
226
|
+
_toggleCollapse(wrapper){if(!wrapper)return;const codeEl=this._getCodeEl(wrapper);if(!codeEl)return;const btn=wrapper.querySelector('.code-header-collapse');const span=btn?btn.querySelector('span'):null;const L_COLLAPSE=wrapper.getAttribute('data-locale-collapse')||'Collapse';const L_EXPAND=wrapper.getAttribute('data-locale-expand')||'Expand';const idx=String(wrapper.getAttribute('data-index')||'');const arr=window.__collapsed_idx||(window.__collapsed_idx=[]);const isHidden=(codeEl.style.display==='none');if(isHidden){codeEl.style.display='block';if(span)span.textContent=L_COLLAPSE;const p=arr.indexOf(idx);if(p!==-1)arr.splice(p,1);if(btn)btn.setAttribute('title',L_COLLAPSE);}else{codeEl.style.display='none';if(span)span.textContent=L_EXPAND;if(!arr.includes(idx))arr.push(idx);if(btn)btn.setAttribute('title',L_EXPAND);}
|
|
227
|
+
if(btn){try{if(btn.__popTimer){clearTimeout(btn.__popTimer);btn.__popTimer=0;}}catch(_){}
|
|
228
|
+
btn.classList.add('copied');btn.__popTimer=setTimeout(()=>{try{btn.classList.remove('copied');}catch(_){}
|
|
229
|
+
btn.__popTimer=0;},1200);}}
|
|
230
|
+
install(){try{history.scrollRestoration="manual";}catch(_){}
|
|
231
|
+
this.handlers.keydown=(event)=>{if(event.ctrlKey&&event.key==='f'){window.location.href='bridge://open_find:'+runtime.cfg.PID;event.preventDefault();}
|
|
232
|
+
if(event.key==='Escape'){window.location.href='bridge://escape';event.preventDefault();}};document.addEventListener('keydown',this.handlers.keydown,{passive:false});const container=this.dom.get('container');const inputArea=this.dom.get('_append_input_');const addClassToMsg=(id,className)=>{const el=document.getElementById('msg-bot-'+id);if(el)el.classList.add(className);};const removeClassFromMsg=(id,className)=>{const el=document.getElementById('msg-bot-'+id);if(el)el.classList.remove(className);};this.handlers.mouseover=(event)=>{if(event.target.classList.contains('action-img')){const id=event.target.getAttribute('data-id');addClassToMsg(id,'msg-highlight');}};this.handlers.mouseout=(event)=>{if(event.target.classList.contains('action-img')){const id=event.target.getAttribute('data-id');const el=document.getElementById('msg-bot-'+id);if(el)el.classList.remove('msg-highlight');}};if(container){container.addEventListener('mouseover',this.handlers.mouseover,{passive:true});container.addEventListener('mouseout',this.handlers.mouseout,{passive:true});}
|
|
233
|
+
this.handlers.click=async(ev)=>{const aCode=ev.target&&(ev.target.closest?ev.target.closest('a.code-header-action'):null)||null;const aUserCopy=ev.target&&(ev.target.closest?ev.target.closest('a.msg-copy-btn'):null)||null;if(!aCode&&!aUserCopy)return;ev.preventDefault();ev.stopPropagation();if(aCode){const wrapper=this._findWrapper(aCode);if(!wrapper)return;const isCopy=aCode.classList.contains('code-header-copy');const isCollapse=aCode.classList.contains('code-header-collapse');const isRun=aCode.classList.contains('code-header-run');const isPreview=aCode.classList.contains('code-header-preview');let codeEl=null,text='';if(isCopy||isRun||isPreview){codeEl=this._getCodeEl(wrapper);text=this._collectCodeText(codeEl);}
|
|
234
|
+
try{if(isCopy){const ok=await this._copyTextRobust(text);if(ok)this._flashCopied(aCode,wrapper);}else if(isCollapse){this._toggleCollapse(wrapper);}else if(isRun){if(this.bridge&&typeof this.bridge.runCode==='function')this.bridge.runCode(text);}else if(isPreview){if(this.bridge&&typeof this.bridge.previewCode==='function')this.bridge.previewCode(text);}}catch(_){}
|
|
235
|
+
return;}
|
|
236
|
+
if(aUserCopy){try{const msgBox=aUserCopy.closest('.msg-box.msg-user');const text=this._collectUserText(msgBox);const ok=await this._copyTextRobust(text);const L=(this.cfg&&this.cfg.LOCALE)||{};const L_COPY=L.COPY||'Copy';const L_COPIED=L.COPIED||'Copied';if(ok){this._flashCopied(aUserCopy,null);}}catch(_){}}};if(container)container.addEventListener('click',this.handlers.click,{passive:false});if(inputArea)inputArea.addEventListener('click',this.handlers.click,{passive:false});this.handlers.wheel=(ev)=>{runtime.scrollMgr.userInteracted=true;if(ev.deltaY<0)runtime.scrollMgr.autoFollow=false;else runtime.scrollMgr.maybeEnableAutoFollowByProximity();this.highlighter.scheduleScanVisibleCodes(runtime.stream.activeCode);};document.addEventListener('wheel',this.handlers.wheel,{passive:true});this.handlers.scroll=()=>{const el=Utils.SE;const top=el.scrollTop;if(top+1<runtime.scrollMgr.lastScrollTop)runtime.scrollMgr.autoFollow=false;runtime.scrollMgr.maybeEnableAutoFollowByProximity();runtime.scrollMgr.lastScrollTop=top;const action=runtime.scrollMgr.computeFabAction();if(action!==runtime.scrollMgr.currentFabAction)runtime.scrollMgr.updateScrollFab(false,action,true);this.highlighter.scheduleScanVisibleCodes(runtime.stream.activeCode);};window.addEventListener('scroll',this.handlers.scroll,{passive:true});const fab=this.dom.get('scrollFab');if(fab){this.handlers.fabClick=(ev)=>{ev.preventDefault();ev.stopPropagation();const action=runtime.scrollMgr.computeFabAction();if(action==='up')runtime.scrollMgr.scrollToTopUser();else if(action==='down')runtime.scrollMgr.scrollToBottomUser();runtime.scrollMgr.fabFreezeUntil=Utils.now()+this.cfg.FAB.TOGGLE_DEBOUNCE_MS;runtime.scrollMgr.updateScrollFab(true);};fab.addEventListener('click',this.handlers.fabClick,{passive:false});}
|
|
237
|
+
this.handlers.resize=()=>{runtime.scrollMgr.maybeEnableAutoFollowByProximity();runtime.scrollMgr.scheduleScrollFabUpdate();this.highlighter.scheduleScanVisibleCodes(runtime.stream.activeCode);};window.addEventListener('resize',this.handlers.resize,{passive:true});}
|
|
238
|
+
cleanup(){const container=this.dom.get('container');const inputArea=this.dom.get('_append_input_');if(this.handlers.wheel)document.removeEventListener('wheel',this.handlers.wheel);if(this.handlers.scroll)window.removeEventListener('scroll',this.handlers.scroll);if(this.handlers.resize)window.removeEventListener('resize',this.handlers.resize);const fab=this.dom.get('scrollFab');if(fab&&this.handlers.fabClick)fab.removeEventListener('click',this.handlers.fabClick);if(container&&this.handlers.mouseover)container.removeEventListener('mouseover',this.handlers.mouseover);if(container&&this.handlers.mouseout)container.removeEventListener('mouseout',this.handlers.mouseout);if(container&&this.handlers.click)container.removeEventListener('click',this.handlers.click);if(inputArea&&this.handlers.click)inputArea.removeEventListener('click',this.handlers.click);if(this.handlers.keydown)document.removeEventListener('keydown',this.handlers.keydown);if(this.handlers.docClickFocus)document.removeEventListener('click',this.handlers.docClickFocus);if(this.handlers.visibility)document.removeEventListener('visibilitychange',this.handlers.visibility);if(this.handlers.focus)window.removeEventListener('focus',this.handlers.focus);if(this.handlers.pageshow)window.removeEventListener('pageshow',this.handlers.pageshow);this.handlers={};}};
|
|
239
|
+
|
|
240
|
+
/* data/js/app/highlight.js */
|
|
241
|
+
class Highlighter{constructor(cfg,codeScroll,raf){this.cfg=cfg;this.codeScroll=codeScroll;this.raf=raf;this.hlScheduled=false;this.hlQueue=[];this.hlQueueSet=new WeakSet();this.scanScheduled=false;this._activeCodeEl=null;this._globalScanState=null;this.ALIAS={txt:'plaintext',text:'plaintext',plaintext:'plaintext',sh:'bash',shell:'bash',zsh:'bash','shell-session':'bash',py:'python',python3:'python',py3:'python',js:'javascript',node:'javascript',nodejs:'javascript',ts:'typescript','ts-node':'typescript',yml:'yaml',kt:'kotlin',rs:'rust',csharp:'csharp','c#':'csharp','c++':'cpp',ps:'powershell',ps1:'powershell',pwsh:'powershell',powershell7:'powershell',docker:'dockerfile'};const hint=(cfg&&cfg.RAF&&cfg.RAF.FLUSH_BUDGET_MS)?cfg.RAF.FLUSH_BUDGET_MS:7;this.SCAN_STEP_BUDGET_MS=Math.max(3,Math.min(12,hint));}
|
|
242
|
+
_d(tag,data){try{const lg=this.logger||(this.cfg&&this.cfg.logger)||(window.runtime&&runtime.logger)||null;if(!lg||typeof lg.debug!=='function')return;lg.debug_obj("HL",tag,data);}catch(_){}}
|
|
243
|
+
_decodeEntitiesDeep(text,maxPasses=2){if(!text||text.indexOf('&')===-1)return text||'';const ta=Highlighter._decTA||(Highlighter._decTA=document.createElement('textarea'));const decodeOnce=(s)=>{ta.innerHTML=s;return ta.value;};let prev=String(text),cur=decodeOnce(prev),passes=1;while(passes<maxPasses&&cur!==prev){prev=cur;cur=decodeOnce(prev);passes++;}
|
|
244
|
+
return cur;}
|
|
245
|
+
isDisabled(){return!!this.cfg.HL.DISABLE_ALL;}
|
|
246
|
+
initHLJS(){if(this.isDisabled())return;if(typeof hljs!=='undefined'&&hljs){try{hljs.configure({ignoreUnescapedHTML:true});}catch(_){}}}
|
|
247
|
+
_nearViewport(el){const preload=this.cfg.SCAN.PRELOAD_PX;const vh=window.innerHeight||Utils.SE.clientHeight||800;const r=el.getBoundingClientRect();return r.bottom>=-preload&&r.top<=(vh+preload);}
|
|
248
|
+
queue(codeEl,activeCode){if(this.isDisabled())return;if(!codeEl||!codeEl.isConnected)return;if(activeCode&&activeCode.codeEl)this._activeCodeEl=activeCode.codeEl;if(this._activeCodeEl&&codeEl===this._activeCodeEl)return;if(codeEl.getAttribute('data-highlighted')==='yes')return;if(codeEl.dataset&&(codeEl.dataset.hlStreamSuspended==='1'||codeEl.dataset.finalHlSkip==='1'))return;if(!codeEl.closest('.msg-box.msg-bot'))return;if(!this.hlQueueSet.has(codeEl)){this.hlQueueSet.add(codeEl);this.hlQueue.push(codeEl);}
|
|
249
|
+
if(!this.hlScheduled){this.hlScheduled=true;this.raf.schedule('HL:flush',()=>this.flush(),'Highlighter',1);}
|
|
250
|
+
try{const wrap=codeEl.closest('.code-wrapper');const len=wrap?parseInt(wrap.getAttribute('data-code-len')||'0',10):NaN;this._d('queue',{len,hasWrap:!!wrap});}catch(_){}}
|
|
251
|
+
flush(){if(this.isDisabled()){this.hlScheduled=false;this.hlQueueSet.clear();this.hlQueue.length=0;return;}
|
|
252
|
+
this.hlScheduled=false;const activeEl=this._activeCodeEl;let count=0;while(this.hlQueue.length&&count<this.cfg.HL.PER_FRAME){const el=this.hlQueue.shift();if(el&&el.isConnected)this.safeHighlight(el,activeEl);if(el)this.hlQueueSet.delete(el);count++;try{const sched=(navigator&&navigator.scheduling&&navigator.scheduling.isInputPending)?navigator.scheduling:null;if(sched&&sched.isInputPending({includeContinuous:true})){if(this.hlQueue.length){this.hlScheduled=true;this.raf.schedule('HL:flush',()=>this.flush(),'Highlighter',1);}
|
|
253
|
+
this._d('flush.yield',{processed:count,remaining:this.hlQueue.length});return;}}catch(_){}}
|
|
254
|
+
if(this.hlQueue.length){this.hlScheduled=true;this.raf.schedule('HL:flush',()=>this.flush(),'Highlighter',1);}
|
|
255
|
+
this._d('flush.done',{processed:count,remaining:this.hlQueue.length});}
|
|
256
|
+
_needsDeepDecode(text){if(!text)return false;const s=String(text);return(s.indexOf('&')!==-1)||(s.indexOf('&#')!==-1);}
|
|
257
|
+
_decodeEntitiesCheap(s){return s.replaceAll('&','&').replaceAll('<','<').replaceAll('>','>').replaceAll('"','"').replaceAll(''',"'");}
|
|
258
|
+
detachHandlersIfFinal(el){if(this.isFinalizedCode(el))this.detachHandlers(el);}
|
|
259
|
+
microHighlightNow(root,opts,activeCode){if(this.isDisabled())return;const scope=root||document;const options=Object.assign({maxCount:1,budgetMs:4},opts||{});const activeEl=activeCode&&activeCode.codeEl?activeCode.codeEl:null;const maxLines=(this.cfg.HL&&this.cfg.HL.MICRO_MAX_LINES)||Math.min(80,this.cfg.PROFILE_CODE.finalHighlightMaxLines||200);const maxChars=(this.cfg.HL&&this.cfg.HL.MICRO_MAX_CHARS)||Math.min(4000,this.cfg.PROFILE_CODE.finalHighlightMaxChars||20000);const nodes=scope.querySelectorAll('.msg-box.msg-bot pre code:not([data-highlighted="yes"])');const start=Utils.now();let done=0;for(let i=0;i<nodes.length&&done<options.maxCount;i++){const el=nodes[i];if(!el||!el.isConnected)continue;if(activeEl&&el===activeEl)continue;if(!this._nearViewport(el))continue;let lines=NaN,chars=NaN;const wrap=el.closest('.code-wrapper');if(wrap){const nlAttr=wrap.getAttribute('data-code-nl');const lenAttr=wrap.getAttribute('data-code-len');if(nlAttr)lines=parseInt(nlAttr,10);if(lenAttr)chars=parseInt(lenAttr,10);}
|
|
260
|
+
if((Number.isFinite(lines)&&lines>maxLines)||(Number.isFinite(chars)&&chars>maxChars))continue;try{if(window.hljs){hljs.highlightElement(el);el.setAttribute('data-highlighted','yes');this.codeScroll.attachHandlers(el);}}catch(_){}
|
|
261
|
+
done++;if((Utils.now()-start)>=options.budgetMs)break;}
|
|
262
|
+
if(done)this._d('micro.now',{done});}
|
|
263
|
+
safeHighlight(codeEl,activeEl){if(this.isDisabled())return;if(!window.hljs||!codeEl||!codeEl.isConnected)return;if(!codeEl.closest('.msg-box.msg-bot'))return;if(codeEl.getAttribute('data-highlighted')==='yes')return;if(activeEl&&codeEl===activeEl)return;try{const wrap=codeEl.closest('.code-wrapper');const maxLines=this.cfg.PROFILE_CODE.finalHighlightMaxLines|0;const maxChars=this.cfg.PROFILE_CODE.finalHighlightMaxChars|0;let lines=NaN,chars=NaN;if(wrap){const nlAttr=wrap.getAttribute('data-code-nl');const lenAttr=wrap.getAttribute('data-code-len');if(nlAttr)lines=parseInt(nlAttr,10);if(lenAttr)chars=parseInt(lenAttr,10);}
|
|
264
|
+
if((Number.isFinite(lines)&&maxLines>0&&lines>maxLines)||(Number.isFinite(chars)&&maxChars>0&&chars>maxChars)){codeEl.classList.add('hljs');codeEl.setAttribute('data-highlighted','yes');codeEl.dataset.finalHlSkip='1';try{this.codeScroll.attachHandlers(codeEl);}catch(_){}
|
|
265
|
+
this.codeScroll.scheduleScroll(codeEl,false,false);this._d('hl.skip.size',{lines,chars,maxLines,maxChars});return;}}catch(_){}
|
|
266
|
+
const wasNearBottom=this.codeScroll.isNearBottomEl(codeEl,16);const st=this.codeScroll.state(codeEl);const shouldAutoScrollAfter=(st.autoFollow===true)||wasNearBottom;try{hljs.highlightElement(codeEl);codeEl.setAttribute('data-highlighted','yes');}catch(_){if(!codeEl.classList.contains('hljs'))codeEl.classList.add('hljs');}finally{try{this.codeScroll.attachHandlers(codeEl);}catch(_){}
|
|
267
|
+
const needInitForce=(codeEl.dataset&&(codeEl.dataset.csInitBtm==='1'||codeEl.dataset.justFinalized==='1'));const mustScroll=shouldAutoScrollAfter||needInitForce;if(mustScroll)this.codeScroll.scheduleScroll(codeEl,false,!!needInitForce);this.codeScroll.detachHandlers(codeEl);if(codeEl.dataset){if(codeEl.dataset.csInitBtm==='1')codeEl.dataset.csInitBtm='0';if(codeEl.dataset.justFinalized==='1')codeEl.dataset.justFinalized='0';}
|
|
268
|
+
this._d('hl.done',{autoScroll:mustScroll});}}
|
|
269
|
+
_startGlobalScan(activeCode){if(this.isDisabled())return;this._activeCodeEl=(activeCode&&activeCode.codeEl)?activeCode.codeEl:this._activeCodeEl;const preload=this.cfg.SCAN_PRELOAD_PX||this.cfg.SCAN.PRELOAD_PX;const vh=window.innerHeight||Utils.SE.clientHeight||800;const rectTop=0-preload,rectBottom=vh+preload;const nodes=document.querySelectorAll('.msg-box.msg-bot pre code:not([data-highlighted="yes"])');this._globalScanState={nodes,idx:0,rectTop,rectBottom,activeCodeEl:this._activeCodeEl||null};this._d('scan.start',{candidates:nodes.length});this._scanGlobalStep();}
|
|
270
|
+
_scanGlobalStep(){const state=this._globalScanState;if(!state||!state.nodes||state.idx>=state.nodes.length){this._globalScanState=null;this._d('scan.done',{});return;}
|
|
271
|
+
const start=Utils.now();while(state.idx<state.nodes.length){const code=state.nodes[state.idx++];if(!code||!code.isConnected)continue;if(state.activeCodeEl&&code===state.activeCodeEl)continue;try{const r=code.getBoundingClientRect();if(r.bottom>=state.rectTop&&r.top<=state.rectBottom)this.queue(code,null);}catch(_){}
|
|
272
|
+
if((Utils.now()-start)>=this.SCAN_STEP_BUDGET_MS){this.raf.schedule('HL:scanStep',()=>this._scanGlobalStep(),'Highlighter',2);return;}}
|
|
273
|
+
this._globalScanState=null;this._d('scan.step.end',{});}
|
|
274
|
+
observeNewCode(root,opts,activeCode){const scope=root||document;let nodes;if(scope.nodeType===1&&scope.closest&&scope.closest('.msg-box.msg-bot'))nodes=scope.querySelectorAll('pre code');else nodes=document.querySelectorAll('.msg-box.msg-bot pre code');if(!nodes||!nodes.length)return;const options=Object.assign({deferLastIfStreaming:false,minLinesForLast:2,minCharsForLast:120},(opts||{}));nodes.forEach((code)=>{if(!code.closest('.msg-box.msg-bot'))return;this.codeScroll.attachHandlers(code);if(this.isDisabled())return;if(activeCode&&code===activeCode.codeEl)return;if(options.deferLastIfStreaming&&activeCode&&code===activeCode.codeEl){const tailLen=(activeCode.tailEl&&activeCode.tailEl.textContent)?activeCode.tailEl.textContent.length:0;const tailLines=(typeof activeCode.tailLines==='number')?activeCode.tailLines:0;if(tailLines<options.minLinesForLast&&tailLen<options.minCharsForLast)return;}
|
|
275
|
+
if(this._nearViewport(code))this.queue(code,activeCode);});this._d('observe.codes',{count:nodes.length});}
|
|
276
|
+
scheduleScanVisibleCodes(activeCode){if(this.isDisabled())return;try{const anyCandidate=document.querySelector('.msg-box.msg-bot pre code:not([data-highlighted="yes"])');const hasActive=!!(activeCode&&activeCode.codeEl&&activeCode.codeEl.isConnected);if(!anyCandidate&&!hasActive)return;}catch(_){}
|
|
277
|
+
this._activeCodeEl=(activeCode&&activeCode.codeEl)?activeCode.codeEl:this._activeCodeEl;if(this._globalScanState){this.raf.schedule('HL:scanStep',()=>this._scanGlobalStep(),'Highlighter',2);return;}
|
|
278
|
+
if(this.scanScheduled)return;this.scanScheduled=true;this.raf.schedule('HL:scan',()=>{this.scanScheduled=false;this._startGlobalScan(activeCode||null);},'Highlighter',2);this._d('scan.scheduled',{});}
|
|
279
|
+
scanVisibleCodes(activeCode){this._startGlobalScan(activeCode||null);}
|
|
280
|
+
scanVisibleCodesInRoot(root,activeCode){if(this.isDisabled())return;const preload=this.cfg.SCAN_PRELOAD_PX||this.cfg.SCAN.PRELOAD_PX;const vh=window.innerHeight||Utils.SE.clientHeight||800;const rectTop=0-preload,rectBottom=vh+preload;const scope=root||document;const nodes=scope.querySelectorAll('.msg-box.msg-bot pre code:not([data-highlighted="yes"])');nodes.forEach((code)=>{if(!code.isConnected)return;if(activeCode&&code===activeCode.codeEl)return;const r=code.getBoundingClientRect();if(r.bottom>=rectTop&&r.top<=rectBottom)this.queue(code,activeCode);});this._d('scan.root',{count:nodes.length});}
|
|
281
|
+
installBoxObserver(){}
|
|
282
|
+
observeMsgBoxes(root,onBoxIntersect){const scope=root||document;let boxes;if(scope.nodeType===1)boxes=scope.querySelectorAll('.msg-box.msg-bot');else boxes=document.querySelectorAll('.msg-box.msg-bot');boxes.forEach((box)=>{onBoxIntersect&&onBoxIntersect(box);});this._d('observe.boxes',{count:boxes.length});}
|
|
283
|
+
cleanup(){try{this.raf.cancelGroup('Highlighter');}catch(_){}
|
|
284
|
+
this.hlScheduled=false;this.scanScheduled=false;this._globalScanState=null;this._activeCodeEl=null;this.hlQueueSet.clear();this.hlQueue.length=0;this._d('cleanup',{});}};
|
|
285
|
+
|
|
286
|
+
/* data/js/app/logger.js */
|
|
287
|
+
class Logger{constructor(cfg){this.cfg=cfg||{LOG:{}};this.queue=[];this.queueBytes=0;this.armed=false;this.maxTries=480;this.tries=0;this.bridge=null;this._idleId=0;this._lastFlushQueueBytes=0;this.raf=null;this._rafScheduled=false;this._rafKey={t:'Logger:tick'};const L=this.cfg.LOG||{};this.MAX_QUEUE=Utils.g('LOG_MAX_QUEUE',L.MAX_QUEUE??400);this.MAX_BYTES=Utils.g('LOG_MAX_BYTES',L.MAX_BYTES??256*1024);this.BATCH_MAX=Utils.g('LOG_BATCH_MAX',L.BATCH_MAX??64);this.RATE_LIMIT_PER_SEC=Utils.g('LOG_RATE_LIMIT_PER_SEC',L.RATE_LIMIT_PER_SEC??0);this._rlWindowMs=1000;this._rlCount=0;this._rlWindowStart=Utils.now();}
|
|
288
|
+
bindBridge(bridge){this.bridge=bridge||null;this.flush();}
|
|
289
|
+
bindRaf(raf){this.raf=raf||null;}
|
|
290
|
+
isEnabled(ns){if(!ns)return!!(window.STREAM_DEBUG||window.MD_LANG_DEBUG);const key1=ns+'_DEBUG';const key2=ns.toUpperCase()+'_DEBUG';return!!(window[key1]||window[key2]||window.STREAM_DEBUG||window.MD_LANG_DEBUG);}
|
|
291
|
+
pv(s,n=120){if(!s)return'';s=String(s);if(s.length<=n)return s.replace(/\n/g,'\\n');const k=Math.floor(n/2);return(s.slice(0,k)+' … '+s.slice(-k)).replace(/\n/g,'\\n');}
|
|
292
|
+
j(o){try{return JSON.stringify(o);}catch(_){try{return String(o);}catch(__){return'[unserializable]';}}}
|
|
293
|
+
_emit(msg){try{if(this.bridge){if(typeof this.bridge.log_batch==='function'){this.bridge.log_batch([String(msg)]);return true;}
|
|
294
|
+
if(typeof this.bridge.logBatch==='function'){this.bridge.logBatch([String(msg)]);return true;}
|
|
295
|
+
if(typeof this.bridge.log==='function'){this.bridge.log(String(msg));return true;}}
|
|
296
|
+
if(window.runtime&&runtime.bridge&&typeof runtime.bridge.log==='function'){runtime.bridge.log(String(msg));return true;}}catch(_){}
|
|
297
|
+
return false;}
|
|
298
|
+
_emitBatch(arr){try{if(!arr||!arr.length)return 0;if(this.bridge&&typeof this.bridge.log_batch==='function'){this.bridge.log_batch(arr.map(String));return arr.length;}
|
|
299
|
+
if(this.bridge&&typeof this.bridge.logBatch==='function'){this.bridge.logBatch(arr.map(String));return arr.length;}
|
|
300
|
+
if(this.bridge&&typeof this.bridge.log==='function'){for(let i=0;i<arr.length;i++)this.bridge.log(String(arr[i]));return arr.length;}}catch(_){}
|
|
301
|
+
return 0;}
|
|
302
|
+
_maybeDropForCaps(len){if(this.queue.length<=this.MAX_QUEUE&&this.queueBytes<=this.MAX_BYTES)return;const targetLen=Math.floor(this.MAX_QUEUE*0.8);const targetBytes=Math.floor(this.MAX_BYTES*0.8);while((this.queue.length>targetLen||this.queueBytes>targetBytes)&&this.queue.length){const removed=this.queue.shift();this.queueBytes-=(removed?removed.length*2:0);}
|
|
303
|
+
const notice='[LOGGER] queue trimmed due to caps';this.queue.unshift(notice);this.queueBytes+=notice.length*2;}
|
|
304
|
+
_passRateLimit(){if(!this.RATE_LIMIT_PER_SEC||this.RATE_LIMIT_PER_SEC<=0)return true;const now=Utils.now();if(now-this._rlWindowStart>this._rlWindowMs){this._rlWindowStart=now;this._rlCount=0;}
|
|
305
|
+
if(this._rlCount>=this.RATE_LIMIT_PER_SEC)return false;return true;}
|
|
306
|
+
log(text){const msg=String(text);if(this.bridge&&(typeof this.bridge.log==='function'||typeof this.bridge.log_batch==='function'||typeof this.bridge.logBatch==='function')){if(this._passRateLimit()){const ok=this._emit(msg);if(ok)return true;}}
|
|
307
|
+
this.queue.push(msg);this.queueBytes+=msg.length*2;this._maybeDropForCaps(msg.length);this._arm();return false;}
|
|
308
|
+
debug(ns,line,ctx){if(!this.isEnabled(ns))return false;let msg=`[${ns}] ${line || ''}`;if(typeof ctx!=='undefined')msg+=' '+this.j(ctx);return this.log(msg);}
|
|
309
|
+
debug_obj(ns,tag,data){try{const lg=this.logger||(this.cfg&&this.cfg.logger)||(window.runtime&&runtime.logger)||null;if(!this.isEnabled(ns))return false;const safeJson=(v)=>{try{const seen=new WeakSet();const s=JSON.stringify(v,(k,val)=>{if(typeof val==='object'&&val!==null){if(val.nodeType){const nm=(val.nodeName||val.tagName||'DOM').toString();return`[DOM ${nm}]`;}
|
|
310
|
+
if(seen.has(val))return'[Circular]';seen.add(val);}
|
|
311
|
+
if(typeof val==='string'&&val.length>800)return val.slice(0,800)+'…';return val;});return s;}catch(_){try{return String(v);}catch{return'';}}};let line=String(tag||'');if(typeof data!=='undefined'){const payload=safeJson(data);if(payload&&payload!=='""')line+=' '+payload;}
|
|
312
|
+
this.debug(ns,line);}catch(_){}}
|
|
313
|
+
flush(maxPerTick=this.BATCH_MAX){if(!this.bridge&&!(window.runtime&&runtime.bridge&&typeof runtime.bridge.log==='function'))return 0;const n=Math.min(maxPerTick,this.queue.length);if(!n)return 0;const batch=this.queue.splice(0,n);let bytes=0;for(let i=0;i<batch.length;i++)bytes+=batch[i].length*2;this.queueBytes=Math.max(0,this.queueBytes-bytes);const sent=this._emitBatch(batch);if(sent<batch.length){const remain=batch.slice(sent);let remBytes=0;for(let i=0;i<remain.length;i++)remBytes+=remain[i].length*2;for(let i=remain.length-1;i>=0;i--)this.queue.unshift(remain[i]);this.queueBytes+=remBytes;}
|
|
314
|
+
return sent;}
|
|
315
|
+
_scheduleTick(tick){const preferIdle=!this.bridge;const scheduleIdle=()=>{try{if(this._idleId)Utils.cancelIdle(this._idleId);}catch(_){}
|
|
316
|
+
this._idleId=Utils.idle(()=>{this._idleId=0;tick();},800);};if(preferIdle){scheduleIdle();return;}
|
|
317
|
+
if(this._rafScheduled)return;this._rafScheduled=true;const run=()=>{this._rafScheduled=false;tick();};try{if(this.raf&&typeof this.raf.schedule==='function'){this.raf.schedule(this._rafKey,run,'Logger',3);}else if(typeof runtime!=='undefined'&&runtime.raf&&typeof runtime.raf.schedule==='function'){runtime.raf.schedule(this._rafKey,run,'Logger',3);}else{Promise.resolve().then(run);}}catch(_){Promise.resolve().then(run);}}
|
|
318
|
+
_arm(){if(this.armed)return;this.armed=true;this.tries=0;const tick=()=>{if(!this.armed)return;this.flush();this.tries++;if(this.queue.length===0||this.tries>this.maxTries){this.armed=false;try{if(this._idleId)Utils.cancelIdle(this._idleId);}catch(_){}
|
|
319
|
+
this._idleId=0;return;}
|
|
320
|
+
this._scheduleTick(tick);};this._scheduleTick(tick);}};
|
|
321
|
+
|
|
322
|
+
/* data/js/app/markdown.js */
|
|
323
|
+
class MarkdownRenderer{constructor(cfg,customMarkup,logger,asyncer,raf){this.cfg=cfg;this.customMarkup=customMarkup;this.MD=null;this.logger=logger||new Logger(cfg);this.asyncer=asyncer||new AsyncRunner(cfg,raf);this.raf=raf||null;this.MD_STREAM=null;this.hooks={observeNewCode:()=>{},observeMsgBoxes:()=>{},scheduleMathRender:()=>{},codeScrollInit:()=>{}};this._codeByEnv=new WeakMap();this._codeSeq=0;this._inited=false;}
|
|
324
|
+
_d(tag,data){try{const lg=this.logger||(this.cfg&&this.cfg.logger)||(window.runtime&&runtime.logger)||null;if(!lg||typeof lg.debug!=='function')return;lg.debug_obj("MD",tag,data);}catch(_){}}
|
|
325
|
+
_regCode(env,content){if(!env)env=(this._tmpEnv||(this._tmpEnv={}));let m=this._codeByEnv.get(env);if(!m){m=new Map();this._codeByEnv.set(env,m);}
|
|
326
|
+
const id=`c${++this._codeSeq}`;m.set(id,content);this._d('code.reg',{id,len:(content||'').length});return id;}
|
|
327
|
+
_resolveCodesIn(root,env){const m=this._codeByEnv.get(env);if(!m||!root)return;let count=0;root.querySelectorAll('code[data-code-id]').forEach(el=>{const id=el.getAttribute('data-code-id');const s=m.get(id);if(s!=null){if(!el.firstChild)el.textContent=s;el.removeAttribute('data-code-id');m.delete(id);count++;}});if(count)this._d('code.resolve',{count});}
|
|
328
|
+
_releaseEnvCodes(env){this._codeByEnv.delete(env);}
|
|
329
|
+
init(){if(this._inited)return;if(!window.markdownit){this._d('init.skip',{reason:'no-markdownit'});return;}
|
|
330
|
+
this._inited=true;this.MD=window.markdownit({html:false,linkify:true,breaks:true,highlight:()=>''});this.MD_STREAM=window.markdownit({html:false,linkify:false,breaks:true,highlight:()=>''});const installLinkValidator=(md)=>{const orig=(md&&typeof md.validateLink==='function')?md.validateLink.bind(md):null;md.validateLink=(url)=>{try{const s=String(url||'').trim().toLowerCase();if(s.startsWith('file:'))return true;if(s.startsWith('qrc:'))return true;if(s.startsWith('bridge:'))return true;if(s.startsWith('blob:'))return true;if(s.startsWith('data:image/'))return true;}catch(_){}
|
|
331
|
+
return orig?orig(url):true;};};installLinkValidator(this.MD);installLinkValidator(this.MD_STREAM);if(!this.cfg.MD||this.cfg.MD.ALLOW_INDENTED_CODE!==true){try{this.MD.block.ruler.disable('code');}catch(_){}
|
|
332
|
+
try{this.MD_STREAM.block.ruler.disable('code');}catch(_){}}
|
|
333
|
+
const escapeHtml=Utils.escapeHtml;const mathDollarPlaceholderPlugin=(md)=>{function notEscaped(src,pos){let back=0;while(pos-back-1>=0&&src.charCodeAt(pos-back-1)===0x5C)back++;return(back%2)===0;}
|
|
334
|
+
function math_block_dollar(state,startLine,endLine,silent){const pos=state.bMarks[startLine]+state.tShift[startLine];const max=state.eMarks[startLine];if(pos+1>=max)return false;if(state.src.charCodeAt(pos)!==0x24||state.src.charCodeAt(pos+1)!==0x24)return false;let nextLine=startLine+1,found=false;for(;nextLine<endLine;nextLine++){let p=state.bMarks[nextLine]+state.tShift[nextLine];const pe=state.eMarks[nextLine];if(p+1<pe&&state.src.charCodeAt(p)===0x24&&state.src.charCodeAt(p+1)===0x24){found=true;break;}}
|
|
335
|
+
if(!found)return false;if(silent)return true;const contentStart=state.bMarks[startLine]+state.tShift[startLine]+2;const contentEndLine=nextLine-1;let content='';if(contentEndLine>=startLine+1){const startIdx=state.bMarks[startLine+1];const endIdx=state.eMarks[contentEndLine];content=state.src.slice(startIdx,endIdx);}
|
|
336
|
+
const token=state.push('math_block_dollar','',0);token.block=true;token.content=content;state.line=nextLine+1;return true;}
|
|
337
|
+
function math_inline_dollar(state,silent){const pos=state.pos,src=state.src,max=state.posMax;if(pos>=max)return false;if(src.charCodeAt(pos)!==0x24)return false;if(pos+1<max&&src.charCodeAt(pos+1)===0x24)return false;const after=pos+1<max?src.charCodeAt(pos+1):0;if(after===0x20||after===0x0A||after===0x0D)return false;let i=pos+1;while(i<max){const ch=src.charCodeAt(i);if(ch===0x24&¬Escaped(src,i)){const before=i-1>=0?src.charCodeAt(i-1):0;if(before===0x20||before===0x0A||before===0x0D){i++;continue;}
|
|
338
|
+
break;}
|
|
339
|
+
i++;}
|
|
340
|
+
if(i>=max||src.charCodeAt(i)!==0x24)return false;if(!silent){const token=state.push('math_inline_dollar','',0);token.block=false;token.content=src.slice(pos+1,i);}
|
|
341
|
+
state.pos=i+1;return true;}
|
|
342
|
+
md.block.ruler.before('fence','math_block_dollar',math_block_dollar,{alt:['paragraph','reference','blockquote','list']});md.inline.ruler.before('escape','math_inline_dollar',math_inline_dollar);md.renderer.rules.math_inline_dollar=(tokens,idx)=>{const tex=tokens[idx].content||'';return`<span class="math-pending" data-display="0"><span class="math-fallback">$${escapeHtml(tex)}$</span><script type="math/tex">${escapeHtml(tex)}</script></span>`;};md.renderer.rules.math_block_dollar=(tokens,idx)=>{const tex=tokens[idx].content||'';return`<div class="math-pending" data-display="1"><div class="math-fallback">$$${escapeHtml(tex)}$$</div><script type="math/tex; mode=display">${escapeHtml(tex)}</script></div>`;};};const mathBracketsPlaceholderPlugin=(md)=>{function math_brackets(state,silent){const src=state.src,pos=state.pos,max=state.posMax;if(pos+1>=max||src.charCodeAt(pos)!==0x5C)return false;const next=src.charCodeAt(pos+1);if(next!==0x28&&next!==0x5B)return false;const isInline=(next===0x28);const close=isInline?'\\)':'\\]';const start=pos+2;const end=src.indexOf(close,start);if(end<0)return false;const content=src.slice(start,end);if(!silent){const t=state.push(isInline?'math_inline_bracket':'math_block_bracket','',0);t.content=content;t.block=!isInline;}
|
|
343
|
+
state.pos=end+2;return true;}
|
|
344
|
+
md.inline.ruler.before('escape','math_brackets',math_brackets);md.renderer.rules.math_inline_bracket=(tokens,idx)=>{const tex=tokens[idx].content||'';return`<span class="math-pending" data-display="0"><span class="math-fallback">\\(${escapeHtml(tex)}\\)</span><script type="math/tex">${escapeHtml(tex)}</script></span>`;};md.renderer.rules.math_block_bracket=(tokens,idx)=>{const tex=tokens[idx].content||'';return`<div class="math-pending" data-display="1"><div class="math-fallback">\\${'['}${escapeHtml(tex)}\\${']'}</div><script type="math/tex; mode=display">${escapeHtml(tex)}</script></div>`;};};this.MD.use(mathDollarPlaceholderPlugin);this.MD.use(mathBracketsPlaceholderPlugin);this.MD_STREAM.use(mathDollarPlaceholderPlugin);this.MD_STREAM.use(mathBracketsPlaceholderPlugin);const cfg=this.cfg;const logger=this.logger;(function codeWrapperPlugin(md,logger,renderer){let CODE_IDX=1;const ALIAS={txt:'plaintext',text:'plaintext',plaintext:'plaintext',sh:'bash',shell:'bash',zsh:'bash','shell-session':'bash',py:'python',python3:'python',py3:'python',js:'javascript',node:'javascript',nodejs:'javascript',ts:'typescript','ts-node':'typescript',yml:'yaml',kt:'kotlin',rs:'rust',csharp:'csharp','c#':'csharp','c++':'cpp',ps:'powershell',ps1:'powershell',pwsh:'powershell',powershell7:'powershell',docker:'dockerfile'};function normLang(s){if(!s)return'';const v=String(s).trim().toLowerCase();return ALIAS[v]||v;}
|
|
345
|
+
function isSupportedByHLJS(lang){try{return!!(window.hljs&&hljs.getLanguage&&hljs.getLanguage(lang));}catch(_){return false;}}
|
|
346
|
+
function classForHighlight(lang){if(!lang)return'plaintext';return isSupportedByHLJS(lang)?lang:'plaintext';}
|
|
347
|
+
function stripBOM(s){return(s&&s.charCodeAt(0)===0xFEFF)?s.slice(1):s;}
|
|
348
|
+
function normForFP(s){if(!s)return'';let t=String(s);if(t.charCodeAt(0)===0xFEFF)t=t.slice(1);t=t.replace(/\r\n?/g,'\n');if(t.endsWith('\n'))t=t.slice(0,-1);return t;}
|
|
349
|
+
function hash32FNV(str){let h=0x811c9dc5>>>0;for(let i=0;i<str.length;i++){h^=str.charCodeAt(i);h=(h+((h<<1)+(h<<4)+(h<<7)+(h<<8)+(h<<24)))>>>0;}
|
|
350
|
+
return('00000000'+h.toString(16)).slice(-8);}
|
|
351
|
+
function makeStableFP(langToken,rawContent){const norm=normForFP(rawContent||'');return`${langToken || 'plaintext'}|${norm.length}|${hash32FNV(norm)}`;}
|
|
352
|
+
function detectFromFirstLine(raw,rid){if(!raw)return{lang:'',content:raw,isOutput:false};const lines=raw.split(/\r?\n/);if(!lines.length)return{lang:'',content:raw,isOutput:false};let i=0;while(i<lines.length&&!lines[i].trim())i++;if(i>=lines.length)return{lang:'',content:raw,isOutput:false};let first=stripBOM(lines[i]).trim();first=first.replace(/^\s*lang(?:uage)?\s*[:=]\s*/i,'').trim();let token=first.split(/\s+/)[0].replace(/:$/,'');if(!/^[A-Za-z][\w#+\-\.]{0,30}$/.test(token))return{lang:'',content:raw,isOutput:false};let cand=normLang(token);if(cand==='output'){const content=lines.slice(i+1).join('\n');return{lang:'python',headerLabel:'output',content,isOutput:true};}
|
|
353
|
+
const rest=lines.slice(i+1).join('\n');if(!rest.trim())return{lang:'',content:raw,isOutput:false};return{lang:cand,headerLabel:cand,content:rest,isOutput:false};}
|
|
354
|
+
function resolveLanguageAndContent(info,raw,rid){const infoLangRaw=(info||'').trim().split(/\s+/)[0]||'';let cand=normLang(infoLangRaw);const shortOrUnsupported=!cand||cand.length<3||!isSupportedByHLJS(cand);if(cand==='output'){return{lang:'python',headerLabel:'output',content:raw,isOutput:true};}
|
|
355
|
+
if(!shortOrUnsupported){return{lang:cand,headerLabel:cand,content:raw,isOutput:false};}
|
|
356
|
+
const det=detectFromFirstLine(raw,rid);if(det&&(det.lang||det.isOutput))return det;return{lang:'',headerLabel:'code',content:raw,isOutput:false};}
|
|
357
|
+
md.renderer.rules.fence=(tokens,idx,options,env)=>renderFence(tokens[idx],env);md.renderer.rules.code_block=(tokens,idx,options,env)=>renderFence({info:'',content:tokens[idx].content||''},env);function renderFence(token,env){const rendererRef=renderer||(window.runtime&&window.runtime.renderer)||null;const raw=token.content||'';const rid=String(CODE_IDX+'');const res=resolveLanguageAndContent(token.info||'',raw,rid);const isOutput=!!res.isOutput;const rawToken=(res.lang||'').trim();const langClass=isOutput?'python':classForHighlight(rawToken);let headerLabel=isOutput?'output':(res.headerLabel||(rawToken||'code'));if(!isOutput){if(rawToken&&!isSupportedByHLJS(rawToken)&&rawToken.length<3)headerLabel='code';}
|
|
358
|
+
const content=res.content||'';const len=content.length;const head=content.slice(0,64);const tail=content.slice(-64);const headEsc=Utils.escapeHtml(head);const tailEsc=Utils.escapeHtml(tail);const nl=Utils.countNewlines(content);const fpStable=makeStableFP(langClass,content);const idxLocal=CODE_IDX++;let actions='';if(langClass==='html'){actions+=`<a href="empty:${idxLocal}" class="code-header-action code-header-preview"><img src="${cfg.ICONS.CODE_PREVIEW}" class="action-img" data-id="${idxLocal}"><span>${Utils.escapeHtml(cfg.LOCALE.PREVIEW)}</span></a>`;}else if(langClass==='python'&&headerLabel!=='output'){actions+=`<a href="empty:${idxLocal}" class="code-header-action code-header-run"><img src="${cfg.ICONS.CODE_RUN}" class="action-img" data-id="${idxLocal}"><span>${Utils.escapeHtml(cfg.LOCALE.RUN)}</span></a>`;}
|
|
359
|
+
actions+=`<a href="empty:${idxLocal}" class="code-header-action code-header-collapse" title="${Utils.escapeHtml(cfg.LOCALE.COLLAPSE)}"><img src="${cfg.ICONS.CODE_MENU}" class="action-img" data-id="${idxLocal}"></a>`;actions+=`<a href="empty:${idxLocal}" class="code-header-action code-header-copy" title="${Utils.escapeHtml(cfg.LOCALE.COPY)}"><img src="${cfg.ICONS.CODE_COPY}" class="action-img" data-id="${idxLocal}"></a>`;const canUseRegistry=!!(rendererRef&&typeof rendererRef._regCode==='function'&&env);if(canUseRegistry){const codeId=rendererRef._regCode(env,content);rendererRef._d&&rendererRef._d('fence.stream',{idxLocal,lang:langClass,headerLabel,len});return(`<div class="code-wrapper highlight" data-index="${idxLocal}"`+` data-code-lang="${Utils.escapeHtml(res.lang || '')}"`+` data-code-len="${String(len)}" data-code-head="${headEsc}" data-code-tail="${tailEsc}" data-code-nl="${String(nl)}"`+` data-fp="${Utils.escapeHtml(fpStable)}"`+` data-locale-collapse="${Utils.escapeHtml(cfg.LOCALE.COLLAPSE)}" data-locale-expand="${Utils.escapeHtml(cfg.LOCALE.EXPAND)}"`+` data-locale-copy="${Utils.escapeHtml(cfg.LOCALE.COPY)}" data-locale-copied="${Utils.escapeHtml(cfg.LOCALE.COPIED)}" data-style="${Utils.escapeHtml(cfg.CODE_STYLE)}">`+`<p class="code-header-wrapper"><span><span class="code-header-lang">${Utils.escapeHtml(headerLabel)} </span>${actions}</span></p>`+`<pre><code class="language-${Utils.escapeHtml(langClass)} hljs" data-code-id="${String(codeId)}"></code></pre>`+`</div>`);}
|
|
360
|
+
rendererRef&&rendererRef._d&&rendererRef._d('fence.stream.fallback',{idxLocal,lang:langClass,len});return(`<div class="code-wrapper highlight" data-index="${idxLocal}"`+` data-code-lang="${Utils.escapeHtml(res.lang || '')}"`+` data-code-len="${String(len)}" data-code-head="${headEsc}" data-code-tail="${tailEsc}" data-code-nl="${String(nl)}"`+` data-fp="${Utils.escapeHtml(fpStable)}"`+` data-locale-collapse="${Utils.escapeHtml(cfg.LOCALE.COLLAPSE)}" data-locale-expand="${Utils.escapeHtml(cfg.LOCALE.EXPAND)}"`+` data-locale-copy="${Utils.escapeHtml(cfg.LOCALE.COPY)}" data-locale-copied="${Utils.escapeHtml(cfg.LOCALE.COPIED)}" data-style="${Utils.escapeHtml(cfg.CODE_STYLE)}">`+`<p class="code-header-wrapper"><span><span class="code-header-lang">${Utils.escapeHtml(headerLabel)} </span>${actions}</span></p>`+`<pre><code class="language-${Utils.escapeHtml(langClass)} hljs">${Utils.escapeHtml(content)}</code></pre>`+`</div>`);}})(this.MD_STREAM,this.logger,this);(function codeWrapperPlugin(md,logger,renderer){let CODE_IDX=1;const ALIAS={txt:'plaintext',text:'plaintext',plaintext:'plaintext',sh:'bash',shell:'bash',zsh:'bash','shell-session':'bash',py:'python',python3:'python',py3:'python',js:'javascript',node:'javascript',nodejs:'javascript',ts:'typescript','ts-node':'typescript',yml:'yaml',kt:'kotlin',rs:'rust',csharp:'csharp','c#':'csharp','c++':'cpp',ps:'powershell',ps1:'powershell',pwsh:'powershell',powershell7:'powershell',docker:'dockerfile'};function normLang(s){if(!s)return'';const v=String(s).trim().toLowerCase();return ALIAS[v]||v;}
|
|
361
|
+
function isSupportedByHLJS(lang){try{return!!(window.hljs&&hljs.getLanguage&&hljs.getLanguage(lang));}catch(_){return false;}}
|
|
362
|
+
function classForHighlight(lang){if(!lang)return'plaintext';return isSupportedByHLJS(lang)?lang:'plaintext';}
|
|
363
|
+
function stripBOM(s){return(s&&s.charCodeAt(0)===0xFEFF)?s.slice(1):s;}
|
|
364
|
+
function normForFP(s){if(!s)return'';let t=String(s);if(t.charCodeAt(0)===0xFEFF)t=t.slice(1);t=t.replace(/\r\n?/g,'\n');if(t.endsWith('\n'))t=t.slice(0,-1);return t;}
|
|
365
|
+
function hash32FNV(str){let h=0x811c9dc5>>>0;for(let i=0;i<str.length;i++){h^=str.charCodeAt(i);h=(h+((h<<1)+(h<<4)+(h<<7)+(h<<8)+(h<<24)))>>>0;}
|
|
366
|
+
return('00000000'+h.toString(16)).slice(-8);}
|
|
367
|
+
function makeStableFP(langToken,rawContent){const norm=normForFP(rawContent||'');return`${langToken || 'plaintext'}|${norm.length}|${hash32FNV(norm)}`;}
|
|
368
|
+
function detectFromFirstLine(raw,rid){if(!raw)return{lang:'',content:raw,isOutput:false};const lines=raw.split(/\r?\n/);if(!lines.length)return{lang:'',content:raw,isOutput:false};let i=0;while(i<lines.length&&!lines[i].trim())i++;if(i>=lines.length)return{lang:'',content:raw,isOutput:false};let first=stripBOM(lines[i]).trim();first=first.replace(/^\s*lang(?:uage)?\s*[:=]\s*/i,'').trim();let token=first.split(/\s+/)[0].replace(/:$/,'');if(!/^[A-Za-z][\w#+\-\.]{0,30}$/.test(token))return{lang:'',content:raw,isOutput:false};let cand=normLang(token);if(cand==='output'){const content=lines.slice(i+1).join('\n');return{lang:'python',headerLabel:'output',content,isOutput:true};}
|
|
369
|
+
const rest=lines.slice(i+1).join('\n');if(!rest.trim())return{lang:'',content:raw,isOutput:false};return{lang:cand,headerLabel:cand,content:rest,isOutput:false};}
|
|
370
|
+
function resolveLanguageAndContent(info,raw,rid){const infoLangRaw=(info||'').trim().split(/\s+/)[0]||'';let cand=normLang(infoLangRaw);const shortOrUnsupported=!cand||cand.length<3||!isSupportedByHLJS(cand);if(cand==='output'){return{lang:'python',headerLabel:'output',content:raw,isOutput:true};}
|
|
371
|
+
if(!shortOrUnsupported){return{lang:cand,headerLabel:cand,content:raw,isOutput:false};}
|
|
372
|
+
const det=detectFromFirstLine(raw,rid);if(det&&(det.lang||det.isOutput))return det;return{lang:'',headerLabel:'code',content:raw,isOutput:false};}
|
|
373
|
+
md.renderer.rules.fence=(tokens,idx,options,env,slf)=>renderFence(tokens[idx],env);md.renderer.rules.code_block=(tokens,idx,options,env,slf)=>renderFence({info:'',content:tokens[idx].content||''},env);function renderFence(token,env){const rendererRef=renderer||(window.runtime&&window.runtime.renderer)||null;const raw=token.content||'';const rid=String(CODE_IDX+'');const res=resolveLanguageAndContent(token.info||'',raw,rid);const isOutput=!!res.isOutput;const rawToken=(res.lang||'').trim();const langClass=isOutput?'python':classForHighlight(rawToken);let headerLabel=isOutput?'output':(res.headerLabel||(rawToken||'code'));if(!isOutput){if(rawToken&&!isSupportedByHLJS(rawToken)&&rawToken.length<3)headerLabel='code';}
|
|
374
|
+
const content=res.content||'';const len=content.length;const head=content.slice(0,64);const tail=content.slice(-64);const headEsc=Utils.escapeHtml(head);const tailEsc=Utils.escapeHtml(tail);const nl=Utils.countNewlines(content);const fpStable=makeStableFP(langClass,content);const idxLocal=CODE_IDX++;let actions='';if(langClass==='html'){actions+=`<a href="empty:${idxLocal}" class="code-header-action code-header-preview"><img src="${cfg.ICONS.CODE_PREVIEW}" class="action-img" data-id="${idxLocal}"><span>${Utils.escapeHtml(cfg.LOCALE.PREVIEW)}</span></a>`;}else if(langClass==='python'&&headerLabel!=='output'){actions+=`<a href="empty:${idxLocal}" class="code-header-action code-header-run"><img src="${cfg.ICONS.CODE_RUN}" class="action-img" data-id="${idxLocal}"><span>${Utils.escapeHtml(cfg.LOCALE.RUN)}</span></a>`;}
|
|
375
|
+
actions+=`<a href="empty:${idxLocal}" class="code-header-action code-header-collapse" title="${Utils.escapeHtml(cfg.LOCALE.COLLAPSE)}"><img src="${cfg.ICONS.CODE_MENU}" class="action-img" data-id="${idxLocal}"></a>`;actions+=`<a href="empty:${idxLocal}" class="code-header-action code-header-copy" title="${Utils.escapeHtml(cfg.LOCALE.COPY)}"><img src="${cfg.ICONS.CODE_COPY}" class="action-img" data-id="${idxLocal}"></a>`;const canUseRegistry=!!(rendererRef&&typeof rendererRef._regCode==='function'&&env);if(canUseRegistry){const codeId=rendererRef._regCode(env,content);rendererRef._d&&rendererRef._d('fence.full',{idxLocal,lang:langClass,headerLabel,len});return(`<div class="code-wrapper highlight" data-index="${idxLocal}"`+` data-code-lang="${Utils.escapeHtml(res.lang || '')}"`+` data-code-len="${String(len)}" data-code-head="${headEsc}" data-code-tail="${tailEsc}" data-code-nl="${String(nl)}" data-fp="${Utils.escapeHtml(fpStable)}"`+` data-locale-collapse="${Utils.escapeHtml(cfg.LOCALE.COLLAPSE)}" data-locale-expand="${Utils.escapeHtml(cfg.LOCALE.EXPAND)}"`+` data-locale-copy="${Utils.escapeHtml(cfg.LOCALE.COPY)}" data-locale-copied="${Utils.escapeHtml(cfg.LOCALE.COPIED)}" data-style="${Utils.escapeHtml(cfg.CODE_STYLE)}">`+`<p class="code-header-wrapper"><span><span class="code-header-lang">${Utils.escapeHtml(headerLabel)} </span>${actions}</span></p>`+`<pre><code class="language-${Utils.escapeHtml(langClass)} hljs" data-code-id="${String(codeId)}"></code></pre>`+`</div>`);}
|
|
376
|
+
rendererRef&&rendererRef._d&&rendererRef._d('fence.full.fallback',{idxLocal,lang:langClass,len});const inner=Utils.escapeHtml(content);return(`<div class="code-wrapper highlight" data-index="${idxLocal}"`+` data-code-lang="${Utils.escapeHtml(res.lang || '')}"`+` data-code-len="${String(len)}" data-code-head="${headEsc}" data-code-tail="${tailEsc}" data-code-nl="${String(nl)}" data-fp="${Utils.escapeHtml(fpStable)}"`+` data-locale-collapse="${Utils.escapeHtml(cfg.LOCALE.COLLAPSE)}" data-locale-expand="${Utils.escapeHtml(cfg.LOCALE.EXPAND)}"`+` data-locale-copy="${Utils.escapeHtml(cfg.LOCALE.COPY)}" data-locale-copied="${Utils.escapeHtml(cfg.LOCALE.COPIED)}" data-style="${Utils.escapeHtml(cfg.CODE_STYLE)}">`+`<p class="code-header-wrapper"><span><span class="code-header-lang">${Utils.escapeHtml(headerLabel)} </span>${actions}</span></p>`+`<pre><code class="language-${Utils.escapeHtml(langClass)} hljs">${inner}</code></pre>`+`</div>`);}})(this.MD,this.logger,this);this._d('init.done',{});}
|
|
377
|
+
preprocessMD(s){const out=(s||'').replace(/\]\(sandbox:/g,'](file://');if(out!==s)this._d('md.preprocess',{replaced:true});return out;}
|
|
378
|
+
b64ToUtf8(b64){const bin=atob(b64);const bytes=new Uint8Array(bin.length);for(let i=0;i<bin.length;i++)bytes[i]=bin.charCodeAt(i);return Utils.utf8Decode(bytes);}
|
|
379
|
+
applyCustomMarkupForBots(root){const MD=this.MD;try{const scope=root||document;const targets=[];if(scope&&scope.nodeType===1&&scope.classList&&scope.classList.contains('msg-box')&&scope.classList.contains('msg-bot')){targets.push(scope);}
|
|
380
|
+
if(scope&&typeof scope.querySelectorAll==='function'){const list=scope.querySelectorAll('.msg-box.msg-bot');for(let i=0;i<list.length;i++)targets.push(list[i]);}
|
|
381
|
+
if(scope&&scope.nodeType===1&&typeof scope.closest==='function'){const closestMsg=scope.closest('.msg-box.msg-bot');if(closestMsg)targets.push(closestMsg);}
|
|
382
|
+
const seen=new Set();for(const el of targets){if(!el||!el.isConnected||seen.has(el))continue;seen.add(el);this.customMarkup.apply(el,MD);}
|
|
383
|
+
this._d('cm.applyBots',{count:seen.size});}catch(_){}}
|
|
384
|
+
_md(streamingHint){return streamingHint?(this.MD_STREAM||this.MD):(this.MD||this.MD_STREAM);}
|
|
385
|
+
async renderPendingMarkdown(root){const MD=this.MD;if(!MD)return;const scope=root||document;const nodes=Array.from(scope.querySelectorAll('[data-md64], [md-block-markdown]'));if(nodes.length===0){try{const hasBots=!!(scope&&scope.querySelector&&scope.querySelector('.msg-box.msg-bot'));const hasWrappers=!!(scope&&scope.querySelector&&scope.querySelector('.code-wrapper'));const hasCodes=!!(scope&&scope.querySelector&&scope.querySelector('.msg-box.msg-bot pre code'));const hasUnhighlighted=!!(scope&&scope.querySelector&&scope.querySelector('.msg-box.msg-bot pre code:not([data-highlighted="yes"])'));const hasMath=!!(scope&&scope.querySelector&&scope.querySelector('script[type^="math/tex"]'));if(hasBots)this.applyCustomMarkupForBots(scope);if(hasWrappers)this.restoreCollapsedCode(scope);this.hooks.codeScrollInit(scope);if(hasCodes){this.hooks.observeMsgBoxes(scope);this.hooks.observeNewCode(scope,{deferLastIfStreaming:true,minLinesForLast:this.cfg.PROFILE_CODE.minLinesForHL,minCharsForLast:this.cfg.PROFILE_CODE.minCharsForHL});if(hasUnhighlighted&&typeof runtime!=='undefined'&&runtime.highlighter){runtime.highlighter.scanVisibleCodesInRoot(scope,runtime.stream.activeCode||null);}}
|
|
386
|
+
if(hasMath)this.hooks.scheduleMathRender(scope);}catch(_){}
|
|
387
|
+
return;}
|
|
388
|
+
this._d('md.pending.start',{nodes:nodes.length});const touchedBoxes=new Set();const perSlice=(this.cfg.ASYNC&&this.cfg.ASYNC.MD_NODES_PER_SLICE)||12;let sliceCount=0;let startedAt=Utils.now();for(let j=0;j<nodes.length;j++){const el=nodes[j];if(!el||!el.isConnected)continue;let md='';const isNative=el.hasAttribute('md-block-markdown');const msgBox=(el.closest&&el.closest('.msg-box.msg-bot, .msg-box.msg-user'))||null;const isUserMsg=!!(msgBox&&msgBox.classList.contains('msg-user'));const isBotMsg=!!(msgBox&&msgBox.classList.contains('msg-bot'));if(isNative){try{md=isUserMsg?(el.textContent||''):this.preprocessMD(el.textContent||'');}catch(_){md='';}
|
|
389
|
+
try{el.removeAttribute('md-block-markdown');}catch(_){}}else{const b64=el.getAttribute('data-md64');if(!b64)continue;try{md=this.b64ToUtf8(b64);}catch(_){md='';}
|
|
390
|
+
el.removeAttribute('data-md64');if(!isUserMsg){try{md=this.preprocessMD(md);}catch(_){}}}
|
|
391
|
+
if(isUserMsg){const span=document.createElement('span');span.textContent=md;el.replaceWith(span);}else if(isBotMsg){let html='';const env={__box:msgBox};try{let src=md;if(this.customMarkup&&typeof this.customMarkup.transformSource==='function'){src=this.customMarkup.transformSource(src,{streaming:false});}
|
|
392
|
+
html=this.MD.render(src,env);}catch(_){html=Utils.escapeHtml(md);}
|
|
393
|
+
const tpl=document.createElement('template');tpl.innerHTML=html;const frag=tpl.content;try{this._resolveCodesIn(frag,env);this._releaseEnvCodes(env);}catch(_){}
|
|
394
|
+
el.replaceWith(frag);touchedBoxes.add(msgBox);}else{const span=document.createElement('span');span.textContent=md;el.replaceWith(span);}
|
|
395
|
+
sliceCount++;if(sliceCount>=perSlice||this.asyncer.shouldYield(startedAt)){await this.asyncer.yield();startedAt=Utils.now();sliceCount=0;}}
|
|
396
|
+
try{touchedBoxes.forEach(box=>{try{this.customMarkup.apply(box,this.MD);}catch(_){}});}catch(_){}
|
|
397
|
+
this.restoreCollapsedCode(scope);this.hooks.observeNewCode(scope,{deferLastIfStreaming:true,minLinesForLast:this.cfg.PROFILE_CODE.minLinesForHL,minCharsForLast:this.cfg.PROFILE_CODE.minCharsForHL});this.hooks.observeMsgBoxes(scope);this.hooks.scheduleMathRender(scope);this.hooks.codeScrollInit(scope);if(typeof runtime!=='undefined'&&runtime.highlighter){runtime.highlighter.scanVisibleCodesInRoot(scope,runtime.stream.activeCode||null);}
|
|
398
|
+
this._d('md.pending.end',{boxes:touchedBoxes.size});}
|
|
399
|
+
renderStreamingSnapshot(src){const md=this._md(true);if(!md)return'';try{let s=String(src||'');if(this.customMarkup&&typeof this.customMarkup.transformSource==='function'){s=this.customMarkup.transformSource(s,{streaming:true});}
|
|
400
|
+
return md.render(s,{});}catch(_){return Utils.escapeHtml(src);}}
|
|
401
|
+
renderStreamingSnapshotFragment(src){const md=this._md(true);if(!md){const tpl0=document.createElement('template');tpl0.innerHTML='';return tpl0.content;}
|
|
402
|
+
let html='';const env={};try{let s=String(src||'');if(this.customMarkup&&typeof this.customMarkup.transformSource==='function'){s=this.customMarkup.transformSource(s,{streaming:true});}
|
|
403
|
+
html=md.render(s,env);}catch(_){html=Utils.escapeHtml(src||'');}
|
|
404
|
+
const tpl=document.createElement('template');tpl.innerHTML=html;const frag=tpl.content;try{this._resolveCodesIn(frag,env);this._releaseEnvCodes(env);}catch(_){}
|
|
405
|
+
this._d('md.render.stream.frag',{srcLen:(src||'').length,htmlLen:html.length});return frag;}
|
|
406
|
+
renderInlineStreaming(src){const md=this._md(true);if(!md||typeof md.renderInline!=='function')return Utils.escapeHtml(src||'');try{const s=String(src||'');return md.renderInline(s);}catch(_){return Utils.escapeHtml(src||'');}}
|
|
407
|
+
renderFinalSnapshot(src){const md=this._md(false);if(!md)return'';try{let s=String(src||'');if(this.customMarkup&&typeof this.customMarkup.transformSource==='function'){s=this.customMarkup.transformSource(s,{streaming:false});}
|
|
408
|
+
return md.render(s);}catch(_){return Utils.escapeHtml(src);}}
|
|
409
|
+
renderFinalSnapshotFragment(src){const md=this._md(false);if(!md){const tpl0=document.createElement('template');tpl0.innerHTML='';return tpl0.content;}
|
|
410
|
+
let html='';const env={};try{let s=String(src||'');if(this.customMarkup&&typeof this.customMarkup.transformSource==='function'){s=this.customMarkup.transformSource(s,{streaming:false});}
|
|
411
|
+
html=md.render(s,env);}catch(_){html=Utils.escapeHtml(src);}
|
|
412
|
+
const tpl=document.createElement('template');tpl.innerHTML=html;const frag=tpl.content;try{this._resolveCodesIn(frag,env);this._releaseEnvCodes(env);}catch(_){}
|
|
413
|
+
this._d('md.render.final.frag',{srcLen:(src||'').length,htmlLen:html.length});return frag;}
|
|
414
|
+
restoreCollapsedCode(root){const scope=root||document;const wrappers=scope.querySelectorAll('.code-wrapper');wrappers.forEach((wrapper)=>{const index=wrapper.getAttribute('data-index');const localeCollapse=wrapper.getAttribute('data-locale-collapse');const localeExpand=wrapper.getAttribute('data-locale-expand');const source=wrapper.querySelector('code');const isCollapsed=(window.__collapsed_idx||[]).includes(index);if(!source)return;const btn=wrapper.querySelector('.code-header-collapse');if(isCollapsed){source.style.display='none';if(btn){const span=btn.querySelector('span');if(span)span.textContent=localeExpand;btn.setAttribute('title',localeExpand||'Expand');}}else{source.style.display='block';if(btn){const span=btn.querySelector('span');if(span)span.textContent=localeCollapse;btn.setAttribute('title',localeCollapse||'Collapse');}}});}};
|
|
415
|
+
|
|
416
|
+
/* data/js/app/math.js */
|
|
417
|
+
class MathRenderer{constructor(cfg,raf,asyncer){this.cfg=cfg;this.raf=raf;this.asyncer=asyncer;this.scheduled=false;this.rafKey={t:'Math:render'};this._pendingRoots=new Set();this._pendingDoc=false;}
|
|
418
|
+
async renderAsync(root){if(typeof katex==='undefined')return;const scope=root||document;const scripts=Array.from(scope.querySelectorAll('script[type^="math/tex"]'));const useToString=(typeof katex.renderToString==='function');const batchFn=async(script)=>{if(!script||!script.isConnected)return;if(!script.closest('.msg-box.msg-bot'))return;const t=script.getAttribute('type')||'';const displayMode=t.indexOf('mode=display')>-1;const mathContent=script.textContent||'';const parent=script.parentNode;if(!parent)return;try{if(useToString){let html='';try{html=katex.renderToString(mathContent,{displayMode,throwOnError:false});}catch(_){const fb=displayMode?`\\[${mathContent}\\]`:`\\(${mathContent}\\)`;html=(displayMode?`<div>${Utils.escapeHtml(fb)}</div>`:`<span>${Utils.escapeHtml(fb)}</span>`);}
|
|
419
|
+
const host=document.createElement(displayMode?'div':'span');host.innerHTML=html;const el=host.firstElementChild||host;if(parent.classList&&parent.classList.contains('math-pending'))parent.replaceWith(el);else parent.replaceChild(el,script);}else{const el=document.createElement(displayMode?'div':'span');try{katex.render(mathContent,el,{displayMode,throwOnError:false});}catch(_){el.textContent=(displayMode?`\\[${mathContent}\\]`:`\\(${mathContent}\\)`);}
|
|
420
|
+
if(parent.classList&&parent.classList.contains('math-pending'))parent.replaceWith(el);else parent.replaceChild(el,script);}}catch(_){}};await this.asyncer.forEachChunk(scripts,batchFn,'MathRenderer');}
|
|
421
|
+
schedule(root,_delayIgnored=0,forceNow=false){if(typeof katex==='undefined')return;const targetRoot=root||document;let hasMath=true;if(!forceNow){try{hasMath=!!(targetRoot&&targetRoot.querySelector&&targetRoot.querySelector('script[type^="math/tex"]'));}catch(_){hasMath=false;}
|
|
422
|
+
if(!hasMath)return;}
|
|
423
|
+
if(targetRoot===document||targetRoot===document.documentElement||targetRoot===document.body){this._pendingDoc=true;this._pendingRoots.clear();}else if(!this._pendingDoc){this._pendingRoots.add(targetRoot);}
|
|
424
|
+
if(this.scheduled&&this.raf&&typeof this.raf.isScheduled==='function'&&this.raf.isScheduled(this.rafKey))return;this.scheduled=true;const priority=forceNow?0:2;this.raf.schedule(this.rafKey,()=>{this.scheduled=false;const useDoc=this._pendingDoc;const roots=[];if(useDoc){roots.push(document);}else{this._pendingRoots.forEach((r)=>{try{if(r&&(r.isConnected===undefined||r.isConnected))roots.push(r);}catch(_){roots.push(r);}});}
|
|
425
|
+
this._pendingDoc=false;this._pendingRoots.clear();(async()=>{for(let i=0;i<roots.length;i++){try{await this.renderAsync(roots[i]);}catch(_){}}})();},'Math',priority);}
|
|
426
|
+
cleanup(){try{this.raf.cancelGroup('Math');}catch(_){}
|
|
427
|
+
this.scheduled=false;try{this._pendingRoots.clear();}catch(_){}
|
|
428
|
+
this._pendingDoc=false;}};
|
|
429
|
+
|
|
430
|
+
/* data/js/app/nodes.js */
|
|
431
|
+
class NodesManager{constructor(dom,renderer,highlighter,math){this.dom=dom;this.renderer=renderer;this.highlighter=highlighter;this.math=math;this._userCollapse=new UserCollapseManager(this.renderer.cfg);}
|
|
432
|
+
_isUserOnlyContent(html){try{const tmp=document.createElement('div');tmp.innerHTML=html;const hasBot=!!tmp.querySelector('.msg-box.msg-bot');const hasUser=!!tmp.querySelector('.msg-box.msg-user');const hasMD64=!!tmp.querySelector('[data-md64]');const hasMDNative=!!tmp.querySelector('[md-block-markdown]');const hasCode=!!tmp.querySelector('pre code');const hasMath=!!tmp.querySelector('script[type^="math/tex"]');return hasUser&&!hasBot&&!hasMD64&&!hasMDNative&&!hasCode&&!hasMath;}catch(_){return false;}}
|
|
433
|
+
_materializeUserMdAsPlainText(scopeEl){try{const nodes=scopeEl.querySelectorAll('.msg-box.msg-user [data-md64], .msg-box.msg-user [md-block-markdown]');nodes.forEach(el=>{let txt='';if(el.hasAttribute('data-md64')){const b64=el.getAttribute('data-md64')||'';el.removeAttribute('data-md64');try{txt=this.renderer.b64ToUtf8(b64);}catch(_){txt='';}}else{try{txt=el.textContent||'';}catch(_){txt='';}
|
|
434
|
+
try{el.removeAttribute('md-block-markdown');}catch(_){}}
|
|
435
|
+
const span=document.createElement('span');span.textContent=txt;el.replaceWith(span);});}catch(_){}}
|
|
436
|
+
_ensureUserCopyIcons(root){try{const scope=root||document;const cfg=(this.renderer&&this.renderer.cfg)||{};const I=cfg.ICONS||{};const L=cfg.LOCALE||{};const copyIcon=I.CODE_COPY||'';const copyTitle=L.COPY||'Copy';const list=scope.querySelectorAll('.msg-box.msg-user .msg');for(let i=0;i<list.length;i++){const msg=list[i];if(!msg||!msg.isConnected)continue;const existing=msg.querySelector('.msg-copy-btn');if(existing){try{const p=existing.parentElement;if(p&&p.classList&&p.classList.contains('uc-content')){msg.insertAdjacentElement('afterbegin',existing);}}catch(_){}
|
|
437
|
+
continue;}
|
|
438
|
+
const a=document.createElement('a');a.href='empty:0';a.className='msg-copy-btn';a.setAttribute('role','button');a.setAttribute('title',copyTitle);a.setAttribute('aria-label',copyTitle);a.setAttribute('data-tip',copyTitle);try{const box=msg.closest('.msg-box.msg-user');if(box&&box.id&&box.id.startsWith('msg-user-')){const id=box.id.slice('msg-user-'.length);a.setAttribute('data-id',id);}}catch(_){}
|
|
439
|
+
const img=document.createElement('img');img.className='copy-img';img.src=copyIcon;img.alt=copyTitle;a.appendChild(img);try{msg.insertAdjacentElement('afterbegin',a);}catch(_){try{msg.appendChild(a);}catch(__){}}}}catch(_){}}
|
|
440
|
+
appendToInput(content){const el=this.dom.get('_append_input_');if(!el)return;let html=String(content||'');const trimmed=html.trim();const isWrapped=(trimmed.startsWith('<div')&&/class=["']msg-box msg-user["']/.test(trimmed));if(!isWrapped){const safe=(typeof Utils!=='undefined'&&Utils.escapeHtml)?Utils.escapeHtml(html):String(html).replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));const body=safe.replace(/\r?\n/g,'<br>');html=`<div class="msg-box msg-user"><div class="msg"><p style="margin:0">${body}</p></div></div>`;}
|
|
441
|
+
el.insertAdjacentHTML('beforeend',html);try{this._userCollapse.apply(el);}catch(_){}
|
|
442
|
+
try{this._ensureUserCopyIcons(el);}catch(_){}}
|
|
443
|
+
appendNode(content,scrollMgr){scrollMgr.userInteracted=false;scrollMgr.prevScroll=0;this.dom.clearStreamBefore();const el=this.dom.get('_nodes_');if(!el)return;el.classList.remove('empty_list');const userOnly=this._isUserOnlyContent(content);if(userOnly){el.insertAdjacentHTML('beforeend',content);this._materializeUserMdAsPlainText(el);try{this._userCollapse.apply(el);}catch(_){}
|
|
444
|
+
try{this._ensureUserCopyIcons(el);}catch(_){}
|
|
445
|
+
scrollMgr.scrollToBottom(false);scrollMgr.scheduleScrollFabUpdate();return;}
|
|
446
|
+
el.insertAdjacentHTML('beforeend',content);try{const maybePromise=this.renderer.renderPendingMarkdown(el);const post=()=>{try{this.highlighter.scheduleScanVisibleCodes(null);}catch(_){}
|
|
447
|
+
try{if(getMathMode()==='finalize-only')this.math.schedule(el,0,true);}catch(_){}
|
|
448
|
+
try{this._userCollapse.apply(el);}catch(_){}
|
|
449
|
+
try{this._ensureUserCopyIcons(el);}catch(_){}
|
|
450
|
+
scrollMgr.scrollToBottom(false);scrollMgr.scheduleScrollFabUpdate();};if(maybePromise&&typeof maybePromise.then==='function'){maybePromise.then(post);}else{post();}}catch(_){scrollMgr.scrollToBottom(false);scrollMgr.scheduleScrollFabUpdate();}}
|
|
451
|
+
replaceNodes(content,scrollMgr){scrollMgr.userInteracted=false;scrollMgr.prevScroll=0;this.dom.clearStreamBefore();const el=this.dom.hardReplaceByClone('_nodes_');if(!el)return;el.classList.remove('empty_list');const userOnly=this._isUserOnlyContent(content);if(userOnly){el.insertAdjacentHTML('beforeend',content);this._materializeUserMdAsPlainText(el);try{this._userCollapse.apply(el);}catch(_){}
|
|
452
|
+
try{this._ensureUserCopyIcons(el);}catch(_){}
|
|
453
|
+
scrollMgr.scrollToBottom(false,true);scrollMgr.scheduleScrollFabUpdate();return;}
|
|
454
|
+
el.insertAdjacentHTML('beforeend',content);try{const maybePromise=this.renderer.renderPendingMarkdown(el);const post=()=>{try{this.highlighter.scheduleScanVisibleCodes(null);}catch(_){}
|
|
455
|
+
try{if(getMathMode()==='finalize-only')this.math.schedule(el,0,true);}catch(_){}
|
|
456
|
+
try{this._userCollapse.apply(el);}catch(_){}
|
|
457
|
+
try{this._ensureUserCopyIcons(el);}catch(_){}
|
|
458
|
+
scrollMgr.scrollToBottom(false,true);scrollMgr.scheduleScrollFabUpdate();};if(maybePromise&&typeof maybePromise.then==='function'){maybePromise.then(post);}else{post();}}catch(_){scrollMgr.scrollToBottom(false,true);scrollMgr.scheduleScrollFabUpdate();}}
|
|
459
|
+
appendExtra(id,content,scrollMgr){const el=document.getElementById('msg-bot-'+id);if(!el)return;const extra=el.querySelector('.msg-extra');if(!extra)return;extra.insertAdjacentHTML('beforeend',content);try{const maybePromise=this.renderer.renderPendingMarkdown(extra);const post=()=>{const activeCode=(typeof runtime!=='undefined'&&runtime.stream)?runtime.stream.activeCode:null;try{this.highlighter.observeNewCode(extra,{deferLastIfStreaming:true,minLinesForLast:this.renderer.cfg.PROFILE_CODE.minLinesForHL,minCharsForLast:this.renderer.cfg.PROFILE_CODE.minCharsForHL},activeCode);this.highlighter.observeMsgBoxes(extra,(box)=>this._onBox(box));}catch(_){}
|
|
460
|
+
try{const mm=getMathMode();if(mm==='finalize-only')this.math.schedule(extra,0,true);else this.math.schedule(extra);}catch(_){}};if(maybePromise&&typeof maybePromise.then==='function'){maybePromise.then(post);}else{post();}}catch(_){}
|
|
461
|
+
scrollMgr.scheduleScroll(true);}
|
|
462
|
+
_onBox(box){const activeCode=(typeof runtime!=='undefined'&&runtime.stream)?runtime.stream.activeCode:null;this.highlighter.observeNewCode(box,{deferLastIfStreaming:true,minLinesForLast:this.renderer.cfg.PROFILE_CODE.minLinesForHL,minCharsForLast:this.renderer.cfg.PROFILE_CODE.minCharsForHL},activeCode);this.renderer.hooks.codeScrollInit(box);}
|
|
463
|
+
removeNode(id,scrollMgr){scrollMgr.prevScroll=0;let el=document.getElementById('msg-user-'+id);if(el)el.remove();el=document.getElementById('msg-bot-'+id);if(el)el.remove();this.dom.resetEphemeral();try{this.renderer.renderPendingMarkdown();}catch(_){}
|
|
464
|
+
scrollMgr.scheduleScroll(true);}
|
|
465
|
+
removeNodesFromId(id,scrollMgr){scrollMgr.prevScroll=0;const container=this.dom.get('_nodes_');if(!container)return;const elements=container.querySelectorAll('.msg-box');let remove=false;elements.forEach((element)=>{if(element.id&&element.id.endsWith('-'+id))remove=true;if(remove)element.remove();});this.dom.resetEphemeral();try{this.renderer.renderPendingMarkdown(container);}catch(_){}
|
|
466
|
+
scrollMgr.scheduleScroll(true);}};
|
|
467
|
+
|
|
468
|
+
/* data/js/app/raf.js */
|
|
469
|
+
class RafManager{constructor(cfg){this.cfg=cfg||{RAF:{},ASYNC:{}};this.tasks=new Map();this.groups=new Map();this.tickId=0;this._mode='raf';this.scheduled=false;this._flushInProgress=false;this._watchdogId=0;this._weakKeyTokens=new WeakMap();const R=(this.cfg&&this.cfg.RAF)||{};this.FLUSH_BUDGET_MS=Utils.g('RAF_FLUSH_BUDGET_MS',R.FLUSH_BUDGET_MS??7);this.MAX_TASKS_PER_FLUSH=Utils.g('RAF_MAX_TASKS_PER_FLUSH',R.MAX_TASKS_PER_FLUSH??120);this.SORT_THRESHOLD=Utils.g('RAF_SORT_THRESHOLD',R.SORT_THRESHOLD??32);this.VISIBILITY_FALLBACK_MS=Utils.g('RAF_VISIBILITY_FALLBACK_MS',R.VISIBILITY_FALLBACK_MS??300);this.USE_VISIBILITY_FALLBACK=(R.USE_VISIBILITY_FALLBACK??true);}
|
|
470
|
+
_normalizeKey(key){if(!key)return Symbol('raf:anon');const typ=typeof key;if(typ==='string'||typ==='symbol'||typ==='number')return key;try{if(typeof Node!=='undefined'&&key instanceof Node){let tok=this._weakKeyTokens.get(key);if(!tok){tok=Symbol('raf:k');this._weakKeyTokens.set(key,tok);}
|
|
471
|
+
return tok;}}catch(_){}
|
|
472
|
+
return key;}
|
|
473
|
+
_armPump(){if(this.scheduled)return;this.scheduled=true;const canRAF=typeof requestAnimationFrame==='function';if(canRAF){this._mode='raf';try{this.tickId=requestAnimationFrame(()=>this.flush());if(this.USE_VISIBILITY_FALLBACK&&!this._watchdogId){this._watchdogId=setTimeout(()=>{if(this.scheduled||this.tickId){try{this.flush();}catch(_){}}},this.VISIBILITY_FALLBACK_MS);}
|
|
474
|
+
return;}catch(_){}}
|
|
475
|
+
this._mode='raf';Promise.resolve().then(()=>this.flush());}
|
|
476
|
+
schedule(key,fn,group='default',priority=0){if(!key)key={k:'anon'};key=this._normalizeKey(key);const prev=this.tasks.get(key);if(prev&&prev.group&&prev.group!==group){const oldSet=this.groups.get(prev.group);if(oldSet){oldSet.delete(key);if(oldSet.size===0)this.groups.delete(prev.group);}}
|
|
477
|
+
this.tasks.set(key,{fn,group,priority});if(group){let set=this.groups.get(group);if(!set){set=new Set();this.groups.set(group,set);}
|
|
478
|
+
set.add(key);}
|
|
479
|
+
this._armPump();}
|
|
480
|
+
flush(){try{if(this.tickId)cancelAnimationFrame(this.tickId);}catch(_){}
|
|
481
|
+
this.tickId=0;this.scheduled=false;if(this._watchdogId){clearTimeout(this._watchdogId);this._watchdogId=0;}
|
|
482
|
+
const list=[];this.tasks.forEach((v,key)=>list.push({key,...v}));this.tasks.clear();if(list.length>1&&list.length>this.SORT_THRESHOLD){list.sort((a,b)=>a.priority-b.priority);}
|
|
483
|
+
const start=Utils.now();let processed=0;for(let idx=0;idx<list.length;idx++){const t=list[idx];try{t.fn();}catch(_){}
|
|
484
|
+
processed++;if(t.group){const set=this.groups.get(t.group);if(set){set.delete(t.key);if(set.size===0)this.groups.delete(t.group);}}
|
|
485
|
+
const elapsed=Utils.now()-start;if(processed>=this.MAX_TASKS_PER_FLUSH||elapsed>=this.FLUSH_BUDGET_MS){for(let j=idx+1;j<list.length;j++){const r=list[j];this.tasks.set(r.key,{fn:r.fn,group:r.group,priority:r.priority});if(r.group){let set=this.groups.get(r.group);if(!set){set=new Set();this.groups.set(r.group,set);}
|
|
486
|
+
set.add(r.key);}}
|
|
487
|
+
this._armPump();return;}}
|
|
488
|
+
if(this.tasks.size)this._armPump();}
|
|
489
|
+
kick(forceImmediate=true){if(forceImmediate&&this.tasks.size){if(this._flushInProgress)return;this._flushInProgress=true;try{this.scheduled=true;this.flush();}catch(_){}finally{this._flushInProgress=false;}
|
|
490
|
+
return;}
|
|
491
|
+
this._armPump();}
|
|
492
|
+
cancel(key){key=this._normalizeKey(key);const t=this.tasks.get(key);if(!t)return;this.tasks.delete(key);if(t.group){const set=this.groups.get(t.group);if(set){set.delete(key);if(set.size===0)this.groups.delete(t.group);}}}
|
|
493
|
+
cancelGroup(group){const set=this.groups.get(group);if(!set)return;for(const key of set)this.tasks.delete(key);this.groups.delete(group);}
|
|
494
|
+
cancelAll(){this.tasks.clear();this.groups.clear();try{if(this.tickId)cancelAnimationFrame(this.tickId);}catch(_){}
|
|
495
|
+
this.tickId=0;this.scheduled=false;if(this._watchdogId){clearTimeout(this._watchdogId);this._watchdogId=0;}}
|
|
496
|
+
isScheduled(key){return this.tasks.has(this._normalizeKey(key));}
|
|
497
|
+
nextFrame(){return new Promise((resolve)=>{const key=Symbol('raf:nextFrame');this.schedule(key,()=>resolve(),'RafNext',0);});}}
|
|
498
|
+
function getMathMode(){const v=String(window.MATH_STREAM_MODE||'finalize-only').toLowerCase();return(v==='idle'||v==='always'||v==='finalize-only')?v:'finalize-only';};
|
|
499
|
+
|
|
500
|
+
/* data/js/app/scroll.js */
|
|
501
|
+
class ScrollManager{constructor(cfg,dom,raf){this.cfg=cfg;this.dom=dom;this.raf=raf;this.autoFollow=true;this.userInteracted=false;this.lastScrollTop=0;this.prevScroll=0;this.currentFabAction='none';this.fabFreezeUntil=0;this.scrollScheduled=false;this.scrollFabUpdateScheduled=false;this.scrollRAF=0;this.scrollFabRAF=0;}
|
|
502
|
+
isNearBottom(marginPx=100){const el=Utils.SE;const distance=el.scrollHeight-el.clientHeight-el.scrollTop;return distance<=marginPx;}
|
|
503
|
+
scheduleScroll(live=false){if(live===true&&this.autoFollow!==true)return;if(this.scrollScheduled)return;this.scrollScheduled=true;this.raf.schedule('SM:scroll',()=>{this.scrollScheduled=false;this.scrollToBottom(live);this.scheduleScrollFabUpdate();},'ScrollManager',1);}
|
|
504
|
+
cancelPendingScroll(){try{this.raf.cancelGroup('ScrollManager');}catch(_){}
|
|
505
|
+
this.scrollScheduled=false;this.scrollFabUpdateScheduled=false;this.scrollRAF=0;this.scrollFabRAF=0;}
|
|
506
|
+
forceScrollToBottomImmediate(){const el=Utils.SE;el.scrollTop=el.scrollHeight;this.prevScroll=el.scrollHeight;}
|
|
507
|
+
scrollToBottom(live=false,force=false){const el=Utils.SE;const marginPx=this.cfg.UI.SCROLL_NEAR_MARGIN_PX;const behavior='instant';const h=el.scrollHeight;if(live===true&&this.autoFollow!==true){this.prevScroll=h;return;}
|
|
508
|
+
if((live===true&&this.userInteracted===false)||this.isNearBottom(marginPx)||live===false||force){try{el.scrollTo({top:h,behavior});}catch(_){el.scrollTop=h;}}
|
|
509
|
+
this.prevScroll=el.scrollHeight;}
|
|
510
|
+
hasVerticalScroll(){const el=Utils.SE;return(el.scrollHeight-el.clientHeight)>1;}
|
|
511
|
+
computeFabAction(){const el=Utils.SE;const h=el.scrollHeight;const c=el.clientHeight;const hasScroll=(h-c)>1;if(!hasScroll)return'none';const dist=h-c-el.scrollTop;if(dist<=2)return'up';if(dist>=this.cfg.FAB.SHOW_DOWN_THRESHOLD_PX)return'down';return'none';}
|
|
512
|
+
updateScrollFab(force=false,actionOverride=null,bypassFreeze=false){const btn=this.dom.get('scrollFab');const icon=this.dom.get('scrollFabIcon');if(!btn||!icon)return;const now=Utils.now();const action=actionOverride||this.computeFabAction();if(!force&&!bypassFreeze&&now<this.fabFreezeUntil&&action!==this.currentFabAction)return;if(action==='none'){if(this.currentFabAction!=='none'||force){btn.classList.remove('visible');this.currentFabAction='none';}
|
|
513
|
+
return;}
|
|
514
|
+
if(action!==this.currentFabAction||force){if(action==='up'){if(icon.dataset.dir!=='up'){icon.src=this.cfg.ICONS.COLLAPSE;icon.dataset.dir='up';}
|
|
515
|
+
btn.title="Go to top";}else{if(icon.dataset.dir!=='down'){icon.src=this.cfg.ICONS.EXPAND;icon.dataset.dir='down';}
|
|
516
|
+
btn.title="Go to bottom";}
|
|
517
|
+
btn.setAttribute('aria-label',btn.title);this.currentFabAction=action;btn.classList.add('visible');}else if(!btn.classList.contains('visible'))btn.classList.add('visible');}
|
|
518
|
+
scheduleScrollFabUpdate(){if(this.scrollFabUpdateScheduled)return;this.scrollFabUpdateScheduled=true;this.raf.schedule('SM:fab',()=>{this.scrollFabUpdateScheduled=false;const action=this.computeFabAction();if(action!==this.currentFabAction)this.updateScrollFab(false,action);},'ScrollManager',2);}
|
|
519
|
+
maybeEnableAutoFollowByProximity(){const el=Utils.SE;if(!this.autoFollow){const dist=el.scrollHeight-el.clientHeight-el.scrollTop;if(dist<=this.cfg.UI.AUTO_FOLLOW_REENABLE_PX)this.autoFollow=true;}}
|
|
520
|
+
scrollToTopUser(){this.userInteracted=true;this.autoFollow=false;try{const el=Utils.SE;el.scrollTo({top:0,behavior:'instant'});this.lastScrollTop=el.scrollTop;}catch(_){const el=Utils.SE;el.scrollTop=0;this.lastScrollTop=0;}}
|
|
521
|
+
scrollToBottomUser(){this.userInteracted=true;this.autoFollow=false;try{const el=Utils.SE;el.scrollTo({top:el.scrollHeight,behavior:'instant'});this.lastScrollTop=el.scrollTop;}catch(_){const el=Utils.SE;el.scrollTop=el.scrollHeight;this.lastScrollTop=el.scrollTop;}
|
|
522
|
+
this.maybeEnableAutoFollowByProximity();}}
|
|
523
|
+
class CodeScrollState{constructor(cfg,raf){this.cfg=cfg;this.raf=raf;this.map=new WeakMap();this.rafMap=new WeakMap();this.rafIds=new Set();this.rafKeyMap=new WeakMap();}
|
|
524
|
+
state(el){let s=this.map.get(el);if(!s){s={autoFollow:false,lastScrollTop:0,userInteracted:false,freezeUntil:0,listeners:null,};this.map.set(el,s);}
|
|
525
|
+
return s;}
|
|
526
|
+
isFinalizedCode(el){if(!el||el.tagName!=='CODE')return false;if(el.dataset&&el.dataset._active_stream==='1')return false;const highlighted=(el.getAttribute('data-highlighted')==='yes')||el.classList.contains('hljs');return highlighted;}
|
|
527
|
+
isNearBottomEl(el,margin=100){if(!el)return true;const distance=el.scrollHeight-el.clientHeight-el.scrollTop;return distance<=margin;}
|
|
528
|
+
scrollToBottom(el,live=false,force=false){if(!el||!el.isConnected)return;if(!force&&this.isFinalizedCode(el))return;const st=this.state(el);const now=Utils.now();if(!force&&st.freezeUntil&&now<st.freezeUntil)return;const distNow=el.scrollHeight-el.clientHeight-el.scrollTop;if(!force&&distNow<=1){st.lastScrollTop=el.scrollTop;return;}
|
|
529
|
+
const marginPx=live?96:this.cfg.CODE_SCROLL.NEAR_MARGIN_PX;const behavior='instant';if(!force){if(live&&st.autoFollow!==true)return;if(!live&&!(st.autoFollow===true||this.isNearBottomEl(el,marginPx)||!st.userInteracted))return;}
|
|
530
|
+
try{el.scrollTo({top:el.scrollHeight,behavior});}catch(_){el.scrollTop=el.scrollHeight;}
|
|
531
|
+
st.lastScrollTop=el.scrollTop;}
|
|
532
|
+
scheduleScroll(el,live=false,force=false){if(!el||!el.isConnected)return;if(!force&&this.isFinalizedCode(el))return;if(this.rafMap.get(el))return;this.rafMap.set(el,true);let key=this.rafKeyMap.get(el);if(!key){key=Symbol('codeScroll');this.rafKeyMap.set(el,key);}
|
|
533
|
+
this.raf.schedule(key,()=>{this.rafMap.delete(el);this.scrollToBottom(el,live,force);},'CodeScroll',0);}
|
|
534
|
+
attachHandlers(codeEl){if(!codeEl||codeEl.dataset.csListeners==='1')return;if(codeEl.dataset._active_stream!=='1')return;codeEl.dataset.csListeners='1';const st=this.state(codeEl);const onScroll=(ev)=>{const top=codeEl.scrollTop;const isUser=!!(ev&&ev.isTrusted===true);const now=Utils.now();if(this.isFinalizedCode(codeEl)){if(isUser)st.userInteracted=true;st.autoFollow=false;st.lastScrollTop=top;return;}
|
|
535
|
+
if(isUser){if(top+1<st.lastScrollTop){st.autoFollow=false;st.userInteracted=true;st.freezeUntil=now+1000;}else if(this.isNearBottomEl(codeEl,this.cfg.CODE_SCROLL.AUTO_FOLLOW_REENABLE_PX)){st.autoFollow=true;}}else{if(this.isNearBottomEl(codeEl,this.cfg.CODE_SCROLL.AUTO_FOLLOW_REENABLE_PX))st.autoFollow=true;}
|
|
536
|
+
st.lastScrollTop=top;};const onWheel=(ev)=>{st.userInteracted=true;const now=Utils.now();if(this.isFinalizedCode(codeEl)){st.autoFollow=false;return;}
|
|
537
|
+
if(ev.deltaY<0){st.autoFollow=false;st.freezeUntil=now+1000;}else if(this.isNearBottomEl(codeEl,this.cfg.CODE_SCROLL.AUTO_FOLLOW_REENABLE_PX)){st.autoFollow=true;}};const onTouchStart=()=>{st.userInteracted=true;};codeEl.addEventListener('scroll',onScroll,{passive:true});codeEl.addEventListener('wheel',onWheel,{passive:true});codeEl.addEventListener('touchstart',onTouchStart,{passive:true});st.listeners={onScroll,onWheel,onTouchStart};}
|
|
538
|
+
detachHandlers(codeEl){if(!codeEl)return;const st=this.map.get(codeEl);const h=st&&st.listeners;if(!h){codeEl.dataset.csListeners='0';return;}
|
|
539
|
+
try{codeEl.removeEventListener('scroll',h.onScroll);}catch(_){}
|
|
540
|
+
try{codeEl.removeEventListener('wheel',h.onWheel);}catch(_){}
|
|
541
|
+
try{codeEl.removeEventListener('touchstart',h.onTouchStart);}catch(_){}
|
|
542
|
+
st.listeners=null;codeEl.dataset.csListeners='0';}
|
|
543
|
+
initScrollableBlocks(root){const scope=root||document;let nodes=[];if(scope.nodeType===1&&scope.closest&&scope.closest('.msg-box.msg-bot')){nodes=scope.querySelectorAll('pre code');}else{nodes=document.querySelectorAll('.msg-box.msg-bot pre code');}
|
|
544
|
+
if(!nodes.length)return;nodes.forEach((code)=>{if(code.dataset._active_stream==='1'){this.attachHandlers(code);const st=this.state(code);st.autoFollow=true;this.scheduleScroll(code,true,false);}else{this.detachHandlers(code);}});}
|
|
545
|
+
transfer(oldEl,newEl){if(!oldEl||!newEl||oldEl===newEl)return;const oldState=this.map.get(oldEl);if(oldState)this.map.set(newEl,{...oldState});this.detachHandlers(oldEl);this.attachHandlers(newEl);}
|
|
546
|
+
cancelAllScrolls(){try{this.raf.cancelGroup('CodeScroll');}catch(_){}
|
|
547
|
+
this.rafMap=new WeakMap();this.rafIds.clear();this.rafKeyMap=new WeakMap();}};
|
|
548
|
+
|
|
549
|
+
/* data/js/app/stream.js */
|
|
550
|
+
const RE_SAFE_BREAK=/\s|[.,;:!?()\[\]{}'"«»„”“—–\-…>]/;const RE_STRUCT_BOUNDARY=/\n(\n|[-*]\s|\d+\.\s|#{1,6}\s|>\s)/;const RE_MD_INLINE_TRIGGER=/(\*\*|__|[_`]|~~|\[[^\]]+\]\([^)]+\))/;const RE_LINE_END=/[\n\r]$/;class StreamEngine{constructor(cfg,dom,renderer,math,highlighter,codeScroll,scrollMgr,raf,asyncer,logger){this.cfg=cfg;this.dom=dom;this.renderer=renderer;this.math=math;this.highlighter=highlighter;this.codeScroll=codeScroll;this.scrollMgr=scrollMgr;this.raf=raf;this.asyncer=asyncer;this.logger=logger||new Logger(cfg);this.streamBuf='';this._sbParts=[];this._sbLen=0;this._tailMaterializeAt=((this.cfg&&this.cfg.STREAM&&(this.cfg.STREAM.MATERIALIZE_TAIL_AT_LEN|0))||262144);this.fenceOpen=false;this.fenceMark='`';this.fenceLen=3;this.fenceTail='';this.fenceBuf='';this.lastSnapshotTs=0;this.nextSnapshotStep=cfg.PROFILE_TEXT.base;this.snapshotScheduled=false;this.snapshotRAF=0;this.codeStream={open:false,lines:0,chars:0};this.activeCode=null;this.suppressPostFinalizePass=false;this._promoteScheduled=false;this._firstCodeOpenSnapDone=false;this.isStreaming=false;this._lastInjectedEOL=false;this._customFenceSpecs=[];this._fenceCustom=null;this.plain={active:false,container:null,anchor:null,lastMDTs:0,noMdNL:0,suppressInline:false,forceFullMDOnce:false,enabled:false,_carry:''};this._mdQuickRe=/(\*\*|__|~~|`|!\[|\[[^\]]+\]\([^)]+\)|^> |\n> |\n#{1,6}\s|\n[-*+]\s|\n\d+\.\s)/m;this._reSafeBreak=RE_SAFE_BREAK;this._reStructBoundary=RE_STRUCT_BOUNDARY;this._reMDInlineTrigger=RE_MD_INLINE_TRIGGER;this._reLineEnd=RE_LINE_END;this._tpl=(typeof document!=='undefined')?document.createElement('template'):null;this._isWordChar=(ch)=>{if(!ch)return false;const c=ch.charCodeAt(0);if((c>=48&&c<=57)||(c>=65&&c<=90)||(c>=97&&c<=122))return true;if(c>=0x00C0&&c<=0x02AF)return true;return false;};this._isSafeBreakChar=(ch)=>{if(!ch)return false;return this._reSafeBreak.test(ch);};this._d('init',{materializeTailAt:this._tailMaterializeAt,hasTpl:!!this._tpl});}
|
|
551
|
+
_d(tag,data){try{const lg=this.logger||(this.cfg&&this.cfg.logger)||(window.runtime&&runtime.logger)||null;if(!lg||typeof lg.debug!=='function')return;lg.debug_obj("STREAM",tag,data);}catch(_){}}
|
|
552
|
+
setCustomFenceSpecs(specs){this._customFenceSpecs=Array.isArray(specs)?specs.slice():[];this._d('customFence.set',{count:(this._customFenceSpecs||[]).length});}
|
|
553
|
+
_appendChunk(s){if(!s)return;this._d('chunk.append',{len:s.length,nl:Utils.countNewlines(s),head:String(s).slice(0,160),tail:String(s).slice(-160),hasAngle:/[<>]/.test(String(s)),hasFenceToken:/```|~~~/.test(String(s))});this._sbParts.push(s);this._sbLen+=s.length;if(this._sbLen>=this._tailMaterializeAt){this._materializeTail();}}
|
|
554
|
+
_materializeTail(){this._d('tail.materialize',{streamBufLen:this.streamBuf.length,parts:this._sbParts.length,sbLen:this._sbLen});if(this._sbLen>0){this.streamBuf+=(this._sbParts.length===1?this._sbParts[0]:this._sbParts.join(''));this._sbParts.length=0;this._sbLen=0;}}
|
|
555
|
+
getStreamLength(){return(this.streamBuf.length+this._sbLen);}
|
|
556
|
+
getStreamText(){if(this._sbLen>0){return this.streamBuf+(this._sbParts.length===1?this._sbParts[0]:this._sbParts.join(''));}
|
|
557
|
+
return this.streamBuf;}
|
|
558
|
+
getDeltaSince(prevLen){const total=this.getStreamLength();if(prevLen>=total)return'';const bufLen=this.streamBuf.length;if(prevLen<=bufLen){if(this._sbLen===0)return'';const out=(this._sbParts.length===1?this._sbParts[0]:this._sbParts.join(''));if(/[<>]/.test(out))this._d('delta.since',{prevLen,deltaLen:out.length,head:out.slice(0,80),tail:out.slice(-80)});return out;}
|
|
559
|
+
let off=prevLen-bufLen;let out=null;for(let i=0;i<this._sbParts.length;i++){const p=this._sbParts[i];const plen=p.length;if(off>=plen){off-=plen;continue;}
|
|
560
|
+
const slice=off>0?p.slice(off):p;if(out===null)out=[slice];else out.push(slice);off=0;}
|
|
561
|
+
if(!out)return'';const ret=(out.length===1?out[0]:out.join(''));if(/[<>]/.test(ret))this._d('delta.since',{prevLen,deltaLen:ret.length,head:ret.slice(0,80),tail:ret.slice(-80)});return ret;}
|
|
562
|
+
_clearStreamBuffer(){this._d('buf.clear',{streamBufLen:this.streamBuf.length,parts:this._sbParts.length,sbLen:this._sbLen});this.streamBuf='';this._sbParts.length=0;this._sbLen=0;}
|
|
563
|
+
_plainThreshold(){const STREAM=(this.cfg&&this.cfg.STREAM)?this.cfg.STREAM:{};const thr=(STREAM.PLAIN_ACTIVATE_AFTER_LINES!=null)?STREAM.PLAIN_ACTIVATE_AFTER_LINES:10;return Math.max(1,thr|0);}
|
|
564
|
+
_plainReset(){this.plain.active=false;this.plain.container=null;this.plain.anchor=null;this.plain.lastMDTs=0;this.plain.noMdNL=0;this.plain.suppressInline=false;this.plain.forceFullMDOnce=false;this.plain.enabled=false;this.plain._carry='';this._d('plain.reset',{});}
|
|
565
|
+
_plainEnsureContainer(snap){if(this.plain.container&&this.plain.container.isConnected&&this.plain.anchor&&this.plain.anchor.parentNode===this.plain.container){const needParent=this._choosePlainParent(snap);if(needParent&&this.plain.container.parentNode!==needParent){try{needParent.appendChild(this.plain.container);}catch(_){}}
|
|
566
|
+
return this.plain.container;}
|
|
567
|
+
const parent=this._choosePlainParent(snap)||snap;const host=document.createElement('span');host.setAttribute('data-plain-stream','1');host.style.whiteSpace='pre-wrap';host.style.display='inline';host.style.wordBreak='normal';host.style.overflowWrap='normal';const tail=document.createTextNode('');const anchor=document.createComment('ps-tail');host.appendChild(tail);host.appendChild(anchor);try{parent.appendChild(host);}catch(_){snap.appendChild(host);}
|
|
568
|
+
this.plain.container=host;this.plain.anchor=anchor;this.plain.active=true;this._d('plain.ensureHost',{created:true});return host;}
|
|
569
|
+
_findSafeFlushIndex(text){if(!text)return 0;if(text.indexOf('\n')!==-1||text.indexOf('\r')!==-1){if(/[<>]/.test(text))this._d('plain.flushIdx.nl',{textLen:text.length});return this._retractIfInsideAngleToken(text,text.length);}
|
|
570
|
+
const PLAIN=(this.cfg&&this.cfg.STREAM&&this.cfg.STREAM.PLAIN)?this.cfg.STREAM.PLAIN:{};const LOOKBACK=(PLAIN.COHESION_LOOKBACK!=null)?PLAIN.COHESION_LOOKBACK:96;const STICKY=(PLAIN.COHESION_STICKY_TAIL!=null)?PLAIN.COHESION_STICKY_TAIL:8;const FLUSH_AT=(PLAIN.COHESION_FLUSH_AT_LEN!=null)?PLAIN.COHESION_FLUSH_AT_LEN:512;if(text.length>=FLUSH_AT){const at=Math.max(0,text.length-STICKY);if(/[<>]/.test(text))this._d('plain.flushIdx.hard',{textLen:text.length,at});return this._retractIfInsideAngleToken(text,at);}
|
|
571
|
+
const start=Math.max(0,text.length-LOOKBACK);for(let i=text.length-1;i>=start;i--){const ch=text[i];if(this._isSafeBreakChar(ch)){if(/[<>]/.test(text))this._d('plain.flushIdx.safe',{textLen:text.length,i,ch});return this._retractIfInsideAngleToken(text,i+1);}}
|
|
572
|
+
const at=Math.max(0,text.length-STICKY);if(/[<>]/.test(text))this._d('plain.flushIdx.sticky',{textLen:text.length,at});return this._retractIfInsideAngleToken(text,at);}
|
|
573
|
+
_choosePlainParent(snap){try{if(!snap||!snap.querySelectorAll)return snap;const pending=snap.querySelectorAll('[data-cm][data-cm-pending="1"]');if(pending&&pending.length)return pending[pending.length-1];}catch(_){}
|
|
574
|
+
return snap;}
|
|
575
|
+
_retractIfInsideAngleToken(text,flushIdx){const PLAIN=(this.cfg&&this.cfg.STREAM&&this.cfg.STREAM.PLAIN)?this.cfg.STREAM.PLAIN:{};const ENABLED=(PLAIN.PROTECT_ANGLE_TOKENS!==false);if(!ENABLED)return flushIdx;if(!text||flushIdx<=0||flushIdx>text.length)return flushIdx;const LOOK=(PLAIN.ANGLE_LOOKBACK!=null)?PLAIN.ANGLE_LOOKBACK:128;const from=Math.max(0,flushIdx-LOOK);const seg=text.slice(from,flushIdx);const lt=seg.lastIndexOf('<');if(lt!==-1&&seg.indexOf('>',lt+1)===-1){const next=seg.charAt(lt+1);const looksLikeTag=!!next&&((next>='A'&&next<='Z')||(next>='a'&&next<='z')||next==='!'||next==='/'||next==='?');if(looksLikeTag)return from+lt;}
|
|
576
|
+
if(flushIdx<text.length){const ch=text.charAt(flushIdx),ch2=text.charAt(flushIdx+1);if(ch==='<'&&ch2&&((ch2>='A'&&ch2<='Z')||(ch2>='a'&&ch2<='z')||ch2==='!'||ch2==='/'||ch2==='?'))return flushIdx;}
|
|
577
|
+
return flushIdx;}
|
|
578
|
+
_plainAppendDelta(snap,delta){if(!delta)return;const host=this._plainEnsureContainer(snap);let combined=(this.plain._carry||'')+String(delta);if(!combined)return;const flushIdx=this._findSafeFlushIndex(combined);let toAppend=combined.slice(0,flushIdx);let carryRemainder=combined.slice(flushIdx);const PLAIN=(this.cfg&&this.cfg.STREAM&&this.cfg.STREAM.PLAIN)?this.cfg.STREAM.PLAIN:{};const MIN_ATOMIC=(PLAIN.MIN_ATOMIC_CHARS!=null)?PLAIN.MIN_ATOMIC_CHARS:3;const isWord=(ch)=>{if(!ch)return false;const c=ch.charCodeAt(0);if((c>=48&&c<=57)||(c>=65&&c<=90)||(c>=97&&c<=122))return true;return(c>=0x00C0&&c<=0x02AF);};const lastA=toAppend?toAppend.charAt(toAppend.length-1):'';const firstB=carryRemainder?carryRemainder.charAt(0):'';const looksUnsafeSplit=(!/\r|\n/.test(toAppend))&&isWord(lastA)&&isWord(firstB);if(toAppend&&looksUnsafeSplit&&toAppend.length<MIN_ATOMIC){this.plain._carry=toAppend+carryRemainder;return;}
|
|
579
|
+
this.plain._carry=carryRemainder;if(!toAppend)return;let tn=this.plain.anchor?this.plain.anchor.previousSibling:null;if(!tn||tn.nodeType!==Node.TEXT_NODE||tn.parentNode!==host){tn=document.createTextNode('');try{host.insertBefore(tn,this.plain.anchor);}catch(_){host.appendChild(tn);}}
|
|
580
|
+
tn.appendData(toAppend);try{const CM=this.renderer&&this.renderer.customMarkup;const MDinline=this.renderer?(this.renderer.MD_STREAM||this.renderer.MD||null):null;if(CM&&typeof CM.maybeApplyStreamOnDelta==='function'){CM.maybeApplyStreamOnDelta(snap,toAppend,MDinline);}}catch(_){}
|
|
581
|
+
this._plainMaybeInlineMarkdown(toAppend,false);this.scrollMgr.scheduleScroll(true);}
|
|
582
|
+
_plainMaybeInlineMarkdown(delta,force){if(!this.plain.active||!this.plain.container||!this.plain.anchor)return;if(this.plain.suppressInline&&!force){this._d('plain.inline.skip.suppressed',{force});return;}
|
|
583
|
+
const PLAIN=(this.cfg&&this.cfg.STREAM&&this.cfg.STREAM.PLAIN)?this.cfg.STREAM.PLAIN:{};const MIN_INTERVAL=(PLAIN.MD_MIN_INTERVAL_MS!=null)?PLAIN.MD_MIN_INTERVAL_MS:120;const MIN_TAIL=(PLAIN.INLINE_MIN_CHARS!=null)?PLAIN.INLINE_MIN_CHARS:64;const WINDOW_MAX=(PLAIN.WINDOW_MAX_CHARS!=null)?PLAIN.WINDOW_MAX_CHARS:2048;const RESERVE_TAIL=(PLAIN.RESERVE_TAIL_CHARS!=null)?PLAIN.RESERVE_TAIL_CHARS:256;const now=Utils.now();if(!force&&(now-(this.plain.lastMDTs||0))<MIN_INTERVAL){this._d('plain.inline.skip.throttle',{since:(now-(this.plain.lastMDTs||0)),MIN_INTERVAL});return;}
|
|
584
|
+
const tn=this.plain.anchor.previousSibling;if(!tn||tn.nodeType!==Node.TEXT_NODE)return;const text=tn.nodeValue||'';if(!text)return;if(force){this._d('plain.inline.skip.forceFull',{});return;}
|
|
585
|
+
if(text.length<MIN_TAIL&&(!delta||delta.indexOf('\n')===-1)){this._d('plain.inline.skip.small',{textLen:text.length,MIN_TAIL});return;}
|
|
586
|
+
const candidate=(delta&&this._reMDInlineTrigger.test(delta))||this._reMDInlineTrigger.test(text);if(!candidate){this._d('plain.inline.skip.noCandidate',{deltaHas:!!(delta&&this._reMDInlineTrigger.test(delta))});return;}
|
|
587
|
+
let cut=text.length;if(text.length>WINDOW_MAX){const target=text.length-RESERVE_TAIL;const nl=text.lastIndexOf('\n',Math.max(0,target));if(nl>=32)cut=nl+1;else cut=Math.max(WINDOW_MAX,text.length-RESERVE_TAIL);}
|
|
588
|
+
let head=text.slice(0,cut);let rest=text.slice(cut);if(head&&rest){const last=head[head.length-1];const first=rest[0];if(this._isWordChar(last)&&this._isWordChar(first)){let backCut=-1;const LOOKBACK=96;const start=Math.max(0,head.length-LOOKBACK);for(let i=head.length-1;i>=start;i--){if(this._isSafeBreakChar(head[i])){backCut=i+1;break;}}
|
|
589
|
+
if(backCut>=0&&backCut<head.length){rest=head.slice(backCut)+rest;head=head.slice(0,backCut);}}}
|
|
590
|
+
let html='';try{if(this.renderer&&typeof this.renderer.renderInlineStreaming==='function'){html=this.renderer.renderInlineStreaming(head);}else if(this.renderer&&this.renderer.MD_STREAM&&typeof this.renderer.MD_STREAM.renderInline==='function'){html=this.renderer.MD_STREAM.renderInline(head);}else{html=Utils.escapeHtml(head);}}catch(_){html=Utils.escapeHtml(head);}
|
|
591
|
+
this._d('plain.inline.promote',{headLen:head.length,restLen:rest.length,htmlLen:html.length});try{if(this._tpl){this._tpl.innerHTML=html;const frag=document.createDocumentFragment();while(this._tpl.content.firstChild)frag.appendChild(this._tpl.content.firstChild);const host=this.plain.container;host.insertBefore(frag,tn);tn.nodeValue=rest;}else{const tpl=document.createElement('template');tpl.innerHTML=html;const frag=tpl.content;const host=this.plain.container;host.insertBefore(frag,tn);tn.nodeValue=rest;}}catch(_){}
|
|
592
|
+
this.plain.lastMDTs=now;}
|
|
593
|
+
reset(){this._d('reset',{});this._clearStreamBuffer();this.fenceOpen=false;this.fenceMark='`';this.fenceLen=3;this.fenceTail='';this.fenceBuf='';this.lastSnapshotTs=0;this.nextSnapshotStep=this.profile().base;this.snapshotScheduled=false;this.snapshotRAF=0;this.codeStream={open:false,lines:0,chars:0};this.activeCode=null;this.suppressPostFinalizePass=false;this._promoteScheduled=false;this._firstCodeOpenSnapDone=false;this._lastInjectedEOL=false;this._fenceCustom=null;this._plainReset();}
|
|
594
|
+
defuseActiveToPlain(){if(!this.activeCode||!this.activeCode.codeEl||!this.activeCode.codeEl.isConnected)return;const codeEl=this.activeCode.codeEl;const fullText=(this.activeCode.frozenEl?.textContent||'')+(this.activeCode.tailEl?.textContent||'');this._d('code.defuseActive',{fullLen:fullText.length});try{codeEl.textContent=fullText;codeEl.removeAttribute('data-highlighted');codeEl.classList.remove('hljs');codeEl.dataset._active_stream='0';const st=this.codeScroll.state(codeEl);st.autoFollow=false;}catch(_){}
|
|
595
|
+
this.activeCode=null;}
|
|
596
|
+
defuseOrphanActiveBlocks(root){try{const scope=root||document;const nodes=scope.querySelectorAll('pre code[data-_active_stream="1"]');let n=0;nodes.forEach(codeEl=>{if(!codeEl.isConnected)return;let text='';const frozen=codeEl.querySelector('.hl-frozen');const tail=codeEl.querySelector('.hl-tail');if(frozen||tail)text=(frozen?.textContent||'')+(tail?.textContent||'');else text=codeEl.textContent||'';codeEl.textContent=text;codeEl.removeAttribute('data-highlighted');codeEl.classList.remove('hljs');codeEl.dataset._active_stream='0';try{this.codeScroll.attachHandlers(codeEl);}catch(_){}
|
|
597
|
+
n++;});if(n)this._d('code.defuseOrphans',{count:n});}catch(e){}}
|
|
598
|
+
abortAndReset(opts){const o=Object.assign({finalizeActive:true,clearBuffer:true,clearMsg:false,defuseOrphans:true,reason:'',suppressLog:false},(opts||{}));this._d('abort',o);try{this.raf.cancelGroup('StreamEngine');}catch(_){}
|
|
599
|
+
try{this.raf.cancel('SE:snapshot');}catch(_){}
|
|
600
|
+
this.snapshotScheduled=false;this.snapshotRAF=0;const hadActive=!!this.activeCode;try{if(this.activeCode){if(o.finalizeActive===true)this.finalizeActiveCode();else this.defuseActiveToPlain();}}catch(e){}
|
|
601
|
+
if(o.defuseOrphans){try{this.defuseOrphanActiveBlocks();}catch(e){}}
|
|
602
|
+
if(o.clearBuffer){this._clearStreamBuffer();this.fenceOpen=false;this.fenceMark='`';this.fenceLen=3;this.fenceTail='';this.fenceBuf='';this.codeStream.open=false;this.codeStream.lines=0;this.codeStream.chars=0;window.__lastSnapshotLen=0;}
|
|
603
|
+
if(o.clearMsg===true){try{this.dom.resetEphemeral();}catch(_){}}
|
|
604
|
+
this._plainReset();}
|
|
605
|
+
profile(){return this.fenceOpen?this.cfg.PROFILE_CODE:this.cfg.PROFILE_TEXT;}
|
|
606
|
+
resetBudget(){this.nextSnapshotStep=this.profile().base;this._d('budget.reset',{step:this.nextSnapshotStep});}
|
|
607
|
+
onlyTrailingWhitespace(s,from,end){for(let i=from;i<end;i++){const c=s.charCodeAt(i);if(c!==0x20&&c!==0x09)return false;}
|
|
608
|
+
return true;}
|
|
609
|
+
updateFenceHeuristic(chunk){const prev=(this.fenceBuf||'');const s=prev+(chunk||'');const preLen=prev.length;const n=s.length;let i=0;let opened=false;let closed=false;let splitAt=-1;let atLineStart=(preLen===0)?true:this._reLineEnd.test(prev);const inNewOrCrosses=(j,k)=>(j>=preLen)||(k>preLen);while(i<n){const ch=s[i];if(ch==='\r'||ch==='\n'){atLineStart=true;i++;continue;}
|
|
610
|
+
if(!atLineStart){i++;continue;}
|
|
611
|
+
atLineStart=false;let j=i;while(j<n){let localSpaces=0;while(j<n&&(s[j]===' '||s[j]==='\t')){localSpaces+=(s[j]==='\t')?4:1;j++;if(localSpaces>3)break;}
|
|
612
|
+
if(j<n&&s[j]==='>'){j++;if(j<n&&s[j]===' ')j++;continue;}
|
|
613
|
+
let saved=j;if(j<n&&(s[j]==='-'||s[j]==='*'||s[j]==='+')){let jj=j+1;if(jj<n&&s[jj]===' ')j=jj+1;else j=saved;}else{let k2=j;let hasDigit=false;while(k2<n&&s[k2]>='0'&&s[k2]<='9'){hasDigit=true;k2++;}
|
|
614
|
+
if(hasDigit&&k2<n&&(s[k2]==='.'||s[k2]===')')){k2++;if(k2<n&&s[k2]===' ')j=k2+1;else j=saved;}else j=saved;}
|
|
615
|
+
break;}
|
|
616
|
+
let indent=0;while(j<n&&(s[j]===' '||s[j]==='\t')){indent+=(s[j]==='\t')?4:1;j++;if(indent>3)break;}
|
|
617
|
+
if(indent>3){i=j;continue;}
|
|
618
|
+
if(!this.fenceOpen&&this._customFenceSpecs&&this._customFenceSpecs.length){for(let ci=0;ci<this._customFenceSpecs.length;ci++){const spec=this._customFenceSpecs[ci];const open=spec&&spec.open?spec.open:'';if(!open)continue;const k=j+open.length;if(k<=n&&s.slice(j,k)===open){if(inNewOrCrosses(j,k)){this.fenceOpen=true;this._fenceCustom=spec;opened=true;this._d('fence.open.custom',{open,at:j});i=k;continue;}}}}else if(this.fenceOpen&&this._fenceCustom&&this._fenceCustom.close){const close=this._fenceCustom.close;const k=j+close.length;if(k<=n&&s.slice(j,k)===close){let eol=k;while(eol<n&&s[eol]!=='\n'&&s[eol]!=='\r')eol++;const onlyWS=this.onlyTrailingWhitespace(s,k,eol);if(onlyWS&&inNewOrCrosses(j,k)){this.fenceOpen=false;this._fenceCustom=null;closed=true;const endInS=k;const rel=endInS-preLen;const splitAt=Math.max(0,Math.min((chunk?chunk.length:0),rel));this._d('fence.close.custom',{close,splitAt});return{opened,closed,splitAt};}}}
|
|
619
|
+
if(j<n&&(s[j]==='`'||s[j]==='~')){const mark=s[j];let k=j;while(k<n&&s[k]===mark)k++;const run=k-j;if(!this.fenceOpen){if(run>=3){if(inNewOrCrosses(j,k)){this.fenceOpen=true;this.fenceMark=mark;this.fenceLen=run;opened=true;this._d('fence.open.std',{mark,run});i=k;continue;}else{i=k;continue;}}}else if(!this._fenceCustom){if(mark===this.fenceMark&&run>=this.fenceLen){if(inNewOrCrosses(j,k)){let eol=k;while(eol<n&&s[eol]!=='\n'&&s[eol]!=='\r')eol++;if(this.onlyTrailingWhitespace(s,k,eol)){this.fenceOpen=false;closed=true;const endInS=k;const rel=endInS-preLen;const splitAt=Math.max(0,Math.min((chunk?chunk.length:0),rel));this._d('fence.close.std',{mark,run,splitAt});return{opened,closed,splitAt};}}else{i=k;continue;}}}}
|
|
620
|
+
i=j+1;}
|
|
621
|
+
const MAX_TAIL=512;this.fenceBuf=s.slice(-MAX_TAIL);this.fenceTail=s.slice(-3);if(opened||closed)this._d('fence.state',{opened,closed,fenceTail:this.fenceTail});return{opened,closed,splitAt:-1};}
|
|
622
|
+
getMsgSnapshotRoot(msg){if(!msg)return null;let snap=msg.querySelector('.md-snapshot-root');if(!snap){snap=document.createElement('div');snap.className='md-snapshot-root';msg.appendChild(snap);this._d('snapshot.root.create',{});}
|
|
623
|
+
return snap;}
|
|
624
|
+
hasStructuralBoundary(chunk){if(!chunk)return false;return this._reStructBoundary.test(chunk);}
|
|
625
|
+
shouldSnapshotOnChunk(chunk,chunkHasNL,hasBoundary){const prof=this.profile();const now=Utils.now();if(this.activeCode&&this.fenceOpen)return false;if((now-this.lastSnapshotTs)<prof.minInterval)return false;if(hasBoundary)return true;const delta=Math.max(0,this.getStreamLength()-(window.__lastSnapshotLen||0));if(this.fenceOpen){if(chunkHasNL&&delta>=this.nextSnapshotStep)return true;return false;}
|
|
626
|
+
if(delta>=this.nextSnapshotStep)return true;return false;}
|
|
627
|
+
maybeScheduleSoftSnapshot(msg,chunkHasNL){const prof=this.profile();if(this.activeCode&&this.fenceOpen)return;if(this.fenceOpen&&this.codeStream.lines<1&&!chunkHasNL)return;const now=Utils.now();if((now-this.lastSnapshotTs)>=prof.softLatency){this._d('snapshot.soft.schedule',{latency:(now-this.lastSnapshotTs),soft:prof.softLatency});this.scheduleSnapshot(msg);}}
|
|
628
|
+
scheduleSnapshot(msg,force=false){if(this.snapshotScheduled&&!this.raf.isScheduled('SE:snapshot'))this.snapshotScheduled=false;if(!force){if(this.snapshotScheduled){this._d('snapshot.schedule.skip',{reason:'alreadyScheduled'});return;}
|
|
629
|
+
if(this.activeCode&&this.fenceOpen){this._d('snapshot.schedule.skip',{reason:'activeCodeFenceOpen'});return;}}else{if(this.snapshotScheduled&&this.raf.isScheduled('SE:snapshot')){this._d('snapshot.schedule.skip',{reason:'alreadyScheduled(forceCollide)'});return;}}
|
|
630
|
+
this.snapshotScheduled=true;this._d('snapshot.schedule',{force,fenceOpen:this.fenceOpen,isStreaming:this.isStreaming});this.raf.schedule('SE:snapshot',()=>{this.snapshotScheduled=false;const msg=this.getMsg(false,'');if(msg)this.renderSnapshot(msg);},'StreamEngine',0);}
|
|
631
|
+
ensureSplitCodeEl(codeEl){if(!codeEl)return null;let frozen=codeEl.querySelector('.hl-frozen');let tail=codeEl.querySelector('.hl-tail');if(frozen&&tail)return{codeEl,frozenEl:frozen,tailEl:tail};const text=codeEl.textContent||'';codeEl.innerHTML='';frozen=document.createElement('span');frozen.className='hl-frozen';tail=document.createElement('span');tail.className='hl-tail';codeEl.appendChild(frozen);codeEl.appendChild(tail);if(text)tail.textContent=text;this._d('code.ensureSplit',{hadText:!!text,textLen:text.length});return{codeEl,frozenEl:frozen,tailEl:tail};}
|
|
632
|
+
setupActiveCodeFromSnapshot(snap){const codes=snap.querySelectorAll('pre code');if(!codes.length)return null;const last=codes[codes.length-1];const cls=Array.from(last.classList).find(c=>c.startsWith('language-'))||'language-plaintext';const lang=(cls.replace('language-','')||'plaintext');const parts=this.ensureSplitCodeEl(last);if(!parts)return null;if(this._lastInjectedEOL&&parts.tailEl&&parts.tailEl.textContent&&parts.tailEl.textContent.endsWith('\n')){parts.tailEl.textContent=parts.tailEl.textContent.slice(0,-1);this._lastInjectedEOL=false;}
|
|
633
|
+
const st=this.codeScroll.state(parts.codeEl);st.autoFollow=true;st.userInteracted=false;parts.codeEl.dataset._active_stream='1';const baseFrozenNL=Utils.countNewlines(parts.frozenEl.textContent||'');const baseTailNL=Utils.countNewlines(parts.tailEl.textContent||'');const ac={codeEl:parts.codeEl,frozenEl:parts.frozenEl,tailEl:parts.tailEl,lang,frozenLen:parts.frozenEl.textContent.length,lastPromoteTs:0,lines:0,tailLines:baseTailNL,linesSincePromote:0,initialLines:baseFrozenNL+baseTailNL,haltHL:false,plainStream:false};this._d('code.active.set',{lang,frozenLen:ac.frozenLen,tailNL:baseTailNL});return ac;}
|
|
634
|
+
rehydrateActiveCode(oldAC,newAC){if(!oldAC||!newAC)return;const newFullText=newAC.codeEl.textContent||'';if(oldAC.plainStream===true){const prevText=oldAC.tailEl?(oldAC.tailEl.textContent||''):'';let delta='';if(newFullText&&newFullText.startsWith(prevText))delta=newFullText.slice(prevText.length);else delta=newFullText;while(newAC.tailEl.firstChild)newAC.tailEl.removeChild(newAC.tailEl.firstChild);let tn=null;if(oldAC._tailTextNode&&oldAC._tailTextNode.parentNode===oldAC.tailEl&&oldAC._tailTextNode.nodeType===Node.TEXT_NODE){tn=oldAC._tailTextNode;}else if(oldAC.tailEl&&oldAC.tailEl.firstChild&&oldAC.tailEl.firstChild.nodeType===Node.TEXT_NODE){tn=oldAC.tailEl.firstChild;}else{tn=document.createTextNode(prevText||'');}
|
|
635
|
+
newAC.tailEl.appendChild(tn);newAC._tailTextNode=tn;if(delta&&delta!==prevText)tn.appendData(delta);newAC.frozenLen=0;newAC.lang=oldAC.lang;newAC.lines=oldAC.lines;newAC.tailLines=Utils.countNewlines((prevText||'')+(delta&&delta!==prevText?delta:''));newAC.lastPromoteTs=oldAC.lastPromoteTs;newAC.linesSincePromote=oldAC.linesSincePromote||0;newAC.initialLines=oldAC.initialLines||0;newAC.haltHL=!!oldAC.haltHL;newAC.plainStream=true;try{oldAC.codeEl=null;oldAC.frozenEl=null;oldAC.tailEl=null;}catch(_){}
|
|
636
|
+
this._d('code.rehydrate.plain',{deltaLen:delta.length});return;}
|
|
637
|
+
const remainder=newFullText.slice(oldAC.frozenLen);if(oldAC.frozenEl){const src=oldAC.frozenEl;const dst=newAC.frozenEl;if(dst&&src){while(src.firstChild)dst.appendChild(src.firstChild);}}
|
|
638
|
+
newAC.tailEl.textContent=remainder;newAC.frozenLen=oldAC.frozenLen;newAC.lang=oldAC.lang;newAC.lines=oldAC.lines;newAC.tailLines=Utils.countNewlines(remainder);newAC.lastPromoteTs=oldAC.lastPromoteTs;newAC.linesSincePromote=oldAC.linesSincePromote||0;newAC.initialLines=oldAC.initialLines||0;newAC.haltHL=!!oldAC.haltHL;newAC.plainStream=!!oldAC.plainStream;try{oldAC.codeEl=null;oldAC.frozenEl=null;oldAC.tailEl=null;}catch(_){}
|
|
639
|
+
this._d('code.rehydrate',{remainderLen:remainder.length,frozenLen:newAC.frozenLen});}
|
|
640
|
+
appendToActiveTail(text){if(!this.activeCode||!this.activeCode.tailEl||!text)return;let tn=this.activeCode._tailTextNode;if(!tn||tn.parentNode!==this.activeCode.tailEl||tn.nodeType!==Node.TEXT_NODE){const t=this.activeCode.tailEl.textContent||'';this.activeCode.tailEl.textContent=t;tn=this.activeCode._tailTextNode=this.activeCode.tailEl.firstChild||document.createTextNode('');if(!tn.parentNode)this.activeCode.tailEl.appendChild(tn);}
|
|
641
|
+
tn.appendData(text);const nl=Utils.countNewlines(text);this.activeCode.tailLines+=nl;this.activeCode.linesSincePromote+=nl;if(((this.activeCode._tailAppends=(this.activeCode._tailAppends|0)+1)%200)===0){this.activeCode.tailEl.normalize();this.activeCode._tailTextNode=this.activeCode.tailEl.firstChild;}
|
|
642
|
+
if(/[<>]/.test(text)){this._d('code.tail.append',{len:text.length,nl,head:text.slice(0,80),tail:text.slice(-80)});}
|
|
643
|
+
this.codeScroll.scheduleScroll(this.activeCode.codeEl,true,false);}
|
|
644
|
+
enforceHLStopBudget(){if(!this.activeCode)return;if(this.cfg.HL.DISABLE_ALL){this.activeCode.haltHL=true;this.activeCode.plainStream=true;return;}
|
|
645
|
+
const stop=(this.cfg.PROFILE_CODE.stopAfterLines|0);const streamPlainLines=(this.cfg.PROFILE_CODE.streamPlainAfterLines|0);const streamPlainChars=(this.cfg.PROFILE_CODE.streamPlainAfterChars|0);const maxFrozenChars=(this.cfg.PROFILE_CODE.maxFrozenChars|0);const totalLines=(this.activeCode.initialLines||0)+(this.activeCode.lines||0);const frozenChars=this.activeCode.frozenLen|0;const tailChars=(this.activeCode.tailEl?.textContent||'').length|0;const totalStreamedChars=frozenChars+tailChars;if((streamPlainLines>0&&totalLines>=streamPlainLines)||(streamPlainChars>0&&totalStreamedChars>=streamPlainChars)||(maxFrozenChars>0&&frozenChars>=maxFrozenChars)){this.activeCode.haltHL=true;this.activeCode.plainStream=true;try{this.activeCode.codeEl.dataset.hlStreamSuspended='1';}catch(_){}
|
|
646
|
+
this._d('code.hl.budget.stop',{totalLines,totalStreamedChars,frozenChars,streamPlainLines,streamPlainChars,maxFrozenChars});return;}
|
|
647
|
+
if(stop>0&&totalLines>=stop){this.activeCode.haltHL=true;this.activeCode.plainStream=true;try{this.activeCode.codeEl.dataset.hlStreamSuspended='1';}catch(_){}
|
|
648
|
+
this._d('code.hl.budget.hardStop',{totalLines,stop});}}
|
|
649
|
+
_aliasLang(token){const v=String(token||'').trim().toLowerCase();return this.highlighter.ALIAS[v]||v;}
|
|
650
|
+
_isHLJSSupported(lang){try{return!!(window.hljs&&hljs.getLanguage&&hljs.getLanguage(lang));}catch(_){return false;}}
|
|
651
|
+
_detectDirectiveLangFromText(text){if(!text)return null;let s=String(text);if(s.charCodeAt(0)===0xFEFF)s=s.slice(1);const lines=s.split(/\r?\n/);let i=0;while(i<lines.length&&!lines[i].trim())i++;if(i>=lines.length)return null;let first=lines[i].trim();first=first.replace(/^\s*lang(?:uage)?\s*[:=]\s*/i,'').trim();let token=first.split(/\s+/)[0].replace(/:$/,'');if(!/^[A-Za-z][\w#+\-\.]{0,30}$/.test(token))return null;let cand=this._aliasLang(token);const rest=lines.slice(i+1).join('\n');if(!rest.trim())return null;let pos=0,seen=0;while(seen<i&&pos<s.length){const nl=s.indexOf('\n',pos);if(nl===-1)return null;pos=nl+1;seen++;}
|
|
652
|
+
let end=s.indexOf('\n',pos);if(end===-1)end=s.length;else end=end+1;this._d('code.lang.directive.detect',{lang:cand,deleteUpto:end});return{lang:cand,deleteUpto:end};}
|
|
653
|
+
_updateCodeLangClass(codeEl,newLang){try{Array.from(codeEl.classList).forEach(c=>{if(c.startsWith('language-'))codeEl.classList.remove(c);});}catch(_){}
|
|
654
|
+
try{codeEl.classList.add('language-'+(newLang||'plaintext'));}catch(_){}}
|
|
655
|
+
_updateCodeHeaderLabel(codeEl,newLabel,newLangToken){try{const wrap=codeEl.closest('.code-wrapper');if(!wrap)return;const span=wrap.querySelector('.code-header-lang');if(span)span.textContent=newLabel||(newLangToken||'code');wrap.setAttribute('data-code-lang',newLangToken||'');}catch(_){}}
|
|
656
|
+
maybePromoteLanguageFromDirective(){if(!this.activeCode||!this.activeCode.codeEl)return;if(this.activeCode.lang&&this.activeCode.lang!=='plaintext')return;const frozenTxt=this.activeCode.frozenEl?this.activeCode.frozenEl.textContent:'';const tailTxt=this.activeCode.tailEl?this.activeCode.tailEl.textContent:'';const combined=frozenTxt+tailTxt;if(!combined)return;const det=this._detectDirectiveLangFromText(combined);if(!det||!det.lang)return;const newLang=det.lang;const newCombined=combined.slice(det.deleteUpto);try{const codeEl=this.activeCode.codeEl;codeEl.innerHTML='';const frozen=document.createElement('span');frozen.className='hl-frozen';const tail=document.createElement('span');tail.className='hl-tail';tail.textContent=newCombined;codeEl.appendChild(frozen);codeEl.appendChild(tail);this.activeCode.frozenEl=frozen;this.activeCode.tailEl=tail;this.activeCode.frozenLen=0;this.activeCode.tailLines=Utils.countNewlines(newCombined);this.activeCode.linesSincePromote=0;this.activeCode.lang=newLang;this._updateCodeLangClass(codeEl,newLang);this._updateCodeHeaderLabel(codeEl,newLang,newLang);this._d('code.lang.directive.promote',{newLang,tailLen:newCombined.length});this.schedulePromoteTail(true);}catch(e){}}
|
|
657
|
+
highlightDeltaText(lang,text){if(this.cfg.HL.DISABLE_ALL)return Utils.escapeHtml(text);if(window.hljs&&lang&&hljs.getLanguage&&hljs.getLanguage(lang)){try{return hljs.highlight(text,{language:lang,ignoreIllegals:true}).value;}catch(_){return Utils.escapeHtml(text);}}
|
|
658
|
+
return Utils.escapeHtml(text);}
|
|
659
|
+
schedulePromoteTail(force=false){if(!this.activeCode||!this.activeCode.tailEl)return;if(this.activeCode.plainStream===true)return;if(this._promoteScheduled)return;this._promoteScheduled=true;this._d('code.promote.schedule',{force});this.raf.schedule('SE:promoteTail',()=>{this._promoteScheduled=false;this._promoteTailWork(force);},'StreamEngine',1);}
|
|
660
|
+
async _promoteTailWork(force=false){if(!this.activeCode||!this.activeCode.tailEl)return;if(this.activeCode.plainStream===true)return;const now=Utils.now();const prof=this.cfg.PROFILE_CODE;const tailText0=this.activeCode.tailEl.textContent||'';if(!tailText0)return;if(!force){if((now-this.activeCode.lastPromoteTs)<prof.promoteMinInterval)return;const enoughLines=(this.activeCode.linesSincePromote||0)>=(prof.promoteMinLines||10);const enoughChars=tailText0.length>=prof.minCharsForHL;if(!enoughLines&&!enoughChars)return;}
|
|
661
|
+
const idx=tailText0.lastIndexOf('\n');const usePlain=this.activeCode.haltHL||this.activeCode.plainStream||!this._isHLJSSupported(this.activeCode.lang);let cut=-1;if(idx>=0)cut=idx+1;else if(usePlain){const PLAIN_PROMOTE_CHARS=this.cfg.PROFILE_CODE.minPlainPromoteChars||8192;if(tailText0.length>=PLAIN_PROMOTE_CHARS||force)cut=tailText0.length;}
|
|
662
|
+
if(cut<=0)return;const delta=tailText0.slice(0,cut);if(!delta)return;this.enforceHLStopBudget();if(!usePlain)await this.asyncer.yield();if(!this.activeCode||!this.activeCode.tailEl)return;const tailNow=this.activeCode.tailEl.textContent||'';if(!tailNow.startsWith(delta)){this._d('code.promote.tailChanged',{expectedLen:delta.length,tailNowLen:tailNow.length});this.schedulePromoteTail(false);return;}
|
|
663
|
+
if(usePlain){let tn=this.activeCode._frozenTextNode;if(!tn||tn.parentNode!==this.activeCode.frozenEl){tn=document.createTextNode('');this.activeCode.frozenEl.appendChild(tn);this.activeCode._frozenTextNode=tn;}
|
|
664
|
+
tn.appendData(delta);}else{let html=Utils.escapeHtml(delta);try{html=this.highlightDeltaText(this.activeCode.lang,delta);}catch(_){html=Utils.escapeHtml(delta);}
|
|
665
|
+
if(this._tpl){this._tpl.innerHTML=html;while(this._tpl.content.firstChild)this.activeCode.frozenEl.appendChild(this._tpl.content.firstChild);}else{this.activeCode.frozenEl.insertAdjacentHTML('beforeend',html);}
|
|
666
|
+
html=null;}
|
|
667
|
+
this.activeCode.tailEl.textContent=tailNow.slice(delta.length);this.activeCode.frozenLen+=delta.length;const promotedLines=Utils.countNewlines(delta);this.activeCode.tailLines=Math.max(0,(this.activeCode.tailLines||0)-promotedLines);this.activeCode.linesSincePromote=Math.max(0,(this.activeCode.linesSincePromote||0)-promotedLines);this.activeCode.lastPromoteTs=Utils.now();this._d('code.promote.done',{plain:usePlain,deltaLen:delta.length,promotedLines,frozenLen:this.activeCode.frozenLen,tailLenNow:(this.activeCode.tailEl.textContent||'').length});}
|
|
668
|
+
_normTextForFP(s){if(!s)return'';let t=String(s);if(t.charCodeAt(0)===0xFEFF)t=t.slice(1);t=t.replace(/\r\n?/g,'\n');if(t.endsWith('\n'))t=t.slice(0,-1);return t;}
|
|
669
|
+
_hash32FNV(str){let h=0x811c9dc5>>>0;for(let i=0;i<str.length;i++){h^=str.charCodeAt(i);h=(h+((h<<1)+(h<<4)+(h<<7)+(h<<8)+(h<<24)))>>>0;}
|
|
670
|
+
return('00000000'+h.toString(16)).slice(-8);}
|
|
671
|
+
_codeLangFromEl(codeEl){try{const cls=Array.from(codeEl.classList).find(c=>c.startsWith('language-'))||'language-plaintext';return(cls.replace('language-','')||'plaintext');}catch(_){return'plaintext';}}
|
|
672
|
+
_fpKeyFromCodeEl(codeEl){try{const lang=this._codeLangFromEl(codeEl);const norm=this._normTextForFP(codeEl.textContent||'');return`${lang}|${norm.length}|${this._hash32FNV(norm)}`;}catch(_){return'';}}
|
|
673
|
+
finalizeActiveCode(){if(!this.activeCode)return;const ac=this.activeCode;const codeEl=ac.codeEl;if(!codeEl||!codeEl.isConnected){this.activeCode=null;return;}
|
|
674
|
+
this._d('code.finalize.begin',{lang:ac.lang,frozenLen:ac.frozenLen,tailLen:(ac.tailEl?(ac.tailEl.textContent||'').length:0),plainStream:!!ac.plainStream});const fromBottomBefore=Math.max(0,codeEl.scrollHeight-codeEl.clientHeight-codeEl.scrollTop);const wasNearBottom=this.codeScroll.isNearBottomEl(codeEl,this.cfg.CODE_SCROLL.NEAR_MARGIN_PX);const tailTXT=ac.tailEl?(ac.tailEl.textContent||''):'';const canHL=!this.cfg.HL.DISABLE_ALL&&!ac.plainStream&&this._isHLJSSupported(ac.lang);const frag=document.createDocumentFragment();try{if(ac.frozenEl){while(ac.frozenEl.firstChild)frag.appendChild(ac.frozenEl.firstChild);}}catch(_){}
|
|
675
|
+
try{if(tailTXT){if(canHL){let tailHTML='';try{tailHTML=this.highlightDeltaText(ac.lang,tailTXT);}catch(_){tailHTML=Utils.escapeHtml(tailTXT);}
|
|
676
|
+
if(this._tpl){this._tpl.innerHTML=tailHTML;while(this._tpl.content.firstChild)frag.appendChild(this._tpl.content.firstChild);}else{const tpl=document.createElement('template');tpl.innerHTML=tailHTML;frag.appendChild(tpl.content);}}else{frag.appendChild(document.createTextNode(tailTXT));}}}catch(_){}
|
|
677
|
+
try{codeEl.textContent='';codeEl.appendChild(frag);codeEl.classList.add('hljs');codeEl.setAttribute('data-highlighted','yes');codeEl.dataset._active_stream='0';}catch(_){}
|
|
678
|
+
try{const totalChars=(ac.frozenLen|0)+(tailTXT?tailTXT.length:0);const totalLines=(ac.initialLines|0)+(ac.lines|0);this._updateCodeWrapperMetaFast(codeEl,totalChars,totalLines,ac.lang);}catch(_){}
|
|
679
|
+
const st=this.codeScroll.state(codeEl);st.autoFollow=false;const maxScrollTop=Math.max(0,codeEl.scrollHeight-codeEl.clientHeight);const target=wasNearBottom?maxScrollTop:Math.max(0,maxScrollTop-fromBottomBefore);try{codeEl.scrollTop=target;}catch(_){}
|
|
680
|
+
st.lastScrollTop=codeEl.scrollTop;try{codeEl.dataset.justFinalized='1';}catch(_){}
|
|
681
|
+
this.codeScroll.scheduleScroll(codeEl,false,true);this.suppressPostFinalizePass=true;try{ac._tailTextNode=null;ac._frozenTextNode=null;ac.frozenEl=null;ac.tailEl=null;ac.codeEl=null;}catch(_){}
|
|
682
|
+
this.activeCode=null;this._d('code.finalize.end',{});}
|
|
683
|
+
codeFingerprint(codeEl){const cls=Array.from(codeEl.classList).find(c=>c.startsWith('language-'))||'language-plaintext';const lang=cls.replace('language-','')||'plaintext';const t=codeEl.textContent||'';const len=t.length;const head=t.slice(0,64);const tail=t.slice(-64);return`${lang}|${len}|${head}|${tail}`;}
|
|
684
|
+
codeFingerprintFromWrapper(codeEl){try{const wrap=codeEl.closest('.code-wrapper');if(!wrap)return null;const fpStable=wrap.getAttribute('data-fp');if(fpStable)return fpStable;const cls=Array.from(codeEl.classList).find(c=>c.startsWith('language-'))||'language-plaintext';const lang=(cls.replace('language-','')||'plaintext');const lenAttr=wrap.getAttribute('data-code-len');const headAttr=wrap.getAttribute('data-code-head')||'';const tailAttr=wrap.getAttribute('data-code-tail')||'';if(!lenAttr)return null;const txt=codeEl.textContent||'';const lenNow=txt.length;const lenNum=parseInt(lenAttr,10);if(!Number.isFinite(lenNum)||lenNum!==lenNow)return null;const headNowEsc=Utils.escapeHtml(txt.slice(0,64));const tailNowEsc=Utils.escapeHtml(txt.slice(-64));if((headAttr&&headAttr!==headNowEsc)||(tailAttr&&tailAttr!==tailNowEsc)){return null;}
|
|
685
|
+
return`${lang}|${lenAttr}|${headAttr}|${tailAttr}`;}catch(_){return null;}}
|
|
686
|
+
preserveStableClosedCodes(oldSnap,newRoot,skipLastIfStreaming){try{const oldCodes=oldSnap.querySelectorAll('pre code');if(!oldCodes||!oldCodes.length)return;const newCodesPre=newRoot.querySelectorAll('pre code');if(!newCodesPre||!newCodesPre.length)return;const limit=(this.cfg.STREAM&&this.cfg.STREAM.PRESERVE_CODES_MAX)||200;if(newCodesPre.length>limit||oldCodes.length>limit)return;this._d('codes.preserve.scan',{old:oldCodes.length,anew:newCodesPre.length,skipLastIfStreaming});const map=new Map();const push=(key,el)=>{if(!key)return;let arr=map.get(key);if(!arr){arr=[];map.set(key,arr);}
|
|
687
|
+
arr.push(el);};const makeAttrKey=(wrap)=>{if(!wrap)return'';const lang=(wrap.getAttribute('data-code-lang')||'plaintext');const len=(wrap.getAttribute('data-code-len')||'0');const head=(wrap.getAttribute('data-code-head')||'');const tail=(wrap.getAttribute('data-code-tail')||'');return`${lang}|${len}|${head}|${tail}`;};for(let idx=0;idx<oldCodes.length;idx++){const el=oldCodes[idx];if(el.querySelector('.hl-frozen'))continue;if(this.activeCode&&el===this.activeCode.codeEl)continue;const wrap=el.closest('.code-wrapper');const fpStable=wrap?wrap.getAttribute('data-fp'):null;if(fpStable){push(`S|${fpStable}`,el);}else{push(`A|${makeAttrKey(wrap)}`,el);}}
|
|
688
|
+
const end=(skipLastIfStreaming&&newCodesPre.length>0)?(newCodesPre.length-1):newCodesPre.length;for(let i=0;i<end;i++){const nc=newCodesPre[i];if(nc.getAttribute('data-highlighted')==='yes')continue;const wrap=nc.closest('.code-wrapper');let swapped=false;const fpStableNew=wrap?wrap.getAttribute('data-fp'):null;if(fpStableNew){const arr=map.get(`S|${fpStableNew}`);if(arr&&arr.length){const oldEl=arr.pop();if(oldEl&&oldEl.isConnected){try{nc.replaceWith(oldEl);this.codeScroll.attachHandlers(oldEl);if(!oldEl.getAttribute('data-highlighted'))oldEl.setAttribute('data-highlighted','yes');const st=this.codeScroll.state(oldEl);st.autoFollow=false;}catch(_){}
|
|
689
|
+
swapped=true;}
|
|
690
|
+
if(!arr.length)map.delete(`S|${fpStableNew}`);}}
|
|
691
|
+
if(swapped)continue;const attrKey=`A|${makeAttrKey(wrap)}`;const arr2=map.get(attrKey);if(arr2&&arr2.length){const oldEl=arr2.pop();if(oldEl&&oldEl.isConnected){try{nc.replaceWith(oldEl);this.codeScroll.attachHandlers(oldEl);if(!oldEl.getAttribute('data-highlighted'))oldEl.setAttribute('data-highlighted','yes');const st=this.codeScroll.state(oldEl);st.autoFollow=false;}catch(_){}}
|
|
692
|
+
if(!arr2.length)map.delete(attrKey);}}}catch(e){}}
|
|
693
|
+
_ensureSplitContainers(codeEl){try{const scope=codeEl||document;const nodes=scope.querySelectorAll('pre code[data-just-finalized="1"]');if(!nodes||!nodes.length)return;nodes.forEach((codeEl)=>{this.codeScroll.scheduleScroll(codeEl,false,true);const wrap=codeEl.closest('.code-wrapper');const idx=wrap?(wrap.getAttribute('data-index')||''):'';const key=`JF:forceBottom#${idx}`;this.raf.schedule(key,()=>{this.codeScroll.scrollToBottom(codeEl,false,true);try{codeEl.dataset.justFinalized='0';}catch(_){}},'CodeScroll',2);});}catch(_){}}
|
|
694
|
+
_ensureBottomForJustFinalized(root){try{const scope=root||document;const nodes=scope.querySelectorAll('pre code[data-just-finalized="1"]');if(!nodes||!nodes.length)return;nodes.forEach((codeEl)=>{const wrap=codeEl.closest('.code-wrapper');const idx=wrap?(wrap.getAttribute('data-index')||''):'';const key=`JF:ensureBottom#${idx}`;this.codeScroll.scheduleScroll(codeEl,false,true);this.raf.schedule(key,()=>{this.codeScroll.scrollToBottom(codeEl,false,true);try{codeEl.dataset.justFinalized='0';}catch(_){}},'CodeScroll',2);});}catch(_){}}
|
|
695
|
+
kickVisibility(){const msg=this.getMsg(false,'');if(!msg)return;if(this.codeStream.open&&!this.activeCode){this._d('kick.visibility',{reason:'codeStreamOpenNoActive'});this.scheduleSnapshot(msg,true);return;}
|
|
696
|
+
const needSnap=(this.getStreamLength()!==(window.__lastSnapshotLen||0));if(needSnap){this._d('kick.visibility',{reason:'bufferDelta'});this.scheduleSnapshot(msg,true);}
|
|
697
|
+
if(this.activeCode&&this.activeCode.codeEl){this.codeScroll.scheduleScroll(this.activeCode.codeEl,true,false);this.schedulePromoteTail(true);}}
|
|
698
|
+
stabilizeHeaderLabel(prevAC,newAC){try{if(!newAC||!newAC.codeEl||!newAC.codeEl.isConnected)return;const wrap=newAC.codeEl.closest('.code-wrapper');if(!wrap)return;const span=wrap.querySelector('.code-header-lang');const curLabel=(span&&span.textContent?span.textContent.trim():'').toLowerCase();if(curLabel==='output')return;const tokNow=(wrap.getAttribute('data-code-lang')||'').trim().toLowerCase();const sticky=(wrap.getAttribute('data-lang-sticky')||'').trim().toLowerCase();const prev=(prevAC&&prevAC.lang&&prevAC.lang!=='plaintext')?prevAC.lang.toLowerCase():'';const valid=(t)=>!!t&&t!=='plaintext'&&this._isHLJSSupported(t);let finalTok='';if(valid(tokNow))finalTok=tokNow;else if(valid(prev))finalTok=prev;else if(valid(sticky))finalTok=sticky;if(finalTok){this._updateCodeLangClass(newAC.codeEl,finalTok);this._updateCodeHeaderLabel(newAC.codeEl,finalTok,finalTok);try{wrap.setAttribute('data-code-lang',finalTok);}catch(_){}
|
|
699
|
+
try{wrap.setAttribute('data-lang-sticky',finalTok);}catch(_){}
|
|
700
|
+
newAC.lang=finalTok;this._d('code.header.stabilize',{finalTok});}else{if(span&&curLabel&&curLabel.length<3)span.textContent='code';}}catch(_){}}
|
|
701
|
+
_patchSnapshotRoot(snap,frag){try{const oldKids=snap.childNodes;const newKids=frag.childNodes;const aLen=oldKids.length;const bLen=newKids.length;if(aLen===0){snap.appendChild(frag);this._d('snapshot.patch.first',{newCount:bLen});return;}
|
|
702
|
+
const MAX_CMP=6;const eq=(a,b)=>{try{if(!a||!b)return false;if(a.nodeType!==b.nodeType)return false;if(a.nodeType===3||a.nodeType===8)return a.nodeValue===b.nodeValue;if(a.nodeType===1){const ae=a,be=b;if(ae.tagName!==be.tagName)return false;const acls=ae.className||'';if(acls!==(be.className||''))return false;return ae.isEqualNode(be);}
|
|
703
|
+
return false;}catch(_){return false;}};let i=0,j=0;const iMax=Math.min(aLen,bLen,MAX_CMP);while(i<iMax&&eq(oldKids[i],newKids[i]))i++;const jMax=Math.min(aLen-i,bLen-i,MAX_CMP);while(j<jMax&&eq(oldKids[aLen-1-j],newKids[bLen-1-j]))j++;const removeStart=i;const removeEnd=aLen-j;for(let k=removeStart;k<removeEnd;k++){const node=snap.childNodes[removeStart];if(node){try{snap.removeChild(node);}catch(_){}}}
|
|
704
|
+
const insStart=i,insEnd=bLen-j;if(insStart<insEnd){const mid=document.createDocumentFragment();for(let k=insStart;k<insEnd;k++){if(newKids[insStart])mid.appendChild(newKids[insStart]);}
|
|
705
|
+
const ref=(i<snap.childNodes.length)?snap.childNodes[i]:null;if(ref)snap.insertBefore(mid,ref);else snap.appendChild(mid);}
|
|
706
|
+
this._d('snapshot.patch',{oldCount:aLen,newCount:bLen,removed:(removeEnd-removeStart),inserted:(bLen-j-i)});}catch(_){try{snap.replaceChildren(frag);this._d('snapshot.patch.replaceAll',{});}catch(__){}}}
|
|
707
|
+
_chunkHasMarkdown(s){try{return this._mdQuickRe.test(String(s||''));}catch(_){return false;}}
|
|
708
|
+
_chunkHasCustomOpeners(s){try{const CM=this.renderer&&this.renderer.customMarkup;if(!CM||typeof CM.hasAnyStreamOpenToken!=='function')return false;return CM.hasAnyStreamOpenToken(String(s||''));}catch(_){return false;}}
|
|
709
|
+
renderSnapshot(msg){const streaming=!!this.isStreaming;const snap=this.getMsgSnapshotRoot(msg);if(!snap)return;const prevLen=(window.__lastSnapshotLen||0);const curLen=this.getStreamLength();if(!this.fenceOpen&&!this.activeCode&&curLen===prevLen){this.lastSnapshotTs=Utils.now();return;}
|
|
710
|
+
const forceFull=!!this.plain.forceFullMDOnce;const streamingPlain=streaming&&!this.fenceOpen&&!forceFull&&this.plain.enabled;this._d('snapshot.begin',{streaming,fenceOpen:this.fenceOpen,streamingPlain,forceFull,prevLen,curLen});if(streamingPlain){const delta=this.getDeltaSince(prevLen);this._plainAppendDelta(snap,delta);window.__lastSnapshotLen=curLen;this.lastSnapshotTs=Utils.now();const prof=this.profile();if(prof.adaptiveStep){const maxStep=this.cfg.STREAM.SNAPSHOT_MAX_STEP||8000;this.nextSnapshotStep=Math.min(Math.ceil(this.nextSnapshotStep*prof.growth),maxStep);}else{this.nextSnapshotStep=prof.base;}
|
|
711
|
+
this.scrollMgr.scheduleScroll(true);this.scrollMgr.fabFreezeUntil=Utils.now()+this.cfg.FAB.TOGGLE_DEBOUNCE_MS;this.scrollMgr.scheduleScrollFabUpdate();this._d('snapshot.end.plain',{nextStep:this.nextSnapshotStep});return;}
|
|
712
|
+
if(forceFull)this.plain.forceFullMDOnce=false;let allText=this.getStreamText();this.plain._carry='';const needSyntheticEOL=(this.fenceOpen&&!/[\r\n]$/.test(allText));this._lastInjectedEOL=!!needSyntheticEOL;let src=needSyntheticEOL?(allText+'\n'):allText;if(/[<>]/.test(src))this._d('snapshot.full.src',{len:src.length,head:src.slice(0,120),tail:src.slice(-120),injectedEOL:needSyntheticEOL});let frag=null;if(streaming)frag=this.renderer.renderStreamingSnapshotFragment(src);else frag=this.renderer.renderFinalSnapshotFragment(src);try{if(this.renderer&&this.renderer.customMarkup&&this.renderer.customMarkup.hasStreamRules()){const MDinline=this.renderer.MD_STREAM||this.renderer.MD||null;this.renderer.customMarkup.applyStream(frag,MDinline);}}catch(_){}
|
|
713
|
+
this.preserveStableClosedCodes(snap,frag,this.fenceOpen===true);this._patchSnapshotRoot(snap,frag);try{if(this.highlighter&&typeof this.highlighter.microHighlightNow==='function'){this.highlighter.microHighlightNow(snap,{maxCount:1,budgetMs:4},this.activeCode);}}catch(_){}
|
|
714
|
+
this.renderer.restoreCollapsedCode(snap);this._ensureBottomForJustFinalized(snap);const prevAC=this.activeCode;if(this.fenceOpen){const newAC=this.setupActiveCodeFromSnapshot(snap);if(prevAC&&newAC)this.rehydrateActiveCode(prevAC,newAC);this.stabilizeHeaderLabel(prevAC||null,newAC||null);this.activeCode=newAC||null;}else{this.activeCode=null;}
|
|
715
|
+
if(!this.fenceOpen){this.codeScroll.initScrollableBlocks(snap);}
|
|
716
|
+
this.highlighter.observeNewCode(snap,{deferLastIfStreaming:true,minLinesForLast:this.cfg.PROFILE_CODE.minLinesForHL,minCharsForLast:this.cfg.PROFILE_CODE.minCharsForHL},this.activeCode);this.highlighter.observeMsgBoxes(snap,(box)=>{this.highlighter.observeNewCode(box,{deferLastIfStreaming:true,minLinesForLast:this.cfg.PROFILE_CODE.minLinesForHL,minCharsForLast:this.cfg.PROFILE_CODE.minCharsForHL},this.activeCode);this.codeScroll.initScrollableBlocks(box);});const mm=getMathMode();if(!this.suppressPostFinalizePass){if(mm==='idle')this.math.schedule(snap);else if(mm==='always')this.math.schedule(snap,0,true);}
|
|
717
|
+
if(this.fenceOpen&&this.activeCode&&this.activeCode.codeEl){this.codeScroll.attachHandlers(this.activeCode.codeEl);this.codeScroll.scheduleScroll(this.activeCode.codeEl,true,false);}else if(!this.fenceOpen){this.codeScroll.initScrollableBlocks(snap);}
|
|
718
|
+
window.__lastSnapshotLen=this.getStreamLength();this.lastSnapshotTs=Utils.now();const prof=this.profile();if(prof.adaptiveStep){const maxStep=this.cfg.STREAM.SNAPSHOT_MAX_STEP||8000;this.nextSnapshotStep=Math.min(Math.ceil(this.nextSnapshotStep*prof.growth),maxStep);}else{this.nextSnapshotStep=prof.base;}
|
|
719
|
+
this.scrollMgr.scheduleScroll(true);this.scrollMgr.fabFreezeUntil=Utils.now()+this.cfg.FAB.TOGGLE_DEBOUNCE_MS;this.scrollMgr.scheduleScrollFabUpdate();if(this.suppressPostFinalizePass)this.suppressPostFinalizePass=false;frag=null;src=null;allText=null;this._d('snapshot.end.full',{nextStep:this.nextSnapshotStep,fenceOpen:this.fenceOpen,hasActiveCode:!!this.activeCode});}
|
|
720
|
+
_updateCodeWrapperMeta(codeEl){try{const wrap=codeEl.closest('.code-wrapper');if(!wrap)return;const txt=codeEl.textContent||'';wrap.setAttribute('data-code-len',String(txt.length));wrap.setAttribute('data-code-head',Utils.escapeHtml(txt.slice(0,64)));wrap.setAttribute('data-code-tail',Utils.escapeHtml(txt.slice(-64)));wrap.setAttribute('data-code-nl',String(Utils.countNewlines(txt)));const lang=this._codeLangFromEl(codeEl);wrap.setAttribute('data-code-lang',lang);const norm=this._normTextForFP(txt);const fp=`${lang}|${norm.length}|${this._hash32FNV(norm)}`;wrap.setAttribute('data-fp',fp);}catch(_){}}
|
|
721
|
+
_updateCodeWrapperMetaFast(codeEl,len,nl,langTok){try{const wrap=codeEl.closest('.code-wrapper');if(!wrap)return;if(Number.isFinite(len))wrap.setAttribute('data-code-len',String(len));if(Number.isFinite(nl))wrap.setAttribute('data-code-nl',String(nl));if(langTok){wrap.setAttribute('data-code-lang',String(langTok));this._updateCodeLangClass(codeEl,langTok);}}catch(_){}}
|
|
722
|
+
getMsg(create,name_header){return this.dom.getStreamMsg(create,name_header);}
|
|
723
|
+
beginStream(chunk=false){this.isStreaming=true;this._d('stream.begin',{chunk});if(chunk){try{runtime.loading.hide();}catch(_){}}
|
|
724
|
+
this.scrollMgr.userInteracted=false;this.dom.clearOutput();this.reset();this.scrollMgr.forceScrollToBottomImmediate();this.scrollMgr.scheduleScroll();}
|
|
725
|
+
endStream(){this.isStreaming=false;const msg=this.getMsg(false,'');if(msg)this.renderSnapshot(msg);this.snapshotScheduled=false;try{this.raf.cancel('SE:snapshot');}catch(_){}
|
|
726
|
+
try{this.raf.cancelGroup('StreamEngine');}catch(_){}
|
|
727
|
+
try{this.raf.cancelGroup('CodeScroll');}catch(_){}
|
|
728
|
+
try{this.raf.cancelGroup('ScrollMgr');}catch(_){}
|
|
729
|
+
this.snapshotRAF=0;const hadActive=!!this.activeCode;if(this.activeCode)this.finalizeActiveCode();if(!hadActive){if(this.highlighter.hlQueue&&this.highlighter.hlQueue.length){this.highlighter.flush(this.activeCode);}
|
|
730
|
+
const snap=msg?this.getMsgSnapshotRoot(msg):null;if(snap)this.math.renderAsync(snap);}
|
|
731
|
+
this._clearStreamBuffer();this.fenceOpen=false;this.codeStream.open=false;this.activeCode=null;this.lastSnapshotTs=Utils.now();this.suppressPostFinalizePass=false;this._plainReset();this._d('stream.end',{hadActive});}
|
|
732
|
+
_maybeEagerSnapshotForCustomOpeners(msg,chunkStr){try{const CM=this.renderer&&this.renderer.customMarkup;if(!CM||!CM.hasStreamRules())return;if(this.fenceOpen||this.codeStream.open)return;const isFirstSnapshot=((window.__lastSnapshotLen||0)===0);if(isFirstSnapshot){let head;try{head=this.getStreamText();}catch(_){head=String(chunkStr||'');}
|
|
733
|
+
if(CM.hasStreamOpenerAtStart(head)){this._d('snapshot.eager.custom',{reason:'headHasOpener'});this.scheduleSnapshot(msg,true);return;}}
|
|
734
|
+
const rules=(CM.getRules()||[]).filter(r=>r&&r.stream&&typeof r.open==='string');if(rules.length&&CM.hasAnyOpenToken(String(chunkStr||''),rules)){this._d('snapshot.eager.custom',{reason:'chunkHasOpener'});this.scheduleSnapshot(msg);}}catch(_){}}
|
|
735
|
+
applyStream(name_header,chunk,alreadyBuffered=false){if(!this.activeCode&&!this.fenceOpen){try{if(document.querySelector('pre code[data-_active_stream="1"]'))this.defuseOrphanActiveBlocks();}catch(_){}}
|
|
736
|
+
if(this.snapshotScheduled&&!this.raf.isScheduled('SE:snapshot'))this.snapshotScheduled=false;const msg=this.getMsg(true,name_header);if(!msg||!chunk)return;const s=String(chunk);if(/[<>]/.test(s)){this._d('apply.chunk',{len:s.length,nl:Utils.countNewlines(s),head:s.slice(0,120),tail:s.slice(-120)});}
|
|
737
|
+
if(!alreadyBuffered)this._appendChunk(s);const change=this.updateFenceHeuristic(s);const nlCount=Utils.countNewlines(s);const chunkHasNL=nlCount>0;if(!change.opened&&!this.fenceOpen){this._maybeEagerSnapshotForCustomOpeners(msg,s);}
|
|
738
|
+
if(!this.fenceOpen&&!this.codeStream.open){const mdPresent=this._chunkHasMarkdown(s)||this._chunkHasCustomOpeners(s)||change.opened;const thr=this._plainThreshold();if(mdPresent){if(this.plain.noMdNL!==0){this._d('apply.plain.resetOnMD',{noMdNL:this.plain.noMdNL});}
|
|
739
|
+
this.plain.noMdNL=0;if(this.plain.enabled){this.plain.enabled=false;this.plain.suppressInline=false;this.plain.forceFullMDOnce=true;this._d('apply.plain.disableOnMD',{});this.scheduleSnapshot(msg,true);}}else if(chunkHasNL){this.plain.noMdNL+=nlCount;if(!this.plain.enabled&&this.plain.noMdNL>=thr){this.plain.enabled=true;this.plain.suppressInline=true;this._d('apply.plain.enable',{noMdNL:this.plain.noMdNL,thr});this.scheduleSnapshot(msg);}}}
|
|
740
|
+
let didImmediateOpenSnap=false;if(change.opened){this.codeStream.open=true;this.codeStream.lines=0;this.codeStream.chars=0;this.resetBudget();this._d('code.open',{});this.scheduleSnapshot(msg);if(!this._firstCodeOpenSnapDone&&!this.activeCode&&((window.__lastSnapshotLen||0)===0)){try{this.renderSnapshot(msg);try{this.raf.cancel('SE:snapshot');}catch(_){}
|
|
741
|
+
this.snapshotScheduled=false;this._firstCodeOpenSnapDone=true;didImmediateOpenSnap=true;this._d('code.open.immediateSnap',{});}catch(_){}}}
|
|
742
|
+
if(this.codeStream.open){this.codeStream.lines+=nlCount;this.codeStream.chars+=s.length;if(this.activeCode&&this.activeCode.codeEl&&this.activeCode.codeEl.isConnected){let partForCode=s;let remainder='';if(didImmediateOpenSnap)partForCode='';else if(change.closed&&change.splitAt>=0&&change.splitAt<=s.length){partForCode=s.slice(0,change.splitAt);remainder=s.slice(change.splitAt);}
|
|
743
|
+
if(partForCode){this.appendToActiveTail(partForCode);this.activeCode.lines+=Utils.countNewlines(partForCode);this.maybePromoteLanguageFromDirective();this.enforceHLStopBudget();const tailLenNow=(this.activeCode.tailEl.textContent||'').length;const hasNL=partForCode.indexOf('\n')>=0;if(!this.activeCode.plainStream){const HL_MIN=this.cfg.PROFILE_CODE.minCharsForHL;if(hasNL||tailLenNow>=HL_MIN)this.schedulePromoteTail(false);}}
|
|
744
|
+
this.scrollMgr.scrollFabUpdateScheduled=false;this.scrollMgr.scheduleScroll(true);this.scrollMgr.fabFreezeUntil=Utils.now()+this.cfg.FAB.TOGGLE_DEBOUNCE_MS;this.scrollMgr.scheduleScrollFabUpdate();if(change.closed){this._d('code.close',{remainderLen:remainder.length});this.finalizeActiveCode();this.codeStream.open=false;this.resetBudget();this.plain.forceFullMDOnce=true;this.scheduleSnapshot(msg,true);if(remainder&&remainder.length){this.applyStream(name_header,remainder,true);}}
|
|
745
|
+
return;}else{if(!this.activeCode&&(this.codeStream.lines>=2||this.codeStream.chars>=80)){this._d('code.awaitActive.forceSnap',{lines:this.codeStream.lines,chars:this.codeStream.chars});this.scheduleSnapshot(msg,true);return;}
|
|
746
|
+
if(change.closed){this.codeStream.open=false;this.resetBudget();this._d('code.closed.outside',{});this.plain.forceFullMDOnce=true;this.scheduleSnapshot(msg,true);}else{const boundary=this.hasStructuralBoundary(s);if(this.shouldSnapshotOnChunk(s,chunkHasNL,boundary)){this._d('snapshot.decide',{reason:'boundary/step'});this.scheduleSnapshot(msg);}else{this.maybeScheduleSoftSnapshot(msg,chunkHasNL);}}
|
|
747
|
+
return;}}
|
|
748
|
+
if(change.closed){this.codeStream.open=false;this.resetBudget();this._d('code.closed.outside',{});this.scheduleSnapshot(msg);}else{const boundary=this.hasStructuralBoundary(s);if(this.shouldSnapshotOnChunk(s,chunkHasNL,boundary)){this._d('snapshot.decide',{reason:'boundary/step'});this.scheduleSnapshot(msg);}else{this.maybeScheduleSoftSnapshot(msg,chunkHasNL);}}}};
|
|
749
|
+
|
|
750
|
+
/* data/js/app/queue.js */
|
|
751
|
+
class StreamQueue{constructor(cfg,engine,scrollMgr,raf){this.cfg=cfg;this.engine=engine;this.scrollMgr=scrollMgr;this.raf=raf;this.q=[];this.rd=0;this.drainScheduled=false;this.batching=false;this.needScroll=false;this.DRAIN_KEY=Symbol('SQ:drain');const R=(this.cfg&&this.cfg.RAF)||{};this.DRAIN_BUDGET_MS=(R.STREAM_DRAIN_BUDGET_MS!=null)?R.STREAM_DRAIN_BUDGET_MS:4;this.COMPACT_SLICE_THRESHOLD=1024;this._lastCompactRd=0;}
|
|
752
|
+
_qCount(){return Math.max(0,this.q.length-this.rd);}
|
|
753
|
+
_compactContiguousSameName(){const n=this._qCount();if(n<2)return;const out=[];let prev=null;for(let i=this.rd;i<this.q.length;i++){const cur=this.q[i];if(!cur)continue;if(prev&&prev.name===cur.name){if(cur.parts&&cur.parts.length){for(let k=0;k<cur.parts.length;k++)prev.parts.push(cur.parts[k]);}else if(cur.chunk){prev.parts.push(cur.chunk);}
|
|
754
|
+
prev.len+=(cur.len|0);if(cur.parts)cur.parts.length=0;cur.chunk='';cur.len=0;cur.name='';}else{const parts=cur.parts?cur.parts:(cur.chunk?[cur.chunk]:[]);prev={name:cur.name,parts:parts,len:cur.len!=null?cur.len:(cur.chunk?cur.chunk.length:0)};out.push(prev);if(cur.parts)cur.parts=[];cur.chunk='';cur.len=0;cur.name='';}}
|
|
755
|
+
this.q=out;this.rd=0;this._lastCompactRd=0;}
|
|
756
|
+
_maybeCompact(){if(this.rd===0)return;const n=this._qCount();if(n===0){this.q=[];this.rd=0;this._lastCompactRd=0;return;}
|
|
757
|
+
if(this.rd>=this.COMPACT_SLICE_THRESHOLD){this.q=this.q.slice(this.rd);this.rd=0;this._lastCompactRd=0;return;}
|
|
758
|
+
if(this.rd-this._lastCompactRd>=128||(this.rd>64&&this.rd>=(this.q.length>>1))){this.q=this.q.slice(this.rd);this.rd=0;this._lastCompactRd=0;}}
|
|
759
|
+
_scheduleDrain(){if(this.drainScheduled)return;this.drainScheduled=true;this.raf.schedule(this.DRAIN_KEY,()=>this.drain(),'StreamQueue',-5);}
|
|
760
|
+
enqueue(name_header,chunk){if(!chunk||chunk.length===0)return;const name=name_header;const hasPending=this._qCount()>0;const tail=hasPending?this.q[this.q.length-1]:null;if(tail&&tail.name===name){tail.parts.push(chunk);tail.len+=chunk.length;}else{this.q.push({name,parts:[chunk],len:chunk.length});}
|
|
761
|
+
const cnt=this._qCount();if(cnt>(this.cfg.STREAM.EMERGENCY_COALESCE_LEN|0))this._compactContiguousSameName();else if(cnt>(this.cfg.STREAM.QUEUE_MAX_ITEMS|0))this._compactContiguousSameName();this._scheduleDrain();}
|
|
762
|
+
drain(){this.drainScheduled=false;const adaptive=(this.cfg.STREAM.COALESCE_MODE==='adaptive');const coalesceAggressive=adaptive&&(this._qCount()>=(this.cfg.STREAM.EMERGENCY_COALESCE_LEN|0));const basePerFrame=this.cfg.STREAM.MAX_PER_FRAME|0;const perFrame=adaptive?Math.min(basePerFrame+Math.floor(this._qCount()/20),basePerFrame*4):basePerFrame;const start=Utils.now();const sched=(navigator&&navigator.scheduling&&navigator.scheduling.isInputPending)?navigator.scheduling:null;this.batching=true;let processed=0;while(this.rd<this.q.length&&processed<perFrame){const idx=this.rd++;const e=this.q[idx];if(!e)continue;if(coalesceAggressive){while(this.rd<this.q.length&&this.q[this.rd]&&this.q[this.rd].name===e.name){const n=this.q[this.rd++];if(n.parts&&n.parts.length){for(let k=0;k<n.parts.length;k++)e.parts.push(n.parts[k]);}else if(n.chunk){e.parts.push(n.chunk);}
|
|
763
|
+
e.len+=(n.len|0);if(n.parts)n.parts.length=0;n.chunk='';n.len=0;n.name='';this.q[this.rd-1]=null;}}
|
|
764
|
+
let payload='';if(!e.parts||e.parts.length===0)payload=e.chunk||'';else if(e.parts.length===1)payload=e.parts[0]||'';else payload=e.parts.join('');this.engine.applyStream(e.name,payload);processed++;if(e.parts)e.parts.length=0;e.chunk='';e.len=0;e.name='';this.q[idx]=null;payload='';if(sched&&sched.isInputPending({includeContinuous:true}))break;if((Utils.now()-start)>=this.DRAIN_BUDGET_MS)break;}
|
|
765
|
+
this.batching=false;if(this.needScroll){this.scrollMgr.scheduleScroll(true);this.needScroll=false;}
|
|
766
|
+
this._maybeCompact();if(this._qCount()>0)this._scheduleDrain();}
|
|
767
|
+
kick(){if(this._qCount()||this.drainScheduled)this._scheduleDrain();}
|
|
768
|
+
clear(){for(let i=this.rd;i<this.q.length;i++){const e=this.q[i];if(!e)continue;if(e.parts)e.parts.length=0;e.chunk='';e.len=0;e.name='';this.q[i]=null;}
|
|
769
|
+
this.q=[];this.rd=0;this._lastCompactRd=0;try{this.raf.cancelGroup('StreamQueue');}catch(_){}
|
|
770
|
+
this.drainScheduled=false;}};
|
|
771
|
+
|
|
772
|
+
/* data/js/app/template.js */
|
|
773
|
+
class NodeTemplateEngine{constructor(cfg,logger){this.cfg=cfg||{};this.logger=logger||{debug:()=>{}};}
|
|
774
|
+
_esc(s){return(s==null)?'':String(s);}
|
|
775
|
+
_escapeHtml(s){return(typeof Utils!=='undefined')?Utils.escapeHtml(s):String(s).replace(/[&<>"']/g,m=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[m]));}
|
|
776
|
+
_nameHeader(role,name,avatarUrl){if(!name&&!avatarUrl)return'';const cls=(role==='user')?'name-user':'name-bot';const img=avatarUrl?`<img src="${this._esc(avatarUrl)}" class="avatar"> `:'';return`<div class="name-header ${cls}">${img}${this._esc(name || '')}</div>`;}
|
|
777
|
+
_renderUser(block){const id=block.id;const inp=block.input||{};const msgId=`msg-user-${id}`;const personalize=!!(block&&block.extra&&block.extra.personalize===true);const nameHeader=personalize?this._nameHeader('user',inp.name||'',inp.avatar_img||null):'';const content=this._escapeHtml(inp.text||'').replace(/\r?\n/g,'<br>');const I=(this.cfg&&this.cfg.ICONS)||{};const L=(this.cfg&&this.cfg.LOCALE)||{};const copyIcon=I.CODE_COPY||'';const copyTitle=L.COPY||'Copy';const copyBtn=`<a href="empty:${this._esc(id)}" class="msg-copy-btn" data-id="${this._esc(id)}" data-tip="${this._escapeHtml(copyTitle)}" title="${this._escapeHtml(copyTitle)}" aria-label="${this._escapeHtml(copyTitle)}" role="button"><img src="${this._esc(copyIcon)}" class="copy-img" alt="${this._escapeHtml(copyTitle)}" data-id="${this._esc(id)}"></a>`;return`<div class="msg-box msg-user" id="${msgId}">${nameHeader}<div class="msg">${copyBtn}<p style="margin:0">${content}</p></div></div>`;}
|
|
778
|
+
_renderExtras(block){const parts=[];const images=block.images||{};const keysI=Object.keys(images);if(keysI.length){keysI.forEach((k)=>{const it=images[k];if(!it)return;const url=this._esc(it.url);const path=this._esc(it.path);const bn=this._esc(it.basename||'');if(it.is_video){const src=(it.ext==='.webm'||!it.webm_path)?path:this._esc(it.webm_path);const ext=(src.endsWith('.webm')?'webm':(path.split('.').pop()||'mp4'));parts.push(`<div class="extra-src-video-box" title="${url}">`+`<video class="video-player" controls>`+`<source src="${src}" type="video/${ext}">`+`</video>`+`<p><a href="bridge://play_video/${url}" class="title">${this._escapeHtml(bn)}</a></p>`+`</div>`);}else{parts.push(`<div class="extra-src-img-box" title="${url}">`+`<div class="img-outer"><div class="img-wrapper"><a href="${url}"><img src="${path}" class="image"></a></div>`+`<a href="${url}" class="title">${this._escapeHtml(bn)}</a></div>`+`</div><br/>`);}});}
|
|
779
|
+
const files=block.files||{};const kF=Object.keys(files);if(kF.length){const rows=[];kF.forEach((k)=>{const it=files[k];if(!it)return;const url=this._esc(it.url);const path=this._esc(it.path);const icon=(typeof window!=='undefined'&&window.ICON_ATTACHMENTS)?`<img src="${window.ICON_ATTACHMENTS}" class="extra-src-icon">`:'';rows.push(`${icon} <b> [${k}] </b> <a href="${url}">${path}</a>`);});if(rows.length)parts.push(`<div>${rows.join("<br/><br/>")}</div>`);}
|
|
780
|
+
const urls=block.urls||{};const kU=Object.keys(urls);if(kU.length){const rows=[];kU.forEach((k)=>{const it=urls[k];if(!it)return;const url=this._esc(it.url);const icon=(typeof window!=='undefined'&&window.ICON_URL)?`<img src="${window.ICON_URL}" class="extra-src-icon">`:'';rows.push(`${icon}<a href="${url}" title="${url}">${url}</a> <small> [${k}] </small>`);});if(rows.length)parts.push(`<div>${rows.join("<br/><br/>")}</div>`);}
|
|
781
|
+
const extra=block.extra||{};const docsRaw=Array.isArray(extra.docs)?extra.docs:null;if(docsRaw&&docsRaw.length){const icon=(typeof window!=='undefined'&&window.ICON_DB)?`<img src="${window.ICON_DB}" class="extra-src-icon">`:'';const prefix=(typeof window!=='undefined'&&window.LOCALE_DOC_PREFIX)?String(window.LOCALE_DOC_PREFIX):'Doc:';const limit=3;const normalized=[];docsRaw.forEach((it)=>{if(!it||typeof it!=='object')return;if('uuid'in it&&'meta'in it&&typeof it.meta==='object'){normalized.push({uuid:String(it.uuid),meta:it.meta||{}});}else{const keys=Object.keys(it);if(keys.length===1){const uuid=keys[0];const meta=it[uuid];if(meta&&typeof meta==='object'){normalized.push({uuid:String(uuid),meta});}}}});const rows=[];for(let i=0;i<Math.min(limit,normalized.length);i++){const d=normalized[i];const meta=d.meta||{};const entries=Object.keys(meta).map(k=>`<b>${this._escapeHtml(k)}:</b> ${this._escapeHtml(String(meta[k]))}`).join(', ');rows.push(`<p><small>[${i + 1}] ${this._escapeHtml(d.uuid)}: ${entries}</small></p>`);}
|
|
782
|
+
if(rows.length){parts.push(`<p>${icon}<small><b>${this._escapeHtml(prefix)}:</b></small></p>`);parts.push(`<div class="cmd"><p>${rows.join('')}</p></div>`);}}else{const docs_html=extra&&extra.docs_html?String(extra.docs_html):'';if(docs_html)parts.push(docs_html);}
|
|
783
|
+
const tool_extra_html=extra&&extra.tool_extra_html?String(extra.tool_extra_html):'';if(tool_extra_html)parts.push(`<div class="msg-extra">${tool_extra_html}</div>`);return parts.join('');}
|
|
784
|
+
_renderActions(block){const extra=block.extra||{};const actions=extra.actions||[];if(!actions||!actions.length)return'';const parts=actions.map((a)=>{const href=this._esc(a.href||'#');const title=this._esc(a.title||'');const icon=this._esc(a.icon||'');const id=this._esc(a.id||block.id);return`<a href="${href}" class="action-icon" data-id="${id}" role="button"><span class="cmd"><img src="${icon}" class="action-img" title="${title}" alt="${title}" data-id="${id}"></span></a>`;});return`<div class="action-icons" data-id="${this._esc(block.id)}">${parts.join('')}</div>`;}
|
|
785
|
+
_renderToolOutputWrapper(block){const extra=block.extra||{};const tool_output_html=(extra.tool_output!=null)?String(extra.tool_output):'';const wrapperDisplay=(extra.tool_output_visible===true)?'':'display:none';const toggleTitle=(typeof trans!=='undefined'&&trans)?trans('action.cmd.expand'):'Expand';const expIcon=(typeof window!=='undefined'&&window.ICON_EXPAND)?window.ICON_EXPAND:'';return(`<div class='tool-output' style='${wrapperDisplay}'>`+`<span class='toggle-cmd-output' onclick='toggleToolOutput(${this._esc(block.id)});' `+`title='${this._escapeHtml(toggleTitle)}' role='button'>`+`<img src='${this._esc(expIcon)}' width='25' height='25' valign='middle'>`+`</span>`+`<div class='content' style='display:none' data-trusted='1'>${tool_output_html}</div>`+`</div>`);}
|
|
786
|
+
_renderBot(block){const id=block.id;const out=block.output||{};const msgId=`msg-bot-${id}`;const personalize=!!(block&&block.extra&&block.extra.personalize===true);const nameHeader=personalize?this._nameHeader('bot',out.name||'',out.avatar_img||null):'';const mdText=this._escapeHtml(out.text||'');const toolWrap=this._renderToolOutputWrapper(block);const extras=this._renderExtras(block);const actions=(block.extra&&block.extra.footer_icons)?this._renderActions(block):'';const debug=(block.extra&&block.extra.debug_html)?String(block.extra.debug_html):'';return(`<div class='msg-box msg-bot' id='${msgId}'>`+`${nameHeader}`+`<div class='msg'>`+`<div class='md-block' md-block-markdown='1'>${mdText}</div>`+`<div class='msg-tool-extra'></div>`+`${toolWrap}`+`<div class='msg-extra'>${extras}</div>`+`${actions}${debug}`+`</div>`+`</div>`);}
|
|
787
|
+
renderNode(block){const parts=[];if(block&&block.input&&block.input.text)parts.push(this._renderUser(block));if(block&&block.output&&block.output.text)parts.push(this._renderBot(block));return parts.join('');}
|
|
788
|
+
renderNodes(blocks){if(!Array.isArray(blocks))return'';const out=[];for(let i=0;i<blocks.length;i++){const b=blocks[i]||null;if(!b)continue;out.push(this.renderNode(b));}
|
|
789
|
+
return out.join('');}};
|
|
790
|
+
|
|
791
|
+
/* data/js/app/tool.js */
|
|
792
|
+
class ToolOutput{showLoader(){return;}
|
|
793
|
+
hideLoader(){const elements=document.querySelectorAll('.msg-bot');if(elements.length>0)elements.forEach(el=>{const s=el.querySelector('.spinner');if(s)s.style.display='none';});}
|
|
794
|
+
begin(){this.showLoader();}
|
|
795
|
+
end(){this.hideLoader();}
|
|
796
|
+
enable(){const els=document.querySelectorAll('.tool-output');if(els.length)els[els.length-1].style.display='block';}
|
|
797
|
+
disable(){const els=document.querySelectorAll('.tool-output');if(els.length)els[els.length-1].style.display='none';}
|
|
798
|
+
append(content){this.hideLoader();this.enable();const els=document.querySelectorAll('.tool-output');if(els.length){const contentEl=els[els.length-1].querySelector('.content');if(contentEl)contentEl.insertAdjacentHTML('beforeend',content);}}
|
|
799
|
+
update(content){this.hideLoader();this.enable();const els=document.querySelectorAll('.tool-output');if(els.length){const contentEl=els[els.length-1].querySelector('.content');if(contentEl)contentEl.innerHTML=content;}}
|
|
800
|
+
clear(){this.hideLoader();this.enable();const els=document.querySelectorAll('.tool-output');if(els.length){const contentEl=els[els.length-1].querySelector('.content');if(contentEl)contentEl.replaceChildren();}}
|
|
801
|
+
toggle(id){const el=document.getElementById('msg-bot-'+id);if(!el)return;const outputEl=el.querySelector('.tool-output');if(!outputEl)return;const contentEl=outputEl.querySelector('.content');if(contentEl)contentEl.style.display=(contentEl.style.display==='none')?'block':'none';const toggleEl=outputEl.querySelector('.toggle-cmd-output img');if(toggleEl)toggleEl.classList.toggle('toggle-expanded');}};
|
|
802
|
+
|
|
803
|
+
/* data/js/app/ui.js */
|
|
804
|
+
class UIManager{updateCSS(styles){let style=document.getElementById('app-style');if(!style){style=document.createElement('style');style.id='app-style';document.head.appendChild(style);}
|
|
805
|
+
style.textContent=styles;}
|
|
806
|
+
ensureStickyHeaderStyle(){let style=document.getElementById('code-sticky-style');if(style)return;style=document.createElement('style');style.id='code-sticky-style';style.textContent=['.code-wrapper { position: relative; }','.code-wrapper .code-header-wrapper { position: sticky; top: var(--code-header-sticky-top, -2px); z-index: 2; box-shadow: 0 1px 0 rgba(0,0,0,.06); }','.code-wrapper pre { overflow: visible; margin-top: 0; }','.code-wrapper pre code { display: block; white-space: pre; max-height: 100dvh; overflow: auto;',' overscroll-behavior: contain; -webkit-overflow-scrolling: touch; overflow-anchor: none; scrollbar-gutter: stable both-edges; scroll-behavior: auto; }','#_loader_.hidden { display: none !important; visibility: hidden !important; }','#_loader_.visible { display: block; visibility: visible; }','.msg-box.msg-user .msg { position: relative; }','.msg-box.msg-user .msg > .uc-content { display: block; overflow: visible; }','.msg-box.msg-user .msg > .uc-content.uc-collapsed { max-height: 1000px; overflow: hidden; }','.msg-box.msg-user .msg > .uc-toggle { display: none; margin-top: 8px; text-align: center; cursor: pointer; user-select: none; }','.msg-box.msg-user .msg > .uc-toggle.visible { display: block; }','.msg-box.msg-user .msg > .uc-toggle img { width: var(--uc-toggle-icon-size, 26px); height: var(--uc-toggle-icon-size, 26px); opacity: .8; }','.msg-box.msg-user .msg > .uc-toggle:hover img { opacity: 1; }','.msg-box.msg-user .msg .msg-copy-btn { position: absolute; top: 2px; right: 0px; z-index: 3;',' opacity: 0; pointer-events: none; transition: opacity .15s ease, transform .15s ease, background-color .15s ease, border-color .15s ease;',' border-radius: 6px; padding: 4px; line-height: 0; border: 1px solid transparent; background: transparent; }','.msg-box.msg-user:hover .msg .msg-copy-btn, .msg-box.msg-user .msg:focus-within .msg-copy-btn { opacity: 1; pointer-events: auto; }','.msg-box.msg-user .msg .msg-copy-btn:hover { transform: scale(1.06); background: var(--copy-btn-bg-hover, rgba(0,0,0,.86)); border-color: var(--copy-btn-border, rgba(0,0,0,.08)); }','.msg-box.msg-user .msg .msg-copy-btn.copied { background: var(--copy-btn-bg-copied, rgba(150,150,150,.12)); border-color: var(--copy-btn-border-copied, rgba(150,150,150,.35)); animation: msg-copy-pop .25s ease; }','.msg-box.msg-user .msg .msg-copy-btn img { display: block; width: 18px; height: 18px; }','.code-wrapper .code-header-action.code-header-copy,','.code-wrapper .code-header-action.code-header-collapse { display: inline-flex; align-items: center; border-radius: 6px; padding: 2px; line-height: 0; border: 1px solid transparent; transition: transform .15s ease, background-color .15s ease, border-color .15s ease; }','.code-wrapper .code-header-action.code-header-copy:hover,','.code-wrapper .code-header-action.code-header-collapse:hover { transform: scale(1.06); background: var(--copy-btn-bg-hover, rgba(0,0,0,.76)); border-color: var(--copy-btn-border, rgba(0,0,0,.08)); }','.code-wrapper .code-header-action.copied { background: var(--copy-btn-bg-copied, rgba(150,150,150,.12)); border-color: var(--copy-btn-border-copied, rgba(150,150,150,.35)); animation: msg-copy-pop .25s ease; }','@keyframes msg-copy-pop { 0%{ transform: scale(1); } 60%{ transform: scale(1.1); } 100%{ transform: scale(1); } }'].join('\n');document.head.appendChild(style);}
|
|
807
|
+
enableEditIcons(){document.body&&document.body.classList.add('display-edit-icons');}
|
|
808
|
+
disableEditIcons(){document.body&&document.body.classList.remove('display-edit-icons');}
|
|
809
|
+
enableTimestamp(){document.body&&document.body.classList.add('display-timestamp');}
|
|
810
|
+
disableTimestamp(){document.body&&document.body.classList.remove('display-timestamp');}
|
|
811
|
+
enableBlocks(){document.body&&document.body.classList.add('display-blocks');}
|
|
812
|
+
disableBlocks(){document.body&&document.body.classList.remove('display-blocks');}};
|
|
813
|
+
|
|
814
|
+
/* data/js/app/user.js */
|
|
815
|
+
class UserCollapseManager{constructor(cfg){this.cfg=cfg||{};this.threshold=Utils.g('USER_MSG_COLLAPSE_HEIGHT_PX',1000);this._processed=new Set();this.ellipsisText=' [...]';}
|
|
816
|
+
_icons(){const I=(this.cfg&&this.cfg.ICONS)||{};return{expand:I.EXPAND||'',collapse:I.COLLAPSE||''};}
|
|
817
|
+
_labels(){const L=(this.cfg&&this.cfg.LOCALE)||{};return{expand:L.EXPAND||'Expand',collapse:L.COLLAPSE||'Collapse'};}
|
|
818
|
+
_afterLayout(fn){try{if(typeof runtime!=='undefined'&&runtime.raf&&typeof runtime.raf.schedule==='function'){const key={t:'UC:afterLayout',i:Math.random()};runtime.raf.schedule(key,()=>{try{fn&&fn();}catch(_){}},'UserCollapse',0);return;}}catch(_){}
|
|
819
|
+
try{requestAnimationFrame(()=>{try{fn&&fn();}catch(_){}});}catch(_){setTimeout(()=>{try{fn&&fn();}catch(__){}},0);}}
|
|
820
|
+
_scrollToggleIntoView(toggleEl){if(!toggleEl||!toggleEl.isConnected)return;try{if(runtime&&runtime.scrollMgr){runtime.scrollMgr.userInteracted=true;runtime.scrollMgr.autoFollow=false;}}catch(_){}
|
|
821
|
+
this._afterLayout(()=>{try{if(toggleEl.scrollIntoView){try{toggleEl.scrollIntoView({block:'nearest',inline:'nearest',behavior:'instant'});}catch(_){toggleEl.scrollIntoView(false);}}}catch(_){}});}
|
|
822
|
+
_ensureStructure(msg){if(!msg||!msg.isConnected)return null;let content=msg.querySelector('.uc-content');if(!content){content=document.createElement('div');content.className='uc-content';const frag=document.createDocumentFragment();while(msg.firstChild)frag.appendChild(msg.firstChild);content.appendChild(frag);msg.appendChild(content);}
|
|
823
|
+
let toggle=msg.querySelector('.uc-toggle');if(!toggle){const icons=this._icons();const labels=this._labels();toggle=document.createElement('div');toggle.className='uc-toggle';toggle.tabIndex=0;toggle.setAttribute('role','button');toggle.setAttribute('aria-expanded','false');toggle.title=labels.expand;const img=document.createElement('img');img.className='uc-toggle-icon';img.alt=labels.expand;img.src=icons.expand;img.width=26;img.height=26;toggle.appendChild(img);toggle.addEventListener('click',(ev)=>{ev.preventDefault();ev.stopPropagation();this.toggleFromToggle(toggle);});toggle.addEventListener('keydown',(ev)=>{if(ev.key==='Enter'||ev.key===' '){ev.preventDefault();ev.stopPropagation();this.toggleFromToggle(toggle);}},{passive:false});msg.appendChild(toggle);}
|
|
824
|
+
this._processed.add(msg);msg.dataset.ucInit='1';return{content,toggle};}
|
|
825
|
+
_ensureEllipsisEl(msg,contentEl){const content=contentEl||(msg&&msg.querySelector('.uc-content'));if(!content)return null;if(getComputedStyle(content).position==='static'){content.style.position='relative';}
|
|
826
|
+
let dot=content.querySelector('.uc-ellipsis');if(!dot){dot=document.createElement('span');dot.className='uc-ellipsis';dot.textContent=this.ellipsisText;dot.style.position='absolute';dot.style.right='0';dot.style.bottom='0';dot.style.paddingLeft='6px';dot.style.pointerEvents='none';dot.style.zIndex='1';dot.style.fontWeight='500';dot.style.opacity='0.75';dot.setAttribute('aria-hidden','true');dot.setAttribute('data-copy-ignore','1');content.appendChild(dot);}
|
|
827
|
+
return dot;}
|
|
828
|
+
_showEllipsis(msg,contentEl){const dot=this._ensureEllipsisEl(msg,contentEl);if(dot)dot.style.display='inline';}
|
|
829
|
+
_hideEllipsis(msg){const content=msg&&msg.querySelector('.uc-content');if(!content)return;const dot=content.querySelector('.uc-ellipsis');if(dot&&dot.parentNode){dot.parentNode.removeChild(dot);}
|
|
830
|
+
try{if(content&&content.style&&content.querySelector('.uc-ellipsis')==null){content.style.position='';}}catch(_){}}
|
|
831
|
+
apply(root){const scope=root||document;let list;if(scope.nodeType===1)list=scope.querySelectorAll('.msg-box.msg-user .msg');else list=document.querySelectorAll('.msg-box.msg-user .msg');if(!list||!list.length)return;for(let i=0;i<list.length;i++){const msg=list[i];const st=this._ensureStructure(msg);if(!st)continue;this._update(msg,st.content,st.toggle);}}
|
|
832
|
+
_update(msg,contentEl,toggleEl){const c=contentEl||(msg&&msg.querySelector('.uc-content'));if(!msg||!c)return;if(this.threshold===0||this.threshold==='0'){const t=toggleEl||msg.querySelector('.uc-toggle');const labels=this._labels();c.classList.remove('uc-collapsed');c.classList.remove('uc-expanded');msg.dataset.ucState='expanded';this._hideEllipsis(msg);if(t){t.classList.remove('visible');t.setAttribute('aria-expanded','false');t.title=labels.expand;const img=t.querySelector('img');if(img){img.alt=labels.expand;}}
|
|
833
|
+
return;}
|
|
834
|
+
c.classList.remove('uc-collapsed');c.classList.remove('uc-expanded');const fullHeight=Math.ceil(c.scrollHeight);const labels=this._labels();const icons=this._icons();const t=toggleEl||msg.querySelector('.uc-toggle');if(fullHeight>this.threshold){if(t)t.classList.add('visible');const desired=msg.dataset.ucState||'collapsed';const expand=(desired==='expanded');if(expand){c.classList.add('uc-expanded');this._hideEllipsis(msg);}else{c.classList.add('uc-collapsed');this._showEllipsis(msg,c);}
|
|
835
|
+
if(t){const img=t.querySelector('img');if(img){if(expand){img.src=icons.collapse;img.alt=labels.collapse;}else{img.src=icons.expand;img.alt=labels.expand;}}
|
|
836
|
+
t.setAttribute('aria-expanded',expand?'true':'false');t.title=expand?labels.collapse:labels.expand;}}else{c.classList.remove('uc-collapsed');c.classList.remove('uc-expanded');msg.dataset.ucState='expanded';this._hideEllipsis(msg);if(t){t.classList.remove('visible');t.setAttribute('aria-expanded','false');t.title=labels.expand;}}}
|
|
837
|
+
toggleFromToggle(toggleEl){const msg=toggleEl&&toggleEl.closest?toggleEl.closest('.msg-box.msg-user .msg'):null;if(!msg)return;this.toggle(msg);}
|
|
838
|
+
toggle(msg){if(!msg||!msg.isConnected)return;const c=msg.querySelector('.uc-content');if(!c)return;const t=msg.querySelector('.uc-toggle');const labels=this._labels();const icons=this._icons();const isCollapsed=c.classList.contains('uc-collapsed');if(isCollapsed){c.classList.remove('uc-collapsed');c.classList.add('uc-expanded');msg.dataset.ucState='expanded';this._hideEllipsis(msg);if(t){t.setAttribute('aria-expanded','true');t.title=labels.collapse;const img=t.querySelector('img');if(img){img.src=icons.collapse;img.alt=labels.collapse;}}}else{c.classList.remove('uc-expanded');c.classList.add('uc-collapsed');msg.dataset.ucState='collapsed';this._showEllipsis(msg,c);if(t){t.setAttribute('aria-expanded','false');t.title=labels.expand;const img=t.querySelector('img');if(img){img.src=icons.expand;img.alt=labels.expand;}
|
|
839
|
+
this._scrollToggleIntoView(t);}}}
|
|
840
|
+
remeasureAll(){const arr=Array.from(this._processed||[]);for(let i=0;i<arr.length;i++){const msg=arr[i];if(!msg||!msg.isConnected){this._processed.delete(msg);continue;}
|
|
841
|
+
this._update(msg);}}};
|
|
842
|
+
|
|
843
|
+
/* data/js/app/utils.js */
|
|
844
|
+
class Utils{static g(name,dflt){return(typeof window[name]!=='undefined')?window[name]:dflt;}
|
|
845
|
+
static now(){return(typeof performance!=='undefined'&&performance.now)?performance.now():Date.now();}
|
|
846
|
+
static escapeHtml(s){const d=Utils._escDiv||(Utils._escDiv=document.createElement('div'));d.textContent=String(s??'');return d.innerHTML;}
|
|
847
|
+
static countNewlines(s){if(!s)return 0;let c=0,i=-1;while((i=s.indexOf('\n',i+1))!==-1)c++;return c;}
|
|
848
|
+
static reEscape(s){return String(s).replace(/[.*+?^${}()|[\]\\]/g,'\\$&');}
|
|
849
|
+
static idle(fn,timeout){if('requestIdleCallback'in window)return requestIdleCallback(fn,{timeout:timeout||800});return setTimeout(fn,50);}
|
|
850
|
+
static cancelIdle(id){try{if('cancelIdleCallback'in window)cancelIdleCallback(id);else clearTimeout(id);}catch(_){}}
|
|
851
|
+
static get SE(){return document.scrollingElement||document.documentElement;}
|
|
852
|
+
static utf8Decode(bytes){if(!Utils._td)Utils._td=new TextDecoder('utf-8');return Utils._td.decode(bytes);}};
|
|
853
|
+
|
|
854
|
+
/* data/js/app/runtime.js */
|
|
855
|
+
class Runtime{constructor(){this.cfg=new Config();this.logger=new Logger(this.cfg);this.dom=new DOMRefs();this.customMarkup=new CustomMarkup(this.cfg,this.logger);this.raf=new RafManager(this.cfg);try{this.logger.bindRaf(this.raf);}catch(_){}
|
|
856
|
+
this.async=new AsyncRunner(this.cfg,this.raf);this.renderer=new MarkdownRenderer(this.cfg,this.customMarkup,this.logger,this.async,this.raf);this.math=new MathRenderer(this.cfg,this.raf,this.async);this.codeScroll=new CodeScrollState(this.cfg,this.raf);this.highlighter=new Highlighter(this.cfg,this.codeScroll,this.raf);this.scrollMgr=new ScrollManager(this.cfg,this.dom,this.raf);this.toolOutput=new ToolOutput();this.loading=new Loading(this.dom);this.nodes=new NodesManager(this.dom,this.renderer,this.highlighter,this.math);this.bridge=new BridgeManager(this.cfg,this.logger);this.ui=new UIManager();this.stream=new StreamEngine(this.cfg,this.dom,this.renderer,this.math,this.highlighter,this.codeScroll,this.scrollMgr,this.raf,this.async,this.logger);this.streamQ=new StreamQueue(this.cfg,this.stream,this.scrollMgr,this.raf);this.events=new EventManager(this.cfg,this.dom,this.scrollMgr,this.highlighter,this.codeScroll,this.toolOutput,this.bridge);try{this.stream.setCustomFenceSpecs(this.customMarkup.getSourceFenceSpecs());}catch(_){}
|
|
857
|
+
this.templates=new NodeTemplateEngine(this.cfg,this.logger);this.data=new DataReceiver(this.cfg,this.templates,this.nodes,this.scrollMgr);this.tips=null;this._lastHeavyResetMs=0;this.renderer.hooks.observeNewCode=(root,opts)=>this.highlighter.observeNewCode(root,opts,this.stream.activeCode);this.renderer.hooks.observeMsgBoxes=(root)=>this.highlighter.observeMsgBoxes(root,(box)=>{this.highlighter.observeNewCode(box,{deferLastIfStreaming:true,minLinesForLast:this.cfg.PROFILE_CODE.minLinesForHL,minCharsForLast:this.cfg.PROFILE_CODE.minCharsForHL},this.stream.activeCode);this.codeScroll.initScrollableBlocks(box);});this.renderer.hooks.scheduleMathRender=(root)=>{const mm=getMathMode();if(mm==='idle')this.math.schedule(root);else if(mm==='always')this.math.schedule(root,0,true);};this.renderer.hooks.codeScrollInit=(root)=>this.codeScroll.initScrollableBlocks(root);}
|
|
858
|
+
resetStreamState(origin,opts){try{this.streamQ.clear();}catch(_){}
|
|
859
|
+
const def=Object.assign({finalizeActive:true,clearBuffer:true,clearMsg:false,defuseOrphans:true,forceHeavy:false,reason:String(origin||'external-op')},(opts||{}));const now=Utils.now();const withinDebounce=(now-(this._lastHeavyResetMs||0))<=(this.cfg.RESET.HEAVY_DEBOUNCE_MS||24);const mustHeavyByOrigin=def.forceHeavy===true||def.clearMsg===true||origin==='beginStream'||origin==='nextStream'||origin==='clearStream'||origin==='replaceNodes'||origin==='clearNodes'||origin==='clearOutput'||origin==='clearLive'||origin==='clearInput';const shouldHeavy=mustHeavyByOrigin||!withinDebounce;const suppressLog=withinDebounce&&origin!=='beginStream';try{this.stream.abortAndReset({...def,suppressLog});}catch(_){}
|
|
860
|
+
if(shouldHeavy){try{this.highlighter.cleanup();}catch(_){}
|
|
861
|
+
try{this.math.cleanup();}catch(_){}
|
|
862
|
+
try{this.codeScroll.cancelAllScrolls();}catch(_){}
|
|
863
|
+
try{this.scrollMgr.cancelPendingScroll();}catch(_){}
|
|
864
|
+
try{this.raf.cancelAll();}catch(_){}
|
|
865
|
+
this._lastHeavyResetMs=now;}else{try{this.raf.cancelGroup('StreamQueue');}catch(_){}}
|
|
866
|
+
try{this.tips&&this.tips.hide();}catch(_){}}
|
|
867
|
+
api_onChunk=(name,chunk,type)=>{const t=String(type||'text_delta');if(t==='text_delta'){this.api_appendStream(name,chunk);return;}
|
|
868
|
+
this.logger.debug('STREAM','IGNORED_NON_TEXT_CHUNK',{type:t,len:(chunk?String(chunk).length:0)});};api_beginStream=(chunk=false)=>{this.tips&&this.tips.hide();this.resetStreamState('beginStream',{clearMsg:true,finalizeActive:false,forceHeavy:true});this.stream.beginStream(chunk);};api_endStream=()=>{this.stream.endStream();};api_applyStream=(name,chunk)=>{this.stream.applyStream(name,chunk);};api_appendStream=(name,chunk)=>{this.streamQ.enqueue(name,chunk);};api_nextStream=()=>{this.tips&&this.tips.hide();const element=this.dom.get('_append_output_');const before=this.dom.get('_append_output_before_');if(element&&before){const frag=document.createDocumentFragment();while(element.firstChild)frag.appendChild(element.firstChild);before.appendChild(frag);}
|
|
869
|
+
this.resetStreamState('nextStream',{clearMsg:true,finalizeActive:false,forceHeavy:true});this.scrollMgr.scheduleScroll();};api_clearStream=()=>{this.tips&&this.tips.hide();this.resetStreamState('clearStream',{clearMsg:true,forceHeavy:true});const el=this.dom.getStreamContainer();if(!el)return;el.replaceChildren();};api_appendNode=(payload)=>{this.resetStreamState('appendNode');this.data.append(payload);};api_replaceNodes=(payload)=>{this.resetStreamState('replaceNodes',{clearMsg:true,forceHeavy:true});this.dom.clearNodes();this.data.replace(payload);};api_appendToInput=(payload)=>{this.nodes.appendToInput(payload);this.scrollMgr.autoFollow=true;this.scrollMgr.userInteracted=false;try{this.scrollMgr.lastScrollTop=Utils.SE.scrollTop|0;}catch(_){}
|
|
870
|
+
this.scrollMgr.scheduleScroll();};api_clearNodes=()=>{this.dom.clearNodes();this.resetStreamState('clearNodes',{clearMsg:true,forceHeavy:true});};api_clearInput=()=>{this.resetStreamState('clearInput',{forceHeavy:true});this.dom.clearInput();};api_clearOutput=()=>{this.dom.clearOutput();this.resetStreamState('clearOutput',{clearMsg:true,forceHeavy:true});};api_clearLive=()=>{this.dom.clearLive();this.resetStreamState('clearLive',{forceHeavy:true});};api_appendToolOutput=(c)=>this.toolOutput.append(c);api_updateToolOutput=(c)=>this.toolOutput.update(c);api_clearToolOutput=()=>this.toolOutput.clear();api_beginToolOutput=()=>this.toolOutput.begin();api_endToolOutput=()=>this.toolOutput.end();api_enableToolOutput=()=>this.toolOutput.enable();api_disableToolOutput=()=>this.toolOutput.disable();api_toggleToolOutput=(id)=>this.toolOutput.toggle(id);api_appendExtra=(id,c)=>this.nodes.appendExtra(id,c,this.scrollMgr);api_removeNode=(id)=>this.nodes.removeNode(id,this.scrollMgr);api_removeNodesFromId=(id)=>this.nodes.removeNodesFromId(id,this.scrollMgr);api_replaceLive=(content)=>{const el=this.dom.get('_append_live_');if(!el)return;if(el.classList.contains('hidden')){el.classList.remove('hidden');el.classList.add('visible');}
|
|
871
|
+
el.innerHTML=content;try{const maybePromise=this.renderer.renderPendingMarkdown(el);const post=()=>{try{this.highlighter.observeNewCode(el,{deferLastIfStreaming:true,minLinesForLast:this.cfg.PROFILE_CODE.minLinesForHL,minCharsForLast:this.cfg.PROFILE_CODE.minCharsForHL},this.stream.activeCode);this.highlighter.observeMsgBoxes(el,(box)=>{this.highlighter.observeNewCode(box,{deferLastIfStreaming:true,minLinesForLast:this.cfg.PROFILE_CODE.minLinesForHL,minCharsForLast:this.cfg.PROFILE_CODE.minCharsForHL},this.stream.activeCode);this.codeScroll.initScrollableBlocks(box);});}catch(_){}
|
|
872
|
+
try{const mm=getMathMode();if(mm==='finalize-only')this.math.schedule(el,0,true);else this.math.schedule(el);}catch(_){}
|
|
873
|
+
this.scrollMgr.scheduleScroll();};if(maybePromise&&typeof maybePromise.then==='function'){maybePromise.then(post);}else{post();}}catch(_){this.scrollMgr.scheduleScroll();}};api_updateFooter=(html)=>{const el=this.dom.get('_footer_');if(el)el.innerHTML=html;};api_enableEditIcons=()=>this.ui.enableEditIcons();api_disableEditIcons=()=>this.ui.disableEditIcons();api_enableTimestamp=()=>this.ui.enableTimestamp();api_disableTimestamp=()=>this.ui.disableTimestamp();api_enableBlocks=()=>this.ui.enableBlocks();api_disableBlocks=()=>this.ui.disableBlocks();api_updateCSS=(styles)=>this.ui.updateCSS(styles);api_getScrollPosition=()=>{this.bridge.updateScrollPosition(window.scrollY);};api_setScrollPosition=(pos)=>{try{window.scrollTo(0,pos);this.scrollMgr.prevScroll=parseInt(pos);}catch(_){}};api_showLoading=()=>this.loading.show();api_hideLoading=()=>this.loading.hide();api_restoreCollapsedCode=(root)=>this.renderer.restoreCollapsedCode(root);api_scrollToTopUser=()=>this.scrollMgr.scrollToTopUser();api_scrollToBottomUser=()=>this.scrollMgr.scrollToBottomUser();api_showTips=()=>this.tips.show();api_hideTips=()=>this.tips.hide();api_getCustomMarkupRules=()=>this.customMarkup.getRules();api_setCustomMarkupRules=(rules)=>{this.customMarkup.setRules(rules);try{this.stream.setCustomFenceSpecs(this.customMarkup.getSourceFenceSpecs());}catch(_){}};init(){this.highlighter.initHLJS();this.dom.init();this.ui.ensureStickyHeaderStyle();this.tips=new TipsManager(this.dom);this.events.install();this.bridge.initQWebChannel(this.cfg.PID,(bridge)=>{const onChunk=(name,chunk,type)=>this.api_onChunk(name,chunk,type);const onNode=(payload)=>this.api_appendNode(payload);const onNodeReplace=(payload)=>this.api_replaceNodes(payload);const onNodeInput=(html)=>this.api_appendToInput(html);this.bridge.connect(onChunk,onNode,onNodeReplace,onNodeInput);try{this.logger.bindBridge(this.bridge.bridge||this.bridge);}catch(_){}});this.renderer.init();try{this.renderer.renderPendingMarkdown(document);}catch(_){}
|
|
874
|
+
this.highlighter.observeMsgBoxes(document,(box)=>{this.highlighter.observeNewCode(box,{deferLastIfStreaming:true,minLinesForLast:this.cfg.PROFILE_CODE.minLinesForHL,minCharsForLast:this.cfg.PROFILE_CODE.minCharsForHL},this.stream.activeCode);this.codeScroll.initScrollableBlocks(box);});this.highlighter.observeNewCode(document,{deferLastIfStreaming:true,minLinesForLast:this.cfg.PROFILE_CODE.minLinesForHL,minCharsForLast:this.cfg.PROFILE_CODE.minCharsForHL},this.stream.activeCode);this.highlighter.scheduleScanVisibleCodes(this.stream.activeCode);this.tips.cycle();this.scrollMgr.updateScrollFab(true);}
|
|
875
|
+
cleanup(){this.tips.cleanup();try{this.bridge.disconnect();}catch(_){}
|
|
876
|
+
this.events.cleanup();this.highlighter.cleanup();this.math.cleanup();this.streamQ.clear();this.dom.cleanup();}}
|
|
877
|
+
if(typeof RafManager!=='undefined'&&RafManager.prototype&&typeof RafManager.prototype.cancel==='function'){RafManager.prototype.cancel=function(key){const t=this.tasks.get(key);if(!t)return;this.tasks.delete(key);if(t.group){const set=this.groups.get(t.group);if(set){set.delete(key);if(set.size===0)this.groups.delete(t.group);}}};}
|
|
878
|
+
window.__collapsed_idx=window.__collapsed_idx||[];const runtime=new Runtime();document.addEventListener('DOMContentLoaded',()=>runtime.init());Object.defineProperty(window,'SE',{get(){return Utils.SE;}});window.beginStream=(chunk)=>runtime.api_beginStream(chunk);window.endStream=()=>runtime.api_endStream();window.applyStream=(name,chunk)=>runtime.api_applyStream(name,chunk);window.appendStream=(name,chunk)=>runtime.api_appendStream(name,chunk);window.appendStreamTyped=(type,name,chunk)=>runtime.api_onChunk(name,chunk,type);window.nextStream=()=>runtime.api_nextStream();window.clearStream=()=>runtime.api_clearStream();window.appendNode=(payload)=>runtime.api_appendNode(payload);window.replaceNodes=(payload)=>runtime.api_replaceNodes(payload);window.appendToInput=(html)=>runtime.api_appendToInput(html);window.clearNodes=()=>runtime.api_clearNodes();window.clearInput=()=>runtime.api_clearInput();window.clearOutput=()=>runtime.api_clearOutput();window.clearLive=()=>runtime.api_clearLive();window.appendToolOutput=(c)=>runtime.api_appendToolOutput(c);window.updateToolOutput=(c)=>runtime.api_updateToolOutput(c);window.clearToolOutput=()=>runtime.api_clearToolOutput();window.beginToolOutput=()=>runtime.api_beginToolOutput();window.endToolOutput=()=>runtime.api_endToolOutput();window.enableToolOutput=()=>runtime.api_enableToolOutput();window.disableToolOutput=()=>runtime.api_disableToolOutput();window.toggleToolOutput=(id)=>runtime.api_toggleToolOutput(id);window.appendExtra=(id,c)=>runtime.api_appendExtra(id,c);window.removeNode=(id)=>runtime.api_removeNode(id);window.removeNodesFromId=(id)=>runtime.api_removeNodesFromId(id);window.replaceLive=(c)=>runtime.api_replaceLive(c);window.updateFooter=(c)=>runtime.api_updateFooter(c);window.enableEditIcons=()=>runtime.api_enableEditIcons();window.disableEditIcons=()=>runtime.api_disableEditIcons();window.enableTimestamp=()=>runtime.api_enableTimestamp();window.disableTimestamp=()=>runtime.api_disableTimestamp();window.enableBlocks=()=>runtime.api_enableBlocks();window.disableBlocks=()=>runtime.api_disableBlocks();window.updateCSS=(s)=>runtime.api_updateCSS(s);window.getScrollPosition=()=>runtime.api_getScrollPosition();window.setScrollPosition=(pos)=>runtime.api_setScrollPosition(pos);window.showLoading=()=>runtime.api_showLoading();window.hideLoading=()=>runtime.api_hideLoading();window.restoreCollapsedCode=(root)=>runtime.api_restoreCollapsedCode(root);window.scrollToTopUser=()=>runtime.api_scrollToTopUser();window.scrollToBottomUser=()=>runtime.api_scrollToBottomUser();window.showTips=()=>runtime.api_showTips();window.hideTips=()=>runtime.api_hideTips();window.getCustomMarkupRules=()=>runtime.api_getCustomMarkupRules();window.setCustomMarkupRules=(rules)=>runtime.api_setCustomMarkupRules(rules);window.__pygpt_cleanup=()=>runtime.cleanup();RafManager.prototype.stats=function(){const byGroup=new Map();for(const[key,t]of this.tasks){const g=t.group||'default';byGroup.set(g,(byGroup.get(g)||0)+1);}
|
|
879
|
+
return{tasks:this.tasks.size,groups:Array.from(byGroup,([group,count])=>({group,count})).sort((a,b)=>b.count-a.count)};};RafManager.prototype.dumpHotGroups=function(label=''){const s=this.stats();console.log('[RAF]',label,'tasks=',s.tasks,'byGroup=',s.groups.slice(0,8));};RafManager.prototype.findDomTasks=function(){const out=[];for(const[key,t]of this.tasks){let el=null;if(key&&key.nodeType===1)el=key;else if(key&&key.el&&key.el.nodeType===1)el=key.el;if(el)out.push({group:t.group,tag:el.tagName,connected:el.isConnected});}
|
|
880
|
+
return out;};function gaugeSE(se){const ropeLen=(se.streamBuf.length+se._sbLen);const ac=se.activeCode;const domFrozen=ac?.frozenEl?.textContent?.length||0;const domTail=ac?.tailEl?.textContent?.length||0;const domLen=domFrozen+domTail;return{ropeLen,domLen,totalChars:ropeLen+domLen,ratioRopeToDom:(domLen?(ropeLen/domLen).toFixed(2):'n/a'),fenceOpen:se.fenceOpen,codeOpen:se.codeStream?.open};};
|