@artooi/agents-web-components 0.0.0-stage → 0.1.1
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.
- package/CHANGELOG.md +77 -0
- package/LICENSE +21 -0
- package/README.md +4397 -2
- package/dist/agents-web-components.bundle.js +5708 -0
- package/dist/agents-web-components.bundle.js.map +7 -0
- package/dist/bundle.d.ts +3 -0
- package/dist/bundle.d.ts.map +1 -0
- package/dist/chat.d.ts +3 -0
- package/dist/chat.d.ts.map +1 -0
- package/dist/chat.js +16373 -0
- package/dist/chat.js.map +7 -0
- package/dist/chunk-ARNLFGCC.js +7715 -0
- package/dist/chunk-ARNLFGCC.js.map +7 -0
- package/dist/constants.d.ts +575 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/core/activity_registration.d.ts +19 -0
- package/dist/core/activity_registration.d.ts.map +1 -0
- package/dist/core/activity_registry.d.ts +46 -0
- package/dist/core/activity_registry.d.ts.map +1 -0
- package/dist/core/activity_renderer.d.ts +20 -0
- package/dist/core/activity_renderer.d.ts.map +1 -0
- package/dist/core/ag_ui_chat.d.ts +836 -0
- package/dist/core/ag_ui_chat.d.ts.map +1 -0
- package/dist/core/agui_client.d.ts +370 -0
- package/dist/core/agui_client.d.ts.map +1 -0
- package/dist/core/attachment.d.ts +42 -0
- package/dist/core/attachment.d.ts.map +1 -0
- package/dist/core/chat_registry.d.ts +23 -0
- package/dist/core/chat_registry.d.ts.map +1 -0
- package/dist/core/client_seed.d.ts +27 -0
- package/dist/core/client_seed.d.ts.map +1 -0
- package/dist/core/conversation_store.d.ts +195 -0
- package/dist/core/conversation_store.d.ts.map +1 -0
- package/dist/core/create_http_agent.d.ts +57 -0
- package/dist/core/create_http_agent.d.ts.map +1 -0
- package/dist/core/define_chat.d.ts +13 -0
- package/dist/core/define_chat.d.ts.map +1 -0
- package/dist/core/events/attachments_detail.d.ts +9 -0
- package/dist/core/events/attachments_detail.d.ts.map +1 -0
- package/dist/core/events/bar_height_detail.d.ts +6 -0
- package/dist/core/events/bar_height_detail.d.ts.map +1 -0
- package/dist/core/events/custom_agent_detail.d.ts +8 -0
- package/dist/core/events/custom_agent_detail.d.ts.map +1 -0
- package/dist/core/events/dock_width_detail.d.ts +8 -0
- package/dist/core/events/dock_width_detail.d.ts.map +1 -0
- package/dist/core/events/feedback_detail.d.ts +28 -0
- package/dist/core/events/feedback_detail.d.ts.map +1 -0
- package/dist/core/events/invalidate_detail.d.ts +16 -0
- package/dist/core/events/invalidate_detail.d.ts.map +1 -0
- package/dist/core/events/maximize_detail.d.ts +5 -0
- package/dist/core/events/maximize_detail.d.ts.map +1 -0
- package/dist/core/events/run_finished_detail.d.ts +36 -0
- package/dist/core/events/run_finished_detail.d.ts.map +1 -0
- package/dist/core/events/state_detail.d.ts +5 -0
- package/dist/core/events/state_detail.d.ts.map +1 -0
- package/dist/core/events/submit_detail.d.ts +8 -0
- package/dist/core/events/submit_detail.d.ts.map +1 -0
- package/dist/core/events/thread_detail.d.ts +27 -0
- package/dist/core/events/thread_detail.d.ts.map +1 -0
- package/dist/core/events/thread_title_detail.d.ts +8 -0
- package/dist/core/events/thread_title_detail.d.ts.map +1 -0
- package/dist/core/events/toggle_detail.d.ts +5 -0
- package/dist/core/events/toggle_detail.d.ts.map +1 -0
- package/dist/core/events/tool_run.d.ts +11 -0
- package/dist/core/events/tool_run.d.ts.map +1 -0
- package/dist/core/events/unread_detail.d.ts +11 -0
- package/dist/core/events/unread_detail.d.ts.map +1 -0
- package/dist/core/message_role.d.ts +4 -0
- package/dist/core/message_role.d.ts.map +1 -0
- package/dist/core/read_flag.d.ts +11 -0
- package/dist/core/read_flag.d.ts.map +1 -0
- package/dist/core/read_json_attribute.d.ts +15 -0
- package/dist/core/read_json_attribute.d.ts.map +1 -0
- package/dist/core/read_max_tool_rounds.d.ts +9 -0
- package/dist/core/read_max_tool_rounds.d.ts.map +1 -0
- package/dist/core/remote_conversation_store.d.ts +71 -0
- package/dist/core/remote_conversation_store.d.ts.map +1 -0
- package/dist/core/run_handlers.d.ts +85 -0
- package/dist/core/run_handlers.d.ts.map +1 -0
- package/dist/core/run_index.d.ts +58 -0
- package/dist/core/run_index.d.ts.map +1 -0
- package/dist/core/storage_scope.d.ts +118 -0
- package/dist/core/storage_scope.d.ts.map +1 -0
- package/dist/core/tool_outcome.d.ts +27 -0
- package/dist/core/tool_outcome.d.ts.map +1 -0
- package/dist/core/transcribe_audio.d.ts +32 -0
- package/dist/core/transcribe_audio.d.ts.map +1 -0
- package/dist/core/upload_attachment.d.ts +44 -0
- package/dist/core/upload_attachment.d.ts.map +1 -0
- package/dist/core/utils.d.ts +117 -0
- package/dist/core/utils.d.ts.map +1 -0
- package/dist/dom/animations.d.ts +122 -0
- package/dist/dom/animations.d.ts.map +1 -0
- package/dist/dom/dom_driver.d.ts +28 -0
- package/dist/dom/dom_driver.d.ts.map +1 -0
- package/dist/dom/highlight_overlay.d.ts +39 -0
- package/dist/dom/highlight_overlay.d.ts.map +1 -0
- package/dist/dom/native_setter.d.ts +5 -0
- package/dist/dom/native_setter.d.ts.map +1 -0
- package/dist/dom/ring_color.d.ts +16 -0
- package/dist/dom/ring_color.d.ts.map +1 -0
- package/dist/dom/utils.d.ts +3 -0
- package/dist/dom/utils.d.ts.map +1 -0
- package/dist/index.d.ts +62 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +223 -0
- package/dist/index.js.map +7 -0
- package/dist/skills/fill_template.d.ts +16 -0
- package/dist/skills/fill_template.d.ts.map +1 -0
- package/dist/skills/parse_skills.d.ts +8 -0
- package/dist/skills/parse_skills.d.ts.map +1 -0
- package/dist/skills/skill.d.ts +33 -0
- package/dist/skills/skill.d.ts.map +1 -0
- package/dist/skills/skill_catalog.d.ts +69 -0
- package/dist/skills/skill_catalog.d.ts.map +1 -0
- package/dist/skills/skill_name_from.d.ts +12 -0
- package/dist/skills/skill_name_from.d.ts.map +1 -0
- package/dist/tools/chat_surface_tools.d.ts +77 -0
- package/dist/tools/chat_surface_tools.d.ts.map +1 -0
- package/dist/tools/client_tool_registry.d.ts +58 -0
- package/dist/tools/client_tool_registry.d.ts.map +1 -0
- package/dist/tools/is_destructive.d.ts +14 -0
- package/dist/tools/is_destructive.d.ts.map +1 -0
- package/dist/tools/is_navigates.d.ts +9 -0
- package/dist/tools/is_navigates.d.ts.map +1 -0
- package/dist/tools/page_action_tools.d.ts +30 -0
- package/dist/tools/page_action_tools.d.ts.map +1 -0
- package/dist/tools/page_map.d.ts +16 -0
- package/dist/tools/page_map.d.ts.map +1 -0
- package/dist/tools/page_state.d.ts +27 -0
- package/dist/tools/page_state.d.ts.map +1 -0
- package/dist/tools/parse_tool_catalog.d.ts +21 -0
- package/dist/tools/parse_tool_catalog.d.ts.map +1 -0
- package/dist/tools/route_map.d.ts +37 -0
- package/dist/tools/route_map.d.ts.map +1 -0
- package/dist/tools/tool_catalog.d.ts +86 -0
- package/dist/tools/tool_catalog.d.ts.map +1 -0
- package/dist/tools/tool_dispatch.d.ts +82 -0
- package/dist/tools/tool_dispatch.d.ts.map +1 -0
- package/dist/ui/charts/chart_block.d.ts +57 -0
- package/dist/ui/charts/chart_block.d.ts.map +1 -0
- package/dist/ui/charts/chart_spec_from.d.ts +12 -0
- package/dist/ui/charts/chart_spec_from.d.ts.map +1 -0
- package/dist/ui/charts/chart_styles.d.ts +2 -0
- package/dist/ui/charts/chart_styles.d.ts.map +1 -0
- package/dist/ui/charts/chart_tool.d.ts +15 -0
- package/dist/ui/charts/chart_tool.d.ts.map +1 -0
- package/dist/ui/composer/attachment_styles.d.ts +2 -0
- package/dist/ui/composer/attachment_styles.d.ts.map +1 -0
- package/dist/ui/composer/attachment_tray.d.ts +53 -0
- package/dist/ui/composer/attachment_tray.d.ts.map +1 -0
- package/dist/ui/composer/auto_grow.d.ts +10 -0
- package/dist/ui/composer/auto_grow.d.ts.map +1 -0
- package/dist/ui/composer/build_composer.d.ts +32 -0
- package/dist/ui/composer/build_composer.d.ts.map +1 -0
- package/dist/ui/composer/composer_attachments.d.ts +57 -0
- package/dist/ui/composer/composer_attachments.d.ts.map +1 -0
- package/dist/ui/composer/composer_styles.d.ts +2 -0
- package/dist/ui/composer/composer_styles.d.ts.map +1 -0
- package/dist/ui/composer/composer_voice.d.ts +48 -0
- package/dist/ui/composer/composer_voice.d.ts.map +1 -0
- package/dist/ui/composer/skill_styles.d.ts +2 -0
- package/dist/ui/composer/skill_styles.d.ts.map +1 -0
- package/dist/ui/composer/skills_menu.d.ts +34 -0
- package/dist/ui/composer/skills_menu.d.ts.map +1 -0
- package/dist/ui/composer/voice_input.d.ts +46 -0
- package/dist/ui/composer/voice_input.d.ts.map +1 -0
- package/dist/ui/excerpts/attach_copy_buttons.d.ts +13 -0
- package/dist/ui/excerpts/attach_copy_buttons.d.ts.map +1 -0
- package/dist/ui/excerpts/copy_payload.d.ts +30 -0
- package/dist/ui/excerpts/copy_payload.d.ts.map +1 -0
- package/dist/ui/excerpts/page_quote_offer.d.ts +33 -0
- package/dist/ui/excerpts/page_quote_offer.d.ts.map +1 -0
- package/dist/ui/excerpts/place_offer.d.ts +9 -0
- package/dist/ui/excerpts/place_offer.d.ts.map +1 -0
- package/dist/ui/excerpts/quote_selection.d.ts +66 -0
- package/dist/ui/excerpts/quote_selection.d.ts.map +1 -0
- package/dist/ui/excerpts/transcript_quote_offer.d.ts +57 -0
- package/dist/ui/excerpts/transcript_quote_offer.d.ts.map +1 -0
- package/dist/ui/fill_ui_string.d.ts +32 -0
- package/dist/ui/fill_ui_string.d.ts.map +1 -0
- package/dist/ui/history/checkpoint_menu.d.ts +41 -0
- package/dist/ui/history/checkpoint_menu.d.ts.map +1 -0
- package/dist/ui/history/conversation_history.d.ts +317 -0
- package/dist/ui/history/conversation_history.d.ts.map +1 -0
- package/dist/ui/history/history_styles.d.ts +2 -0
- package/dist/ui/history/history_styles.d.ts.map +1 -0
- package/dist/ui/history/relative_time.d.ts +23 -0
- package/dist/ui/history/relative_time.d.ts.map +1 -0
- package/dist/ui/history/thread_drawer.d.ts +64 -0
- package/dist/ui/history/thread_drawer.d.ts.map +1 -0
- package/dist/ui/history/utils.d.ts +2 -0
- package/dist/ui/history/utils.d.ts.map +1 -0
- package/dist/ui/interrupts/approval_card.d.ts +64 -0
- package/dist/ui/interrupts/approval_card.d.ts.map +1 -0
- package/dist/ui/interrupts/approval_styles.d.ts +2 -0
- package/dist/ui/interrupts/approval_styles.d.ts.map +1 -0
- package/dist/ui/interrupts/confirmation_card.d.ts +51 -0
- package/dist/ui/interrupts/confirmation_card.d.ts.map +1 -0
- package/dist/ui/interrupts/confirmation_styles.d.ts +2 -0
- package/dist/ui/interrupts/confirmation_styles.d.ts.map +1 -0
- package/dist/ui/interrupts/pending_decision.d.ts +22 -0
- package/dist/ui/interrupts/pending_decision.d.ts.map +1 -0
- package/dist/ui/interrupts/question_card.d.ts +49 -0
- package/dist/ui/interrupts/question_card.d.ts.map +1 -0
- package/dist/ui/interrupts/question_styles.d.ts +2 -0
- package/dist/ui/interrupts/question_styles.d.ts.map +1 -0
- package/dist/ui/place/place.d.ts +17 -0
- package/dist/ui/place/place.d.ts.map +1 -0
- package/dist/ui/place/place_chip.d.ts +26 -0
- package/dist/ui/place/place_chip.d.ts.map +1 -0
- package/dist/ui/place/place_from_route.d.ts +9 -0
- package/dist/ui/place/place_from_route.d.ts.map +1 -0
- package/dist/ui/place/place_styles.d.ts +2 -0
- package/dist/ui/place/place_styles.d.ts.map +1 -0
- package/dist/ui/placement/clamp_launcher.d.ts +20 -0
- package/dist/ui/placement/clamp_launcher.d.ts.map +1 -0
- package/dist/ui/placement/clamp_panel.d.ts +13 -0
- package/dist/ui/placement/clamp_panel.d.ts.map +1 -0
- package/dist/ui/placement/collapse_styles.d.ts +2 -0
- package/dist/ui/placement/collapse_styles.d.ts.map +1 -0
- package/dist/ui/placement/dock_styles.d.ts +2 -0
- package/dist/ui/placement/dock_styles.d.ts.map +1 -0
- package/dist/ui/placement/embedded_styles.d.ts +2 -0
- package/dist/ui/placement/embedded_styles.d.ts.map +1 -0
- package/dist/ui/placement/launcher_drag.d.ts +49 -0
- package/dist/ui/placement/launcher_drag.d.ts.map +1 -0
- package/dist/ui/placement/launcher_placement.d.ts +77 -0
- package/dist/ui/placement/launcher_placement.d.ts.map +1 -0
- package/dist/ui/placement/launcher_styles.d.ts +2 -0
- package/dist/ui/placement/launcher_styles.d.ts.map +1 -0
- package/dist/ui/placement/page_styles.d.ts +2 -0
- package/dist/ui/placement/page_styles.d.ts.map +1 -0
- package/dist/ui/placement/panel_drag.d.ts +40 -0
- package/dist/ui/placement/panel_drag.d.ts.map +1 -0
- package/dist/ui/placement/panel_placement.d.ts +173 -0
- package/dist/ui/placement/panel_placement.d.ts.map +1 -0
- package/dist/ui/placement/place_widget.d.ts +31 -0
- package/dist/ui/placement/place_widget.d.ts.map +1 -0
- package/dist/ui/placement/preset_styles.d.ts +2 -0
- package/dist/ui/placement/preset_styles.d.ts.map +1 -0
- package/dist/ui/placement/resize_handle.d.ts +78 -0
- package/dist/ui/placement/resize_handle.d.ts.map +1 -0
- package/dist/ui/placement/resize_styles.d.ts +2 -0
- package/dist/ui/placement/resize_styles.d.ts.map +1 -0
- package/dist/ui/placement/sidebar_styles.d.ts +2 -0
- package/dist/ui/placement/sidebar_styles.d.ts.map +1 -0
- package/dist/ui/placement/small_viewport_styles.d.ts +2 -0
- package/dist/ui/placement/small_viewport_styles.d.ts.map +1 -0
- package/dist/ui/placement/surface_for.d.ts +93 -0
- package/dist/ui/placement/surface_for.d.ts.map +1 -0
- package/dist/ui/progress/prettify_tool_name.d.ts +11 -0
- package/dist/ui/progress/prettify_tool_name.d.ts.map +1 -0
- package/dist/ui/progress/run_announcer.d.ts +41 -0
- package/dist/ui/progress/run_announcer.d.ts.map +1 -0
- package/dist/ui/progress/run_notice.d.ts +21 -0
- package/dist/ui/progress/run_notice.d.ts.map +1 -0
- package/dist/ui/progress/run_notice_styles.d.ts +2 -0
- package/dist/ui/progress/run_notice_styles.d.ts.map +1 -0
- package/dist/ui/progress/subagent_panel.d.ts +101 -0
- package/dist/ui/progress/subagent_panel.d.ts.map +1 -0
- package/dist/ui/progress/subagent_progress.d.ts +57 -0
- package/dist/ui/progress/subagent_progress.d.ts.map +1 -0
- package/dist/ui/progress/subagent_update.d.ts +28 -0
- package/dist/ui/progress/subagent_update.d.ts.map +1 -0
- package/dist/ui/progress/thoughts_block.d.ts +57 -0
- package/dist/ui/progress/thoughts_block.d.ts.map +1 -0
- package/dist/ui/progress/thoughts_styles.d.ts +2 -0
- package/dist/ui/progress/thoughts_styles.d.ts.map +1 -0
- package/dist/ui/progress/tool_call_card.d.ts +167 -0
- package/dist/ui/progress/tool_call_card.d.ts.map +1 -0
- package/dist/ui/progress/tool_group_styles.d.ts +2 -0
- package/dist/ui/progress/tool_group_styles.d.ts.map +1 -0
- package/dist/ui/progress/tool_step_group.d.ts +50 -0
- package/dist/ui/progress/tool_step_group.d.ts.map +1 -0
- package/dist/ui/progress/tool_step_styles.d.ts +2 -0
- package/dist/ui/progress/tool_step_styles.d.ts.map +1 -0
- package/dist/ui/shell/adopt_styles.d.ts +28 -0
- package/dist/ui/shell/adopt_styles.d.ts.map +1 -0
- package/dist/ui/shell/build_header.d.ts +45 -0
- package/dist/ui/shell/build_header.d.ts.map +1 -0
- package/dist/ui/shell/build_launcher.d.ts +33 -0
- package/dist/ui/shell/build_launcher.d.ts.map +1 -0
- package/dist/ui/shell/collapse_glyph.d.ts +14 -0
- package/dist/ui/shell/collapse_glyph.d.ts.map +1 -0
- package/dist/ui/shell/frame_styles.d.ts +2 -0
- package/dist/ui/shell/frame_styles.d.ts.map +1 -0
- package/dist/ui/shell/glyph_slot.d.ts +7 -0
- package/dist/ui/shell/glyph_slot.d.ts.map +1 -0
- package/dist/ui/shell/header_button.d.ts +11 -0
- package/dist/ui/shell/header_button.d.ts.map +1 -0
- package/dist/ui/shell/icon_element.d.ts +12 -0
- package/dist/ui/shell/icon_element.d.ts.map +1 -0
- package/dist/ui/shell/is_unread_badge_enabled.d.ts +10 -0
- package/dist/ui/shell/is_unread_badge_enabled.d.ts.map +1 -0
- package/dist/ui/shell/read_launcher_icon_url.d.ts +8 -0
- package/dist/ui/shell/read_launcher_icon_url.d.ts.map +1 -0
- package/dist/ui/shell/theme_styles.d.ts +2 -0
- package/dist/ui/shell/theme_styles.d.ts.map +1 -0
- package/dist/ui/shell/token_styles.d.ts +2 -0
- package/dist/ui/shell/token_styles.d.ts.map +1 -0
- package/dist/ui/styles.d.ts +2 -0
- package/dist/ui/styles.d.ts.map +1 -0
- package/dist/ui/themes/classic_styles.d.ts +2 -0
- package/dist/ui/themes/classic_styles.d.ts.map +1 -0
- package/dist/ui/themes/classic_tokens.d.ts +2 -0
- package/dist/ui/themes/classic_tokens.d.ts.map +1 -0
- package/dist/ui/themes/code_tokens.d.ts +2 -0
- package/dist/ui/themes/code_tokens.d.ts.map +1 -0
- package/dist/ui/themes/ledger_styles.d.ts +2 -0
- package/dist/ui/themes/ledger_styles.d.ts.map +1 -0
- package/dist/ui/themes/ledger_tokens.d.ts +2 -0
- package/dist/ui/themes/ledger_tokens.d.ts.map +1 -0
- package/dist/ui/themes/modern_styles.d.ts +2 -0
- package/dist/ui/themes/modern_styles.d.ts.map +1 -0
- package/dist/ui/themes/quiet_styles.d.ts +2 -0
- package/dist/ui/themes/quiet_styles.d.ts.map +1 -0
- package/dist/ui/themes/scheme_styles.d.ts +2 -0
- package/dist/ui/themes/scheme_styles.d.ts.map +1 -0
- package/dist/ui/themes/soft_styles.d.ts +2 -0
- package/dist/ui/themes/soft_styles.d.ts.map +1 -0
- package/dist/ui/themes/soft_tokens.d.ts +2 -0
- package/dist/ui/themes/soft_tokens.d.ts.map +1 -0
- package/dist/ui/themes/theme_hosts.d.ts +15 -0
- package/dist/ui/themes/theme_hosts.d.ts.map +1 -0
- package/dist/ui/transcript/answer_actions.d.ts +50 -0
- package/dist/ui/transcript/answer_actions.d.ts.map +1 -0
- package/dist/ui/transcript/answer_stream.d.ts +56 -0
- package/dist/ui/transcript/answer_stream.d.ts.map +1 -0
- package/dist/ui/transcript/attachment_chip_styles.d.ts +2 -0
- package/dist/ui/transcript/attachment_chip_styles.d.ts.map +1 -0
- package/dist/ui/transcript/attachment_chips.d.ts +21 -0
- package/dist/ui/transcript/attachment_chips.d.ts.map +1 -0
- package/dist/ui/transcript/build_transcript.d.ts +21 -0
- package/dist/ui/transcript/build_transcript.d.ts.map +1 -0
- package/dist/ui/transcript/greeting_styles.d.ts +2 -0
- package/dist/ui/transcript/greeting_styles.d.ts.map +1 -0
- package/dist/ui/transcript/groups_tool_steps.d.ts +13 -0
- package/dist/ui/transcript/groups_tool_steps.d.ts.map +1 -0
- package/dist/ui/transcript/message_action_styles.d.ts +2 -0
- package/dist/ui/transcript/message_action_styles.d.ts.map +1 -0
- package/dist/ui/transcript/message_actions.d.ts +74 -0
- package/dist/ui/transcript/message_actions.d.ts.map +1 -0
- package/dist/ui/transcript/message_styles.d.ts +2 -0
- package/dist/ui/transcript/message_styles.d.ts.map +1 -0
- package/dist/ui/transcript/render_markdown.d.ts +40 -0
- package/dist/ui/transcript/render_markdown.d.ts.map +1 -0
- package/dist/ui/transcript/render_or_warn.d.ts +16 -0
- package/dist/ui/transcript/render_or_warn.d.ts.map +1 -0
- package/dist/ui/transcript/reveal_words.d.ts +8 -0
- package/dist/ui/transcript/reveal_words.d.ts.map +1 -0
- package/dist/ui/transcript/starter_chips.d.ts +21 -0
- package/dist/ui/transcript/starter_chips.d.ts.map +1 -0
- package/dist/ui/transcript/stick_to_bottom.d.ts +55 -0
- package/dist/ui/transcript/stick_to_bottom.d.ts.map +1 -0
- package/dist/ui/transcript/suggestion_chips.d.ts +29 -0
- package/dist/ui/transcript/suggestion_chips.d.ts.map +1 -0
- package/dist/ui/transcript/transcript.d.ts +196 -0
- package/dist/ui/transcript/transcript.d.ts.map +1 -0
- package/dist/ui/transcript/transcript_styles.d.ts +2 -0
- package/dist/ui/transcript/transcript_styles.d.ts.map +1 -0
- package/dist/ui/ui_strings.d.ts +352 -0
- package/dist/ui/ui_strings.d.ts.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.d.ts.map +1 -0
- package/package.json +86 -3
- package/src/bundle.ts +2 -0
- package/src/chat.ts +2 -0
- package/src/constants.ts +650 -0
- package/src/core/activity_registration.ts +19 -0
- package/src/core/activity_registry.ts +133 -0
- package/src/core/activity_renderer.ts +19 -0
- package/src/core/ag_ui_chat.ts +3966 -0
- package/src/core/agui_client.ts +1028 -0
- package/src/core/attachment.ts +62 -0
- package/src/core/chat_registry.ts +53 -0
- package/src/core/client_seed.ts +27 -0
- package/src/core/conversation_store.ts +478 -0
- package/src/core/create_http_agent.ts +97 -0
- package/src/core/define_chat.ts +25 -0
- package/src/core/events/attachments_detail.ts +9 -0
- package/src/core/events/bar_height_detail.ts +5 -0
- package/src/core/events/custom_agent_detail.ts +7 -0
- package/src/core/events/dock_width_detail.ts +7 -0
- package/src/core/events/feedback_detail.ts +27 -0
- package/src/core/events/invalidate_detail.ts +15 -0
- package/src/core/events/maximize_detail.ts +4 -0
- package/src/core/events/run_finished_detail.ts +36 -0
- package/src/core/events/state_detail.ts +4 -0
- package/src/core/events/submit_detail.ts +8 -0
- package/src/core/events/thread_detail.ts +26 -0
- package/src/core/events/thread_title_detail.ts +7 -0
- package/src/core/events/toggle_detail.ts +4 -0
- package/src/core/events/tool_run.ts +10 -0
- package/src/core/events/unread_detail.ts +10 -0
- package/src/core/message_role.ts +4 -0
- package/src/core/read_flag.ts +13 -0
- package/src/core/read_json_attribute.ts +30 -0
- package/src/core/read_max_tool_rounds.ts +13 -0
- package/src/core/remote_conversation_store.ts +279 -0
- package/src/core/run_handlers.ts +524 -0
- package/src/core/run_index.ts +114 -0
- package/src/core/storage_scope.ts +291 -0
- package/src/core/tool_outcome.ts +39 -0
- package/src/core/transcribe_audio.ts +76 -0
- package/src/core/upload_attachment.ts +130 -0
- package/src/core/utils.ts +230 -0
- package/src/dom/animations.ts +341 -0
- package/src/dom/dom_driver.ts +91 -0
- package/src/dom/highlight_overlay.ts +204 -0
- package/src/dom/native_setter.ts +40 -0
- package/src/dom/ring_color.ts +206 -0
- package/src/dom/utils.ts +5 -0
- package/src/index.ts +220 -0
- package/src/skills/fill_template.ts +31 -0
- package/src/skills/parse_skills.ts +31 -0
- package/src/skills/skill.ts +32 -0
- package/src/skills/skill_catalog.ts +172 -0
- package/src/skills/skill_name_from.ts +19 -0
- package/src/tools/chat_surface_tools.ts +183 -0
- package/src/tools/client_tool_registry.ts +80 -0
- package/src/tools/is_destructive.ts +17 -0
- package/src/tools/is_navigates.ts +12 -0
- package/src/tools/page_action_tools.ts +123 -0
- package/src/tools/page_map.ts +26 -0
- package/src/tools/page_state.ts +57 -0
- package/src/tools/parse_tool_catalog.ts +41 -0
- package/src/tools/route_map.ts +132 -0
- package/src/tools/tool_catalog.ts +334 -0
- package/src/tools/tool_dispatch.ts +453 -0
- package/src/ui/charts/chart_block.ts +519 -0
- package/src/ui/charts/chart_spec_from.ts +125 -0
- package/src/ui/charts/chart_styles.ts +63 -0
- package/src/ui/charts/chart_tool.ts +72 -0
- package/src/ui/composer/attachment_styles.ts +71 -0
- package/src/ui/composer/attachment_tray.ts +295 -0
- package/src/ui/composer/auto_grow.ts +12 -0
- package/src/ui/composer/build_composer.ts +114 -0
- package/src/ui/composer/composer_attachments.ts +324 -0
- package/src/ui/composer/composer_styles.ts +177 -0
- package/src/ui/composer/composer_voice.ts +93 -0
- package/src/ui/composer/skill_styles.ts +120 -0
- package/src/ui/composer/skills_menu.ts +188 -0
- package/src/ui/composer/voice_input.ts +282 -0
- package/src/ui/excerpts/attach_copy_buttons.ts +73 -0
- package/src/ui/excerpts/copy_payload.ts +156 -0
- package/src/ui/excerpts/page_quote_offer.ts +203 -0
- package/src/ui/excerpts/place_offer.ts +24 -0
- package/src/ui/excerpts/quote_selection.ts +345 -0
- package/src/ui/excerpts/transcript_quote_offer.ts +175 -0
- package/src/ui/fill_ui_string.ts +41 -0
- package/src/ui/history/checkpoint_menu.ts +300 -0
- package/src/ui/history/conversation_history.ts +1169 -0
- package/src/ui/history/history_styles.ts +492 -0
- package/src/ui/history/relative_time.ts +50 -0
- package/src/ui/history/thread_drawer.ts +471 -0
- package/src/ui/history/utils.ts +11 -0
- package/src/ui/interrupts/approval_card.ts +202 -0
- package/src/ui/interrupts/approval_styles.ts +52 -0
- package/src/ui/interrupts/confirmation_card.ts +138 -0
- package/src/ui/interrupts/confirmation_styles.ts +114 -0
- package/src/ui/interrupts/pending_decision.ts +33 -0
- package/src/ui/interrupts/question_card.ts +213 -0
- package/src/ui/interrupts/question_styles.ts +73 -0
- package/src/ui/place/place.ts +16 -0
- package/src/ui/place/place_chip.ts +146 -0
- package/src/ui/place/place_from_route.ts +27 -0
- package/src/ui/place/place_styles.ts +108 -0
- package/src/ui/placement/clamp_launcher.ts +38 -0
- package/src/ui/placement/clamp_panel.ts +30 -0
- package/src/ui/placement/collapse_styles.ts +472 -0
- package/src/ui/placement/dock_styles.ts +116 -0
- package/src/ui/placement/embedded_styles.ts +14 -0
- package/src/ui/placement/launcher_drag.ts +206 -0
- package/src/ui/placement/launcher_placement.ts +133 -0
- package/src/ui/placement/launcher_styles.ts +189 -0
- package/src/ui/placement/page_styles.ts +47 -0
- package/src/ui/placement/panel_drag.ts +138 -0
- package/src/ui/placement/panel_placement.ts +1975 -0
- package/src/ui/placement/place_widget.ts +64 -0
- package/src/ui/placement/preset_styles.ts +49 -0
- package/src/ui/placement/resize_handle.ts +229 -0
- package/src/ui/placement/resize_styles.ts +201 -0
- package/src/ui/placement/sidebar_styles.ts +113 -0
- package/src/ui/placement/small_viewport_styles.ts +70 -0
- package/src/ui/placement/surface_for.ts +183 -0
- package/src/ui/progress/prettify_tool_name.ts +16 -0
- package/src/ui/progress/run_announcer.ts +67 -0
- package/src/ui/progress/run_notice.ts +61 -0
- package/src/ui/progress/run_notice_styles.ts +52 -0
- package/src/ui/progress/subagent_panel.ts +227 -0
- package/src/ui/progress/subagent_progress.ts +200 -0
- package/src/ui/progress/subagent_update.ts +89 -0
- package/src/ui/progress/thoughts_block.ts +165 -0
- package/src/ui/progress/thoughts_styles.ts +74 -0
- package/src/ui/progress/tool_call_card.ts +429 -0
- package/src/ui/progress/tool_group_styles.ts +313 -0
- package/src/ui/progress/tool_step_group.ts +317 -0
- package/src/ui/progress/tool_step_styles.ts +486 -0
- package/src/ui/shell/adopt_styles.ts +34 -0
- package/src/ui/shell/build_header.ts +121 -0
- package/src/ui/shell/build_launcher.ts +79 -0
- package/src/ui/shell/collapse_glyph.ts +42 -0
- package/src/ui/shell/frame_styles.ts +147 -0
- package/src/ui/shell/glyph_slot.ts +12 -0
- package/src/ui/shell/header_button.ts +22 -0
- package/src/ui/shell/icon_element.ts +33 -0
- package/src/ui/shell/is_unread_badge_enabled.ts +11 -0
- package/src/ui/shell/read_launcher_icon_url.ts +9 -0
- package/src/ui/shell/theme_styles.ts +11 -0
- package/src/ui/shell/token_styles.ts +480 -0
- package/src/ui/styles.ts +110 -0
- package/src/ui/themes/classic_styles.ts +32 -0
- package/src/ui/themes/classic_tokens.ts +51 -0
- package/src/ui/themes/code_tokens.ts +21 -0
- package/src/ui/themes/ledger_styles.ts +169 -0
- package/src/ui/themes/ledger_tokens.ts +33 -0
- package/src/ui/themes/modern_styles.ts +80 -0
- package/src/ui/themes/quiet_styles.ts +118 -0
- package/src/ui/themes/scheme_styles.ts +26 -0
- package/src/ui/themes/soft_styles.ts +149 -0
- package/src/ui/themes/soft_tokens.ts +29 -0
- package/src/ui/themes/theme_hosts.ts +14 -0
- package/src/ui/transcript/answer_actions.ts +165 -0
- package/src/ui/transcript/answer_stream.ts +123 -0
- package/src/ui/transcript/attachment_chip_styles.ts +116 -0
- package/src/ui/transcript/attachment_chips.ts +82 -0
- package/src/ui/transcript/build_transcript.ts +67 -0
- package/src/ui/transcript/greeting_styles.ts +171 -0
- package/src/ui/transcript/groups_tool_steps.ts +16 -0
- package/src/ui/transcript/message_action_styles.ts +155 -0
- package/src/ui/transcript/message_actions.ts +234 -0
- package/src/ui/transcript/message_styles.ts +262 -0
- package/src/ui/transcript/render_markdown.ts +181 -0
- package/src/ui/transcript/render_or_warn.ts +22 -0
- package/src/ui/transcript/reveal_words.ts +41 -0
- package/src/ui/transcript/starter_chips.ts +42 -0
- package/src/ui/transcript/stick_to_bottom.ts +126 -0
- package/src/ui/transcript/suggestion_chips.ts +73 -0
- package/src/ui/transcript/transcript.ts +555 -0
- package/src/ui/transcript/transcript_styles.ts +153 -0
- package/src/ui/ui_strings.ts +550 -0
- package/src/version.ts +1 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/constants.ts", "../src/core/agui_client.ts", "../src/core/utils.ts", "../src/core/attachment.ts", "../src/ui/progress/prettify_tool_name.ts", "../src/core/conversation_store.ts", "../src/core/create_http_agent.ts", "../src/core/remote_conversation_store.ts", "../src/core/run_index.ts", "../src/core/tool_outcome.ts", "../src/core/transcribe_audio.ts", "../src/core/upload_attachment.ts", "../src/core/chat_registry.ts", "../src/dom/ring_color.ts", "../src/dom/highlight_overlay.ts", "../src/dom/native_setter.ts", "../src/dom/utils.ts", "../src/dom/animations.ts", "../src/tools/chat_surface_tools.ts", "../src/tools/client_tool_registry.ts", "../src/tools/is_destructive.ts", "../src/tools/is_navigates.ts", "../src/tools/page_action_tools.ts", "../src/tools/page_map.ts", "../src/tools/page_state.ts", "../src/tools/parse_tool_catalog.ts", "../src/tools/route_map.ts", "../src/ui/charts/chart_block.ts", "../src/ui/charts/chart_spec_from.ts", "../src/ui/charts/chart_tool.ts", "../src/ui/excerpts/quote_selection.ts", "../src/ui/excerpts/place_offer.ts", "../src/ui/excerpts/page_quote_offer.ts", "../src/ui/ui_strings.ts", "../src/ui/fill_ui_string.ts", "../src/ui/history/relative_time.ts", "../src/ui/history/utils.ts", "../src/ui/history/checkpoint_menu.ts", "../src/ui/interrupts/approval_card.ts", "../src/ui/interrupts/confirmation_card.ts", "../src/ui/interrupts/question_card.ts", "../src/ui/progress/tool_call_card.ts", "../src/ui/transcript/message_actions.ts", "../node_modules/.pnpm/dompurify@3.4.17/node_modules/dompurify/src/utils.ts", "../node_modules/.pnpm/dompurify@3.4.17/node_modules/dompurify/src/tags.ts", "../node_modules/.pnpm/dompurify@3.4.17/node_modules/dompurify/src/attrs.ts", "../node_modules/.pnpm/dompurify@3.4.17/node_modules/dompurify/src/regexp.ts", "../node_modules/.pnpm/dompurify@3.4.17/node_modules/dompurify/src/purify.ts", "../node_modules/.pnpm/marked@18.1.3/node_modules/marked/src/defaults.ts", "../node_modules/.pnpm/marked@18.1.3/node_modules/marked/src/rules.ts", "../node_modules/.pnpm/marked@18.1.3/node_modules/marked/src/helpers.ts", "../node_modules/.pnpm/marked@18.1.3/node_modules/marked/src/Tokenizer.ts", "../node_modules/.pnpm/marked@18.1.3/node_modules/marked/src/Lexer.ts", "../node_modules/.pnpm/marked@18.1.3/node_modules/marked/src/Renderer.ts", "../node_modules/.pnpm/marked@18.1.3/node_modules/marked/src/TextRenderer.ts", "../node_modules/.pnpm/marked@18.1.3/node_modules/marked/src/Parser.ts", "../node_modules/.pnpm/marked@18.1.3/node_modules/marked/src/Hooks.ts", "../node_modules/.pnpm/marked@18.1.3/node_modules/marked/src/Instance.ts", "../node_modules/.pnpm/marked@18.1.3/node_modules/marked/src/marked.ts", "../src/ui/transcript/render_markdown.ts", "../src/ui/transcript/suggestion_chips.ts"],
|
|
4
|
+
"sourcesContent": ["// The package's single home for enums and constant-like values, and per\n// CLAUDE.md the only file allowed to export multiple symbols.\n\n/** The root every sessionStorage and localStorage key this package writes starts with. */\nexport const STORAGE_ROOT = \"agents-web-components\";\n\n/** The Custom Element tag name registered by {@link defineChat}. */\nexport const ELEMENT_TAG = \"ag-ui-chat\";\n\n/**\n * User submitted a message. `detail` is {@link SubmitDetail}.\n *\n * Fires for every turn the user sends: with Send, through `sendMessage`, and\n * as the next turn of a run resumed or forked from the checkpoint panel. A\n * listener runs while that turn is already the one in flight, so a\n * `sendMessage` from it is refused rather than starting a second run.\n */\nexport const SUBMIT_EVENT = \"ag-ui-submit\";\n\n/**\n * Collapsed state changed, via the built-in toggle or `setCollapsed`; and,\n * under `collapse-to=\"none\"`, once at connect with the state it mounted in.\n * `detail` is {@link ToggleDetail}.\n */\nexport const TOGGLE_EVENT = \"ag-ui-toggle\";\n\n/**\n * Maximized state changed, via the built-in header control, the `maximized`\n * property or attribute, or on leaving it for a collapse, a placement without\n * the control, or a viewport of 600px or less. `detail` is {@link MaximizeDetail}.\n */\nexport const MAXIMIZE_EVENT = \"ag-ui-maximize\";\n\n/**\n * The bottom bar's height changed (`collapse-to=\"bar\"`): the host pads its\n * page by it. `detail` is {@link BarHeightDetail}; 0 when no bar is drawn.\n */\nexport const BAR_HEIGHT_EVENT = \"ag-ui-bar-height\";\n\n/**\n * The width a docked panel covers at rest changed (`placement=\"sidebar\"` or\n * `\"side\"`): the host pushes its page by it. `detail` is {@link DockWidthDetail};\n * 0 when the panel covers none of the page.\n */\nexport const DOCK_WIDTH_EVENT = \"ag-ui-dock-width\";\n\n/**\n * The count of answers that arrived while collapsed changed. `detail` is\n * {@link UnreadDetail}. The built-in launcher badge renders exactly this; a\n * host driving its own chrome sets `data-unread-badge=\"false\"` and listens.\n */\nexport const UNREAD_EVENT = \"ag-ui-unread\";\n\n/**\n * AG-UI shared state changed \u2014 a streamed `STATE_SNAPSHOT` / `STATE_DELTA`, or\n * a host assignment to `sharedState`. `detail` is {@link StateDetail}.\n *\n * The protocol's own state channel, distinct from `registerPageState`, which\n * exposes host state to the agent as ordinary tools.\n */\nexport const STATE_EVENT = \"ag-ui-state\";\n\n/**\n * The attachment tray changed \u2014 a file queued, an upload finishing or failing,\n * a chip removed, the tray cleared after a send. `detail` is\n * {@link AttachmentsDetail}, carrying the refs that finished uploading and how\n * many are still in flight. A host driving its own composer uses this to know\n * whether a send would leave files behind.\n */\nexport const ATTACHMENT_EVENT = \"ag-ui-attachments\";\n\n/**\n * An interaction has finished, whatever ended it. `detail` is\n * {@link RunFinishedDetail}, listing the tools that ran and which side ran them.\n *\n * For hosts that render data the agent can change. A server-side tool writes\n * without the page's knowledge \u2014 nothing else the element dispatches implies\n * \"something may have moved underneath you\", so a page showing that data has no\n * reason to refetch and quietly goes stale. Shared state\n * ({@link STATE_EVENT}) is the richer channel, but it needs the agent to emit\n * state; this needs nothing of the agent at all.\n *\n * Fires once per interaction rather than once per tool round, on completion,\n * error and cancellation alike, since a partial write is still a write.\n */\nexport const RUN_FINISHED_EVENT = \"ag-ui-run-finished\";\n\n/**\n * The conversation on screen changed: a new chat, a thread switched to, the\n * active thread deleted, the stored thread restored, or a `user-key` change\n * handing the element to another principal. `detail` is {@link ThreadDetail}.\n *\n * Fires once per change, after the transcript has been replaced, so a listener\n * reads the conversation it is told about. A host listing conversations in its\n * own chrome marks the active one from here rather than watching attributes.\n */\nexport const THREAD_EVENT = \"ag-ui-thread\";\n\n/**\n * The title of the thread on screen changed: its first send, a rename, a\n * switch, a new chat or a delete, or a title the conversation list brought in.\n * `detail` is {@link ThreadTitleDetail}. `title-text=\"auto\"` draws it in the\n * header without a listener; a host drawing its own chrome listens.\n */\nexport const THREAD_TITLE_EVENT = \"ag-ui-thread-title\";\n\n/**\n * The agent sent an AG-UI `CUSTOM` event. `detail` is {@link CustomAgentDetail}.\n *\n * `CUSTOM` is one of exactly two carriers whose payload name the protocol leaves\n * an open string, and it is the **imperative** one: something for the host page\n * to *do*, with no place in the transcript. Its sibling `ACTIVITY_SNAPSHOT`\n * carries transcript **content**, which is why that one is materialised into a\n * message, persisted, and replayed on restore while this one is not.\n *\n * That asymmetry is the rule for choosing between them. Content has a place in\n * the conversation and should replay; an imperative has no place and no meaning\n * once acted on, so replaying it on a thread load would be a bug. Anything that\n * must survive a reload belongs on the other carrier.\n *\n * The element takes no view of what a name means -- it forwards every one. A\n * host that does not recognise a name ignores the event, which is the graceful\n * outcome the open field exists for.\n */\nexport const CUSTOM_AGENT_EVENT = \"ag-ui-custom\";\n\n/**\n * The agent named resources its write has moved. `detail` is\n * {@link InvalidateDetail}.\n *\n * A convention on top of {@link CUSTOM_AGENT_EVENT}, not a second channel: the\n * wire carries an ordinary AG-UI `CUSTOM` event whose `name` is\n * {@link INVALIDATE_CUSTOM_NAME}, and this is that one name routed to its own\n * DOM event so a host does not have to string-match. Every other name still\n * arrives as `ag-ui-custom`.\n *\n * Fires **as each announcement arrives**, during the run, which is what makes a\n * long multi-step run feel live: the list refreshes as the third of eight writes\n * lands rather than when everything finishes. {@link RUN_FINISHED_EVENT} carries\n * the same keys again at the end, de-duplicated, for a host that would rather\n * refetch once.\n */\nexport const INVALIDATE_EVENT = \"ag-ui-invalidate\";\n\n/**\n * Fired when the user rates an assistant message from its action row.\n *\n * `detail` is a {@link FeedbackDetail}: which message was rated -- its AG-UI\n * `messageId` and the `threadId` it belongs to, plus the `runId` that streamed\n * it when it arrived live (absent on a restored message, which carries no run\n * id) -- with its text and the rating. A host stores the rating against\n * `messageId`, not `content`: two answers can read the same. A restored\n * message is named by the id its store returns, so with a server-backed store\n * the id holds across a reload only where the server persists the ids it\n * streamed; the built-in browser store keeps them as they streamed.\n *\n * **Nothing is stored** -- a rating belongs to whatever the host already uses\n * to hold product signals, and a write-only table inside a chat widget is a\n * schema nobody reads.\n */\nexport const FEEDBACK_EVENT = \"ag-ui-feedback\";\n\n/**\n * The `activity_type` carrying server-pushed follow-up prompts.\n *\n * Matches django-ag-ui's `SUGGESTIONS_ACTIVITY_TYPE`. A convention inside the\n * protocol's open `activity_type` field, not an extension of it -- so a client\n * that has never heard of it ignores the event, and this one is not privileged.\n */\nexport const SUGGESTIONS_ACTIVITY_TYPE = \"suggestions\";\n\n/**\n * The AG-UI `CUSTOM` event `name` that carries an invalidation.\n *\n * Matched exactly. Namespaced so it cannot collide with a host's own custom\n * events, which share the field.\n */\nexport const INVALIDATE_CUSTOM_NAME = \"ag_ui.invalidate\";\n\n/**\n * The AG-UI `CUSTOM` event `name` carrying one step a delegated sub-agent took.\n *\n * Matched exactly, and namespaced the way {@link INVALIDATE_CUSTOM_NAME} is, so\n * it cannot collide with a host's own custom events on the same open field.\n *\n * Routed to the delegating tool card rather than dispatched to the page: the\n * payload keys on the **parent's own `delegate_task` call id**, so what it\n * describes is already on screen and the progress belongs beside it. Every other\n * name still reaches the host as {@link CUSTOM_AGENT_EVENT}.\n *\n * **This carries the steps only.** The delegation's own lifetime arrives on the\n * protocol's `SUBAGENT_STARTED` / `SUBAGENT_FINISHED` / `SUBAGENT_ERROR` events,\n * which name the same card through their `parentToolCallId`. The two are joined\n * by that id, which is why the panel is keyed on it rather than on the\n * `subagentRunId` the protocol's events carry.\n *\n * Deliberately on the imperative carrier and not on an activity, which means it\n * is **never persisted and never replayed**. That is the right half of the\n * split: a delegation that was live an hour ago is not live now, and replaying\n * its progress on a thread restore would be a lie about a run that is over. On a\n * reload mid-run the nested detail is gone and the tool card remains. The three\n * lifecycle events share that property -- `@ag-ui/client` dispatches them to\n * subscribers without writing them into `agent.messages` -- which is what made\n * them safe to adopt while the steps stayed here.\n */\nexport const SUBAGENT_CUSTOM_NAME = \"ag_ui.subagent\";\n\n/**\n * The phases one delegation moves through, as the panel draws them.\n *\n * Exactly one `STARTED` opens a delegation and exactly one `FINISHED` or\n * `FAILED` closes it; the two tool phases repeat in between, once per call the\n * child makes and once per result it gets back.\n *\n * **These are this element's five visual states, and they no longer come off one\n * wire.** `TOOL_CALL` and `TOOL_RESULT` are spelled by the server, on the\n * {@link SUBAGENT_CUSTOM_NAME} payload's `phase` field. The other three are this\n * element's own names for the protocol's `SUBAGENT_STARTED` / `SUBAGENT_FINISHED`\n * / `SUBAGENT_ERROR` events, which carry no phase field of their own because the\n * event type *is* the phase. Keeping one vocabulary is what lets the panel stay\n * a single state machine with one `data-phase` attribute for a host to style.\n *\n * `FAILED` carries **no exception text** from us \u2014 the protocol's error event\n * has a required `message`, and the server sends only the sub-agent's name in\n * it, on the same reasoning that redacts a `RUN_ERROR`, since an exception's\n * words are written for an operator. The detail rides the ordinary\n * `TOOL_CALL_RESULT` for that delegation, on the card the progress is already\n * attached to.\n */\nexport const SUBAGENT_PHASE = {\n STARTED: \"started\",\n TOOL_CALL: \"tool_call\",\n TOOL_RESULT: \"tool_result\",\n FINISHED: \"finished\",\n FAILED: \"failed\",\n} as const;\n\n/** Roles a chat message can take. */\nexport const MESSAGE_ROLE = {\n USER: \"user\",\n ASSISTANT: \"assistant\",\n} as const;\n\n/**\n * Schema-root key marking a tool destructive: the element gates its execution\n * behind the confirmation card unless `autoConfirm` is set. All four `x-*` keys\n * below mirror the `django-ag-ui` server side.\n */\nexport const X_DESTRUCTIVE_KEY = \"x-destructive\";\n\n/**\n * Schema-root key holding a confirmation prompt (e.g. `\"Activate this\n * project?\"`), shown instead of the generic `Run \"<tool>\"?`.\n */\nexport const X_CONFIRM_KEY = \"x-confirm\";\n\n/**\n * Schema-root key holding a short label for a tool (e.g. `\"Query orders\"` for\n * `query_model`), shown on the card instead of the raw tool name.\n */\nexport const X_SUMMARY_KEY = \"x-summary\";\n\n/**\n * Schema-root key marking a tool as navigating \u2014 its handler triggers a full\n * page reload. The element checkpoints the call before the reload and resumes\n * the run loop once the next page mounts.\n */\nexport const X_NAVIGATES_KEY = \"x-navigates\";\n\n/**\n * The built-in tool that re-reads the current page, registered only when a\n * page-map provider is set. Named here because the stale-page guard must exempt\n * it: refusing the one call that would refresh the agent's view deadlocks.\n */\nexport const READ_PAGE_TOOL = \"read_page\";\n\n/** The description of the context entry carrying the page map. */\nexport const PAGE_MAP_CONTEXT = \"page_map\";\n\n/**\n * The description of the context entry carrying the place the chip shows. Its\n * value is the place as JSON: the label, and the detail and href when set.\n */\nexport const PLACE_CONTEXT = \"place\";\n\n/**\n * Default upper bound on frontend tool-call \u2192 re-run rounds within one send.\n * Overridable via `data-max-tool-rounds`, or `AgUiClientConfig.maxToolRounds`\n * for a host driving the client directly.\n */\nexport const MAX_TOOL_ROUNDS = 10;\n\n/**\n * The actions a finished assistant message's row can carry, and the tokens\n * `data-message-actions` selects them by.\n *\n * All three are on when the attribute is absent. Naming them individually\n * rather than shipping one on/off switch is what the three differ over: feedback\n * is only useful to a host listening for {@link FEEDBACK_EVENT}, retry re-runs\n * the agent and a constrained surface may not permit that, and copy is the one\n * nobody objects to. A single switch would make dropping either of the first two\n * cost the third, and a host that only wanted one gone would rebuild the row\n * from `attachMessageActions` -- reimplementing the part names, the accessible\n * grouping and the retry hand-off to lose two buttons.\n */\nexport const MESSAGE_ACTIONS = {\n COPY: \"copy\",\n RETRY: \"retry\",\n FEEDBACK: \"feedback\",\n} as const;\n\n/**\n * Lifecycle status of a rendered tool-call card. A card opens as `PENDING`\n * while the call runs, then settles to `DONE`, `ERROR`, `DECLINED` or\n * `INTERRUPTED`.\n *\n * `INTERRUPTED` is a call that never produced a result and that nobody refused:\n * the run was stopped or failed before it finished, or no tool here answered it.\n * Neither of the older terminal states is true of it. `DONE` claimed a success\n * nothing achieved, and `DECLINED` says a person or a guard refused.\n *\n * `DEFERRED` is the one non-terminal state that is not \"running\": a server-side\n * tool a `ToolGuard` gated never executed, the run finished on an interrupt, and\n * the call is waiting on a person. Without it such a card sat at `PENDING` and\n * read \"running\u2026\" while the stream was over and the server idle \u2014 a status enum\n * missing a state does not omit that state, it renders it as whichever neighbour\n * is closest, and here the closest one claimed the opposite of the truth. A\n * *frontend* tool waiting on its own card (`ask_user`) stays `PENDING`, because\n * the browser really is running it.\n */\nexport const TOOL_CALL_STATUS = {\n PENDING: \"pending\",\n DEFERRED: \"deferred\",\n DONE: \"done\",\n ERROR: \"error\",\n DECLINED: \"declined\",\n INTERRUPTED: \"interrupted\",\n} as const;\n\n/**\n * How a tool call ended, as the server states it under `outcome` in a\n * `TOOL_CALL_RESULT`'s `metadata`.\n *\n * The vocabulary is pydantic-ai's own `ToolReturnPart.outcome`, carried whole\n * rather than re-spelled, so the four repos that pass a refusal along agree on\n * one word for it.\n *\n * **Absent means {@link TOOL_OUTCOME.SUCCESS}, and that is load-bearing.** Every\n * server written before the field existed omits it, so a missing field has to\n * render exactly as a plain result did \u2014 which is why this is an optional\n * key in the event's metadata and not a required field. `FAILED` is a call that ran\n * and failed; `DENIED` is one a person or a guard refused, so it never ran at\n * all. The two are worth distinguishing on screen because only the second is\n * something the user did. `INTERRUPTED` is a call that produced no result because\n * the run ended first: pydantic-ai writes it when it repairs a history a\n * cancelled stream left, and the element writes it for the same reason when a\n * run ends with a call still unanswered, so the next request carries a result\n * for every call without claiming anyone refused one.\n *\n * Anything *else* on the wire \u2014 a value from a later protocol version \u2014 is read\n * as a success rather than rejected.\n * A card is a claim about what happened, and \"I do not know this word\" is not\n * grounds for claiming failure. `toolStatusFromOutcome` is where that is done.\n */\nexport const TOOL_OUTCOME = {\n SUCCESS: \"success\",\n FAILED: \"failed\",\n DENIED: \"denied\",\n INTERRUPTED: \"interrupted\",\n} as const;\n\n/**\n * Lifecycle status of a pending-attachment chip in the composer tray. A chip\n * opens as `UPLOADING` (with a progress bar), then settles to `READY` (a durable\n * ref) or `ERROR` (with a retry control).\n */\nexport const ATTACHMENT_STATUS = {\n UPLOADING: \"uploading\",\n READY: \"ready\",\n ERROR: \"error\",\n} as const;\n\n/**\n * Default client-side upload size cap (10 MiB), matching django-ag-ui's\n * `ATTACHMENT_MAX_BYTES`. Overridable via `data-attachment-max-bytes`; the\n * server stays authoritative.\n */\nexport const DEFAULT_ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024;\n\n/**\n * How much detail a tool-call card shows. Set via `data-tool-display`; the\n * default is `grouped`.\n *\n * - `grouped` \u2014 a run's consecutive calls fold into one quiet row (\"Worked\n * through 5 steps\"), with the calls one click down as `full` cards, or as\n * {@link TOOL_GROUP_DISPLAY} names.\n * - `inline` \u2014 one status row (icon + summary), no card chrome, result behind\n * its own toggle. Reads as a line of the answer rather than a boxed card.\n * - `minimal` \u2014 tool name + status pill only. No args, no result body.\n * - `compact` \u2014 name + status, args and result behind one \"Details\" toggle.\n * - `full` \u2014 args inline, result behind its own toggle.\n */\nexport const TOOL_DISPLAY = {\n GROUPED: \"grouped\",\n INLINE: \"inline\",\n MINIMAL: \"minimal\",\n COMPACT: \"compact\",\n FULL: \"full\",\n} as const;\n\n/**\n * How an opened step group draws its calls. Set via `data-tool-group-display`\n * and read only while `data-tool-display` is `grouped`; an outer card mode\n * flattens the groups into its own cards and this value is ignored there.\n *\n * The same four card modes as {@link TOOL_DISPLAY}, applied to the calls inside\n * the group: `full` (the default, and what an absent or unknown value reads\n * as), `compact`, `minimal` and `inline`. A call waiting on an approval shows\n * its arguments in every one of them.\n */\nexport const TOOL_GROUP_DISPLAY = {\n INLINE: \"inline\",\n MINIMAL: \"minimal\",\n COMPACT: \"compact\",\n FULL: \"full\",\n} as const;\n\n/** One of the {@link TOOL_GROUP_DISPLAY} values. */\nexport type ToolGroupDisplayMode = (typeof TOOL_GROUP_DISPLAY)[keyof typeof TOOL_GROUP_DISPLAY];\n\n/**\n * `activityType` of the `ACTIVITY_SNAPSHOT` event django-ag-ui emits when a\n * compaction capability trimmed the history. `content` carries\n * `{ removed, before, after }`.\n */\nexport const COMPACTION_ACTIVITY_TYPE = \"compaction\";\n\n/**\n * Pydantic-AI's built-in tool for loading a deferred capability, with `{ id }`\n * naming it. Agent skills are deferred capabilities keyed by skill name, so a\n * call to this tool is the only signal that the agent picked a skill.\n *\n * Distinct from the host-provided {@link Skill} catalog, which is a human\n * affordance launched from the slash palette.\n */\nexport const LOAD_CAPABILITY_TOOL = \"load_capability\";\n\n/**\n * The chrome's glyphs, as inline SVG markup.\n *\n * Static author-written markup assigned as a `<slot>`'s fallback content, so it\n * never passes through the sanitiser \u2014 nothing here is user or server data, and\n * nothing user-supplied may be interpolated into it. Each icon is a 24x24\n * viewBox carrying the shared `glyph` class, which `STYLES` sizes and paints\n * from `currentColor`; `glyph--solid` fills instead of stroking. A host wanting\n * its own mark projects a matching `slot=\"icon-\u2026\"` child instead of editing\n * these.\n */\nexport const ICON_SEND = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M12 19.5V5m-6.5 6.5L12 5l6.5 6.5\"/></svg>`;\n\n/** The Stop glyph the composer button wears while a run is in flight. */\nexport const ICON_STOP = `<svg class=\"glyph glyph--solid\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><rect x=\"7\" y=\"7\" width=\"10\" height=\"10\" rx=\"2.5\"/></svg>`;\n\n/** The file-picker glyph (a paperclip). */\nexport const ICON_ATTACH = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M17 8.5V15a5 5 0 0 1-10 0V7a3 3 0 0 1 6 0v7.5a1 1 0 0 1-2 0V8.5\"/></svg>`;\n\n/** The voice-input glyph (a microphone on its stand). */\nexport const ICON_VOICE = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M12 4a3 3 0 0 1 3 3v5a3 3 0 0 1-6 0V7a3 3 0 0 1 3-3z\"/><path d=\"M5 11v1a7 7 0 0 0 14 0v-1\"/><path d=\"M12 19v3\"/></svg>`;\n\n/** The place chip's mark when the place brings no icon of its own (a map pin). */\nexport const ICON_PLACE = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M12 21s-6.5-5.6-6.5-11a6.5 6.5 0 0 1 13 0c0 5.4-6.5 11-6.5 11z\"/><circle cx=\"12\" cy=\"10\" r=\"2.3\"/></svg>`;\n\n/** The place toggle while the place is sent (an open eye). */\nexport const ICON_PLACE_SHARED = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M2.5 12s3.5-6.5 9.5-6.5 9.5 6.5 9.5 6.5-3.5 6.5-9.5 6.5S2.5 12 2.5 12z\"/><circle cx=\"12\" cy=\"12\" r=\"2.8\"/></svg>`;\n\n/** The place toggle while the place is withheld (the eye struck through). */\nexport const ICON_PLACE_WITHHELD = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M2.5 12s3.5-6.5 9.5-6.5c2 0 3.7.7 5.1 1.7M21.5 12s-3.5 6.5-9.5 6.5c-2 0-3.7-.7-5.1-1.7\"/><path d=\"M4 20 20 4\"/></svg>`;\n\n/**\n * The theme toggle's two marks, drawn rather than typed.\n *\n * They were the emoji `\\u{1F319}` and `\\u2600\\uFE0F`, which is why this one\n * control never sat right beside the others: an emoji is painted by the\n * platform's own font, at its own weight and colour, and its ink routinely\n * exceeds the text metrics it is laid out with -- so it drew outside the box\n * measured for it and clipped, while every neighbour is a stroked path that\n * fits its viewBox exactly.\n *\n * The moon is drawn as one closed crescent rather than a disc with a second\n * disc cut out of it, because these are stroked (`fill: none`) and a cut-out\n * needs a fill to hide anything.\n */\nexport const ICON_MOON = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M20 14.5A8.5 8.5 0 0 1 9.5 4a8.5 8.5 0 1 0 10.5 10.5z\"/></svg>`;\n\n/** The other half of the pair; see {@link ICON_MOON}. */\nexport const ICON_SUN = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"4\"/><path d=\"M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4\"/></svg>`;\n\n/**\n * The header controls' marks, drawn for the reason the theme pair is: typed\n * glyphs (U+2630, U+21BA, U+271A, U+2014, U+25A1, U+2750) were painted by the\n * platform font at its own weight and size, so they never matched the moon\n * beside them. Maximize points outward, restore inward.\n */\nexport const ICON_MAXIMIZE = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M14 10l6-6M15 4h5v5M10 14l-6 6M4 15v5h5\"/></svg>`;\n\n/** The maximize control's mark while the panel is maximized; see {@link ICON_MAXIMIZE}. */\nexport const ICON_RESTORE = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M20 4l-6 6M14 5v5h5M4 20l6-6M5 14h5v5\"/></svg>`;\n\n/**\n * The collapse control's marks, chosen by `data-collapse-icon`. The panel mark\n * is a window with its docked pane and an arrow into the edge it hides into;\n * its left twin, and the up and left chevrons, are the right and down ones\n * turned in the path data, so each mark is told apart by its paths alone.\n */\nexport const ICON_PANEL_CLOSE_RIGHT = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2.5\"/><path d=\"M15 4v16\"/><path d=\"M8 9.5l2.5 2.5L8 14.5\"/></svg>`;\n\n/** The panel mark for a panel docked to the left edge; see {@link ICON_PANEL_CLOSE_RIGHT}. */\nexport const ICON_PANEL_CLOSE_LEFT = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2.5\"/><path d=\"M9 4v16\"/><path d=\"M16 9.5L13.5 12l2.5 2.5\"/></svg>`;\n\n/** A chevron down, the corner placements' collapse mark; see {@link ICON_PANEL_CLOSE_RIGHT}. */\nexport const ICON_CHEVRON_DOWN = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M6 9.5l6 6 6-6\"/></svg>`;\n\n/** A chevron up; see {@link ICON_PANEL_CLOSE_RIGHT}. */\nexport const ICON_CHEVRON_UP = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M6 14.5l6-6 6 6\"/></svg>`;\n\n/** A chevron right; see {@link ICON_PANEL_CLOSE_RIGHT}. */\nexport const ICON_CHEVRON_RIGHT = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M9.5 6l6 6-6 6\"/></svg>`;\n\n/** A chevron left; see {@link ICON_PANEL_CLOSE_RIGHT}. */\nexport const ICON_CHEVRON_LEFT = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M14.5 6l-6 6 6 6\"/></svg>`;\n\n/** The new-chat control's mark (a pencil on a square). */\nexport const ICON_NEW_CHAT = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M11 4.5H6.5a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2V13\"/><path d=\"M17.5 3.5a2.1 2.1 0 0 1 3 3L12 15l-3.5 1 1-3.5z\"/></svg>`;\n\n/** The history control's mark (a clock with a back arrow). */\nexport const ICON_HISTORY = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M3.5 12A8.5 8.5 0 1 0 6 6L3.5 8.5\"/><path d=\"M3.5 4v4.5H8\"/><path d=\"M12 7.5V12l3 2\"/></svg>`;\n\n/** The checkpoints control's mark (an arrow turning back, counter-clockwise). */\nexport const ICON_CHECKPOINTS = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M9 14L4 9l5-5\"/><path d=\"M4 9h10.5a5.5 5.5 0 0 1 0 11H11\"/></svg>`;\n\n/** The default launcher mark (a speech bubble), shown when the host slots none. */\nexport const ICON_LAUNCHER = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H9l-5 4z\"/></svg>`;\n\n/**\n * The generic attachment-chip mark, for a file family with nothing more\n * specific to say. The chip marks share the contract of the chrome glyphs\n * above; `iconFor` selects one by MIME family, never interpolating the MIME\n * string into the markup.\n */\n/** Copy: two overlapping sheets, the shape every toolbar uses for it. */\nexport const ICON_COPY: string = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><rect x=\"9\" y=\"9\" width=\"11\" height=\"11\" rx=\"2\"/><path d=\"M5 15V6a2 2 0 0 1 2-2h8\"/></svg>`;\n\n/** Retry: a circular arrow. */\nexport const ICON_RETRY: string = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M20 12a8 8 0 1 1-2.5-5.8\"/><path d=\"M20 4v4h-4\"/></svg>`;\n\n/** Rate up. */\nexport const ICON_THUMB_UP: string = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M7 10v10H4V10z\"/><path d=\"M7 10l4.5-7a2 2 0 0 1 3.4 2L13.5 9H19a2 2 0 0 1 2 2.3l-1.1 6.4A2 2 0 0 1 17.9 20H7\"/></svg>`;\n\n/** Rate down: the up mark turned over, so the pair reads as one control. */\nexport const ICON_THUMB_DOWN: string = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M17 14V4h3v10z\"/><path d=\"M17 14l-4.5 7a2 2 0 0 1-3.4-2l1.4-4H5a2 2 0 0 1-2-2.3l1.1-6.4A2 2 0 0 1 6.1 4H17\"/></svg>`;\n\nexport const ICON_FILE = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z\"/><path d=\"M14 3v5h5\"/></svg>`;\n\n/** An image attachment: a framed picture with a horizon and a sun. */\nexport const ICON_FILE_IMAGE = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><rect x=\"3.5\" y=\"4.5\" width=\"17\" height=\"15\" rx=\"2.5\"/><circle cx=\"9\" cy=\"10\" r=\"1.5\"/><path d=\"M4.5 17.5 9 13.5l3.5 3 3-2.5 4.5 4\"/></svg>`;\n\n/** A PDF: the generic page, banded to read as a labelled document. */\nexport const ICON_FILE_PDF = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z\"/><path d=\"M14 3v5h5\"/><rect class=\"glyph--solid\" x=\"7.5\" y=\"13.5\" width=\"9\" height=\"4.5\" rx=\"1\"/></svg>`;\n\n/** A text document: the generic page, ruled. */\nexport const ICON_FILE_TEXT = `<svg class=\"glyph\" viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z\"/><path d=\"M14 3v5h5\"/><path d=\"M8.5 13.5h7M8.5 17h4.5\"/></svg>`;\n\n/**\n * ``activityType`` of the ``ACTIVITY_SNAPSHOT`` / ``ACTIVITY_DELTA`` events a\n * server sends to draw a chart.\n *\n * A convention inside an extension point the protocol already provides, not a\n * protocol extension: AG-UI defines the envelope and leaves ``activityType`` an\n * open string. Another vendor's client does not know this name and ignores the\n * event, which is the graceful outcome.\n */\nexport const CHART_ACTIVITY_TYPE = \"chart\";\n\n/**\n * The gutter a floating panel *rests* at, before anyone has touched it.\n *\n * It matches the default `--ag-ui-inset` and the stylesheet's\n * `--ag-ui-edge-gutter`, so an undragged widget resolves to exactly the\n * placement it already had, and it is what the size cap subtracts so a resting\n * panel grown to its limit stops at the far edge rather than one gutter past\n * it.\n *\n * Not a limit on where a *person* may put the widget -- that is\n * {@link SCREEN_EDGE_MARGIN}, and the two being one number is what made a\n * dragged panel feel stuck short of every edge on all four sides at once.\n */\nexport const EDGE_MARGIN = 24;\n\n/**\n * How long a screen-reader status stays in the announcer before it is emptied.\n *\n * Long enough for a reader to pick the change up, short enough that the region\n * is empty again before the next status lands. Emptying is what makes an\n * identical consecutive message announce at all -- a live region is read on\n * *change*, and setting the same string twice is not one.\n */\nexport const ANNOUNCE_CLEAR_MS = 150;\n\n/**\n * Stacking order for the host-page highlight overlay.\n *\n * One above the widget's own default, because the overlay's whole job is to\n * point at something on the page the widget is sitting over -- a ring drawn\n * underneath the panel would be hidden by the thing that asked for it. It takes\n * no pointer events at any point, so being on top costs the page nothing.\n */\nexport const HIGHLIGHT_OVERLAY_Z_INDEX = 2147483001;\n\n/**\n * How many characters a pasted string has to reach before it becomes an\n * attachment rather than composer text.\n *\n * The composer is capped at 40vh, so anything near this is already taller than\n * the box that holds it: the user cannot read what they pasted or edit around\n * it. Roughly where the field stops being usable rather than a number with a\n * meaning of its own -- `data-paste-attach` moves it.\n */\nexport const PASTE_ATTACH_CHARS = 5000;\n\n/**\n * How close the launcher may be pushed to the edge of the screen.\n *\n * Not the panel's 24px gutter, which was rejected here on purpose: a launcher\n * held that far in refuses the corners people actually drag it to. But zero is\n * wrong too. The bubble is a circle with a drop shadow, and one sitting flush\n * against the edge has its shadow cut and its curve running into the boundary,\n * which reads as clipped whether or not a single pixel is missing -- and on a\n * screen with rounded corners, or under a scrollbar, it is genuinely clipped.\n *\n * Small enough that every corner is still reachable, large enough that the\n * circle always closes.\n *\n * The panel obeys the same bound, for the same reason: it is a rounded box\n * with the same drop shadow, and there is no account of why a bubble held off\n * the boundary should sit beside a panel welded to it. Before this was shared\n * there were four answers to one question -- a drag stopped at 0, a resize at\n * 0, a restore at 24 and the launcher at 8 -- so a panel dragged flush leapt\n * 24px inward the next time anything re-placed it.\n */\nexport const SCREEN_EDGE_MARGIN = 8;\n", "import {\n type AbstractAgent,\n type AgentSubscriber,\n buildResumeArray,\n type RunAgentParameters,\n randomUUID,\n} from \"@ag-ui/client\";\nimport {\n type Context,\n contentToText,\n type Interrupt,\n type Message,\n type ResumeEntry,\n type Tool,\n} from \"@ag-ui/core\";\nimport { MAX_TOOL_ROUNDS, TOOL_OUTCOME } from \"../constants.js\";\nimport type { AttachmentRef } from \"./attachment.js\";\nimport type { ToolOutcome } from \"./tool_outcome.js\";\nimport { answerUnansweredCalls } from \"./utils.js\";\n\n/** A tool call surfaced to the host by {@link AgUiClient}. */\nexport interface AgUiToolCall {\n readonly id: string;\n readonly name: string;\n readonly args: Record<string, unknown>;\n}\n\n/**\n * Which message an answer surfaced by {@link AgUiClient} is, as the stream\n * named it.\n */\nexport interface AgUiMessageIds {\n /** The id the message streamed under, on its `TEXT_MESSAGE_START`/`END`. */\n readonly messageId: string;\n /**\n * The run that streamed it, as that run's `RUN_STARTED` declared it.\n *\n * Absent when no `RUN_STARTED` was seen. `@ag-ui/client` 1.0 rejects a\n * stream whose first event is anything else, so over a real agent this is\n * always present; nothing else names the run the server recorded, so\n * nothing is substituted when it is not.\n *\n * Text a sub-agent streams through the parent run carries the parent's run\n * id: that is the stream it arrived on, and the delegation's\n * `subagentRunId` names the child's work rather than a run the answer is\n * recorded under.\n */\n readonly runId?: string;\n}\n\n/** The result of executing a frontend tool, destined for a tool-result message. */\nexport interface ToolExecution {\n /** String content for the AG-UI tool-result message. */\n content: string;\n /** Present when the handler failed; surfaced for logging. */\n error?: string;\n /**\n * How the call ended, in the same vocabulary a server states on\n * `TOOL_CALL_RESULT`. Omit for a success -- absent *is* success, here for the\n * same reason it is on the wire.\n *\n * Distinct from {@link error}, which is a *message* and only exists for the\n * one failure shape that produces one. A refusal has no error and is still\n * not a success, and that is the case this field exists for.\n */\n outcome?: ToolOutcome;\n /**\n * When `true`, a navigating tool triggered a page reload. The loop stops\n * without appending a result \u2014 the result is supplied after the next mount\n * (see the resume path). Mutually exclusive with a usable `content`.\n */\n halt?: boolean;\n}\n\n/**\n * Executes a frontend tool call.\n *\n * Returns the {@link ToolExecution} to post back to the agent, or `null` when\n * there is nothing to post: the call is not a frontend tool the host owns (a\n * server-side tool the server already executed, which the client must not\n * re-run), or its run was stopped or handed over while the call waited. A\n * stopped call is left unanswered here, like the calls after it in the round,\n * and the next request answers it as not finished.\n */\nexport type ExecuteTool = (call: AgUiToolCall) => Promise<ToolExecution | null>;\n\n/**\n * One user decision for a server-side-tool approval interrupt. Structurally\n * matches `@ag-ui/client`'s (non-exported) `ResumeResponse`, the payload\n * {@link buildResumeArray} turns into a `ResumeEntry`: `resolved` approves (with\n * an optional `payload`, e.g. `{ approved: true }`), `cancelled` denies.\n */\nexport type InterruptResponse = { status: \"resolved\"; payload?: unknown } | { status: \"cancelled\" };\n\n/**\n * Resolves the approval interrupts a run finished on, keyed by interrupt id.\n *\n * A gated server-side tool defers instead of executing, so the run finishes on\n * an interrupt outcome; the host collects one decision per interrupt and the\n * loop resumes with the answers. Omit for agents that never gate server-side\n * tools \u2014 an unresolved interrupt then ends the loop.\n */\nexport type ResolveInterrupts = (\n interrupts: readonly Interrupt[],\n) => Promise<Record<string, InterruptResponse>>;\n\n/**\n * Callbacks the {@link AgUiClient} invokes as a run progresses. The host\n * (the `<ag-ui-chat>` element) implements these to render streaming text and\n * tool activity into the chat.\n */\nexport interface AgUiClientHandlers {\n onRunStart(): void;\n /** Fired on every streamed token; `buffer` is the full text so far. */\n onTextDelta(buffer: string): void;\n /**\n * Fired when the assistant message completes; `buffer` is the final text,\n * and `message` names it as the stream did.\n */\n onTextEnd(buffer: string, message: AgUiMessageIds): void;\n /** Fired when the agent finishes calling a tool (server- or frontend-side). */\n onToolCall(call: AgUiToolCall): void;\n /**\n * Fired when a server-side tool's result streams back (AG-UI's\n * `TOOL_CALL_RESULT`). Frontend tools don't emit this \u2014 the client supplies\n * their result itself \u2014 so this is the channel for server-executed output.\n *\n * `outcome` is the `outcome` key of the event's `metadata`, forwarded raw.\n * It is `unknown` rather than {@link ToolOutcome} because metadata is open by\n * key: the protocol declares the object and validates nothing inside it, so\n * neither can this signature honestly claim to. Read it with\n * `toolStatusFromOutcome`, which treats `undefined` and anything unrecognised\n * as a success.\n *\n * Only the metadata is read. A server written against `@ag-ui/client` 0.x\n * states the outcome at the top level of the event, and 1.0 strips that key\n * before any subscriber runs, so from such a server this is `undefined` and\n * the card settles as done.\n */\n onToolResult(toolCallId: string, content: string, outcome?: unknown): void;\n /**\n * Fired for AG-UI activity events \u2014 ambient notices about what the *run* did,\n * as opposed to work the agent asked for. `django-ag-ui` emits one with\n * `activityType: \"compaction\"` when it condensed the history.\n */\n onActivity(activityType: string, content: unknown, messageId: string): void;\n /**\n * An activity's content changed in place \u2014 a snapshot re-sent under the same\n * `messageId` with `replace`, or an `ACTIVITY_DELTA` whose JSON patch\n * `@ag-ui/client` has already applied.\n *\n * Reported after the client has updated its own message, so `content` is the\n * result rather than the instruction. That is the whole reason this is a\n * separate callback: the raw delta event fires *before* the patch lands, and\n * a subscriber acting on it would redraw from stale content.\n */\n onActivityChanged(messageId: string, activityType: string, content: unknown): void;\n /** Fired when a reasoning model starts emitting its chain-of-thought. */\n onReasoningStart(): void;\n /**\n * Fired on every reasoning token, and once more when the block ends.\n *\n * ``buffer`` is the text accumulated *before* the token that triggered the\n * call, which is what the protocol client passes -- so the stream trails by\n * one delta and the final call, at the end of the block, is what completes\n * it. Render the buffer wholesale rather than appending it.\n */\n onReasoningDelta(buffer: string): void;\n /** Fired when the reasoning block ends (before the answer text streams). */\n onReasoningEnd(): void;\n onRunEnd(): void;\n /**\n * The server replaced the whole conversation with `MESSAGES_SNAPSHOT`.\n *\n * `@ag-ui/client` applies the event before any subscriber sees it, so by the\n * time this fires `agent.messages` **is** the server's list -- and the run\n * loop persists `agent.messages`. The replacement therefore reaches the\n * conversation store whatever the host does; this hook exists so the host can\n * stop that being invisible.\n */\n onMessagesSnapshot(messages: readonly Message[]): void;\n /**\n * The agent sent a `CUSTOM` event.\n *\n * Forwarded whole and uninterpreted: `name` is an open string the protocol\n * does not enumerate, so a client that decided which names were legal would\n * be the thing the open field exists to avoid.\n */\n onCustomEvent(name: string, value: unknown): void;\n /**\n * A delegated sub-agent started, inside the run.\n *\n * The protocol's own event, unlike the steps that follow it on\n * {@link SUBAGENT_CUSTOM_NAME}. `parentToolCallId` links the delegation to the\n * `delegate_task` call that spawned it -- the field AG-UI provides for the\n * \"agents as tools\" shape -- and is `null` when the server did not send one,\n * which a host reads as a delegation it has nothing to attach to.\n *\n * `subagentRunId` names the child run and is the only id the two closing\n * events carry, so a host that wants to close what it opened has to remember\n * the pairing.\n */\n onSubAgentStarted(subagentRunId: string, name: string, parentToolCallId: string | null): void;\n /** The delegation named by `subagentRunId` completed. */\n onSubAgentFinished(subagentRunId: string): void;\n /**\n * The delegation named by `subagentRunId` failed.\n *\n * `message` is server text and required by the protocol, but it is not an\n * exception's words: `django-ag-ui` sends only which sub-agent failed, on the\n * same reasoning that redacts a `RUN_ERROR`. Render it as text, never as\n * markup.\n */\n onSubAgentError(subagentRunId: string, message: string): void;\n onError(message: string): void;\n /**\n * Fired when the user cancelled the run ({@link AgUiClient.cancel}) \u2014 the\n * deliberate-stop sibling of `onError`. Partial assistant text already\n * streamed stays valid, so the host keeps the bubble and shows a stopped\n * affordance rather than an error. `onSettled` still follows.\n */\n onCancelled(): void;\n /**\n * Fired exactly once when the interaction settles, however the run loop ended\n * \u2014 server-only round, rounds exhausted, cancellation, or error. The terminal\n * guarantee that the UI returns to rest.\n */\n onSettled(): void;\n}\n\n/**\n * Provider of the per-run frontend tool catalog and context. Both are read\n * fresh on every {@link AgUiClient.send} so the catalog reflects the current\n * page state.\n */\nexport interface AgUiRunInputs {\n getTools?: () => Tool[];\n getContext?: () => Context[];\n}\n\nexport interface AgUiClientConfig extends AgUiRunInputs {\n /** The AG-UI agent to drive. Injected so it can be faked in tests. */\n agent: AbstractAgent;\n handlers: AgUiClientHandlers;\n /** Executes frontend tool calls. Omit for server-only tool sets. */\n executeTool?: ExecuteTool;\n /**\n * Resolves server-side-tool approval interrupts. Omit when no server-side\n * tool is gated for approval \u2014 an interrupt then ends the loop unanswered.\n */\n resolveInterrupts?: ResolveInterrupts;\n /**\n * Invoked with the latest history whenever it changes, so the host can\n * persist it for durability across page reloads. Omit to keep the\n * conversation in-memory only.\n */\n onPersist?: (messages: readonly Message[]) => void;\n /**\n * Called whenever AG-UI shared state changes \u2014 a streamed `STATE_SNAPSHOT` /\n * `STATE_DELTA`, or {@link AgUiClient.setState}. `@ag-ui/client` owns applying\n * those events; this only forwards the result.\n */\n onStateChanged?: (state: Readonly<Record<string, unknown>>) => void;\n /**\n * Error text for {@link AgUiClientHandlers.onError} when a run's stream closes\n * without a terminal AG-UI event. Defaults to `\"Connection lost\"`; the host\n * passes its localized string.\n */\n connectionLostMessage?: string;\n /**\n * Result content for a tool call the conversation moved past without one: a\n * Stop while the stream was arriving, a round that ended on `RUN_ERROR`, a\n * call no {@link executeTool} answered, or history restored with a call still\n * open. Sent to the agent, so it says only that the call did not finish --\n * nobody refused it. Defaults to an English sentence; the host passes its\n * localized string.\n */\n unfinishedMessage?: string;\n /**\n * Result content for a server-side approval that Stop closed while it was\n * open, which the host's {@link resolveInterrupts} answers as declined.\n * Defaults to `\"User declined the action.\"`; the host passes its localized\n * string.\n */\n declinedMessage?: string;\n /**\n * Upper bound on frontend tool-call to re-run rounds within one\n * {@link AgUiClient.send}. Defaults to {@link MAX_TOOL_ROUNDS}.\n *\n * The default suits a chat whose tools answer questions. A page-driving\n * deployment reaches it legitimately -- filling a form field by field is one\n * round each -- and the symptom is not an error but an answer that stops\n * mid-task, which reads as the model giving up. Raise it where a turn is\n * expected to take many small steps.\n *\n * Read once, when the client is built. The bound is a property of the\n * deployment rather than of a run, so re-reading it per round would only make\n * a mid-run change possible, and a mid-run change to how long the run may\n * last is not a thing a host has any way to reason about.\n */\n maxToolRounds?: number;\n}\n\n/**\n * Raised when a run's stream closes cleanly at the transport level but never\n * emits a terminal AG-UI event, so the run neither finished nor errored. Routed\n * to {@link AgUiClientHandlers.onError} (it is not an abort), turning a silent\n * \"stuck pending\" into a visible \"connection lost\".\n */\nexport class ConnectionLostError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ConnectionLostError\";\n }\n}\n\n/**\n * Thin orchestration layer over an AG-UI {@link AbstractAgent}.\n *\n * Translates AG-UI's subscriber callbacks into the host's\n * {@link AgUiClientHandlers}, and appends the user message + current frontend\n * tool catalog + context to each run.\n */\nexport class AgUiClient {\n readonly #agent: AbstractAgent;\n readonly #handlers: AgUiClientHandlers;\n readonly #getTools: () => Tool[];\n readonly #getContext: () => Context[];\n readonly #executeTool: ExecuteTool | null;\n readonly #resolveInterrupts: ResolveInterrupts | null;\n readonly #onPersist: (messages: readonly Message[]) => void;\n /**\n * Message ids the server has already closed, so a reuse can be reported. Per\n * client rather than per run \u2014 the merge happens across runs, which a per-run\n * set would miss entirely.\n */\n readonly #closedMessageIds = new Set<string>();\n readonly #connectionLostMessage: string;\n readonly #unfinishedMessage: string;\n readonly #declinedMessage: string;\n readonly #maxToolRounds: number;\n // Set by cancel(); reset as send() or resume() begins, before either runs\n // any host code. Checked by the loop so a cancel between frontend-tool\n // rounds doesn't start another round, and again just before each request,\n // so a cancel from host code the round itself runs is not sent anyway.\n #cancelled = false;\n\n constructor(config: AgUiClientConfig) {\n this.#agent = config.agent;\n this.#handlers = config.handlers;\n this.#getTools = config.getTools ?? (() => []);\n this.#getContext = config.getContext ?? (() => []);\n this.#executeTool = config.executeTool ?? null;\n this.#resolveInterrupts = config.resolveInterrupts ?? null;\n this.#onPersist = config.onPersist ?? (() => {});\n this.#connectionLostMessage = config.connectionLostMessage ?? \"Connection lost\";\n this.#unfinishedMessage =\n config.unfinishedMessage ??\n \"Not finished: the run ended or moved on before this tool call returned a result.\";\n this.#declinedMessage = config.declinedMessage ?? \"User declined the action.\";\n // Validated here rather than at each caller, so the element's attribute and\n // a direct consumer get the same answer. A bound below one -- or a NaN from\n // an unparseable attribute -- is not a smaller budget but a send that runs\n // the agent zero times, which would look exactly like a broken endpoint.\n const rounds = config.maxToolRounds ?? MAX_TOOL_ROUNDS;\n this.#maxToolRounds = rounds >= 1 ? Math.floor(rounds) : MAX_TOOL_ROUNDS;\n this.#moveSeededKeysIntoMetadata();\n const onStateChanged = config.onStateChanged;\n if (onStateChanged !== undefined) {\n // The agent applies STATE_SNAPSHOT / STATE_DELTA itself; subscribing is\n // how the result is learned rather than re-derived from the event stream.\n // Lives for the agent's lifetime, which is this client's.\n this.#agent.subscribe({\n onStateChanged: ({ state }) => {\n onStateChanged(state as Record<string, unknown>);\n },\n });\n }\n }\n\n /** The current AG-UI shared state, as the agent last applied it. */\n get state(): Readonly<Record<string, unknown>> {\n return this.#agent.state as Record<string, unknown>;\n }\n\n /** Replace the shared state; the next run sends it as `RunAgentInput.state`. */\n setState(state: Readonly<Record<string, unknown>>): void {\n this.#agent.setState({ ...state });\n }\n\n /** Whether a run is currently in flight. */\n get running(): boolean {\n return this.#agent.isRunning;\n }\n\n /** The current conversation history (for persistence / rehydration). */\n get messages(): readonly Message[] {\n return this.#agent.messages;\n }\n\n /**\n * Append a user message and run the agent to completion.\n *\n * When the agent calls frontend tools, this executes them and re-runs the\n * agent with the results, looping until the agent stops calling frontend\n * tools (bounded by {@link AgUiClientConfig.maxToolRounds}, which defaults to\n * {@link MAX_TOOL_ROUNDS}).\n *\n * `attachments` ride in the user message's `metadata`, under\n * `attachments`, which is how the server learns which files the agent can\n * read and how the default store round-trips them for history replay; see\n * {@link messageAttachments}.\n */\n async send(content: string, attachments: readonly AttachmentRef[] = []): Promise<void> {\n // A new interaction, so the Stop of the one before it is forgotten here,\n // ahead of the save below: that save is the host's store, and a Stop it\n // makes (a new chat started from the save) has to stop this turn.\n this.#cancelled = false;\n // In `metadata` because it is the one field on a message `@ag-ui/client`\n // declares open by key. 1.0 strips every undeclared key from the input it\n // sends, so refs at the top level of the message are removed with a\n // console warning and the server is never told a file was attached. No metadata at all\n // without refs: an empty object would put a field on every plain message that says nothing.\n const message: Message = {\n id: randomUUID(),\n role: \"user\",\n content,\n ...(attachments.length > 0 ? { metadata: { attachments } } : {}),\n };\n this.#agent.addMessage(message);\n this.#persist();\n await this.#run();\n }\n\n /**\n * Drop everything after the most recent user message, so the same question\n * can be asked again.\n *\n * Returns the retained history, or `null` when there is nothing to retry (no\n * user message has been sent yet). The shortened history is saved before it\n * replaces the current one, so a save that throws changes nothing and the\n * throw propagates.\n *\n * **Truncates only** -- the caller re-renders from the returned list and then\n * calls {@link resume}, because the transcript belongs to the element and a\n * client that reached into it would own two things. Running here instead\n * would stream the new answer in underneath the old one.\n *\n * Re-running answers the question the agent was last asked, rather than\n * telling it its answer was wrong, which is what makes the result a\n * *different* answer instead of a conversation about the previous one.\n *\n * **A retried turn re-runs its tools.** For a page-driving agent that is not\n * neutral: the previous attempt already clicked what it clicked, and this\n * does not undo it.\n */\n truncateToLastUser(): readonly Message[] | null {\n const messages = [...this.#agent.messages];\n // Forward, keeping the last match, rather than a reverse scan with an\n // index lookup: `noUncheckedIndexedAccess` makes the latter reach for an\n // optional chain whose null arm cannot happen and cannot be covered.\n let lastUser = -1;\n for (const [index, message] of messages.entries()) {\n if (message.role === \"user\") {\n lastUser = index;\n }\n }\n if (lastUser === -1) {\n return null;\n }\n const kept = messages.slice(0, lastUser + 1);\n // Saved before the history is shortened, so a store that throws leaves it\n // as it was and the throw reaches the caller, as a refused save does from\n // send(), rather than leaving this client without an answer the caller's\n // transcript still shows.\n // Handed over directly rather than through #persist, which saves the list\n // the agent holds, because the agent does not hold this one yet.\n this.#onPersist(kept);\n this.#agent.setMessages(kept);\n return kept;\n }\n\n /**\n * Resume the run loop after a navigating tool's result was supplied\n * post-reload (via {@link addToolResult}). Unlike {@link send}, adds no user\n * message; it continues the conversation already in history.\n */\n async resume(): Promise<void> {\n // A new interaction, as in send(); no host code runs between here and the loop.\n this.#cancelled = false;\n await this.#run();\n }\n\n /** Append a frontend tool result to history (used by the resume path). */\n addToolResult(toolCallId: string, content: string): void {\n this.#agent.addMessage({ id: randomUUID(), role: \"tool\", content, toolCallId });\n this.#persist();\n }\n\n /**\n * Cancel the in-flight run (AG-UI has no server cancel route \u2014 aborting the\n * streaming request is the protocol's cancel; the server observes the\n * disconnect). Safe to call with no run in flight. Partial text already\n * streamed stays in history; {@link AgUiClientHandlers.onCancelled} fires\n * instead of `onError`, and `onSettled` still follows.\n *\n * Also stops a {@link send} or {@link resume} whose request has not been made\n * yet, when host code it runs on the way calls this: the save of the turn,\n * the tool and context providers, the save answering a call left open. No\n * request is made then, and `onCancelled` and `onSettled` fire as for any\n * other Stop. A cancel with nothing in flight is forgotten when the next\n * send or resume begins.\n */\n cancel(): void {\n this.#cancelled = true;\n this.#agent.abortRun();\n }\n\n async #run(): Promise<void> {\n try {\n await this.#runLoop();\n // `@ag-ui/client` filters abort errors inside `runAgent` (it resolves\n // rather than rejects on a cancelled fetch), so a cancelled run usually\n // ends here, not in the catch.\n if (this.#cancelled) {\n this.#onCancelled();\n }\n } catch (error) {\n if (this.#cancelled || isAbortError(error)) {\n this.#onCancelled();\n } else {\n this.#handlers.onError(error instanceof Error ? error.message : String(error));\n }\n } finally {\n this.#handlers.onSettled();\n }\n }\n\n #onCancelled(): void {\n // Persist so the truncated exchange, partial assistant text included,\n // survives a reload.\n this.#persist();\n this.#handlers.onCancelled();\n }\n\n /**\n * Move the keys a history stored by an earlier release carries at the top\n * level of its messages into their `metadata`, where this release writes them.\n *\n * Earlier releases wrote a tool message's `outcome` and a user message's\n * `attachments` beside the protocol's own fields. `@ag-ui/client` 1.0 strips\n * every undeclared key from the input it sends, so a restored conversation\n * sent as it was stored would lose both on its first request: the server\n * would no longer be told about any file attached before the upgrade, and\n * each strip would print a warning. Moved rather than dropped, so the next\n * save writes the conversation in the shape this release reads first and a\n * reload after it still replays a declined card as declined.\n *\n * Merged into the metadata a message already has, with a key already there\n * winning: a message carrying both was last written by the newer writer.\n * `ag_ui_chat_restored_outcome_wire.test.ts` reads the result off the body of\n * a real request. The check before `setMessages` only spares a copy when\n * nothing moves, which is every restore of a store this release wrote;\n * nothing observable depends on it.\n */\n #moveSeededKeysIntoMetadata(): void {\n const seeded = this.#agent.messages;\n const moved = seeded.map(withTopLevelKeysInMetadata);\n if (moved.some((message, index) => message !== seeded[index])) {\n this.#agent.setMessages(moved);\n }\n }\n\n /**\n * Give every tool call in history a result, before a request carries it.\n *\n * Called ahead of every `runAgent`, which makes it the one place the rule is\n * kept for every way a call can be left open -- a live run's Stop or\n * `RUN_ERROR`, a name no tool here owns, a server that sent no result -- and\n * for a client seeded with a restored history just the same. The answer says\n * the call did not finish rather than that anyone declined it: a person\n * declined only where they were asked, and those answers are already here by\n * the time this runs (see {@link #answerStoppedApprovals}).\n *\n * `resuming` names the calls the request is itself answering: a resumed\n * approval runs or denies them server-side, and a result here would answer\n * them twice.\n *\n * The outcome rides in the result's `metadata`, where the client folds a\n * server's own, so the next request carries it and a reload replays it. A\n * server that does not read it ignores it: `metadata` is a declared field.\n */\n #answerUnansweredCalls(resuming: ReadonlySet<string>): void {\n const messages = this.#agent.messages;\n const answered = answerUnansweredCalls(\n messages,\n (toolCallId) => ({\n id: randomUUID(),\n role: \"tool\",\n content: this.#unfinishedMessage,\n toolCallId,\n metadata: { outcome: TOOL_OUTCOME.INTERRUPTED },\n }),\n resuming,\n );\n if (answered !== messages) {\n this.#agent.setMessages([...answered]);\n this.#persist();\n }\n }\n\n /**\n * Answer, as declined, every approval that Stop closed as declined.\n *\n * Stop cancels the resume that would have told the server, so the decline the\n * approval recorded reaches no one unless history carries it. Only calls the\n * host's resolver answered `cancelled` are declined: a person who approved a\n * call and then pressed Stop did not decline it, and\n * {@link #answerUnansweredCalls} answers that one on the next request as not\n * finished.\n *\n * The status check is held by \"does not call an approved call declined, since\n * nobody declined it\" in `ag_ui_chat_unanswered_tool_calls.test.ts`; the\n * `toolCallId` check is held by the type checker, since a result needs an id\n * to answer.\n */\n #answerStoppedApprovals(\n interrupts: readonly Interrupt[],\n responses: Readonly<Record<string, InterruptResponse>>,\n ): void {\n for (const interrupt of interrupts) {\n const toolCallId = interrupt.toolCallId;\n if (toolCallId !== undefined && responses[interrupt.id]?.status === \"cancelled\") {\n this.#agent.addMessage({\n id: randomUUID(),\n role: \"tool\",\n content: this.#declinedMessage,\n toolCallId,\n metadata: { outcome: TOOL_OUTCOME.DENIED },\n });\n }\n }\n this.#persist();\n }\n\n /**\n * Hand the transcript to the host's store.\n *\n * The list as the agent holds it, with nothing added: how each tool call\n * ended rides in its result's `metadata`, which the client folds in from a\n * server's `TOOL_CALL_RESULT` and this class writes for the results it makes\n * itself, so the store sees exactly what the next request sends.\n */\n #persist(): void {\n this.#onPersist(this.#agent.messages);\n }\n\n async #runLoop(): Promise<void> {\n // Carries resolved approval answers into the next run when a round finished\n // on a server-side-tool interrupt. Distinct from the public resume(), which\n // continues an unfinished frontend-tool round after a page load; this stays\n // inside one #run().\n let resume: ResumeEntry[] | undefined;\n let resuming: ReadonlySet<string> = new Set();\n for (let round = 0; round < this.#maxToolRounds; round += 1) {\n // A cancel during the previous round's tool execution lands here: the\n // running handler completed, but no further round starts. The check\n // before the request below would stop the round as well; this one keeps\n // a stopped loop from running the providers and the store for a round\n // it will not send.\n if (this.#cancelled) {\n return;\n }\n const pending: AgUiToolCall[] = [];\n const runState: RunState = { terminal: false, errored: false, interrupts: [] };\n const params: RunAgentParameters = {\n tools: this.#getTools(),\n context: this.#getContext(),\n };\n if (resume !== undefined) {\n params.resume = resume;\n }\n this.#answerUnansweredCalls(resuming);\n // Everything above since the check at the top is host code -- the tool\n // and context providers, and the store saving the answers just made -- and\n // any of it can be what stopped the run, by starting a new chat or\n // changing the principal. `@ag-ui/client` makes a fresh abort controller\n // for each run, so the abort `cancel()` made in that time reached\n // nothing, and only this check keeps the request from going out.\n if (this.#cancelled) {\n return;\n }\n await this.#agent.runAgent(params, this.#buildSubscriber(pending, runState));\n resume = undefined;\n resuming = new Set();\n this.#persist();\n // Cancelled mid-stream: don't execute the tool calls collected before the\n // abort.\n if (this.#cancelled) {\n return;\n }\n // The stream resolved without RUN_FINISHED / RUN_ERROR, so the transport\n // dropped mid-run. Surface it as an error (via #run) rather than resting\n // silently with a stuck pending indicator.\n if (!runState.terminal) {\n throw new ConnectionLostError(this.#connectionLostMessage);\n }\n // RUN_ERROR is terminal and the agent already reported it via onError.\n // Executing the calls collected before it, or starting another round,\n // would run into a broken context and raise a confusing second error.\n // Pending tool cards are swept at onSettled.\n if (runState.errored) {\n return;\n }\n // A gated server-side tool deferred, so the run finished on an interrupt\n // outcome: resolve each interrupt, then re-enter carrying the answers so\n // the follow-up run executes or denies the tool. Must precede the\n // frontend-tool sweep below \u2014 a server-side tool isn't ours to run.\n if (runState.interrupts.length > 0) {\n if (this.#resolveInterrupts === null) {\n return;\n }\n const responses = await this.#resolveInterrupts(runState.interrupts);\n if (this.#cancelled) {\n this.#answerStoppedApprovals(runState.interrupts, responses);\n return;\n }\n resume = buildResumeArray(runState.interrupts, responses);\n resuming = new Set(runState.interrupts.flatMap(({ toolCallId }) => toolCallId ?? []));\n continue;\n }\n if (this.#executeTool === null || pending.length === 0) {\n return;\n }\n let executed = false;\n for (const call of pending) {\n // A cancel while an earlier call in this round ran lands here. That\n // handler could not be aborted and its result is kept, but the calls\n // after it have not started, and a person who pressed Stop during the\n // first page action did not ask for the second. They are answered as not\n // finished before the next request.\n if (this.#cancelled) {\n return;\n }\n const result = await this.#executeTool(call);\n if (result === null) {\n continue;\n }\n if (result.halt === true) {\n // A navigating tool reloaded the page; the result arrives on the\n // next mount. Stop here rather than re-running into a dead context.\n return;\n }\n // A frontend tool's refusal or failure is stated by no server, because\n // no server ran the call, so the client writes it where the client\n // folds a server's: the result's `metadata`. Written with the message,\n // so the very first save of it already carries how it ended, and a\n // reload reads the card off it. A success writes no metadata at all,\n // as a server's success states none.\n this.#agent.addMessage({\n id: randomUUID(),\n role: \"tool\",\n content: result.content,\n toolCallId: call.id,\n ...(result.outcome === undefined ? {} : { metadata: { outcome: result.outcome } }),\n });\n this.#persist();\n executed = true;\n }\n if (!executed) {\n return;\n }\n }\n }\n\n #buildSubscriber(pending: AgUiToolCall[], runState: RunState): AgentSubscriber {\n const h = this.#handlers;\n const closed = this.#closedMessageIds;\n // Read at event time, not captured now: the flag flips mid-run, and the\n // subscriber is built before the run that a later `cancel()` stops.\n const cancelled = (): boolean => this.#cancelled;\n // Charts whose patch has been dispatched but not yet applied. Scoped to the\n // subscriber, so it cannot outlive the run that created it.\n const pendingDeltas = new Set<string>();\n // The run this round's stream declared. Per subscriber, so per round: a\n // turn that calls a tool is two runs, and its answer belongs to the second.\n //\n // Taken from `RUN_STARTED` rather than the `runId` the request carried.\n // The client mints that one, and a server is free to record the run under\n // the id it streams back; the event is the server's own statement of\n // which run this is, so it is the id a host can find again.\n let runId: string | undefined;\n return {\n onRunInitialized() {\n h.onRunStart();\n },\n onRunStartedEvent({ event }) {\n runId = event.runId;\n },\n onTextMessageStartEvent({ event }) {\n // A reused message id merges two answers into one persisted transcript\n // entry. The protocol has no rule to enforce and refusing the event\n // would be worse than the merge, so warn and continue \u2014 but do not stay\n // silent, since the corruption outlives the session.\n if (closed.has(event.messageId)) {\n console.warn(\n `<ag-ui-chat>: the server reused message id \"${event.messageId}\", which was ` +\n \"already closed. Its content will be appended to that earlier message rather \" +\n \"than starting a new one, and the merged result is what gets persisted. \" +\n \"Issue a fresh id per message.\",\n );\n }\n },\n onTextMessageContentEvent({ textMessageBuffer }) {\n h.onTextDelta(textMessageBuffer);\n },\n onTextMessageEndEvent({ event, textMessageBuffer }) {\n closed.add(event.messageId);\n h.onTextEnd(textMessageBuffer, {\n messageId: event.messageId,\n ...(runId === undefined ? {} : { runId }),\n });\n },\n onToolCallEndEvent({ event, toolCallName, toolCallArgs }) {\n const call: AgUiToolCall = {\n id: event.toolCallId,\n name: toolCallName,\n args: toolCallArgs,\n };\n pending.push(call);\n h.onToolCall(call);\n },\n onToolCallResultEvent({ event }) {\n // In the event's `metadata`, the one place on it `@ag-ui/client` 1.0\n // declares open by key. Its enforcement stage strips every undeclared\n // key before a subscriber runs, so an `outcome` stated at the top level\n // of the event never gets here.\n //\n // Nothing is recorded for the transcript: after this returns, the\n // client builds the tool message and folds the event's metadata onto\n // it, so the outcome is already on the message a save writes, word for\n // word as the server said it. A reload reads it back through the same\n // mapping as the live path, which is what keeps the two agreeing.\n const outcome: unknown = event.metadata?.[\"outcome\"];\n // Content may arrive as parts since the protocol's 1.0, so a tool can\n // return an image beside its text. A card shows text, so the text parts\n // are joined and the rest left to the host store, which keeps the\n // message whole; a plain string passes through unchanged.\n h.onToolResult(event.toolCallId, contentToText(event.content), outcome);\n },\n onActivitySnapshotEvent({ event, messages }) {\n // A snapshot for an id already in the list is a replacement, not a new\n // activity: the client has swapped its content in place, and a second\n // append would leave the superseded one on screen.\n const known = messages.some(\n (message) => message.id === event.messageId && message.role === \"activity\",\n );\n if (known) {\n h.onActivityChanged(event.messageId, event.activityType, event.content);\n return;\n }\n h.onActivity(event.activityType, event.content, event.messageId);\n },\n // Deliberately does *not* read the message here. `@ag-ui/client`\n // dispatches this subscriber **before** applying the patch, so the\n // message still holds its previous content: redrawing from it would leave\n // the chart one revision behind for the life of the run, and disagreeing\n // with what a reload shows. Note which chart moved and read the result on\n // the change that follows.\n onActivityDeltaEvent({ event }) {\n pendingDeltas.add(event.messageId);\n },\n onCustomEvent({ event }) {\n h.onCustomEvent(event.name, event.value);\n },\n // The delegation lifecycle. Forwarded rather than interpreted here, for\n // the reason every other subscriber in this block is thin: this file\n // adapts the protocol to the handler surface, and what a delegation looks\n // like on screen is the element's business.\n //\n // `parentToolCallId` is optional on the wire and normalised to `null` so\n // the handler has one absent-value to check rather than two.\n onSubagentStartedEvent({ event }) {\n h.onSubAgentStarted(event.subagentRunId, event.name, event.parentToolCallId ?? null);\n },\n onSubagentFinishedEvent({ event }) {\n h.onSubAgentFinished(event.subagentRunId);\n },\n onSubagentErrorEvent({ event }) {\n h.onSubAgentError(event.subagentRunId, event.message);\n },\n onMessagesSnapshotEvent({ event }) {\n h.onMessagesSnapshot(event.messages as readonly Message[]);\n },\n // Emitted after the client has written the patched messages, which is the\n // first moment the result exists. Only the ids marked above are looked at,\n // so an ordinary text delta does not walk the transcript.\n onMessagesChanged({ messages }) {\n for (const id of pendingDeltas) {\n const message = messages.find((entry) => entry.id === id);\n if (message !== undefined && message.role === \"activity\") {\n h.onActivityChanged(id, message.activityType, message.content);\n }\n }\n pendingDeltas.clear();\n },\n // THINKING_* left the protocol in its 1.0, but `@ag-ui/client` still\n // converts a server's THINKING_* events onto these REASONING_* callbacks,\n // with a console warning, for a deprecation window it sets. Nothing in the\n // family emits THINKING_*: pydantic-ai has sent REASONING_* at every\n // protocol version django-ag-ui admits.\n onReasoningStartEvent() {\n h.onReasoningStart();\n },\n onReasoningMessageContentEvent({ reasoningMessageBuffer }) {\n h.onReasoningDelta(reasoningMessageBuffer);\n },\n // The delta callback reports the buffer as it stood *before* the announced\n // delta was appended, so on its own it always trails the stream by one and\n // renders nothing at all for a block that arrives as a single delta. The\n // answer text is spared that because its own end event carries the whole\n // message; this is the reasoning counterpart, and it has to be\n // REASONING_MESSAGE_END rather than REASONING_END, because only the former\n // carries a buffer.\n onReasoningMessageEndEvent({ reasoningMessageBuffer }) {\n h.onReasoningDelta(reasoningMessageBuffer);\n },\n onReasoningEndEvent() {\n h.onReasoningEnd();\n },\n onRunFinishedEvent(params) {\n // RUN_FINISHED is terminal for both a normal finish and an interrupt.\n // Capture the interrupts here rather than reading the agent's\n // `pendingInterrupts` afterwards, to stay independent of that field's\n // cross-run clearing semantics.\n runState.terminal = true;\n if (params.outcome === \"interrupt\") {\n runState.interrupts = params.interrupts;\n }\n },\n onRunErrorEvent({ event }) {\n runState.terminal = true;\n runState.errored = true;\n // Cancelling aborts the response mid-read, and the browser's own words\n // for that can arrive here as a RUN_ERROR \u2014 Chrome's is\n // \"BodyStreamBuffer was aborted\". The run is over either way, but a\n // deliberate stop is not a failure, and reporting it would raise a\n // warning bubble above the stopped note saying the same thing twice.\n // The promise route in `#run` reports the cancellation.\n if (cancelled()) {\n return;\n }\n h.onError(event.message);\n },\n onRunFinalized() {\n runState.terminal = true;\n h.onRunEnd();\n },\n };\n }\n}\n\n/** Per-run mutable flags the subscriber writes and {@link AgUiClient} reads. */\ninterface RunState {\n terminal: boolean;\n errored: boolean;\n /** Approval interrupts a run finished on (empty for a normal finish). */\n interrupts: Interrupt[];\n}\n\n/**\n * Whether a rejection came from aborting the run's fetch. Belt-and-suspenders\n * with the `#cancelled` flag: some `@ag-ui/client` versions re-throw the\n * `AbortError` instead of filtering it.\n *\n * Aborting a fetch whose body is mid-read does not always surface as an\n * `AbortError`. Chrome raises `TypeError: BodyStreamBuffer was aborted`, which\n * is the same event wearing a different name, so a message naming the abort is\n * read as one too. Narrow on purpose: only a `TypeError`, and only when it says\n * so \u2014 a genuine type error carries no such word, and misreading one as a\n * cancellation would hide a real failure behind a stopped note.\n */\nfunction isAbortError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n return (\n error.name === \"AbortError\" || (error instanceof TypeError && /abort/i.test(error.message))\n );\n}\n\n/**\n * `message` with the keys an earlier release wrote at its top level -- a tool\n * message's `outcome`, a user message's `attachments` -- moved into its\n * `metadata`, or `message` itself when it carries neither.\n *\n * Both keys move whatever the role: no message the protocol defines declares\n * either, so a top-level one can only be this component's own. A key already in\n * the metadata wins over the one being moved, and a `metadata` that is not an\n * object is replaced rather than spread -- a store is not trusted to hold the\n * shape anything here wrote, and a spread string would scatter into numbered\n * keys.\n *\n * Held by \"carries history stored by an earlier release into metadata\" in\n * `agui_client.test.ts`, which seeds a message with only `attachments`, one\n * with only `outcome`, one whose metadata already has the key, and one whose\n * metadata is a string: deleting either half of the early return, or the\n * object check, fails it.\n */\nfunction withTopLevelKeysInMetadata(message: Message): Message {\n const { outcome, attachments, ...wire } = message as Message & {\n outcome?: unknown;\n attachments?: unknown;\n };\n if (outcome === undefined && attachments === undefined) {\n return message;\n }\n const existing = (wire as { metadata?: unknown }).metadata;\n return {\n ...wire,\n metadata: {\n ...(outcome === undefined ? {} : { outcome }),\n ...(attachments === undefined ? {} : { attachments }),\n // `null` passes the check and spreads as nothing, which is what it means.\n ...(typeof existing === \"object\" ? existing : {}),\n },\n } as Message;\n}\n", "// Non-exported-from-index helpers shared by the core modules.\n\nimport { randomUUID } from \"@ag-ui/client\";\nimport type { Message } from \"@ag-ui/core\";\nimport type { ClientConversationStore } from \"./conversation_store.js\";\n\n/**\n * Overlay a `credentials` mode onto a fetch `init`, or hand the `init` back\n * untouched when none is configured.\n *\n * Absent and `undefined` differ: `exactOptionalPropertyTypes` rejects an\n * explicit `credentials: undefined`, and writing one anyway would state a mode\n * where the point is to leave the browser's own default in place.\n */\nexport function withCredentials(\n init: RequestInit | undefined,\n credentials: RequestCredentials | undefined,\n): RequestInit | undefined {\n return credentials === undefined ? init : { ...init, credentials };\n}\n\n/**\n * Start a new conversation in `store` and return its id.\n *\n * `newThread` is optional on the interface, so a store without it is\n * driven the only other way the interface allows: mint an id here and make it\n * active. That path loses the store's own note that the thread is new, so a\n * remote store would go on to ask the server for a conversation that cannot\n * exist yet \u2014 which is why every store in this package implements the method.\n *\n * What neither path does is clear the thread being left behind. Starting a\n * conversation is not a reason to destroy the previous one.\n */\nexport function mintThread(store: ClientConversationStore): string {\n if (store.newThread !== undefined) {\n return store.newThread();\n }\n const id = randomUUID();\n store.setActiveThread(id);\n return id;\n}\n\n/**\n * Announce host credentials about to leave the document's origin.\n *\n * `endpoint` and its six sibling URL attributes are plain HTML, and a page that\n * interpolates one from a query parameter or from tenant-authored\n * configuration has handed an attacker the destination. The browser preflights\n * the custom header, any server willing to answer `Access-Control-Allow-Headers`\n * receives it, and the token leaves on the element's very first request \u2014\n * before the user has done anything. Nothing else in this package compares a\n * configured URL against an expected origin, so without this the delivery is\n * silent, which is the only part of that sequence worth changing.\n *\n * A warning rather than a refusal because a cross-origin agent is a documented\n * deployment: refusing would break working installations to defend against a\n * page that is already interpolating untrusted data into its own markup. What\n * it removes is the silence.\n *\n * `warned` is supplied by the caller rather than held here, per this package's\n * rule against shared mutable state: two elements on one page must each get\n * their own notice, and the set lives exactly as long as its owner.\n *\n * Every configured URL goes through this, not the agent endpoint alone. The\n * tool catalog, the skills list, the thread and attachment endpoints and the\n * upload target are all named by the same kind of host attribute and all carry\n * the same headers, so covering one of them and not the rest would report the\n * least interesting of the seven.\n */\nexport function warnOnCrossOriginCredentials(\n url: string | URL,\n credentialNames: readonly string[],\n trustedOrigins: readonly string[],\n warned: Set<string>,\n): void {\n if (credentialNames.length === 0) {\n return;\n }\n // Resolved against the document, so a relative endpoint \u2014 the ordinary case \u2014\n // lands on this origin and says nothing.\n const destination = new URL(String(url), location.href).origin;\n if (\n destination === location.origin ||\n trustedOrigins.includes(destination) ||\n warned.has(destination)\n ) {\n return;\n }\n warned.add(destination);\n console.warn(\n `<ag-ui-chat>: sending host credentials (${credentialNames.join(\", \")}) to ` +\n `${destination}, which is not this page's origin (${location.origin}). Those headers ` +\n \"are the page's own authentication, and whichever server answers the browser's \" +\n \"preflight receives them \u2014 so a URL attribute built from a query parameter or from \" +\n \"tenant-authored configuration is a channel for the token to leave on. If this \" +\n \"destination is deliberate, name it in `trustedOrigins` to confirm it and \" +\n \"silence this notice. Reported once per origin.\",\n );\n}\n\n/**\n * The tokens of a comma-separated attribute value, trimmed, with empty ones\n * dropped -- so `\"scroll, drag,\"` is `[\"scroll\", \"drag\"]`.\n *\n * Shared by every attribute that names a set of opt-ins, so each one reads a\n * stray space or a trailing comma the same way.\n */\nexport function commaTokens(value: string): string[] {\n return value\n .split(\",\")\n .map((token) => token.trim())\n .filter((token) => token !== \"\");\n}\n\n/**\n * `messages` with a result for every tool call that has none, each placed at the\n * end of the round that made the call.\n *\n * **Why every call.** Several model providers reject a request carrying a tool\n * call with no result, and a conversation that sends one cannot continue. A run\n * leaves calls unanswered in more ways than any one path can list: Stop while\n * the stream is still arriving, a round ending on `RUN_ERROR`, a name no tool\n * here owns, a server that never streamed a result, a page reloaded mid-run.\n * Answering whatever is unanswered, rather than each of those where it happens,\n * is what keeps a path nobody listed from sending one.\n *\n * **Where each result goes.** At the end of its round: the assistant turns\n * carrying calls, then the results that follow them. That is the shape the run\n * loop writes for a round it executed, and a provider reads a result only in the\n * turn straight after the calls; appended at the end of history, it would sit\n * behind a user turn or a reply the conversation has moved on to. A call with a\n * result after a *later* turn is left alone, since it is answered.\n *\n * `answer` builds the one message for a call id, so the caller decides what is\n * true to say and where the label for a reload goes. Calls in `except` are about\n * to be answered by something else -- a resumed approval, or a navigation\n * result -- and must not be answered twice.\n *\n * Returns `messages` itself when nothing is owed.\n *\n * Every condition deciding a round's end is one branch arc, which a coverage\n * gate reports as covered with any part of it deleted. Each is held by a test in\n * `ag_ui_chat_unanswered_tool_calls.test.ts`: a result continuing the round by\n * \"answers it after the round's own results\"; a turn without calls closing it by\n * \"sends a not-finished result for a call that arrived before it\"; a turn with\n * calls after a result closing it by \"answers each round's open call before the\n * next round starts\"; the answered check by \"sends the decline Stop gave the\n * open approval\"; and the exclusion by \"leaves the call it resumes for the\n * server to answer\".\n */\nexport function answerUnansweredCalls(\n messages: readonly Message[],\n answer: (toolCallId: string) => Message,\n except: ReadonlySet<string> = new Set(),\n): readonly Message[] {\n const answered = new Set<string>(except);\n for (const message of messages) {\n if (message.role === \"tool\") {\n answered.add(message.toolCallId);\n }\n }\n const result: Message[] = [];\n let owed: string[] = [];\n let afterResult = false;\n for (const message of messages) {\n const calls = message.role === \"assistant\" ? toolCallIds(message.toolCalls) : [];\n const continuesRound = message.role === \"tool\" || (calls.length > 0 && !afterResult);\n if (!continuesRound) {\n result.push(...owed.map(answer));\n owed = [];\n }\n result.push(message);\n afterResult = message.role === \"tool\";\n for (const id of calls) {\n if (!answered.has(id)) {\n // Marked as it is owed, so a store holding the same id twice gets one\n // answer rather than two, which a provider rejects just the same.\n answered.add(id);\n owed.push(id);\n }\n }\n }\n if (result.length + owed.length === messages.length) {\n return messages;\n }\n result.push(...owed.map(answer));\n return result;\n}\n\n/**\n * The ids of the tool calls an assistant turn carries, skipping anything without\n * one.\n *\n * The field is read off the wire or out of a store, and neither is held to its\n * declared type: a server dumping Python models sends `null` for no calls, and a\n * stored conversation may be hand-edited or written by an older version. A throw\n * here would cost the whole request, so a shapeless entry is passed over.\n */\nfunction toolCallIds(value: unknown): string[] {\n // `Object()` boxes a `null` or a primitive entry into something with no `id`,\n // so one read covers every shape without a branch per shape.\n return Array.isArray(value)\n ? value\n .map((call: unknown) => (Object(call) as { id?: unknown }).id)\n .filter((id): id is string => typeof id === \"string\")\n : [];\n}\n\n/**\n * A key a message carries in its `metadata`, or the same key at the message's\n * top level when its metadata has none.\n *\n * Two keys are read this way, a tool message's `outcome` and a user message's\n * `attachments`, and both for the same reason. `@ag-ui/client` 1.0 strips every\n * key its schemas do not declare, off an inbound event and off the outgoing\n * input, and `metadata` is the one place it declares open by key, so that is\n * where this component writes them. A conversation stored by an earlier release\n * has them at the top level instead, and a reload has to replay it as it\n * settled.\n *\n * Metadata first, so a message carrying both says what the newer writer said.\n * The result is `unknown` because it comes out of a store, which is not trusted\n * to hold the shape anything here wrote; the caller narrows it. `Object()` boxes\n * an absent, `null` or primitive `metadata` into an object with neither key,\n * which reads as no metadata without a branch per shape.\n */\nexport function metadataOrTopLevel(message: Message, key: \"outcome\" | \"attachments\"): unknown {\n const metadata = Object((message as { metadata?: unknown }).metadata) as Record<string, unknown>;\n return metadata[key] ?? (message as unknown as Record<string, unknown>)[key];\n}\n", "import type { Message } from \"@ag-ui/core\";\nimport { metadataOrTopLevel } from \"./utils.js\";\n\n/**\n * A durable, lightweight reference to one uploaded file \u2014 what an upload\n * returns and what rides on a sent message, never the bytes.\n *\n * Mirrors django-ag-ui's `AttachmentRef`: the file uploads out-of-band to the\n * attachments endpoint, the server hands back this ref, and the agent reads the\n * content server-side via the `read_attachment` tool.\n */\nexport interface AttachmentRef {\n /** Opaque, owner-scoped handle the server resolves back to bytes. */\n readonly id: string;\n /** Original filename, for display on the chip. */\n readonly name: string;\n /** Declared content type (a hint \u2014 the server is authoritative). */\n readonly mime: string;\n /** Size in bytes. */\n readonly size: number;\n /** Optional direct fetch URL (the owner-checked download endpoint). */\n readonly url?: string;\n}\n\n/**\n * The attachment refs a user message carries.\n *\n * `AgUiClient.send` writes them into the message's `metadata`, under\n * `attachments`. That is the one place they survive the trip: `@ag-ui/client`\n * 1.0 strips every key its schemas do not declare from the outgoing input, so\n * refs written at the top level of the message never reach the server, while\n * `metadata` is declared open by key and sent as it is. The server reads them\n * from there to tell the agent which files it can read, and the default store\n * round-trips them, so a restored conversation re-renders its chips.\n *\n * A conversation stored by an earlier release has them at the top level, so\n * that is read when the metadata has none. An older server reads only the top\n * level, so against one the agent is never told about a file at all.\n *\n * Storage is untrusted \u2014 hand-edited, truncated, or corrupted \u2014 so malformed\n * entries are dropped here; a shapeless one would throw in `iconFor` and abort\n * the whole history replay.\n */\nexport function messageAttachments(message: Message): readonly AttachmentRef[] {\n const refs = metadataOrTopLevel(message, \"attachments\");\n return Array.isArray(refs) ? refs.filter(isAttachmentRef) : [];\n}\n\n/** Whether an unknown value is a structurally valid {@link AttachmentRef}. */\nfunction isAttachmentRef(value: unknown): value is AttachmentRef {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const ref = value as Record<string, unknown>;\n return (\n typeof ref[\"id\"] === \"string\" &&\n typeof ref[\"name\"] === \"string\" &&\n typeof ref[\"mime\"] === \"string\" &&\n typeof ref[\"size\"] === \"number\" &&\n (ref[\"url\"] === undefined || typeof ref[\"url\"] === \"string\")\n );\n}\n", "/**\n * Prettify a raw tool name for display: separators become spaces and the\n * first letter is capitalised \u2014 `list_projects` \u2192 \"List projects\",\n * `invoices.retrieve` \u2192 \"Invoices retrieve\".\n *\n * Final fallback of the tool-card label chain (`x-summary` \u2192\n * `toolSummaries` \u2192 fetched catalog \u2192 this). Purely cosmetic: the original\n * name still rides on the card's dataset for debugging.\n */\nexport function prettifyToolName(name: string): string {\n const spaced = name.replace(/[._-]+/g, \" \").trim();\n if (spaced === \"\") {\n return name;\n }\n return spaced.charAt(0).toUpperCase() + spaced.slice(1);\n}\n", "import { randomUUID } from \"@ag-ui/client\";\nimport type { Message } from \"@ag-ui/core\";\nimport { STORAGE_ROOT } from \"../constants.js\";\nimport { prettifyToolName } from \"../ui/progress/prettify_tool_name.js\";\n\n/**\n * A checkpoint recorded just before a navigating tool reloads the page.\n *\n * The reload destroys the in-memory run loop, so the element persists this\n * marker first; on the next mount it supplies the tool's result and resumes.\n */\nexport interface NavigationCheckpoint {\n /** The tool-call id whose result must be supplied after the reload. */\n readonly toolCallId: string;\n}\n\n/**\n * Lightweight metadata for one conversation \u2014 the thread-drawer row shape, so\n * the drawer renders without loading message bodies. `title` defaults to a\n * truncation of the first user message until an explicit rename, `preview` is a\n * one-line excerpt of the latest message, and `updatedAt` is epoch ms of the\n * last change, which orders the list.\n */\nexport interface ThreadMeta {\n readonly threadId: string;\n readonly title: string;\n readonly updatedAt: number;\n readonly preview: string;\n /**\n * Whether the thread holds an answer the user has not seen, as a server store\n * knows it (from a last-read timestamp). Optional: a store that cannot tell\n * leaves it out, and the element counts only what finishes in this page.\n */\n readonly unread?: boolean;\n}\n\n/**\n * Client-side persistence seam for the conversation and a pending-navigation\n * checkpoint, keyed by `thread_id`.\n *\n * The default {@link SessionStorageStore} keeps everything per-tab. A host may\n * inject a server-backed store instead, which is why `loadMessages` and\n * `listThreads` are async. The checkpoint methods stay synchronous: the marker\n * is a small local hint a server store can derive from history and no-op.\n *\n * Thread enumeration backs the chat-history drawer; deleting a thread reuses\n * {@link clear}, and \"new chat\" is {@link newThread} \u2014 which leaves the\n * conversation it moves off of intact, for the drawer to offer back.\n */\nexport interface ClientConversationStore {\n /** The active conversation id, generated and persisted on first read. */\n threadId(): string;\n /**\n * Start a fresh conversation, make it active, and return its id.\n *\n * Existing threads are left where they are: \"new chat\" adds one, and\n * {@link clear} is the only method that takes one away.\n *\n * Optional: for a store without it, the caller mints the id itself and\n * hands it to {@link setActiveThread}, which loses only the store's own\n * record that the thread is new (see {@link isUnsent}).\n */\n newThread?(): string;\n /** Load the persisted message history, or `null` when none exists. */\n loadMessages(threadId: string): Promise<readonly Message[] | null>;\n /** Persist the message history (and refresh the thread's drawer metadata). */\n saveMessages(threadId: string, messages: readonly Message[]): void;\n /** Load the pending-navigation checkpoint, or `null` when none is set. */\n loadCheckpoint(threadId: string): NavigationCheckpoint | null;\n /** Set the pending-navigation checkpoint, or clear it when given `null`. */\n saveCheckpoint(threadId: string, checkpoint: NavigationCheckpoint | null): void;\n /** Forget the conversation and checkpoint (a \"delete thread\" / \"new chat\"). */\n clear(threadId: string): void;\n /** The user's threads as drawer metadata (no message bodies), newest first. */\n listThreads(): Promise<readonly ThreadMeta[]>;\n /** Make `threadId` the active conversation (the drawer selecting a row). */\n setActiveThread(threadId: string): void;\n /** Set a thread's display title (the drawer renaming a row). */\n renameThread(threadId: string, title: string): void;\n /**\n * Whether `threadId` was minted here and has never been saved \u2014 a thread in\n * which nothing has been sent yet.\n *\n * Exists so a server-backed store can skip asking a server for history that\n * cannot be there: the element mints an id on first mount and immediately tries\n * to restore it, which answers `404` and logs one in the console on every first\n * visit. Nothing is wrong, and it looks exactly like something being wrong.\n *\n * Optional, and deliberately narrow. A store that cannot tell omits it and the\n * fetch happens as before, which is also the right answer for a store that\n * holds nothing locally: \"I have no messages for this id\" is not the same claim\n * as \"this id is new\", and only the store that minted the id can make the\n * second one. A thread picked from the drawer was never minted here, so it is\n * still fetched.\n */\n isUnsent?(threadId: string): boolean;\n /**\n * Record that the user has seen `threadId`'s answers.\n *\n * The element calls it when a thread with unseen answers is on screen with\n * the panel expanded, and when an answer finishes there in view. A server\n * store maps it to its read endpoint, and should report the thread with\n * `unread: false` from {@link listThreads} afterwards. It is called inside the\n * element's expand and thread-change paths, so it must not throw: a store that\n * writes to a server sends the request without awaiting it and handles its own\n * failure, the way a failed save is handled.\n *\n * Optional: a store without it still has its threads counted and cleared in\n * the page; nothing is recorded beyond it.\n */\n markRead?(threadId: string): void;\n}\n\nconst THREAD_SUFFIX = \"thread\";\nconst THREADS_SUFFIX = \"threads\";\nconst MESSAGES_SUFFIX = \"messages:\";\nconst CHECKPOINT_SUFFIX = \"checkpoint:\";\n// Marks an id this store minted and nothing has been sent in yet. Dropped on\n// the first save, so it never outlives the one question it answers.\nconst MINTED_SUFFIX = \"minted:\";\n\nconst TITLE_LIMIT = 60;\nconst PREVIEW_LIMIT = 100;\nconst DEFAULT_TITLE = \"New conversation\";\n// A message that is one skill's name and nothing else, as a server-resolved skill sends.\nconst SKILL_TOKEN = /^\\/([A-Za-z0-9][\\w.-]*)$/;\n\n/**\n * Whether its owner has warned about a refused write yet. Each store and each\n * storage scope holds one, so an origin-wide, persistent refusal (a full quota\n * stays full) warns once per owner, not once per persisted turn or, on the\n * resize path, per keystroke.\n */\nexport interface WriteFailureReport {\n reported: boolean;\n}\n\n/**\n * `sessionStorage.setItem` that survives a store which refuses to write.\n *\n * `setItem` throws on an exhausted quota (a long conversation, or one turn\n * carrying a large tool result) and in privacy modes that deny storage\n * altogether. Every write here is a *durability* concern \u2014 surviving a reload \u2014\n * and none of them is worth an exception, because of where they are called\n * from: the element persists the transcript from inside the run loop, so an\n * unguarded throw escapes as a run error and tells the user the agent failed\n * when nothing but the browser's storage did. On the cancel path it escapes as\n * an unhandled rejection instead.\n *\n * So a failed write loses the reload, never the conversation on screen, and\n * says so once per `report`; without one, it says so on every refusal.\n * Recovery is in the user's hands already: deleting the oversized thread from\n * the history drawer is a `removeItem`, which frees the quota.\n */\nexport function writeStoredItem(\n key: string,\n value: string,\n report: WriteFailureReport = { reported: false },\n): void {\n try {\n sessionStorage.setItem(key, value);\n } catch {\n if (report.reported) {\n return;\n }\n report.reported = true;\n console.warn(\n \"<ag-ui-chat>: the browser refused a sessionStorage write \u2014 the quota is \" +\n \"full, or storage is disabled for this context. The conversation \" +\n \"continues, but it will not survive a page reload. Deleting a long \" +\n \"conversation from the history drawer frees the quota.\",\n );\n }\n}\n\n/** The storage-key root for a namespace; `\"\"` is the root of an element with nothing to key on. */\nfunction rootFor(namespace: string): string {\n return namespace === \"\" ? STORAGE_ROOT : `${STORAGE_ROOT}@${namespace}`;\n}\n\n/** The drawer-index entry; `titleCustom` (private) freezes a renamed title. */\ninterface StoredThread {\n threadId: string;\n title: string;\n titleCustom: boolean;\n preview: string;\n updatedAt: number;\n}\n\n/**\n * Default {@link ClientConversationStore}: per-tab `sessionStorage`.\n *\n * Survives full page reloads and same-tab navigation, clears on tab close.\n * Tracks multiple threads per tab: the active id under one key, message history\n * and checkpoint namespaced by id, and a small index feeding the drawer with no\n * server involved.\n *\n * An optional `namespace` scopes every key to one element, so two\n * `<ag-ui-chat>` instances on the same origin keep separate active-thread\n * pointers and drawer indexes instead of clobbering each other. The default\n * empty namespace keeps the origin-global keys.\n */\nexport class SessionStorageStore implements ClientConversationStore {\n readonly #root: string;\n readonly #writeFailure: WriteFailureReport = { reported: false };\n\n constructor(namespace = \"\") {\n this.#root = rootFor(namespace);\n }\n\n /**\n * Move every key a store owns out of `from`'s namespace and into `to`'s.\n *\n * `<ag-ui-chat>` adopts an element-scoped conversation into a\n * principal-scoped one the first time a `user-key` arrives, which is a host\n * naming the user who was already there rather than a handover.\n *\n * Only this store's own suffixes move \u2014 the element's `collapsed` / `size` /\n * `theme` keys share the global root and are deliberately left where they\n * are. A value already present at the destination wins: the destination is\n * the durable record and the source is the stray this move exists to clear.\n * A refused write warns once per call.\n */\n static adopt(from: string, to: string): void {\n const fromRoot = `${rootFor(from)}:`;\n const toRoot = `${rootFor(to)}:`;\n const writeFailure: WriteFailureReport = { reported: false };\n for (const [key, suffix] of ownedKeys(fromRoot)) {\n const value = sessionStorage.getItem(key);\n const destination = toRoot + suffix;\n if (value !== null && sessionStorage.getItem(destination) === null) {\n writeStoredItem(destination, value, writeFailure);\n }\n sessionStorage.removeItem(key);\n }\n }\n\n /**\n * Forget everything a store holds for `namespace`.\n *\n * The logout primitive: `<ag-ui-chat>` calls it when its `user-key` changes,\n * and a host driving its own store can call it from its own sign-out path.\n * Deliberately narrow \u2014 it removes only keys under this exact namespace whose\n * suffix parses as one this store writes, so it can never reach another\n * element's conversation or the host's own `sessionStorage` entries.\n */\n static purge(namespace: string): void {\n for (const [key] of ownedKeys(`${rootFor(namespace)}:`)) {\n sessionStorage.removeItem(key);\n }\n }\n\n threadId(): string {\n return sessionStorage.getItem(this.#key(THREAD_SUFFIX)) ?? this.newThread();\n }\n\n newThread(): string {\n const id = randomUUID();\n this.#write(this.#key(THREAD_SUFFIX), id);\n this.#write(this.#key(MINTED_SUFFIX + id), \"1\");\n return id;\n }\n\n isUnsent(threadId: string): boolean {\n return (\n sessionStorage.getItem(this.#key(MINTED_SUFFIX + threadId)) !== null &&\n sessionStorage.getItem(this.#key(MESSAGES_SUFFIX + threadId)) === null\n );\n }\n\n loadMessages(threadId: string): Promise<readonly Message[] | null> {\n return Promise.resolve(this.#readJson<Message[]>(this.#key(MESSAGES_SUFFIX + threadId)));\n }\n\n saveMessages(threadId: string, messages: readonly Message[]): void {\n this.#write(this.#key(MESSAGES_SUFFIX + threadId), JSON.stringify(messages));\n sessionStorage.removeItem(this.#key(MINTED_SUFFIX + threadId));\n this.#touchThread(threadId, messages);\n }\n\n loadCheckpoint(threadId: string): NavigationCheckpoint | null {\n return this.#readJson<NavigationCheckpoint>(this.#key(CHECKPOINT_SUFFIX + threadId));\n }\n\n saveCheckpoint(threadId: string, checkpoint: NavigationCheckpoint | null): void {\n const key = this.#key(CHECKPOINT_SUFFIX + threadId);\n if (checkpoint === null) {\n sessionStorage.removeItem(key);\n return;\n }\n this.#write(key, JSON.stringify(checkpoint));\n }\n\n clear(threadId: string): void {\n sessionStorage.removeItem(this.#key(MESSAGES_SUFFIX + threadId));\n sessionStorage.removeItem(this.#key(CHECKPOINT_SUFFIX + threadId));\n sessionStorage.removeItem(this.#key(MINTED_SUFFIX + threadId));\n this.#writeThreads(this.#readThreads().filter((thread) => thread.threadId !== threadId));\n // Only drop the active pointer when the active thread itself is cleared, so\n // the next `threadId()` mints a fresh one. Deleting another thread from the\n // drawer must not disturb the conversation on screen.\n if (sessionStorage.getItem(this.#key(THREAD_SUFFIX)) === threadId) {\n sessionStorage.removeItem(this.#key(THREAD_SUFFIX));\n }\n }\n\n listThreads(): Promise<readonly ThreadMeta[]> {\n const metas = this.#readThreads()\n .sort((a, b) => b.updatedAt - a.updatedAt)\n .map(({ threadId, title, updatedAt, preview }) => ({ threadId, title, updatedAt, preview }));\n return Promise.resolve(metas);\n }\n\n setActiveThread(threadId: string): void {\n this.#write(this.#key(THREAD_SUFFIX), threadId);\n }\n\n renameThread(threadId: string, title: string): void {\n const threads = this.#readThreads();\n const entry = threads.find((thread) => thread.threadId === threadId);\n if (entry === undefined) {\n return;\n }\n entry.title = title;\n entry.titleCustom = true;\n this.#writeThreads(threads);\n }\n\n /** Add or refresh a thread's drawer metadata from its latest messages. */\n #touchThread(threadId: string, messages: readonly Message[]): void {\n const threads = this.#readThreads();\n const entry = threads.find((thread) => thread.threadId === threadId);\n const preview = derivePreview(messages);\n const updatedAt = Date.now();\n if (entry === undefined) {\n threads.push({\n threadId,\n title: deriveTitle(messages),\n titleCustom: false,\n preview,\n updatedAt,\n });\n } else {\n entry.preview = preview;\n entry.updatedAt = updatedAt;\n if (!entry.titleCustom) {\n entry.title = deriveTitle(messages);\n }\n }\n this.#writeThreads(threads);\n }\n\n #readThreads(): StoredThread[] {\n return this.#readJson<StoredThread[]>(this.#key(THREADS_SUFFIX)) ?? [];\n }\n\n #writeThreads(threads: readonly StoredThread[]): void {\n const key = this.#key(THREADS_SUFFIX);\n if (threads.length === 0) {\n sessionStorage.removeItem(key);\n return;\n }\n this.#write(key, JSON.stringify(threads));\n }\n\n #write(key: string, value: string): void {\n writeStoredItem(key, value, this.#writeFailure);\n }\n\n /** This store's fully-qualified key for a suffix (namespaced when set). */\n #key(suffix: string): string {\n return `${this.#root}:${suffix}`;\n }\n\n /** Parse a stored JSON value, returning `null` when absent or corrupt. */\n #readJson<T>(key: string): T | null {\n const raw = sessionStorage.getItem(key);\n if (raw === null) {\n return null;\n }\n try {\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n }\n}\n\n/**\n * Every `sessionStorage` key under `root` that this store wrote, as\n * `[key, suffix]`.\n *\n * Collected into an array before the caller mutates anything: `sessionStorage`\n * is enumerated by index, and removing an entry mid-loop shifts the ones after\n * it out from under the cursor.\n *\n * The suffix test is what makes {@link SessionStorageStore.purge} safe to point\n * at a namespace. It matters most for the global root, which the element's own\n * `collapsed` / `size` / `theme` keys share \u2014 but it also means a namespace\n * whose name happens to be a prefix of another cannot reach into it, since the\n * remainder would have to parse as one of these suffixes.\n */\nfunction ownedKeys(root: string): Array<readonly [string, string]> {\n const found: Array<readonly [string, string]> = [];\n for (let index = 0; index < sessionStorage.length; index += 1) {\n const key = sessionStorage.key(index);\n if (key === null || !key.startsWith(root)) {\n continue;\n }\n const suffix = key.slice(root.length);\n if (isOwnedSuffix(suffix)) {\n found.push([key, suffix]);\n }\n }\n return found;\n}\n\n/** Whether a key suffix belongs to the store (vs the element's own keys). */\nfunction isOwnedSuffix(suffix: string): boolean {\n return (\n suffix === THREAD_SUFFIX ||\n suffix === THREADS_SUFFIX ||\n suffix.startsWith(MESSAGES_SUFFIX) ||\n suffix.startsWith(CHECKPOINT_SUFFIX) ||\n suffix.startsWith(MINTED_SUFFIX)\n );\n}\n\n/** The stored title: {@link threadTitleFrom}, or a placeholder for a thread with no user text. */\nfunction deriveTitle(messages: readonly Message[]): string {\n const title = threadTitleFrom(messages);\n return title === \"\" ? DEFAULT_TITLE : title;\n}\n\n/**\n * A thread's title from its first user message, collapsed and truncated, or `\"\"`\n * when no user message has text.\n *\n * A first message that is exactly a skill's `/token` is named rather than\n * quoted: `skillTitle(token)` when it knows the skill, else the token in words\n * (`/summarize_draw` reads \"Summarize draw\").\n */\nexport function threadTitleFrom(\n messages: readonly Message[],\n skillTitle: (name: string) => string | undefined = () => undefined,\n): string {\n for (const message of messages) {\n if (message.role === \"user\") {\n const text = cleanText(message.content);\n if (text !== \"\") {\n const token = SKILL_TOKEN.exec(text)?.[1];\n const named = token === undefined ? text : (skillTitle(token) ?? prettifyToolName(token));\n return truncate(named, TITLE_LIMIT);\n }\n }\n }\n return \"\";\n}\n\n/** A one-line preview: the latest message with text, collapsed + truncated. */\nfunction derivePreview(messages: readonly Message[]): string {\n for (const message of [...messages].reverse()) {\n const text = cleanText(message.content);\n if (text !== \"\") {\n return truncate(text, PREVIEW_LIMIT);\n }\n }\n return \"\";\n}\n\n/** Whitespace-collapsed message text, or `\"\"` for non-string content. */\nfunction cleanText(content: unknown): string {\n return typeof content === \"string\" ? content.replace(/\\s+/g, \" \").trim() : \"\";\n}\n\nfunction truncate(text: string, limit: number): string {\n return text.length <= limit ? text : `${text.slice(0, limit - 1).trimEnd()}\u2026`;\n}\n", "import { type AbstractAgent, HttpAgent } from \"@ag-ui/client\";\nimport type { Message } from \"@ag-ui/core\";\nimport { warnOnCrossOriginCredentials, withCredentials } from \"./utils.js\";\n\n/** Config for {@link createHttpAgent}. */\nexport interface HttpAgentOptions {\n endpoint: string;\n headers?: Record<string, string>;\n /**\n * Cookie policy for the run request, as `fetch`'s own `credentials` mode.\n * Unset leaves the browser default (`same-origin`), which sends no cookies\n * to an agent endpoint on a different origin or subdomain. A\n * cookie-authenticated cross-origin deployment needs `\"include\"` here plus a\n * server answering with `Access-Control-Allow-Credentials: true` and a\n * concrete origin.\n */\n credentials?: RequestCredentials;\n /**\n * Live header source, re-read on every request, overlaid on `headers`.\n * `HttpAgent` bakes static `headers` in at construction and the element\n * caches the agent for the whole conversation, so rotating credentials (CSRF,\n * short-lived JWT) must come through here.\n */\n getHeaders?: () => Record<string, string>;\n /** Stable conversation id, so the agent's runs share a thread. */\n threadId?: string;\n /** Rehydrated history to seed the agent with (durable conversation). */\n initialMessages?: readonly Message[];\n /**\n * AG-UI shared state to seed the agent with. `@ag-ui/client` sends it as\n * `RunAgentInput.state` on every run and replaces it in place when the\n * server streams `STATE_SNAPSHOT` / `STATE_DELTA`.\n */\n initialState?: Readonly<Record<string, unknown>>;\n /**\n * Origins, besides the document's own, this agent may carry the host's\n * credentials to.\n *\n * Running the agent on another subdomain is a normal deployment and stays\n * supported, so a cross-origin endpoint is not refused \u2014 it is *announced*,\n * once per origin, on the console. Listing an origin here says the\n * destination was chosen deliberately and silences the notice for it.\n *\n * Entries are compared as serialized origins (`https://agent.example.com`,\n * scheme and port included), which is what `URL.origin` produces.\n */\n trustedOrigins?: readonly string[];\n}\n\n/**\n * Build an AG-UI {@link HttpAgent} pointed at `endpoint`.\n *\n * The default agent factory for `<ag-ui-chat>`; tests and advanced hosts\n * override the element's `agentFactory` to inject a different\n * {@link AbstractAgent}.\n */\nexport function createHttpAgent(options: HttpAgentOptions): AbstractAgent {\n const staticHeaders = options.headers ?? {};\n const warned = new Set<string>();\n return new HttpAgent({\n url: options.endpoint,\n headers: staticHeaders,\n initialState: { ...(options.initialState ?? {}) },\n // HttpAgent invokes its configured fetch as a method (`this.fetch(...)`),\n // rebinding the global `fetch` to the agent instance \u2014 \"Illegal invocation\"\n // in browsers. The wrapper keeps `fetch` a free call, and is also where the\n // per-request `getHeaders()` overlay and the cookie policy go, the agent's\n // own config having no seam for either.\n fetch: (url, init) => {\n const fresh = options.getHeaders?.();\n // Only the names the *host* supplied. `HttpAgent` adds `Content-Type` and\n // `Accept` to every request and neither is a credential, so reporting the\n // outgoing header set wholesale would cry wolf on every plain request.\n const credentialNames = [\n ...new Set([...Object.keys(staticHeaders), ...Object.keys(fresh ?? {})]),\n ].sort();\n warnOnCrossOriginCredentials(url, credentialNames, options.trustedOrigins ?? [], warned);\n if (fresh === undefined) {\n return fetch(url, withCredentials(init, options.credentials));\n }\n const headers = new Headers(init?.headers);\n for (const [name, value] of Object.entries(fresh)) {\n headers.set(name, value);\n }\n return fetch(url, withCredentials({ ...init, headers }, options.credentials));\n },\n // Spread conditionally: under `exactOptionalPropertyTypes` an explicit\n // `undefined` is not assignable to an optional field.\n ...(options.threadId !== undefined ? { threadId: options.threadId } : {}),\n ...(options.initialMessages !== undefined\n ? { initialMessages: [...options.initialMessages] }\n : {}),\n });\n}\n\n/** Signature of the agent factory the element calls to build its agent. */\nexport type AgentFactory = (options: HttpAgentOptions) => AbstractAgent;\n", "import type { Message } from \"@ag-ui/core\";\nimport {\n type ClientConversationStore,\n type NavigationCheckpoint,\n SessionStorageStore,\n type ThreadMeta,\n threadTitleFrom,\n} from \"./conversation_store.js\";\nimport { mintThread, withCredentials } from \"./utils.js\";\n\n/** One row of the server thread index (django-ag-ui's `ThreadsView` wire shape). */\ninterface ServerThreadRow {\n readonly thread_id: string;\n readonly title: string;\n readonly updated_at: string | null;\n readonly preview: string;\n}\n\nconst PROVISIONAL_TITLE = \"New conversation\";\n\n/** Live header source, read per request so rotated tokens / CSRF reach the server. */\ntype HeadersProvider = () => Record<string, string>;\n\n/**\n * Live cookie policy, read per request. A provider rather than a value: the\n * store is built once on connect, but a host may configure the element after\n * inserting it, and a captured value would pin that first frame's setting.\n */\ntype CredentialsProvider = () => RequestCredentials | undefined;\n\n/**\n * A {@link ClientConversationStore} backed by a server thread-index endpoint \u2014\n * django-ag-ui's owner-scoped `ThreadsView`, the URL passed to `<ag-ui-chat>`\n * as `data-threads-url`:\n *\n * - `GET <url>` \u2192 list the user's threads (metadata only);\n * - `GET <url><id>/` \u2192 that thread's messages;\n * - `PATCH <url><id>/` \u2192 rename (`{ \"title\": \u2026 }`);\n * - `DELETE <url><id>/` \u2192 delete.\n *\n * Wraps a local store (default {@link SessionStorageStore}) for the client-only\n * concerns \u2014 active thread id, navigation checkpoint, message cache \u2014 and as\n * the fallback when a request fails. Rename and delete apply optimistically via\n * a local overlay, so the drawer reflects them before the fire-and-forget\n * round-trip lands.\n *\n * Pass `cacheMessages: false` to keep message bodies out of the browser\n * entirely; see the constructor.\n */\nexport class RemoteConversationStore implements ClientConversationStore {\n readonly #url: string;\n readonly #headers: HeadersProvider;\n readonly #local: ClientConversationStore;\n readonly #credentials: CredentialsProvider;\n readonly #cacheMessages: boolean;\n readonly #dropped = new Set<string>();\n readonly #renamed = new Map<string, string>();\n /**\n * The row each thread saved here would have, held in memory until the server\n * lists it. Derived from what was sent rather than read from the local store,\n * which holds no body (and so no title) when `cacheMessages` is off.\n */\n readonly #provisional = new Map<string, ThreadMeta>();\n /** The active id as last read or set through this store; listing must not mint one. */\n #active: string | null = null;\n\n /**\n * @param cacheMessages Whether to mirror message bodies into the local store.\n *\n * `true` (the default, and the behaviour this class has always had) keeps a\n * local copy of every turn, so the transcript still replays when the thread\n * endpoint is unreachable. `false` is for the deployment that chose a\n * server-backed store precisely so transcripts do not sit in the browser:\n * regulated content, a shared workstation, an operator who has to be able to\n * say where the conversation lives. It is not the same as passing a local\n * store that does nothing \u2014 the local store also owns the active thread id,\n * the navigation checkpoint and the \"nothing sent here yet\" marker, all of\n * which must keep working \u2014 so the opt-out is scoped to the bodies alone.\n *\n * The cost is deliberate and worth stating: with no local copy there is\n * nothing to fall back to, so a failed request shows an empty transcript\n * rather than a stale one, and the drawer's offline list loses its previews\n * (a preview is an excerpt of a message, which is the very thing being kept\n * off the client).\n */\n constructor(\n url: string,\n headers: HeadersProvider = () => ({}),\n local: ClientConversationStore = new SessionStorageStore(),\n credentials: CredentialsProvider = () => undefined,\n cacheMessages = true,\n ) {\n this.#url = url.endsWith(\"/\") ? url : `${url}/`;\n this.#headers = headers;\n this.#local = local;\n this.#credentials = credentials;\n this.#cacheMessages = cacheMessages;\n }\n\n threadId(): string {\n this.#active = this.#local.threadId();\n return this.#active;\n }\n\n setActiveThread(threadId: string): void {\n this.#local.setActiveThread(threadId);\n this.#active = threadId;\n }\n\n /**\n * Delegated to the local store, which owns the active id \u2014 and deliberately\n * silent on the wire: the server learns of a thread when its first message is\n * persisted, so an abandoned new chat costs no round-trip and leaves no row.\n */\n newThread(): string {\n this.#active = mintThread(this.#local);\n return this.#active;\n }\n\n /** Delegated, so wrapping a store does not lose what it knows about its own ids. */\n isUnsent(threadId: string): boolean {\n return this.#local.isUnsent?.(threadId) === true;\n }\n\n saveMessages(threadId: string, messages: readonly Message[]): void {\n // The agent run persists server-side; keep a local cache for offline replay\n // unless the host asked for the bodies to stay off the client.\n //\n // The empty list is not a way of saying \"nothing happened\". A save is what\n // retires the local store's minted marker, and `loadMessages` skips the\n // server for a thread that store still calls unsent \u2014 so dropping the call\n // entirely would leave every thread permanently unsent and its history\n // unreachable after a reload. Saving an empty list records that the thread\n // is real without recording a word of what was said in it.\n this.#local.saveMessages(threadId, this.#cacheMessages ? messages : []);\n this.#provisional.set(threadId, {\n threadId,\n title: threadTitleFrom(messages) || PROVISIONAL_TITLE,\n updatedAt: Date.now(),\n preview: \"\",\n });\n }\n\n loadCheckpoint(threadId: string): NavigationCheckpoint | null {\n return this.#local.loadCheckpoint(threadId);\n }\n\n saveCheckpoint(threadId: string, checkpoint: NavigationCheckpoint | null): void {\n this.#local.saveCheckpoint(threadId, checkpoint);\n }\n\n renameThread(threadId: string, title: string): void {\n this.#local.renameThread(threadId, title);\n this.#renamed.set(threadId, title);\n void this.#mutate(threadId, \"PATCH\", { title });\n }\n\n clear(threadId: string): void {\n this.#local.clear(threadId);\n this.#dropped.add(threadId);\n this.#provisional.delete(threadId);\n void this.#mutate(threadId, \"DELETE\");\n }\n\n async listThreads(): Promise<readonly ThreadMeta[]> {\n const rows = await this.#fetchThreads();\n if (rows === null) {\n return this.#local.listThreads();\n }\n const metas = rows\n .filter((row) => !this.#dropped.has(row.thread_id))\n .map((row) => this.#toMeta(row));\n const pending = this.#pendingRow(rows);\n return pending === null ? metas : [pending, ...metas];\n }\n\n /**\n * The thread on screen as a provisional row, while the server's index does\n * not have it yet: sent from here, not deleted since, and not yet listed.\n * Once the server lists a thread, its row is the only one.\n */\n #pendingRow(rows: readonly ServerThreadRow[]): ThreadMeta | null {\n for (const listed of rows) {\n this.#provisional.delete(listed.thread_id);\n }\n const row = this.#active === null ? undefined : this.#provisional.get(this.#active);\n if (row === undefined) {\n return null;\n }\n return { ...row, title: this.#renamed.get(row.threadId) ?? row.title };\n }\n\n async loadMessages(threadId: string): Promise<readonly Message[] | null> {\n // Don't ask the server for a thread it cannot have, which would answer\n // `404` on every first visit; see `ClientConversationStore.isUnsent`.\n if (this.#local.isUnsent?.(threadId) === true) {\n return null;\n }\n const response = await this.#get(`${this.#url}${encodeURIComponent(threadId)}/`);\n if (response === null || !response.ok) {\n return this.#local.loadMessages(threadId);\n }\n // A 200 whose body isn't JSON (a proxy's HTML error page, a truncated\n // stream) must not throw an unhandled rejection that the caller's\n // `void rehydrate()` swallows; fall back to the local cache.\n const body = await this.#readJson<{ messages?: readonly Message[] }>(response);\n if (body === null) {\n return this.#local.loadMessages(threadId);\n }\n return body.messages ?? null;\n }\n\n async #fetchThreads(): Promise<readonly ServerThreadRow[] | null> {\n const response = await this.#get(this.#url);\n if (response === null || !response.ok) {\n return null;\n }\n const body = await this.#readJson<{ threads?: readonly ServerThreadRow[] }>(response);\n if (body === null) {\n return null;\n }\n return body.threads ?? [];\n }\n\n /** Parse a `Response` body as JSON, or `null` when it isn't valid JSON. */\n async #readJson<T>(response: Response): Promise<T | null> {\n try {\n return (await response.json()) as T;\n } catch {\n return null;\n }\n }\n\n #toMeta(row: ServerThreadRow): ThreadMeta {\n return {\n threadId: row.thread_id,\n title: this.#renamed.get(row.thread_id) ?? row.title,\n // `null` and an unparseable date both become NaN, Date.parse's own\n // signal, which `relativeTime` renders as a neutral label rather than an\n // epoch-0 or NaN duration.\n updatedAt: row.updated_at === null ? Number.NaN : Date.parse(row.updated_at),\n preview: row.preview,\n };\n }\n\n /** GET that resolves to the `Response`, or `null` on a network error. */\n async #get(url: string): Promise<Response | null> {\n try {\n return await fetch(url, withCredentials({ headers: this.#headers() }, this.#credentials()));\n } catch {\n return null;\n }\n }\n\n /** Fire a best-effort write to the thread endpoint; failures are tolerated. */\n async #mutate(\n threadId: string,\n method: \"PATCH\" | \"DELETE\",\n body?: { title: string },\n ): Promise<void> {\n const headers = this.#headers();\n try {\n await fetch(\n `${this.#url}${encodeURIComponent(threadId)}/`,\n withCredentials(\n {\n method,\n headers:\n body === undefined ? headers : { ...headers, \"content-type\": \"application/json\" },\n body: body === undefined ? null : JSON.stringify(body),\n },\n this.#credentials(),\n ),\n );\n } catch {\n // Best-effort; the optimistic overlay keeps the drawer consistent.\n }\n }\n}\n", "import { withCredentials } from \"./utils.js\";\n\n/** One row of the server run index (django-ag-ui's `RunsView` wire shape). */\nexport interface RunRow {\n readonly run_id: string;\n readonly thread_id: string | null;\n readonly parent_run_id: string | null;\n readonly started_at: string | null;\n /** Whether the run has a snapshot to seed from \u2014 see {@link RunIndex}. */\n readonly continuable: boolean;\n /**\n * The run's first user message, one line, already truncated by the server \u2014\n * the only field in a row a person recognises a conversation by.\n *\n * Optional because a server predating the field does not send it, and\n * `null` where the run holds no words to show (seeded from history alone, or\n * opened with an image and no caption). A row without one falls back to the\n * time plus a short id.\n */\n readonly preview?: string | null;\n}\n\n/** Live header source, read per request so rotated tokens / CSRF reach the server. */\ntype HeadersProvider = () => Record<string, string>;\n\n/** Live cookie policy, read per request; see `RemoteConversationStore`'s note. */\ntype CredentialsProvider = () => RequestCredentials | undefined;\n\n/**\n * Reads the server's run index and derives the resume / fork URLs beside it.\n *\n * Backed by django-ag-ui's owner-scoped `RunsView` \u2014 the URL passed to\n * `<ag-ui-chat>` as `data-runs-url`:\n *\n * - `GET <url>` \u2192 the user's runs, newest first.\n *\n * Only `continuable` rows can be resumed: the server reports whether a run has\n * a saved snapshot to seed from, and a run that never reached a provider-valid\n * boundary has none. Offer the action only for those rows ({@link continuable}\n * filters them) and treat the rest as informational.\n *\n * Resume and fork are siblings of the index rather than separate configuration\n * \u2014 django-ag-ui mounts `runs/`, `resume/<id>/` and `fork/<id>/` under one\n * prefix \u2014 so this one URL locates all three.\n */\nexport class RunIndex {\n readonly #url: string;\n readonly #headers: HeadersProvider;\n readonly #credentials: CredentialsProvider;\n\n constructor(\n url: string,\n headers: HeadersProvider = () => ({}),\n credentials: CredentialsProvider = () => undefined,\n ) {\n this.#url = url.endsWith(\"/\") ? url : `${url}/`;\n this.#headers = headers;\n this.#credentials = credentials;\n }\n\n /**\n * The user's runs, or `[]` when the endpoint is unreachable or errors \u2014 the\n * caller renders its empty state rather than a transport fault the user can\n * do nothing about.\n */\n async list(): Promise<readonly RunRow[]> {\n try {\n const response = await fetch(\n this.#url,\n withCredentials(\n {\n method: \"GET\",\n headers: { Accept: \"application/json\", ...this.#headers() },\n },\n this.#credentials(),\n ),\n );\n if (!response.ok) {\n return [];\n }\n const body = (await response.json()) as { runs?: readonly RunRow[] };\n return body.runs ?? [];\n } catch {\n return [];\n }\n }\n\n /** The rows a client may actually continue. */\n async continuable(): Promise<readonly RunRow[]> {\n return (await this.list()).filter((run) => run.continuable);\n }\n\n /** The endpoint that continues `runId` as a new run. */\n resumeUrl(runId: string): string {\n return this.#sibling(\"resume\", runId);\n }\n\n /** The endpoint that branches `runId` into a new run, leaving the source untouched. */\n forkUrl(runId: string): string {\n return this.#sibling(\"fork\", runId);\n }\n\n /**\n * `<mount>/<verb>/<runId>/`, derived from the index URL's own prefix.\n *\n * String surgery on the trailing `runs/` rather than `new URL`, because the\n * configured value may be root-relative (`/agent/runs/`), the common case in\n * a Django template, and `new URL` needs an absolute base.\n */\n #sibling(verb: string, runId: string): string {\n const prefix = this.#url.slice(0, -\"runs/\".length);\n return `${prefix}${verb}/${encodeURIComponent(runId)}/`;\n }\n}\n", "import { TOOL_CALL_STATUS, TOOL_OUTCOME } from \"../constants.js\";\nimport type { SettledStatus } from \"../ui/progress/tool_call_card.js\";\n\n/**\n * How a tool call ended, in the wire's own words. See {@link TOOL_OUTCOME}.\n *\n * Absent is the fourth case and the common one: a server that has never heard\n * of the field says nothing, and nothing means success.\n */\nexport type ToolOutcome = (typeof TOOL_OUTCOME)[keyof typeof TOOL_OUTCOME];\n\n/**\n * The card status a wire outcome settles into.\n *\n * Takes `unknown` rather than {@link ToolOutcome} on purpose: both callers read\n * this off a boundary the type system does not police -- a key in an AG-UI\n * event's `metadata`, which the protocol declares open and does not validate,\n * and a JSON blob out of the conversation store -- so the narrowing belongs\n * here, once, instead of at each of them.\n *\n * **Everything unrecognised maps to `DONE`.** Not because unknown values are\n * expected to be successes, but because the alternative is worse in the\n * direction that matters: a card claiming a call failed when it did not is a\n * lie the user acts on, while a card claiming success has at least the result\n * text under it for them to read. A future release may add words, and forward\n * compatibility is the point of the open field.\n */\nexport function toolStatusFromOutcome(outcome: unknown): SettledStatus {\n if (outcome === TOOL_OUTCOME.FAILED) {\n return TOOL_CALL_STATUS.ERROR;\n }\n if (outcome === TOOL_OUTCOME.DENIED) {\n return TOOL_CALL_STATUS.DECLINED;\n }\n if (outcome === TOOL_OUTCOME.INTERRUPTED) {\n return TOOL_CALL_STATUS.INTERRUPTED;\n }\n return TOOL_CALL_STATUS.DONE;\n}\n", "import { withCredentials } from \"./utils.js\";\n\n/**\n * The composer's voice-transcription contract: take a recorded audio `Blob` and\n * resolve to the transcript text. The built-in handler is\n * {@link transcribeAudio}; a host swaps in its own (a Web Speech adapter, a\n * direct-to-provider call) via `AgUiChat.transcribeHandler` without touching\n * the mic button.\n */\nexport type TranscribeHandler = (audio: Blob) => Promise<string>;\n\n/** Options for {@link transcribeAudio}. */\nexport interface TranscribeOptions {\n /** The transcription endpoint (`data-transcribe-url`). */\n readonly url: string;\n /** Extra HTTP headers (CSRF / auth), read fresh per request. */\n readonly headers?: Record<string, string>;\n /**\n * Cookie policy, as `fetch`'s own `credentials` mode. Unset leaves the\n * browser default (`same-origin`), which sends no cookies to an endpoint on\n * another origin; a cookie-authenticated cross-origin deployment needs\n * `\"include\"`.\n */\n readonly credentials?: RequestCredentials;\n}\n\n/**\n * POST a recorded clip to the transcription endpoint and resolve to its text.\n *\n * The clip goes as multipart under the `audio` field with the element's\n * `headers`, mirroring {@link uploadAttachment}, and the server replies\n * `{ \"text\": \"<transcript>\" }`. A non-2xx response or a network error rejects\n * so the mic button can surface the failure.\n */\nexport async function transcribeAudio(audio: Blob, options: TranscribeOptions): Promise<string> {\n const form = new FormData();\n // The extension is cosmetic: the server reads the blob's content type.\n form.append(\"audio\", audio, \"recording.webm\");\n\n const response = await fetch(\n options.url,\n withCredentials(\n {\n method: \"POST\",\n headers: { ...(options.headers ?? {}) },\n body: form,\n },\n options.credentials,\n ),\n );\n if (!response.ok) {\n throw new Error(await errorMessage(response));\n }\n const body: unknown = await response.json();\n if (\n typeof body === \"object\" &&\n body !== null &&\n typeof (body as { text?: unknown }).text === \"string\"\n ) {\n return (body as { text: string }).text;\n }\n throw new Error(\"transcription returned an unreadable response\");\n}\n\n/** A human-readable message from a non-2xx transcription response. */\nasync function errorMessage(response: Response): Promise<string> {\n try {\n const body = (await response.json()) as { error?: unknown };\n if (typeof body.error === \"string\") {\n return body.error;\n }\n } catch {\n // Non-JSON error body \u2014 fall through to the status code.\n }\n return `transcription failed (${response.status})`;\n}\n", "import type { AttachmentRef } from \"./attachment.js\";\n\n/**\n * The composer's upload contract: take a `File`, report `0..1` progress, and\n * resolve to a durable {@link AttachmentRef}. The built-in handler is\n * {@link uploadAttachment}; a host swaps in its own (a `tus-js-client` or\n * direct-to-S3 adapter) via `AgUiChat.uploadHandler` without touching the tray,\n * the chips, or the AG-UI wire, refs being transport-agnostic.\n *\n * The optional `signal` fires when the tray removes a chip or the element is\n * torn down; a handler that honours it should abort its own transport, so a\n * cancelled upload doesn't orphan a server-side file.\n */\nexport type UploadHandler = (\n file: File,\n onProgress: (fraction: number) => void,\n signal?: AbortSignal,\n) => Promise<AttachmentRef>;\n\n/** Options for {@link uploadAttachment}. */\nexport interface UploadOptions {\n /** The attachments endpoint (`data-attachments-url`). */\n readonly url: string;\n /** Extra HTTP headers (CSRF / auth), read fresh per upload. */\n readonly headers?: Record<string, string>;\n /**\n * Cookie policy, spelled as `fetch`'s `credentials` mode for consistency with\n * the other endpoints, but carried by `XMLHttpRequest`'s two-state\n * `withCredentials`: `\"include\"` sets it and every other value leaves it off,\n * matching `\"same-origin\"`. `\"omit\"` therefore cannot be honoured for a\n * same-origin upload, XHR always sending cookies there; use a custom\n * {@link UploadHandler} if that matters.\n */\n readonly credentials?: RequestCredentials;\n /** Progress callback, `0..1`, fired as the body uploads. */\n readonly onProgress?: (fraction: number) => void;\n /** Abort signal to cancel the in-flight upload. */\n readonly signal?: AbortSignal | undefined;\n}\n\n/**\n * Upload one file to the attachments endpoint and resolve to its durable\n * {@link AttachmentRef}.\n *\n * Uses `XMLHttpRequest` rather than `fetch` for real upload-progress events.\n * The file goes as multipart under the `file` field with the element's\n * `headers`, so CSRF / auth ride along; a non-2xx response or a network/abort\n * error rejects, letting the tray show an error chip.\n */\nexport function uploadAttachment(file: File, options: UploadOptions): Promise<AttachmentRef> {\n return new Promise<AttachmentRef>((resolve, reject) => {\n const form = new FormData();\n form.append(\"file\", file);\n\n const xhr = new XMLHttpRequest();\n xhr.open(\"POST\", options.url);\n // Cross-origin cookies ride only when asked for, as at the fetch sites.\n // Without this an upload to another subdomain goes anonymous and 401s while\n // the run itself succeeds.\n xhr.withCredentials = options.credentials === \"include\";\n for (const [key, value] of Object.entries(options.headers ?? {})) {\n xhr.setRequestHeader(key, value);\n }\n\n const onProgress = options.onProgress;\n if (onProgress !== undefined) {\n xhr.upload.addEventListener(\"progress\", (event) => {\n if (event.lengthComputable) {\n onProgress(event.total === 0 ? 0 : event.loaded / event.total);\n }\n });\n }\n\n xhr.addEventListener(\"load\", () => {\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n resolve(parseRef(JSON.parse(xhr.responseText)));\n } catch {\n reject(new Error(\"upload returned an unreadable response\"));\n }\n } else {\n reject(new Error(errorMessage(xhr)));\n }\n });\n xhr.addEventListener(\"error\", () => reject(new Error(\"upload failed\")));\n xhr.addEventListener(\"abort\", () => reject(new Error(\"upload cancelled\")));\n\n const signal = options.signal;\n if (signal !== undefined) {\n signal.addEventListener(\"abort\", () => xhr.abort());\n }\n\n xhr.send(form);\n });\n}\n\n/** Validate + narrow the server's `201` body into an {@link AttachmentRef}. */\nfunction parseRef(body: unknown): AttachmentRef {\n if (typeof body !== \"object\" || body === null) {\n throw new Error(\"not an object\");\n }\n const o = body as Record<string, unknown>;\n const id = o[\"id\"];\n const name = o[\"name\"];\n const mime = o[\"mime\"];\n const size = o[\"size\"];\n const url = o[\"url\"];\n if (\n typeof id !== \"string\" ||\n typeof name !== \"string\" ||\n typeof mime !== \"string\" ||\n typeof size !== \"number\"\n ) {\n throw new Error(\"missing fields\");\n }\n return typeof url === \"string\" ? { id, name, mime, size, url } : { id, name, mime, size };\n}\n\n/** A human-readable message from a non-2xx upload response. */\nfunction errorMessage(xhr: XMLHttpRequest): string {\n try {\n const body = JSON.parse(xhr.responseText) as { error?: unknown };\n if (typeof body.error === \"string\") {\n return body.error;\n }\n } catch {\n // Non-JSON error body \u2014 fall through to the status text.\n }\n return `upload failed (${xhr.status})`;\n}\n", "/**\n * The `<ag-ui-chat>` elements connected to this document, oldest first.\n *\n * The highlight ring is drawn in the host's page, outside every chat, so a\n * token set on a chat never reaches it through the cascade. A free `flash()`\n * still has to answer \"which widget is this ring speaking for\", and that is a\n * question about the live elements rather than about any one of them.\n *\n * Module-level on purpose, and the second piece of shared mutable state the\n * repository's `CLAUDE.md` records, beside the claimed storage namespaces. See\n * the conditions it states, and how this one meets them, before adding a\n * third.\n */\nconst CONNECTED_CHATS = new Set<HTMLElement>();\n\n/**\n * One chat's place in the document's list of connected chats.\n *\n * Owned one-to-one by an `<ag-ui-chat>`, which joins on connect and leaves on\n * disconnect, so the list holds exactly the elements that are in a document\n * now. Typed as `HTMLElement` rather than the element's class, because the DOM\n * driver reads it and must not import the element.\n */\nexport class ChatRegistration {\n readonly #chat: HTMLElement;\n\n constructor(chat: HTMLElement) {\n this.#chat = chat;\n }\n\n /**\n * Join, as the most recently connected chat. An element moved in the DOM\n * left on disconnect before it reconnected, so it rejoins at the end and no\n * entry needs removing first.\n */\n join(): void {\n CONNECTED_CHATS.add(this.#chat);\n }\n\n /** Leave. The previous chat, if one is still connected, becomes the latest. */\n leave(): void {\n CONNECTED_CHATS.delete(this.#chat);\n }\n\n /** The most recently connected chat still in the document, or `null`. */\n static latest(): HTMLElement | null {\n let latest: HTMLElement | null = null;\n for (const chat of CONNECTED_CHATS) {\n latest = chat;\n }\n return latest;\n }\n}\n", "import { ChatRegistration } from \"../core/chat_registry.js\";\n\n/** The public ring token, read from the target and then from the chat. */\nconst RING_TOKEN = \"--ag-ui-highlight-ring-color\";\n\n/** The accent a host themes its page with, read from the target. */\nconst ACCENT_TOKEN = \"--ag-ui-accent\";\n\n/**\n * The accent the chat actually resolved, its theme's default included. Read\n * through the private alias because the public token is unset on a page that\n * themed nothing, which is exactly the page this exists for.\n */\nconst CHAT_ACCENT = \"--_accent\";\n\n/** The package indigo, for a page with no chat and no theming at all. */\nconst PACKAGE_ACCENT = \"#4f46e5\";\n\n/**\n * The colour a highlight ring is drawn in when the caller passed none.\n *\n * In order: `--ag-ui-highlight-ring-color` on the target, the same token on the chat, the\n * target's `--ag-ui-accent`, the chat's resolved accent, the package indigo. The target's\n * accent outranks the chat's default so a host theming its page keeps its rings; the ring\n * token outranks both so a host can keep the ring apart from the accent. Only the\n * chat's own accent is adjusted, since it follows the widget's scheme rather than the\n * page's: it is held to 3:1 against the surface behind the target (see\n * {@link surfaceBehind}) by trying the other half of its light-dark pair, then stepping\n * toward black or white. Every other value is a host's choice and is drawn as given.\n *\n * `chat` defaults to the most recently connected `<ag-ui-chat>`.\n */\nexport function ringColor(target: HTMLElement, chat?: HTMLElement): string {\n const onTarget = readToken(target, RING_TOKEN);\n if (onTarget !== \"\") {\n return onTarget;\n }\n const owner = chat ?? ChatRegistration.latest();\n const onChat = owner === null ? \"\" : resolveOn(owner, RING_TOKEN);\n if (onChat !== \"\") {\n return onChat;\n }\n const accent = readToken(target, ACCENT_TOKEN);\n if (accent !== \"\") {\n return accent;\n }\n if (owner === null) {\n return PACKAGE_ACCENT;\n }\n const chatAccent = resolveOn(owner, CHAT_ACCENT);\n return chatAccent === \"\" ? PACKAGE_ACCENT : legible(owner, chatAccent, target);\n}\n\n/** The contrast a ring needs against what it is drawn on (WCAG 2.4.13). */\nconst RING_CONTRAST = 3;\n\n/** How far each step moves a failing accent toward black or white. */\nconst STEP = 0.1;\n\ntype Rgba = readonly [number, number, number, number];\n\n/**\n * `accent`, or the nearest variant of it that holds {@link RING_CONTRAST}\n * against the surface behind `target`.\n *\n * Colours are compared as sRGB bytes painted onto a one-pixel canvas, the one\n * reading that turns a resolved color-mix() or oklch() into numbers. Where\n * there is no 2d context to paint on, nothing can be measured, and the accent\n * is drawn as it was.\n */\nfunction legible(chat: HTMLElement, accent: string, target: HTMLElement): string {\n const paint = document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\n if (paint === null) {\n return accent;\n }\n const bytes = (color: string): Rgba => {\n paint.clearRect(0, 0, 1, 1);\n paint.fillStyle = \"rgb(0 0 0 / 0)\";\n paint.fillStyle = color;\n paint.fillRect(0, 0, 1, 1);\n const [r = 0, g = 0, b = 0, a = 0] = paint.getImageData(0, 0, 1, 1).data;\n return [r, g, b, a / 255];\n };\n const surface = surfaceBehind(target, bytes);\n const holds = (color: Rgba): boolean => contrast(over(color, surface), surface) >= RING_CONTRAST;\n const own = [accent, resolveOn(chat, CHAT_ACCENT, \"light\"), resolveOn(chat, CHAT_ACCENT, \"dark\")];\n const fit = own.find((candidate) => holds(bytes(candidate)));\n if (fit !== undefined) {\n return fit;\n }\n // Black or white, whichever the surface sets off better, holds at least\n // 4.5:1 against any surface, so the walk always ends by the last step.\n const from = over(bytes(accent), surface);\n const black: Rgba = [0, 0, 0, 1];\n const white: Rgba = [255, 255, 255, 1];\n const toward = contrast(black, surface) > contrast(white, surface) ? black : white;\n let step = 1;\n while (!holds(mix(from, toward, step * STEP))) {\n step += 1;\n }\n const [r, g, b] = mix(from, toward, step * STEP);\n return `rgb(${r}, ${g}, ${b})`;\n}\n\n/**\n * The colour of the surface a ring around `target` is drawn on, as opaque\n * sRGB bytes.\n *\n * The ring sits outside the target's border box (the flash outline is offset\n * from it, the overlay leaves a gap), so the target's own fill is not under\n * it: a white field on a dark page is ringed on the dark page. The surface is\n * every background from the target's parent up, composited until one is\n * opaque, over the page canvas, which follows the root's colour scheme. A\n * background image is not read; its colour beneath is.\n */\nfunction surfaceBehind(target: HTMLElement, bytes: (color: string) => Rgba): Rgba {\n const layers: Rgba[] = [];\n for (let el = parentOf(target); el !== null; el = parentOf(el)) {\n const layer = bytes(window.getComputedStyle(el).backgroundColor);\n layers.push(layer);\n if (layer[3] === 1) {\n break;\n }\n }\n const probe = document.createElement(\"span\");\n probe.hidden = true;\n probe.style.color = \"Canvas\";\n document.documentElement.appendChild(probe);\n let surface = bytes(window.getComputedStyle(probe).color);\n probe.remove();\n for (const layer of layers.reverse()) {\n surface = over(layer, surface);\n }\n return surface;\n}\n\n/** The element above `el`, crossing out of a shadow root to its host. */\nfunction parentOf(el: Element): Element | null {\n if (el.parentElement !== null) {\n return el.parentElement;\n }\n const root = el.getRootNode();\n return root instanceof ShadowRoot ? root.host : null;\n}\n\n/** `top` painted over the opaque `under`. */\nfunction over(top: Rgba, under: Rgba): Rgba {\n return mix(under, top, top[3]);\n}\n\n/** `from` moved `share` of the way to `to`, as opaque bytes. */\nfunction mix(from: Rgba, to: Rgba, share: number): Rgba {\n const channel = (index: 0 | 1 | 2): number =>\n Math.round(from[index] + (to[index] - from[index]) * share);\n return [channel(0), channel(1), channel(2), 1];\n}\n\n/** WCAG relative luminance of opaque sRGB bytes. */\nfunction luminance([r, g, b]: Rgba): number {\n const linear = (channel: number): number => {\n const c = channel / 255;\n return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;\n };\n return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);\n}\n\n/** WCAG contrast ratio between two opaque colours. */\nfunction contrast(a: Rgba, b: Rgba): number {\n const [la, lb] = [luminance(a), luminance(b)];\n return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);\n}\n\nfunction readToken(el: HTMLElement, name: string): string {\n return window.getComputedStyle(el).getPropertyValue(name).trim();\n}\n\n/**\n * The custom property `name` on `chat`, as the colour it computes to there, or `\"\"` when\n * unset or not a colour.\n *\n * Resolved by a probe inside the shadow tree, because the chat's colours are `light-dark()`\n * pairs that a custom property keeps unresolved: on a page element the pair would follow the\n * page's scheme. An element with no open shadow root is read as it is. `scheme` forces one\n * half of the pair, to find the chat's other accent.\n */\nfunction resolveOn(chat: HTMLElement, name: string, scheme?: \"light\" | \"dark\"): string {\n const value = readToken(chat, name);\n const root = chat.shadowRoot;\n if (value === \"\" || root === null) {\n return value;\n }\n const probe = document.createElement(\"span\");\n probe.hidden = true;\n if (scheme !== undefined) {\n probe.style.colorScheme = scheme;\n }\n probe.style.color = value;\n // An unparseable value leaves the declaration empty; the probe would report an inherited colour.\n if (probe.style.color === \"\") {\n return \"\";\n }\n root.appendChild(probe);\n const resolved = window.getComputedStyle(probe).color;\n probe.remove();\n return resolved;\n}\n", "import { HIGHLIGHT_OVERLAY_Z_INDEX } from \"../constants.js\";\nimport { ringColor } from \"./ring_color.js\";\n\n/** How the overlay is drawn around the element being pointed at. */\nexport interface HighlightOverlayOptions {\n /** Dim everything except the target. Default false. */\n readonly scrim?: boolean;\n /** Draw the ring as a moving gradient rather than a flat colour. Default false. */\n readonly gradient?: boolean;\n /**\n * Ring colour, and the flat fallback for the gradient. Default:\n * `--ag-ui-highlight-ring-color` on the target, then on the chat, then the\n * target's `--ag-ui-accent`, then the chat's accent, held to 3:1 against the\n * surface behind the target.\n */\n readonly color?: string;\n /** The chat whose ring colour and accent to use. Default: the latest connected. */\n readonly chat?: HTMLElement;\n /** Gap between the target's box and the ring. Default 4. */\n readonly padding?: number;\n /** Corner radius of the cut-out and the ring. Default: the target's own. */\n readonly radius?: number;\n /** Ring thickness. Default 3, or `--ag-ui-highlight-ring-width` on the target. */\n readonly ringWidth?: number;\n /** One pass of the gradient. Default 2400, or `--ag-ui-highlight-flow-ms`. */\n readonly flowMs?: number;\n}\n\n/**\n * Read a `--ag-ui-*` token from the target, not the overlay: the overlay sits in the body, so\n * a host that themes the widget on `ag-ui-chat` or a wrapper would never reach a `var()` there.\n */\nfunction tokenOn(target: HTMLElement, name: string, fallback: string): string {\n const value = window.getComputedStyle(target).getPropertyValue(name).trim();\n return value === \"\" ? fallback : value;\n}\n\n/** Default gap between the target's border box and the ring around it. */\nconst DEFAULT_PADDING_PX = 4;\n\n/**\n * Draw an overlay that points at `target`, and return a function that removes it.\n *\n * An overlay rather than a style on the target: a flat highlight is an `outline` so an\n * `overflow: hidden` ancestor cannot clip it, but an outline takes a colour, never a\n * gradient, and a dim needs a surface larger than the target. Nothing here is a descendant\n * of the target, so none of it is clipped.\n *\n * It is inert: it never takes a pointer event, so the driver can still click what it\n * just pointed at.\n *\n * It follows: the cut-out is recomputed on scroll and resize.\n */\nexport function showHighlightOverlay(\n target: HTMLElement,\n options: HighlightOverlayOptions = {},\n): () => void {\n const root = document.createElement(\"div\");\n root.setAttribute(\"data-ag-ui-highlight\", \"\");\n // Decoration: the agent's message is what announces that the element matters.\n root.setAttribute(\"aria-hidden\", \"true\");\n root.style.cssText = [\n \"position: fixed\",\n \"inset: 0\",\n \"pointer-events: none\",\n // Above the widget's own default, since it points at the page the widget sits over.\n `z-index: ${tokenOn(target, \"--ag-ui-highlight-z-index\", String(HIGHLIGHT_OVERLAY_Z_INDEX))}`,\n ].join(\";\");\n\n const scrim = document.createElement(\"div\");\n const ring = document.createElement(\"div\");\n // Classes, since `::part` cannot reach the host document.\n root.className = \"ag-ui-highlight\";\n scrim.className = \"ag-ui-highlight-scrim\";\n ring.className = \"ag-ui-highlight-ring\";\n if (options.scrim === true) {\n root.append(scrim);\n }\n root.append(ring);\n\n const ringWidth =\n options.ringWidth ?? Number.parseFloat(tokenOn(target, \"--ag-ui-highlight-ring-width\", \"3\"));\n const flowMs =\n options.flowMs ?? Number.parseFloat(tokenOn(target, \"--ag-ui-highlight-flow-ms\", \"2400\"));\n\n const paint = (): void => {\n const box = target.getBoundingClientRect();\n const pad = options.padding ?? DEFAULT_PADDING_PX;\n // No fallback for an unparseable radius: it always resolves for an element in the document.\n const radius = options.radius ?? Number.parseFloat(getComputedStyle(target).borderRadius);\n const left = box.left - pad;\n const top = box.top - pad;\n const width = box.width + pad * 2;\n const height = box.height + pad * 2;\n\n if (options.scrim === true) {\n // One element with a hole; the opposite winding makes evenodd treat the inside as outside.\n scrim.style.cssText = [\n \"position: absolute\",\n \"inset: 0\",\n `background: ${tokenOn(target, \"--ag-ui-highlight-scrim\", \"rgba(15, 15, 25, 0.45)\")}`,\n `clip-path: path(evenodd, '${holePath(left, top, width, height, radius + pad)}')`,\n ].join(\";\");\n }\n\n ring.style.cssText = [\n \"position: absolute\",\n `left: ${left}px`,\n `top: ${top}px`,\n `width: ${width}px`,\n `height: ${height}px`,\n `border-radius: ${radius + pad}px`,\n `border: ${ringWidth}px solid transparent`,\n \"box-sizing: border-box\",\n ringPaint(target, options),\n ].join(\";\");\n };\n\n paint();\n // Animated from script: a keyframe would mean injecting a rule into the host stylesheet,\n // which is module-level state. Reduced motion draws the gradient but stops it travelling.\n let flow: Animation | null = null;\n if (options.gradient === true && !window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) {\n flow = ring.animate([{ backgroundPosition: \"100% 0\" }, { backgroundPosition: \"-100% 0\" }], {\n duration: flowMs,\n iterations: Number.POSITIVE_INFINITY,\n easing: \"linear\",\n });\n }\n // Capture reaches a scroll in any container; passive, as this only reads geometry.\n const listen = { capture: true, passive: true } as const;\n window.addEventListener(\"scroll\", paint, listen);\n window.addEventListener(\"resize\", paint, listen);\n document.body.appendChild(root);\n\n return () => {\n window.removeEventListener(\"scroll\", paint, listen);\n window.removeEventListener(\"resize\", paint, listen);\n // An infinite animation never finishes, so cancel it rather than rely on the engine dropping it.\n flow?.cancel();\n root.remove();\n };\n}\n\n/**\n * A caller's colour, or `null` if it is not one: the value is joined into a `;`-separated\n * `cssText`, so a string carrying a semicolon would write further declarations, and the\n * colour can come from the agent.\n */\nfunction safeColor(value: string | undefined): string | null {\n if (value === undefined) {\n return null;\n }\n return CSS.supports(\"color\", value) ? value : null;\n}\n\n/** The ring's paint: a flat border, or a gradient masked to the frame (border box less padding box). */\nfunction ringPaint(target: HTMLElement, options: HighlightOverlayOptions): string {\n const color = safeColor(options.color) ?? ringColor(target, options.chat);\n if (options.gradient !== true) {\n return `border-color: ${color}`;\n }\n const image = tokenOn(\n target,\n \"--ag-ui-highlight-gradient\",\n `linear-gradient(115deg, transparent 20%, ${color} 50%, transparent 80%)`,\n );\n const mask = \"linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)\";\n return [\n `background-image: ${image}`,\n \"background-origin: border-box\",\n \"background-size: 300% 100%\",\n `-webkit-mask: ${mask}`,\n `mask: ${mask}`,\n \"-webkit-mask-composite: xor\",\n \"mask-composite: exclude\",\n \"background-position: 50% 0\",\n ].join(\";\");\n}\n\n/**\n * A viewport-sized rectangle with a rounded rectangle cut out, as a path for\n * `clip-path: path(evenodd, ...)`. Absolute commands, closed explicitly: an unparseable\n * `clip-path` is dropped silently and the scrim would cover the target.\n */\nfunction holePath(x: number, y: number, width: number, height: number, radius: number): string {\n const r = Math.max(0, Math.min(radius, width / 2, height / 2));\n const right = x + width;\n const bottom = y + height;\n const outer = `M 0 0 H ${window.innerWidth} V ${window.innerHeight} H 0 Z`;\n const hole = [\n `M ${x + r} ${y}`,\n `H ${right - r}`,\n `A ${r} ${r} 0 0 1 ${right} ${y + r}`,\n `V ${bottom - r}`,\n `A ${r} ${r} 0 0 1 ${right - r} ${bottom}`,\n `H ${x + r}`,\n `A ${r} ${r} 0 0 1 ${x} ${bottom - r}`,\n `V ${y + r}`,\n `A ${r} ${r} 0 0 1 ${x + r} ${y}`,\n \"Z\",\n ].join(\" \");\n return `${outer} ${hole}`;\n}\n", "// Set a control's `value` / `checked` through the native prototype setter, so\n// framework value-tracking sees the change. React (and Vue/Svelte) replace the\n// element's own setter with a tracked one, so `el.value = x` hits that override\n// and the following `input` event carries no change: the field looks filled\n// while the framework's state stays empty. Calling the original prototype\n// setter and then dispatching `input` avoids that.\n\ntype ValueSetter = (this: HTMLElement, value: string) => void;\ntype CheckedSetter = (this: HTMLElement, checked: boolean) => void;\n\n/** The original prototype setter for `prop` on `proto`. */\nfunction prototypeSetter(proto: object, prop: string): (this: HTMLElement, value: never) => void {\n // Captured at module load; DOM environments always define these, so the cast is safe.\n const setter = (Object.getOwnPropertyDescriptor(proto, prop) as PropertyDescriptor).set;\n return setter as unknown as (this: HTMLElement, value: never) => void;\n}\n\nconst setInputValue = prototypeSetter(HTMLInputElement.prototype, \"value\") as ValueSetter;\nconst setTextareaValue = prototypeSetter(HTMLTextAreaElement.prototype, \"value\") as ValueSetter;\nconst setSelectValue = prototypeSetter(HTMLSelectElement.prototype, \"value\") as ValueSetter;\nconst setInputChecked = prototypeSetter(HTMLInputElement.prototype, \"checked\") as CheckedSetter;\n\n/** Set `el.value` via the element's native prototype setter. */\nexport function setNativeValue(\n el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,\n value: string,\n): void {\n if (el instanceof HTMLTextAreaElement) {\n setTextareaValue.call(el, value);\n } else if (el instanceof HTMLSelectElement) {\n setSelectValue.call(el, value);\n } else {\n setInputValue.call(el, value);\n }\n}\n\n/** Set `el.checked` via the native prototype setter. */\nexport function setNativeChecked(el: HTMLInputElement, checked: boolean): void {\n setInputChecked.call(el, checked);\n}\n", "/** Dispatch the `input` then `change` events frameworks listen for. */\nexport function dispatchInputAndChange(el: HTMLElement): void {\n el.dispatchEvent(new Event(\"input\", { bubbles: true }));\n el.dispatchEvent(new Event(\"change\", { bubbles: true }));\n}\n", "/**\n * Visible-action animation primitives.\n *\n * These run against the **host page** DOM (not the element's shadow root) so a\n * user watches the agent type, highlight, and click at human-readable speed.\n * Each is configurable; pass small/zero durations in tests (or use fake timers).\n */\n\nimport { showHighlightOverlay } from \"./highlight_overlay.js\";\nimport { setNativeChecked, setNativeValue } from \"./native_setter.js\";\nimport { ringColor } from \"./ring_color.js\";\nimport { dispatchInputAndChange } from \"./utils.js\";\n\nfunction delay(ms: number): Promise<void> {\n return new Promise<void>((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\n/**\n * Whether the user has asked the OS/browser to minimise motion.\n *\n * Honoured by every primitive that moves something, except `typeInto` and\n * `highlightThenClick`, which keep their explicit durations. The flash drops its fade\n * but still holds the ring: reduced motion asks for no animation, not no feedback.\n */\nexport function prefersReducedMotion(): boolean {\n return window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n}\n\n/** Like {@link delay}, but resolves immediately under reduced motion. */\nfunction motionDelay(ms: number): Promise<void> {\n if (ms <= 0 || prefersReducedMotion()) {\n return Promise.resolve();\n }\n return delay(ms);\n}\n\n/**\n * Which `<ag-ui-chat>` a ring speaks for. The ring is drawn in the host page, which a\n * token set on the chat never reaches, so the chat is read directly.\n */\nexport interface RingOwnerOptions {\n /** The chat whose ring colour and accent to use. Default: the latest connected. */\n chat?: HTMLElement;\n}\n\n/** The soft halo of the press and toggle rings: the ring colour at 40%. */\nfunction ringShadow(el: HTMLElement, chat: HTMLElement | undefined): string {\n return `0 0 0 3px color-mix(in srgb, ${ringColor(el, chat)} 40%, transparent)`;\n}\n\n/** Outline `el` in the ring colour and return the function that restores its own outline. */\nfunction outlineElement(el: HTMLElement, chat: HTMLElement | undefined): () => void {\n const previousOutline = el.style.outline;\n const previousOffset = el.style.outlineOffset;\n el.style.outline = `2px solid ${ringColor(el, chat)}`;\n el.style.outlineOffset = \"2px\";\n return () => {\n el.style.outline = previousOutline;\n el.style.outlineOffset = previousOffset;\n };\n}\n\n/** An element whose `value` can be typed into. */\nexport type TextLikeElement = HTMLInputElement | HTMLTextAreaElement;\n\nexport interface TypeOptions {\n /** Milliseconds between characters. Default 35. */\n charDelayMs?: number;\n}\n\n/**\n * Clear `el` and type `value` one character at a time, firing an `input` event\n * per character as a real user would, then a final `change`.\n */\nexport async function typeInto(\n el: TextLikeElement,\n value: string,\n options: TypeOptions = {},\n): Promise<void> {\n const charDelayMs = options.charDelayMs ?? 35;\n setNativeValue(el, \"\");\n el.dispatchEvent(new Event(\"input\", { bubbles: true }));\n for (const char of value) {\n setNativeValue(el, el.value + char);\n el.dispatchEvent(new Event(\"input\", { bubbles: true }));\n if (charDelayMs > 0) {\n await delay(charDelayMs);\n }\n }\n el.dispatchEvent(new Event(\"change\", { bubbles: true }));\n}\n\nexport interface HighlightClickOptions extends RingOwnerOptions {\n /** Milliseconds to hold the highlight before clicking. Default 280. */\n highlightMs?: number;\n}\n\n/** Outline `el`, pause so the user sees it, then click and restore. */\nexport async function highlightThenClick(\n el: HTMLElement,\n options: HighlightClickOptions = {},\n): Promise<void> {\n const restore = outlineElement(el, options.chat);\n await delay(options.highlightMs ?? 280);\n restore();\n el.click();\n}\n\nexport interface ScrollOptions {\n /**\n * How long to wait for a moving scroll to settle before giving up.\n * Default 600.\n */\n settleMs?: number;\n}\n\nconst SCROLL_SETTLE_MS = 600;\n\n/** How long to give a smooth scroll to start moving before assuming it will not. */\nconst SCROLL_START_MS = 100;\n\n/**\n * Scroll `el` to the vertical centre of the viewport.\n *\n * Resolves once the scroll settles, so a ring is not drawn mid-glide. Awaiting is\n * optional; the scroll is requested synchronously.\n */\nexport function scrollIntoCenterView(el: HTMLElement, options: ScrollOptions = {}): Promise<void> {\n const reduced = prefersReducedMotion();\n el.scrollIntoView({\n block: \"center\",\n inline: \"nearest\",\n behavior: reduced ? \"auto\" : \"smooth\",\n });\n if (reduced) {\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n let timer: ReturnType<typeof setTimeout>;\n const settle = (): void => {\n clearTimeout(timer);\n document.removeEventListener(\"scroll\", started, true);\n document.removeEventListener(\"scrollend\", settle, true);\n resolve();\n };\n const started = (): void => {\n document.removeEventListener(\"scroll\", started, true);\n clearTimeout(timer);\n timer = setTimeout(settle, options.settleMs ?? SCROLL_SETTLE_MS);\n };\n // Neither event bubbles, so listen on the document in the capture phase. Two timeouts:\n // an element already in view never fires scrollend (the short probe), and once moving,\n // the longer budget covers browsers without scrollend.\n timer = setTimeout(settle, SCROLL_START_MS);\n document.addEventListener(\"scroll\", started, true);\n document.addEventListener(\"scrollend\", settle, true);\n });\n}\n\n/** Total on-screen life of the flash ring, hold plus fade. */\nconst FLASH_MS = 1200;\n\n/** Share of {@link FLASH_MS} spent fading out rather than holding. */\nconst FLASH_FADE_RATIO = 1 / 3;\n\nexport interface FlashOptions extends RingOwnerOptions {\n /** Total milliseconds the ring is on screen, hold plus fade. Default 1200. */\n flashMs?: number;\n /**\n * Ring colour. Defaults to `--ag-ui-highlight-ring-color` (on the target,\n * then on the chat), then the target's `--ag-ui-accent`, then the chat's\n * accent.\n */\n color?: string;\n /**\n * Dim everything except the target. Draws an overlay outside the element instead of an\n * outline (see {@link showHighlightOverlay}); it takes no pointer event, so the page\n * stays usable.\n */\n scrim?: boolean;\n /** Draw the ring as a moving gradient. Also an overlay, for the same reason. */\n gradient?: boolean;\n /** Gap between the target's box and an overlay ring. Default 4. */\n ringPadding?: number;\n /**\n * Move keyboard focus to the element as well. Defaults to false for\n * {@link flash} and true for {@link focusWithFlash}.\n */\n focus?: boolean;\n}\n\nasync function flashRing(\n el: HTMLElement,\n options: FlashOptions,\n focusByDefault: boolean,\n): Promise<void> {\n if (options.focus ?? focusByDefault) {\n // preventScroll: focus()'s instant scroll would fight a smooth scroll still in flight.\n el.focus({ preventScroll: true });\n }\n const flashMs = options.flashMs ?? FLASH_MS;\n if (flashMs <= 0) {\n return;\n }\n // A scrim or gradient cannot be an outline (a colour only, and clipped with the target).\n if (options.scrim === true || options.gradient === true) {\n const dismiss = showHighlightOverlay(el, {\n scrim: options.scrim === true,\n gradient: options.gradient === true,\n ...(options.color === undefined ? {} : { color: options.color }),\n ...(options.ringPadding === undefined ? {} : { padding: options.ringPadding }),\n ...(options.chat === undefined ? {} : { chat: options.chat }),\n });\n await delay(flashMs);\n dismiss();\n return;\n }\n const previousOutline = el.style.outline;\n const previousOffset = el.style.outlineOffset;\n const previousTransition = el.style.transition;\n const color = options.color ?? ringColor(el, options.chat);\n // outline, not box-shadow: an overflow:hidden ancestor sharing the target's box clips a shadow away.\n el.style.outline = `3px solid ${color}`;\n el.style.outlineOffset = \"2px\";\n const fadeMs = prefersReducedMotion() ? 0 : Math.round(flashMs * FLASH_FADE_RATIO);\n await delay(flashMs - fadeMs);\n if (fadeMs > 0) {\n // Setting the transition and the new colour in one task is fine: transitions start from the after-change style.\n el.style.transition = `outline-color ${fadeMs}ms ease-out`;\n el.style.outline = \"3px solid transparent\";\n await delay(fadeMs);\n }\n el.style.outline = previousOutline;\n el.style.outlineOffset = previousOffset;\n el.style.transition = previousTransition;\n}\n\n/**\n * Flash a ring around `el` without touching focus.\n *\n * Prefer this over {@link focusWithFlash} when the point is to show the user\n * something: moving focus steals it from the composer, can fire blur validation\n * on whatever they were mid-edit in, and can close an open menu.\n */\nexport function flash(el: HTMLElement, options: FlashOptions = {}): Promise<void> {\n return flashRing(el, options, false);\n}\n\n/**\n * Focus `el` and flash a ring around it. Focus moves unless `options.focus`\n * says otherwise; use {@link flash} to leave focus where the user put it.\n */\nexport function focusWithFlash(el: HTMLElement, options: FlashOptions = {}): Promise<void> {\n return flashRing(el, options, true);\n}\n\nexport interface PressOptions extends RingOwnerOptions {\n /** Milliseconds to hold the pressed state before clicking. Default 140. */\n pressMs?: number;\n}\n\n/**\n * Show a brief pressed affordance on a control \u2014 a slight scale-down plus\n * accent ring \u2014 then click it and restore. Reads as a press rather than the\n * plain outline {@link highlightThenClick} draws.\n */\nexport async function pressThenClick(el: HTMLElement, options: PressOptions = {}): Promise<void> {\n const pressMs = options.pressMs ?? 140;\n const previousTransform = el.style.transform;\n const previousTransition = el.style.transition;\n const previousShadow = el.style.boxShadow;\n el.style.transition = \"transform 80ms ease\";\n el.style.transform = \"scale(0.96)\";\n el.style.boxShadow = ringShadow(el, options.chat);\n await motionDelay(pressMs);\n el.style.transform = previousTransform;\n el.style.transition = previousTransition;\n el.style.boxShadow = previousShadow;\n el.click();\n}\n\nexport interface SelectOptions extends RingOwnerOptions {\n /** Milliseconds to hold the highlight before committing. Default 220. */\n highlightMs?: number;\n}\n\n/** Find an option in `el` whose value or visible text equals `value`. */\nfunction findOption(el: HTMLSelectElement, value: string): HTMLOptionElement | null {\n for (const option of Array.from(el.options)) {\n if (option.value === value || option.text === value) {\n return option;\n }\n }\n return null;\n}\n\n/**\n * Outline a `<select>`, pause so the user sees the pick, then set it to the\n * option matching `value` (by value or visible text) and fire `input` +\n * `change`. Throws when no option matches.\n */\nexport async function selectOption(\n el: HTMLSelectElement,\n value: string,\n options: SelectOptions = {},\n): Promise<void> {\n const option = findOption(el, value);\n if (option === null) {\n throw new Error(`no <option> matching \"${value}\"`);\n }\n const restore = outlineElement(el, options.chat);\n await motionDelay(options.highlightMs ?? 220);\n setNativeValue(el, option.value);\n dispatchInputAndChange(el);\n restore();\n}\n\nexport interface ToggleOptions extends RingOwnerOptions {\n /** Milliseconds to hold the flash. Default 200. */\n flashMs?: number;\n}\n\n/**\n * Flash a ring around a checkbox/radio, set its `checked` state, and fire\n * `input` + `change` so frameworks observe the flip.\n */\nexport async function toggleControl(\n el: HTMLInputElement,\n checked: boolean,\n options: ToggleOptions = {},\n): Promise<void> {\n const flashMs = options.flashMs ?? 200;\n const previousShadow = el.style.boxShadow;\n el.style.boxShadow = ringShadow(el, options.chat);\n await motionDelay(flashMs);\n setNativeChecked(el, checked);\n dispatchInputAndChange(el);\n el.style.boxShadow = previousShadow;\n}\n", "import { X_SUMMARY_KEY } from \"../constants.js\";\nimport type { CollapseTarget } from \"../ui/placement/surface_for.js\";\nimport type { ClientTool } from \"./client_tool_registry.js\";\n\n/** Every corner the panel can be sent to, in the order the schema states them. */\nexport const CHAT_CORNERS = [\"top-left\", \"top-right\", \"bottom-left\", \"bottom-right\"] as const;\n\n/** A corner the panel can be sent to. */\nexport type ChatCorner = (typeof CHAT_CORNERS)[number];\n\n/** What the agent is told about the surface it is speaking from. */\nexport interface ChatSurfaceReport {\n /** The placement in force, or `null` when the host set none. */\n readonly placement: string | null;\n /**\n * What the panel collapses to: `launcher`, `rail`, `header`, `bar` (the\n * bottom bar it rises from), `none` (hidden, brought back by the host's own\n * control), or `null` when it cannot collapse.\n */\n readonly collapseTo: CollapseTarget;\n /** Whether the panel is currently collapsed. */\n readonly collapsed: boolean;\n /** Whether this placement has a collapsed state at all. */\n readonly collapsible: boolean;\n /**\n * Whether the reader maximized the panel with its header control. Read-only:\n * no tool changes it, and it is not kept across a reload.\n */\n readonly maximized: boolean;\n /** Whether the panel can be moved, or the placement owns its position. */\n readonly movable: boolean;\n /**\n * Whether this page allows the panel to be moved at all: true for every\n * placement unless the host set `data-launcher-drag=\"false\"`. It is the\n * page's setting alone and does not vary with the placement or `collapse-to`;\n * whether this panel moves is {@link ChatSurfaceReport.movable}. Kept apart because\n * the two refusals need different sentences.\n */\n readonly draggable: boolean;\n /** Whether the panel currently covers the whole viewport. */\n readonly fullBleed: boolean;\n /** The panel's box, in viewport coordinates. */\n readonly box: {\n readonly left: number;\n readonly top: number;\n readonly width: number;\n readonly height: number;\n };\n /**\n * The part of the viewport the panel may rest in, with an origin: a host can reserve\n * edges for its own chrome, so it is not always the screen's.\n */\n readonly viewport: {\n readonly left: number;\n readonly top: number;\n readonly width: number;\n readonly height: number;\n };\n}\n\n/** Whether a string names one of the four corners. */\nexport function isChatCorner(value: string): value is ChatCorner {\n return (CHAT_CORNERS as readonly string[]).includes(value);\n}\n\n/** The part of the widget these tools drive: a port, since the element imports this module. */\nexport interface ChatSurface {\n describeSurface(): ChatSurfaceReport;\n /** `announce` writes a transcript notice with an undo; the tools always pass it. */\n moveTo(corner: ChatCorner, options?: { readonly announce?: boolean }): boolean;\n setCollapsed(collapsed: boolean, options?: { readonly announce?: boolean }): void;\n}\n\n/**\n * Tools that let the agent move or collapse the panel it is speaking from.\n *\n * They report what happened, not what was asked: `move_chat` answers `moved: false`\n * with the reason when the panel cannot move, rather than succeeding on a panel that\n * did not budge.\n */\nexport function createChatSurfaceTools(surface: ChatSurface): ClientTool[] {\n return [\n {\n name: \"read_chat_surface\",\n description:\n \"Describe the chat panel you are speaking from: its placement, whether it is \" +\n \"collapsed, whether it can be moved, and the box it occupies. Read this before \" +\n \"moving or minimising yourself, since a full-screen panel has nowhere to move to. \" +\n \"Read-only.\",\n parameters: {\n type: \"object\",\n properties: {},\n required: [],\n [X_SUMMARY_KEY]: \"Read the chat's own position\",\n },\n handler: () => surface.describeSurface(),\n },\n {\n name: \"move_chat\",\n description:\n \"Move your own panel to a corner, to uncover something the user needs to see. \" +\n \"`corner` is top-left, top-right, bottom-left or bottom-right. Answers \" +\n \"`moved: false` with a reason when the placement owns its position or the panel \" +\n \"fills the screen; check `read_chat_surface` first, and prefer minimise_chat when \" +\n \"there is nowhere to move to.\",\n parameters: {\n type: \"object\",\n properties: {\n corner: {\n type: \"string\",\n enum: [...CHAT_CORNERS],\n },\n },\n required: [\"corner\"],\n [X_SUMMARY_KEY]: \"Move the chat out of the way\",\n },\n handler: (args) => {\n const asked = String(args[\"corner\"] ?? \"\");\n const report = surface.describeSurface();\n // `required` is advisory: an unknown corner would send the panel bottom-right yet report success.\n if (!isChatCorner(asked)) {\n return {\n moved: false,\n reason: `\"${asked}\" is not a corner; use one of ${CHAT_CORNERS.join(\", \")}`,\n };\n }\n if (!report.movable) {\n // A fact the agent can act on (minimise instead), not a malformed call.\n return {\n moved: false,\n reason: report.fullBleed\n ? \"the panel fills the screen, so there is nowhere to move it to\"\n : report.draggable === false\n ? \"this page has turned off moving the panel\"\n : `the \"${report.placement ?? \"\"}\" placement owns the panel's position`,\n suggestion: report.collapsible ? \"minimise_chat\" : null,\n };\n }\n return { moved: surface.moveTo(asked, { announce: true }), corner: asked };\n },\n },\n {\n name: \"minimise_chat\",\n description:\n \"Collapse your own panel, so the user can see the whole page. The user reopens \" +\n \"it from where it collapsed to (a launcher, a rail, a bottom bar or the page's \" +\n \"own control). Answers `minimised: false` when the placement has no collapsed \" +\n \"state, which is the case for a full-page chat.\",\n parameters: {\n type: \"object\",\n properties: {},\n required: [],\n [X_SUMMARY_KEY]: \"Minimise the chat\",\n },\n handler: () => {\n const report = surface.describeSurface();\n if (!report.collapsible) {\n return {\n minimised: false,\n reason: \"this placement has no collapsed state, so there is nothing to minimise to\",\n };\n }\n surface.setCollapsed(true, { announce: true });\n return { minimised: true };\n },\n },\n {\n name: \"restore_chat\",\n description: \"Open your own panel again after minimising it.\",\n parameters: {\n type: \"object\",\n properties: {},\n required: [],\n [X_SUMMARY_KEY]: \"Restore the chat\",\n },\n handler: () => {\n // No notice: the user sees the panel come back.\n surface.setCollapsed(false);\n return { restored: true };\n },\n },\n ];\n}\n", "import type { Tool } from \"@ag-ui/core\";\n\n/** Draws one call from its arguments alone; the replay path takes this, never a `handler`. */\nexport type ChartRenderer = (args: Record<string, unknown>) => Node | null;\n\n/**\n * A tool the frontend declares and executes itself.\n *\n * `parameters` is a JSON Schema (and may carry the `x-destructive` extension).\n * `handler` receives the parsed arguments and returns a result that is\n * JSON-serialised into the AG-UI tool-result message sent back to the agent.\n */\nexport interface ClientTool {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n /**\n * Run the tool. `callId` identifies the call being executed, for a handler\n * that renders into the transcript and needs to place itself against its own\n * card; handlers that only act on the page ignore it.\n */\n handler: (args: Record<string, unknown>, callId?: string) => unknown | Promise<unknown>;\n /**\n * Draw this call, from its arguments alone.\n *\n * Optional, and the only half that is replayed: a restored transcript calls\n * `render`, never {@link handler}, so a reload cannot re-run an effect.\n *\n * It runs again on every restore, so it must be:\n *\n * - a pure function of `args` \u2014 no host state, no network, no clock;\n * - deterministic, so a reload reproduces what was there before;\n * - free of effects outside the node it returns, which the component places.\n *\n * Return `null` for arguments that say nothing worth drawing.\n */\n render?: ChartRenderer;\n}\n\n/**\n * Holds the frontend tools a host has declared on an `<ag-ui-chat>` element.\n *\n * Produces AG-UI {@link Tool} definitions for `RunAgentInput.tools` and looks\n * up handlers when the agent calls a tool. Pure (no DOM); the element owns one\n * instance.\n */\nexport class ClientToolRegistry {\n readonly #tools = new Map<string, ClientTool>();\n\n /**\n * Register a tool, replacing any existing one with the same name.\n *\n * Replacing rather than throwing keeps a re-fired host ref or StrictMode double-invoke safe.\n */\n register(tool: ClientTool): void {\n this.#tools.set(tool.name, tool);\n }\n\n has(name: string): boolean {\n return this.#tools.has(name);\n }\n\n /** Return a registered tool or throw. */\n get(name: string): ClientTool {\n const tool = this.#tools.get(name);\n if (tool === undefined) {\n throw new Error(`tool \"${name}\" is not registered`);\n }\n return tool;\n }\n\n /** AG-UI tool definitions for `RunAgentInput.tools`. */\n tools(): Tool[] {\n return [...this.#tools.values()].map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n }));\n }\n}\n", "import { X_DESTRUCTIVE_KEY } from \"../constants.js\";\n\n/**\n * Whether a tool's JSON-Schema `parameters` marks it destructive.\n *\n * Reads the `x-destructive` extension off a schema the **host** declared \u2014\n * a tool passed to `registerTool`, or one of the built-ins. A server-side\n * tool's schema never reaches the browser: tool definitions travel\n * client-to-server on `RunAgentInput.tools`, and the only channel coming the\n * other way is the tool catalog (`data-tools-url`), which carries labels, not\n * schemas. So a server tool marked destructive there is not gated here, and\n * must be gated server-side instead \u2014 the confirmation this flag drives is a\n * property of tools the browser itself executes.\n */\nexport function isDestructive(parameters: Record<string, unknown>): boolean {\n return parameters[X_DESTRUCTIVE_KEY] === true;\n}\n", "import { X_NAVIGATES_KEY } from \"../constants.js\";\n\n/**\n * Whether a tool's JSON-Schema `parameters` marks it as navigating.\n *\n * Reads the `x-navigates` extension. A navigating tool's handler reloads the\n * page (MPA navigation), so the element checkpoints the call and resumes the\n * run loop after the next page mounts, rather than awaiting a result inline.\n */\nexport function isNavigates(parameters: Record<string, unknown>): boolean {\n return parameters[X_NAVIGATES_KEY] === true;\n}\n", "import { X_SUMMARY_KEY } from \"../constants.js\";\nimport { scrollIntoCenterView } from \"../dom/animations.js\";\nimport type { ClientTool } from \"./client_tool_registry.js\";\n\n/**\n * Resolve a page-action target string to a host-page element, or `null` when it\n * matches nothing. The default treats the string as a CSS selector; a host with\n * a page map overrides it to map its own element ids.\n */\nexport type ResolvePageTarget = (target: string) => HTMLElement | null;\n\n/** The built-in page-action tool tokens, opted in via `data-page-actions`. */\nexport const PAGE_ACTIONS = {\n SCROLL: \"scroll\",\n DRAG: \"drag\",\n /** The widget's own position: see `createChatSurfaceTools`. */\n CHAT: \"chat\",\n} as const;\n\n/**\n * The opt-in page-action tools selected by `enabled` (a set of\n * {@link PAGE_ACTIONS} tokens), bound to a {@link ResolvePageTarget}.\n *\n * - `scroll_to` \u2014 scroll a target (`top` / `bottom` / a resolver target) into\n * view. Benign; no confirmation.\n * - `drag_and_drop` \u2014 drag one element onto another, firing the standard HTML5\n * drag sequence so the host page's own drop handler reacts. Deliberately not\n * stamped destructive: a drag rearranges transient state, and the durable\n * change happens at the page's explicit commit. A host whose page persists on\n * drop must gate it with the element's `confirmPredicate`.\n *\n * Both report a model-readable error when a target resolves to nothing.\n */\nexport function createPageActionTools(\n enabled: ReadonlySet<string>,\n resolveTarget: ResolvePageTarget,\n): ClientTool[] {\n const tools: ClientTool[] = [];\n if (enabled.has(PAGE_ACTIONS.SCROLL)) {\n tools.push(scrollTool(resolveTarget));\n }\n if (enabled.has(PAGE_ACTIONS.DRAG)) {\n tools.push(dragTool(resolveTarget));\n }\n return tools;\n}\n\nfunction scrollTool(resolveTarget: ResolvePageTarget): ClientTool {\n return {\n name: \"scroll_to\",\n description:\n \"Scroll a target into view. `target` is `top`, `bottom`, or a CSS \" +\n \"selector / page-map element id. Read-only: it changes nothing on the page.\",\n parameters: {\n type: \"object\",\n properties: { target: { type: \"string\" } },\n required: [\"target\"],\n [X_SUMMARY_KEY]: \"Scroll into view\",\n },\n handler: (args) => {\n const target = String(args[\"target\"] ?? \"\");\n if (target === \"top\" || target === \"bottom\") {\n const top = target === \"top\" ? 0 : document.body.scrollHeight;\n window.scrollTo({ top, behavior: \"smooth\" });\n return { scrolled: true, target };\n }\n const element = resolveTarget(target);\n if (element === null) {\n throw new Error(`no element matching \"${target}\"`);\n }\n scrollIntoCenterView(element);\n return { scrolled: true, target };\n },\n };\n}\n\nfunction dragTool(resolveTarget: ResolvePageTarget): ClientTool {\n return {\n name: \"drag_and_drop\",\n description:\n \"Drag the `from` element onto the `to` element (CSS selectors or page-map \" +\n \"element ids), firing the page's native drag-and-drop. Use for reordering \" +\n \"sortable lists. The page decides what the drop commits.\",\n parameters: {\n type: \"object\",\n properties: { from: { type: \"string\" }, to: { type: \"string\" } },\n required: [\"from\", \"to\"],\n [X_SUMMARY_KEY]: \"Drag and drop\",\n },\n handler: (args) => {\n const fromTarget = String(args[\"from\"] ?? \"\");\n const toTarget = String(args[\"to\"] ?? \"\");\n const from = resolveTarget(fromTarget);\n if (from === null) {\n throw new Error(`no element matching \"${fromTarget}\"`);\n }\n const to = resolveTarget(toTarget);\n if (to === null) {\n throw new Error(`no element matching \"${toTarget}\"`);\n }\n dispatchDragSequence(from, to);\n return { dragged: true, from: fromTarget, to: toTarget };\n },\n };\n}\n\n/** Fire the HTML5 drag sequence, sharing one {@link DataTransfer} attached to each event explicitly. */\nfunction dispatchDragSequence(from: HTMLElement, to: HTMLElement): void {\n const dataTransfer = new DataTransfer();\n fire(from, \"dragstart\", dataTransfer);\n fire(to, \"dragenter\", dataTransfer);\n fire(to, \"dragover\", dataTransfer);\n fire(to, \"drop\", dataTransfer);\n fire(from, \"dragend\", dataTransfer);\n}\n\nfunction fire(target: HTMLElement, type: string, dataTransfer: DataTransfer): void {\n const event = new Event(type, { bubbles: true, cancelable: true }) as Event & {\n dataTransfer: DataTransfer;\n };\n event.dataTransfer = dataTransfer;\n target.dispatchEvent(event);\n}\n", "import type { Context } from \"@ag-ui/core\";\nimport { PAGE_MAP_CONTEXT } from \"../constants.js\";\n\n/**\n * A compact snapshot of the current page's actionable surface (field\n * names/types/labels, button labels+handles \u2014 not values). Host-defined shape;\n * kept small because it rides in every `RunAgentInput.context`.\n */\nexport type PageMap = Record<string, unknown>;\n\n/**\n * Build the per-run context entry for the page map.\n *\n * Returns a single `page_map` context item when auto-injection is on and a\n * provider is set, else nothing. Recomputed each run so it reflects the page\n * the agent is currently looking at.\n */\nexport function createPageMapContext(\n getPageMap: (() => PageMap) | null,\n autoInject: boolean,\n): Context[] {\n if (!autoInject || getPageMap === null) {\n return [];\n }\n return [{ description: PAGE_MAP_CONTEXT, value: JSON.stringify(getPageMap()) }];\n}\n", "import { X_DESTRUCTIVE_KEY, X_SUMMARY_KEY } from \"../constants.js\";\nimport type { ClientTool } from \"./client_tool_registry.js\";\n\n/**\n * A binding from a named piece of host page state to agent tools.\n *\n * Ergonomic sugar over `registerTool` for SPA state (Redux/Zustand/signals):\n * generates a read tool and, when `write` is given, a destructive set tool.\n *\n * Not AG-UI shared state. `STATE_SNAPSHOT` / `STATE_DELTA` are protocol events\n * carrying state between agent and client; these are ordinary client tools the\n * agent calls like any other.\n */\nexport interface PageState {\n /** Base name; tools become `read_<name>` and `set_<name>`. */\n readonly name: string;\n /** Returns the current state value. */\n readonly read: () => unknown;\n /** Mutates the state from the agent-supplied args. Omit for read-only. */\n readonly write?: (args: Record<string, unknown>) => unknown;\n /** JSON-Schema for the set tool's args. Defaults to an open object. */\n readonly schema?: Record<string, unknown>;\n}\n\n/**\n * Build the tools for a {@link PageState}: always a `read_<name>` (read-only)\n * tool, plus a `set_<name>` (`x-destructive`) tool when `write` is supplied.\n */\nexport function createPageStateTools(binding: PageState): ClientTool[] {\n const tools: ClientTool[] = [\n {\n name: `read_${binding.name}`,\n description: `Read the \"${binding.name}\" state.`,\n parameters: {\n type: \"object\",\n properties: {},\n required: [],\n [X_SUMMARY_KEY]: `Read ${binding.name}`,\n },\n handler: () => binding.read(),\n },\n ];\n const write = binding.write;\n if (write !== undefined) {\n tools.push({\n name: `set_${binding.name}`,\n description: `Update the \"${binding.name}\" state.`,\n parameters: {\n ...(binding.schema ?? { type: \"object\" }),\n [X_DESTRUCTIVE_KEY]: true,\n [X_SUMMARY_KEY]: `Update ${binding.name}`,\n },\n handler: (args) => write(args),\n });\n }\n return tools;\n}\n", "/**\n * One entry in the server-tool catalog served by django-ag-ui's `tools/`\n * endpoint and fetched via the `data-tools-url` attribute.\n */\nexport interface ToolCatalogEntry {\n /** The tool's wire name (matches the name in `TOOL_CALL_START`). */\n readonly name: string;\n /** A friendly card label for the tool. */\n readonly summary: string;\n /** Optional longer blurb (e.g. for a tooltip). */\n readonly description?: string;\n}\n\n/**\n * Parse a fetched tool catalog into a `name \u2192 entry` map, skipping any entry\n * that isn't a `{ name: string, summary: string }` object. Tolerant by design:\n * a malformed payload yields an empty map rather than throwing, and an\n * optional field of the wrong type costs that field rather than the entry.\n * Whole entries are kept, so a consumer can reach `description`.\n */\nexport function parseToolCatalog(data: unknown): Record<string, ToolCatalogEntry> {\n const out: Record<string, ToolCatalogEntry> = {};\n if (!Array.isArray(data)) {\n return out;\n }\n for (const entry of data) {\n if (entry === null || typeof entry !== \"object\") {\n continue;\n }\n const record = entry as Record<string, unknown>;\n const name = record[\"name\"];\n const summary = record[\"summary\"];\n const description = record[\"description\"];\n if (typeof name === \"string\" && typeof summary === \"string\") {\n // `exactOptionalPropertyTypes`: absent is not the same type as present-as-undefined.\n out[name] =\n typeof description === \"string\" ? { name, summary, description } : { name, summary };\n }\n }\n return out;\n}\n", "import { X_NAVIGATES_KEY, X_SUMMARY_KEY } from \"../constants.js\";\nimport type { ClientTool } from \"./client_tool_registry.js\";\n\n/** A single navigable route the host declares for the agent. */\nexport interface Route {\n /** Stable id the agent uses with `navigate_to_route`. */\n readonly id: string;\n /**\n * The URL path to navigate to. May contain `:name` placeholders for dynamic\n * segments (e.g. `/admin/shop/book/:pk/change/`), which the agent fills via\n * `navigate_to_route`'s `params` argument.\n */\n readonly path: string;\n /** Human label shown to the agent. */\n readonly title?: string;\n /** Optional grouping (e.g. an app or section). */\n readonly group?: string;\n /** Optional longer description of when to use the route. */\n readonly description?: string;\n}\n\n/** The host-declared catalog of navigable routes. */\nexport type RouteMap = readonly Route[];\n\n/** A route enriched with its derived dynamic-segment parameter names. */\nexport interface RouteWithParams extends Route {\n /** Names of the `:name` placeholders in {@link Route.path} (may be empty). */\n readonly pathParams: readonly string[];\n}\n\nconst PATH_PARAM_RE = /:([A-Za-z_][A-Za-z0-9_]*)/g;\n\n/** The `:name` path-parameter names declared in a path template, in order. */\nfunction pathParamNames(path: string): string[] {\n // Slicing the match avoids an uncoverable `undefined` guard on the capture group.\n return [...path.matchAll(PATH_PARAM_RE)].map((match) => match[0].slice(1));\n}\n\n/**\n * Substitute `:name` placeholders in `path` from `params`.\n *\n * Returns the concrete path plus the params no placeholder consumed, for the\n * caller to append as a query string. Throws (naming `routeId`) when a declared\n * path param is missing or empty \u2014 a half-filled path must never be navigated\n * to.\n */\nfunction fillPath(\n routeId: string,\n path: string,\n params: Record<string, unknown>,\n): { path: string; leftover: Record<string, unknown> } {\n const leftover: Record<string, unknown> = { ...params };\n const filled = path.replace(PATH_PARAM_RE, (_match, name: string) => {\n const value = params[name];\n if (value === undefined || value === null || String(value) === \"\") {\n throw new Error(`route \"${routeId}\" requires path param \"${name}\"`);\n }\n delete leftover[name];\n return encodeURIComponent(String(value));\n });\n return { path: filled, leftover };\n}\n\n/** Append `params` to `path` as a query string (no-op when empty). */\nfunction withQuery(path: string, params: Record<string, unknown>): string {\n const usp = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n usp.set(key, String(value));\n }\n const query = usp.toString();\n return query === \"\" ? path : `${path}?${query}`;\n}\n\n/**\n * The built-in `route.*` tools, bound to live getters so a host can set\n * `routeMap` / `navigate` before or after mount.\n *\n * `list_routes` is read-only and advertises each route's `pathParams` so the\n * model knows what to supply. `navigate_to_route` fills those params, appends\n * the rest as a query string, and is stamped `x-navigates` so an MPA reload\n * checkpoints and resumes; with a host `navigate(path)` callback (an SPA) it\n * routes client-side and the run loop continues instead.\n */\nexport function createRouteTools(\n getRouteMap: () => RouteMap,\n getNavigate: () => ((path: string) => void) | null,\n): ClientTool[] {\n return [\n {\n name: \"list_routes\",\n description:\n \"List the routes the app can navigate to. Each route's `pathParams` \" +\n \"names the dynamic segments to pass as `params` to `navigate_to_route`.\",\n parameters: { type: \"object\", properties: {}, required: [], [X_SUMMARY_KEY]: \"List pages\" },\n handler: (): RouteWithParams[] =>\n getRouteMap().map((route) => ({ ...route, pathParams: pathParamNames(route.path) })),\n },\n {\n name: \"navigate_to_route\",\n description:\n \"Navigate to one of the app's routes by its id, filling any dynamic \" +\n \"`:name` path segments (and extra query params) from `params`.\",\n parameters: {\n type: \"object\",\n properties: {\n route_id: { type: \"string\" },\n params: { type: \"object\" },\n },\n required: [\"route_id\"],\n [X_NAVIGATES_KEY]: true,\n [X_SUMMARY_KEY]: \"Navigate\",\n },\n handler: (args) => {\n const routeId = args[\"route_id\"];\n const route = getRouteMap().find((r) => r.id === routeId);\n if (route === undefined) {\n throw new Error(`unknown route \"${String(routeId)}\"`);\n }\n const provided = (args[\"params\"] as Record<string, unknown> | undefined) ?? {};\n const { path: filledPath, leftover } = fillPath(route.id, route.path, provided);\n const path = withQuery(filledPath, leftover);\n const navigate = getNavigate();\n if (navigate !== null) {\n navigate(path);\n } else {\n window.location.assign(path);\n }\n return { navigated: true, path };\n },\n },\n ];\n}\n", "/**\n * Draw a {@link ChartSpec} as SVG.\n *\n * Every node is built with `createElement`, never parsed from a string, so this\n * path never reaches the markdown sanitiser and cannot be widened by model\n * output. That is the argument for taking a *spec* rather than markup: the model\n * chooses the numbers, this module chooses the DOM. It is why a chart can be\n * shown on a surface that keeps `img` off by default, a model-controlled URL\n * being a zero-click exfiltration channel.\n *\n * Hand-rolled rather than a charting library, and the difference is not\n * marginal: the whole renderer costs single-digit kilobytes where a library\n * costs roughly half this bundle again, in a component distributed over a CDN.\n *\n * **The drawing is sized in CSS pixels, not scaled to them.** An SVG with a\n * fixed viewBox and `width: 100%` is a picture the browser magnifies: widen the\n * panel and every stroke, every label and the whole frame grow with it. So the\n * geometry is computed for the width the block actually has, one user unit to\n * one CSS pixel, and recomputed when that width changes -- a 10px label is\n * 10px at every size the block is given.\n *\n * How wide the block is allowed to get is the stylesheet's question, not this\n * module's, and the answer there is that a chart stops at its own width rather\n * than stretching with the panel, the way a message does. The two halves are\n * separate on purpose: this one keeps a chart from being magnified, that one\n * keeps it from being stretched, and a host that raises the cap gets a bigger\n * chart with the same 10px labels rather than a magnified one.\n */\n\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\n/** One named series of numbers. */\nexport interface ChartSeries {\n readonly label: string;\n readonly points: readonly number[];\n}\n\n/** How a spec is drawn. */\nexport type ChartKind = \"bar\" | \"line\" | \"pie\" | \"scatter\" | \"stacked\";\n\n/** A chart, as data. */\nexport interface ChartSpec {\n readonly kind: ChartKind;\n readonly title?: string;\n readonly labels: readonly string[];\n readonly series: readonly ChartSeries[];\n}\n\n/** The frame a chart is drawn into, in CSS pixels. */\ninterface Geometry {\n readonly width: number;\n readonly height: number;\n /** The plotting area inside the padding. */\n readonly plotW: number;\n readonly plotH: number;\n}\n\nconst PAD = { top: 20, right: 12, bottom: 30, left: 44 };\n\n/**\n * The width drawn before the block has been measured -- while it is still\n * detached, and in a caller that never puts it in a document at all. It is the\n * width this renderer drew at unconditionally before it could measure, so a\n * chart that is never measured looks exactly as it always did.\n */\nconst DEFAULT_WIDTH = 480;\n\n/**\n * The narrowest frame worth computing. Below this the SVG scales down as it\n * always did, which is the right answer at the bottom end: a 200px chart with\n * 10px labels has no room for the labels either way, and shrinking them keeps\n * the shape readable.\n */\nconst MIN_WIDTH = 220;\n\n/**\n * How tall a chart is for its width, and the band that holds. The ratio is the\n * old fixed 480x220 frame, so the default width draws precisely what it drew\n * before; the band is what stops a wide panel from turning a chart into a\n * banner or a narrow one into a strip.\n */\nconst HEIGHT_RATIO = 220 / 480;\nconst MIN_HEIGHT = 160;\nconst MAX_HEIGHT = 320;\n\n/**\n * The step a measured width is rounded to before it is redrawn.\n *\n * The SVG keeps `width=\"100%\"`, so it fills its block exactly whatever the\n * viewBox says; rounding the viewBox to 8px therefore costs at most a 3%\n * scale at the narrow end and nothing anyone can see, while cutting the\n * redraws during a panel drag from one per pixel to one per eight.\n */\nconst WIDTH_STEP = 8;\n\n/** A rough advance width per character for the 10px axis font. */\nconst AXIS_CHAR_WIDTH = 5.6;\n\n// Read from the theme's palette rather than a fixed ramp. The private alias\n// reads the host's --ag-ui-chart-N first (see token_styles), so a host's\n// colour wins over any theme's, and a theme can still supply its own.\nconst SERIES_COLORS: readonly string[] = [\n \"var(--_chart-1)\",\n \"var(--_chart-2)\",\n \"var(--_chart-3)\",\n \"var(--_chart-4)\",\n \"var(--_chart-5)\",\n \"var(--_chart-6)\",\n];\n\n/** The colour for series `index`, wrapping when there are more series than colours. */\nexport function seriesColor(index: number): string {\n // Cast rather than a `??` fallback: the modulo guarantees a hit, so a\n // fallback would be a branch no test could ever reach.\n return SERIES_COLORS[index % SERIES_COLORS.length] as string;\n}\n\n/** The frame for a block of this width. */\nfunction geometryFor(width: number): Geometry {\n const w = Math.max(MIN_WIDTH, width);\n const h = Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, Math.round(w * HEIGHT_RATIO)));\n return {\n width: w,\n height: h,\n plotW: w - PAD.left - PAD.right,\n plotH: h - PAD.top - PAD.bottom,\n };\n}\n\nfunction el<K extends keyof SVGElementTagNameMap>(\n name: K,\n attrs: Record<string, string | number>,\n): SVGElementTagNameMap[K] {\n const node = document.createElementNS(SVG_NS, name);\n for (const [key, value] of Object.entries(attrs)) {\n node.setAttribute(key, String(value));\n }\n return node;\n}\n\nfunction text(value: string, attrs: Record<string, string | number>): SVGTextElement {\n const node = el(\"text\", {\n \"font-size\": 10,\n fill: \"currentColor\",\n \"fill-opacity\": 0.65,\n ...attrs,\n });\n // `textContent`, so a model-supplied label is text and never markup.\n node.textContent = value;\n return node;\n}\n\n/** Every running subtotal a stack passes through, column by column. */\nfunction stackRunning(spec: ChartSpec): number[] {\n const seen: number[] = [];\n spec.labels.forEach((_label, i) => {\n let running = 0;\n for (const series of spec.series) {\n running += series.points[i] ?? 0;\n seen.push(running);\n }\n });\n return seen;\n}\n\nfunction extent(spec: ChartSpec): { min: number; max: number } {\n // A stack's extent has to cover every *running subtotal*, not just the column\n // totals: with mixed signs the running value swings wider than the total it\n // ends on, and scaling to the total alone puts segments far off the canvas.\n const values =\n spec.kind === \"stacked\"\n ? stackRunning(spec)\n : spec.series.flatMap((series) => [...series.points]);\n const max = Math.max(0, ...values);\n const min = Math.min(0, ...values);\n // A flat series would divide by zero when scaling; give it a nominal span so\n // it draws as a flat line rather than vanishing.\n return max === min ? { min, max: max + 1 } : { min, max };\n}\n\nfunction scaleY(value: number, min: number, max: number, geo: Geometry): number {\n return PAD.top + geo.plotH - ((value - min) / (max - min)) * geo.plotH;\n}\n\nfunction bandCentre(index: number, count: number, geo: Geometry): number {\n const step = geo.plotW / count;\n return PAD.left + step * index + step / 2;\n}\n\n/**\n * Draw every nth label, for the smallest n whose labels have room.\n *\n * Axis text is a fixed 10px now rather than something that shrank with the\n * frame, so at the narrow end the labels are the first thing to collide -- and\n * a smear of overlapping words says less than half as many words with space\n * around them. The character estimate only has to be good enough to pick a\n * step; measuring text properly would mean laying it out first.\n */\nfunction labelStride(labels: readonly string[], geo: Geometry): number {\n const band = geo.plotW / labels.length;\n const widest = Math.max(...labels.map((label) => label.length)) * AXIS_CHAR_WIDTH;\n return Math.max(1, Math.ceil(widest / band));\n}\n\nfunction drawAxes(\n svg: SVGSVGElement,\n spec: ChartSpec,\n geo: Geometry,\n min: number,\n max: number,\n): void {\n for (const value of [min, max]) {\n const y = scaleY(value, min, max, geo);\n svg.appendChild(\n el(\"line\", {\n x1: PAD.left,\n y1: y,\n x2: geo.width - PAD.right,\n y2: y,\n stroke: \"currentColor\",\n \"stroke-opacity\": value === min ? 0.35 : 0.12,\n }),\n );\n svg.appendChild(\n text(String(Math.round(value)), { x: PAD.left - 6, y: y + 4, \"text-anchor\": \"end\" }),\n );\n }\n const stride = labelStride(spec.labels, geo);\n spec.labels.forEach((label, i) => {\n if (i % stride !== 0) {\n return;\n }\n svg.appendChild(\n text(label, {\n x: bandCentre(i, spec.labels.length, geo),\n y: geo.height - PAD.bottom + 16,\n \"text-anchor\": \"middle\",\n }),\n );\n });\n}\n\nfunction drawBars(\n svg: SVGSVGElement,\n spec: ChartSpec,\n geo: Geometry,\n min: number,\n max: number,\n): void {\n const step = geo.plotW / spec.labels.length;\n const width = (step * 0.7) / spec.series.length;\n const base = scaleY(min, min, max, geo);\n spec.series.forEach((series, s) => {\n series.points.forEach((value, i) => {\n const y = scaleY(value, min, max, geo);\n svg.appendChild(\n el(\"rect\", {\n x: PAD.left + step * i + step * 0.15 + width * s,\n y,\n width,\n height: Math.max(1, base - y),\n fill: seriesColor(s),\n rx: 2,\n }),\n );\n });\n });\n}\n\nfunction drawStacked(\n svg: SVGSVGElement,\n spec: ChartSpec,\n geo: Geometry,\n min: number,\n max: number,\n): void {\n const step = geo.plotW / spec.labels.length;\n const width = step * 0.7;\n // Indexed by the same `i` it was built from, so every read is a hit; cast\n // rather than defaulting, which would add a branch nothing can reach.\n const running = spec.labels.map(() => 0);\n spec.series.forEach((series, s) => {\n series.points.forEach((value, i) => {\n // `?? 0` rather than a cast: `renderChart` is exported, so a caller can\n // hand it a series carrying more points than there are labels, which\n // `chartSpecFrom` would have refused. The cast that used to be here\n // claimed that could not happen and wrote `y=\"NaN\"` into the DOM when it\n // did.\n const from = running[i] ?? 0;\n const to = from + value;\n running[i] = to;\n const y = scaleY(to, min, max, geo);\n svg.appendChild(\n el(\"rect\", {\n x: PAD.left + step * i + step * 0.15,\n y,\n width,\n height: Math.max(1, scaleY(from, min, max, geo) - y),\n fill: seriesColor(s),\n }),\n );\n });\n });\n}\n\nfunction drawLines(\n svg: SVGSVGElement,\n spec: ChartSpec,\n geo: Geometry,\n min: number,\n max: number,\n): void {\n spec.series.forEach((series, s) => {\n const points = series.points\n .map(\n (value, i) => `${bandCentre(i, spec.labels.length, geo)},${scaleY(value, min, max, geo)}`,\n )\n .join(\" \");\n svg.appendChild(\n el(\"polyline\", {\n points,\n fill: \"none\",\n stroke: seriesColor(s),\n \"stroke-width\": 2,\n \"stroke-linejoin\": \"round\",\n }),\n );\n });\n}\n\nfunction drawScatter(\n svg: SVGSVGElement,\n spec: ChartSpec,\n geo: Geometry,\n min: number,\n max: number,\n): void {\n spec.series.forEach((series, s) => {\n series.points.forEach((value, i) => {\n svg.appendChild(\n el(\"circle\", {\n cx: bandCentre(i, spec.labels.length, geo),\n cy: scaleY(value, min, max, geo),\n r: 4,\n fill: seriesColor(s),\n \"fill-opacity\": 0.85,\n }),\n );\n });\n });\n}\n\n/**\n * Pie draws the **first** series' points as shares of their own total, one\n * wedge per label -- the only kind whose slices are the labels rather than the\n * series, so a second series has nowhere to go and is ignored rather than\n * silently summed into the first.\n */\nfunction drawPie(svg: SVGSVGElement, points: readonly number[], geo: Geometry): void {\n const total = points.reduce((sum, value) => sum + value, 0);\n const cx = geo.width / 2;\n const cy = PAD.top + geo.plotH / 2;\n const r = Math.min(geo.plotW, geo.plotH) / 2;\n if (total === 0) {\n // Every share is zero, so there is no wedge to draw and a full circle would\n // claim one slice owns everything. An outline says \"nothing here\" honestly.\n svg.appendChild(\n el(\"circle\", { cx, cy, r, fill: \"none\", stroke: \"currentColor\", \"stroke-opacity\": 0.3 }),\n );\n return;\n }\n let angle = -Math.PI / 2;\n points.forEach((value, i) => {\n const sweep = (value / total) * Math.PI * 2;\n const end = angle + sweep;\n // A wedge of the whole circle cannot be drawn as one arc (start and end\n // coincide, so the path collapses); draw it as a plain circle instead.\n if (sweep >= Math.PI * 2) {\n svg.appendChild(el(\"circle\", { cx, cy, r, fill: seriesColor(i) }));\n } else {\n const x1 = cx + r * Math.cos(angle);\n const y1 = cy + r * Math.sin(angle);\n const x2 = cx + r * Math.cos(end);\n const y2 = cy + r * Math.sin(end);\n const large = sweep > Math.PI ? 1 : 0;\n svg.appendChild(\n el(\"path\", {\n d: `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2} Z`,\n fill: seriesColor(i),\n }),\n );\n }\n angle = end;\n });\n}\n\n/** The whole drawing for one spec at one width. */\nfunction drawSvg(spec: ChartSpec, geo: Geometry): SVGSVGElement {\n const svg = el(\"svg\", {\n viewBox: `0 0 ${geo.width} ${geo.height}`,\n width: \"100%\",\n role: \"img\",\n });\n svg.setAttribute(\"aria-label\", spec.title ?? `${spec.kind} chart`);\n\n if (spec.kind === \"pie\") {\n // `series[0]` is guaranteed by renderChart's early return; a pie's slices\n // are its labels, so a second series has nowhere to go and is ignored\n // rather than silently summed into the first. Negative shares are floored,\n // since a wedge cannot sweep backwards.\n const first = spec.series[0] as ChartSeries;\n drawPie(\n svg,\n first.points.map((value) => Math.max(0, value)),\n geo,\n );\n return svg;\n }\n const { min, max } = extent(spec);\n drawAxes(svg, spec, geo, min, max);\n if (spec.kind === \"bar\") {\n drawBars(svg, spec, geo, min, max);\n } else if (spec.kind === \"stacked\") {\n drawStacked(svg, spec, geo, min, max);\n } else if (spec.kind === \"line\") {\n drawLines(svg, spec, geo, min, max);\n } else {\n drawScatter(svg, spec, geo, min, max);\n }\n return svg;\n}\n\nfunction buildLegend(entries: readonly string[]): HTMLDivElement | null {\n if (entries.length < 2) {\n return null;\n }\n const row = document.createElement(\"div\");\n row.className = \"chart-legend\";\n row.setAttribute(\"part\", \"chart-legend\");\n entries.forEach((label, i) => {\n const item = document.createElement(\"span\");\n item.className = \"chart-legend-item\";\n const swatch = document.createElement(\"span\");\n swatch.className = \"chart-legend-swatch\";\n swatch.style.background = seriesColor(i);\n item.append(swatch, document.createTextNode(label));\n row.appendChild(item);\n });\n return row;\n}\n\n/**\n * Redraw `block`'s chart whenever the width it has to fill changes.\n *\n * Nothing disconnects this, and nothing needs to: the observer is referenced\n * only by the closure that made it, and an active observer holds its target\n * rather than the other way round -- so a chart removed from the transcript\n * takes its observer with it.\n *\n * The block's own width is read rather than the entry's box, because that is\n * the number the redraw has to match and the entry carries several.\n */\nfunction fitToWidth(block: HTMLElement, redraw: (width: number) => void): void {\n const observer = new ResizeObserver(() => {\n redraw(Math.round(block.clientWidth / WIDTH_STEP) * WIDTH_STEP);\n });\n observer.observe(block);\n}\n\n/**\n * Render one spec as a self-contained block, or `null` when it says nothing.\n *\n * A spec with no labels or no series is not drawn: an empty frame reads as\n * \"there is no data\" when the truth is \"the caller sent nothing\", and the two\n * deserve different answers.\n *\n * The block returned is already drawn at {@link DEFAULT_WIDTH} and redraws\n * itself once it is in a document and knows how wide it really is, so a caller\n * appends it exactly as before and never has to say how big it should be.\n */\nexport function renderChart(spec: ChartSpec): HTMLDivElement | null {\n if (spec.labels.length === 0 || spec.series.length === 0) {\n return null;\n }\n const block = document.createElement(\"div\");\n block.className = \"chart-block\";\n block.setAttribute(\"part\", \"chart-block\");\n\n if (spec.title !== undefined && spec.title !== \"\") {\n const heading = document.createElement(\"div\");\n heading.className = \"chart-title\";\n heading.setAttribute(\"part\", \"chart-title\");\n heading.textContent = spec.title;\n block.appendChild(heading);\n }\n\n let width = DEFAULT_WIDTH;\n let svg = drawSvg(spec, geometryFor(width));\n block.appendChild(svg);\n\n // Pie's slices are its labels; every other kind's are its series.\n const legend = buildLegend(\n spec.kind === \"pie\" ? spec.labels : spec.series.map((series) => series.label),\n );\n if (legend !== null) {\n block.appendChild(legend);\n }\n\n fitToWidth(block, (measured) => {\n if (measured === width) {\n return;\n }\n width = measured;\n const next = drawSvg(spec, geometryFor(width));\n svg.replaceWith(next);\n svg = next;\n });\n return block;\n}\n", "/**\n * Narrow untrusted input into a {@link ChartSpec}.\n *\n * Both arrival routes are untrusted in the same way \u2014 a model writes one, a\n * server the other \u2014 so neither is taken on shape. Kept out of the renderer\n * because the renderer's job is drawing, and a value that reaches it has\n * already been vouched for.\n */\n\nimport type { ChartKind, ChartSpec } from \"./chart_block.js\";\n\nconst KINDS: readonly ChartKind[] = [\"bar\", \"line\", \"pie\", \"scatter\", \"stacked\"];\n\n/**\n * Most points a spec may carry, across every series.\n *\n * Not a taste limit. `Math.max(0, ...values)` throws `RangeError` on a large\n * enough spread, and the renderer runs inside the history replay, where a throw\n * abandons the replay and takes every later turn of the transcript with it \u2014\n * permanently, on every reload. A chart nobody can read is a far smaller\n * problem than a conversation that silently loses its tail.\n */\nconst MAX_POINTS = 20_000;\n\n/**\n * Whether a spec's *labels* are cheap enough to draw.\n *\n * `MAX_POINTS` bounds the data; this bounds the DOM. Every label produces an\n * axis text node whatever the series count, so a spec well inside the point\n * budget can still emit tens of thousands of nodes and block the main thread \u2014\n * again on every reload, since it is in the transcript. Kept separate because\n * the two limits answer different questions and a single number cannot.\n */\nconst MAX_LABELS = 2_000;\n\n/**\n * Largest magnitude a point may carry.\n *\n * `Number.isFinite` is not enough on its own: two finite extremes still give an\n * infinite *range*, and `(value - min) / Infinity` is `NaN`, which reaches the\n * DOM as `y=\"NaN\"`. Bounding the values bounds the range.\n */\nconst MAX_MAGNITUDE = 1e15;\n\nfunction asKind(value: unknown): ChartKind {\n // Anything unrecognised falls back to `bar` rather than refusing the spec: an\n // unknown kind is a caller reaching for a chart type we do not draw, and the\n // data is still worth showing.\n return KINDS.includes(value as ChartKind) ? (value as ChartKind) : \"bar\";\n}\n\nfunction asNumbers(value: unknown): number[] | null {\n if (!Array.isArray(value)) {\n return null;\n }\n const out: number[] = [];\n for (const item of value) {\n // `Number.isFinite` rather than `typeof === \"number\"`: JSON encoders render\n // NaN and Infinity as nulls or strings depending on the encoder, and either\n // would scale into a chart with no visible extent.\n if (typeof item !== \"number\" || !Number.isFinite(item)) {\n return null;\n }\n if (Math.abs(item) > MAX_MAGNITUDE) {\n return null;\n }\n out.push(item);\n }\n return out;\n}\n\nfunction asStrings(value: unknown): string[] | null {\n if (!Array.isArray(value)) {\n return null;\n }\n // `every` over an index range rather than `Array.prototype.some`, which skips\n // holes: a sparse array passed the old check and drew a chart with blank axis\n // labels, which reads as a rendering bug rather than bad input.\n for (let i = 0; i < value.length; i += 1) {\n if (typeof value[i] !== \"string\") {\n return null;\n }\n }\n return value as string[];\n}\n\n/** A well-formed spec, or `null` for anything that cannot be drawn honestly. */\nexport function chartSpecFrom(value: unknown): ChartSpec | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const raw = value as Record<string, unknown>;\n const labels = asStrings(raw[\"labels\"]);\n if (labels === null || !Array.isArray(raw[\"series\"])) {\n return null;\n }\n\n const series: { label: string; points: number[] }[] = [];\n for (const entry of raw[\"series\"]) {\n if (typeof entry !== \"object\" || entry === null) {\n return null;\n }\n const item = entry as Record<string, unknown>;\n const points = asNumbers(item[\"points\"]);\n // A series with a different number of points than there are labels would\n // silently misalign every value after the gap. A chart that is subtly wrong\n // still reads as authoritative, which is worse than no chart at all.\n if (points === null || points.length !== labels.length) {\n return null;\n }\n series.push({ label: typeof item[\"label\"] === \"string\" ? item[\"label\"] : \"\", points });\n }\n if (series.length === 0) {\n return null;\n }\n if (series.length * labels.length > MAX_POINTS || labels.length > MAX_LABELS) {\n return null;\n }\n\n const kind = asKind(raw[\"kind\"]);\n const title = raw[\"title\"];\n // The key is omitted rather than set to `undefined`: `title` is genuinely\n // optional and this tsconfig distinguishes absent from present-and-undefined.\n return typeof title === \"string\" ? { kind, title, labels, series } : { kind, labels, series };\n}\n", "/**\n * The built-in `render_chart` tool: the agent-called route to a chart.\n *\n * A thin thing on purpose. It carries no `handler` of its own beyond reporting\n * back to the model, because everything it does is drawing \u2014 which lives in\n * `render`, the half the component replays. A consumer wanting charts gets this\n * without writing a renderer; a consumer wanting something else writes their own\n * tool against the same seam.\n */\n\nimport type { ClientTool } from \"../../tools/client_tool_registry.js\";\nimport { renderChart } from \"./chart_block.js\";\nimport { chartSpecFrom } from \"./chart_spec_from.js\";\n\n/** The name the built-in chart tool registers under. */\nexport const CHART_TOOL_NAME = \"render_chart\";\n\nfunction draw(args: Record<string, unknown>): HTMLDivElement | null {\n const spec = chartSpecFrom(args);\n return spec === null ? null : renderChart(spec);\n}\n\n/** Whether these arguments would produce a chart, without producing one. */\nfunction drawable(args: Record<string, unknown>): boolean {\n const spec = chartSpecFrom(args);\n return spec !== null && spec.labels.length > 0 && spec.series.length > 0;\n}\n\nconst REJECTED =\n \"chart not rendered: expected labels (strings) and series, each with one finite number per label\";\n\n/** The built-in chart tool. */\nexport function createChartTool(): ClientTool {\n return {\n name: CHART_TOOL_NAME,\n description:\n \"Show a chart in the conversation. Supply the data and the page draws it. \" +\n \"Every series must have exactly one point per label.\",\n parameters: {\n type: \"object\",\n properties: {\n kind: { type: \"string\", enum: [\"bar\", \"line\", \"pie\", \"scatter\", \"stacked\"] },\n title: { type: \"string\" },\n labels: { type: \"array\", items: { type: \"string\" } },\n series: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n label: { type: \"string\" },\n points: { type: \"array\", items: { type: \"number\" } },\n },\n required: [\"points\"],\n },\n },\n },\n required: [\"labels\", \"series\"],\n \"x-summary\": \"Draw a chart\",\n },\n // Says what happened and nothing else; the drawing is `render`'s job. Told\n // plainly when the arguments are unusable, because the model can fix that\n // and retry \u2014 a silent no-op would leave it believing the chart is on screen.\n // Answers on what will actually be drawn, not on what validated: a spec can\n // pass validation and still have nothing to show, and reporting success\n // then would leave the model believing a chart is on screen. Asks the\n // question without building the chart, because `render` is about to build\n // the same one a moment later and drawing it twice is pure waste on a spec\n // large enough to matter.\n handler: (args: Record<string, unknown>) => (drawable(args) ? \"chart rendered\" : REJECTED),\n render: draw,\n };\n}\n", "/**\n * Reading a text selection out of the shadow tree, and shaping it for the\n * composer.\n *\n * Selection is the one DOM API shadow encapsulation genuinely broke, and it\n * broke it in two different directions. WebKit rescopes a selection made inside\n * a shadow tree to the **host** element, so `document.getSelection()` reports\n * the whole widget and none of the words; Chromium exposes the shadow nodes\n * directly, so the same call reports exactly the words. `getComposedRanges` is\n * the settled answer to both -- it hands back real endpoints for each shadow\n * root it is *given permission to see* -- but it is recent enough that the\n * direct read has to stay behind it.\n */\n\n/**\n * The longest quotation put into the composer, in characters.\n *\n * A cap rather than no cap because the point of a quotation is to say *which*\n * part of an answer the next question is about. Select-all-then-quote is a\n * gesture the transcript already answers -- it is the whole conversation, which\n * the model has -- and pasting it back costs the user tokens to say nothing.\n */\nexport const MAX_QUOTE_CHARS = 500;\n\n/** A selection worth offering to quote. */\nexport interface QuotableSelection {\n /** The selected text, trimmed. Never empty. */\n readonly text: string;\n /**\n * One **line** of the selection, for placing the affordance beside it.\n *\n * Deliberately not the selection's bounding box. See {@link lineToHangFrom}:\n * the union of a selection spanning several elements has a centre with no\n * selected text anywhere near it.\n */\n readonly rect: DOMRect;\n}\n\n/** Where a gesture ended, in viewport coordinates. */\nexport interface Point {\n readonly x: number;\n readonly y: number;\n}\n\n/** A `Selection` on an engine new enough to reach into a shadow tree. */\ntype ComposedSelection = Selection & {\n getComposedRanges?: (...args: readonly unknown[]) => readonly AbstractRange[];\n};\n\n/**\n * The current selection, when it lies wholly inside `container`.\n *\n * `roots` are the shadow roots the read is allowed to look inside, in the shape\n * `getComposedRanges` itself takes. Pass the one holding `container` for a\n * selection made in a shadow tree, or nothing at all for one made in the page.\n *\n * `near` is where the gesture ended, when a pointer made it -- it decides which\n * line of a multi-line selection the offer is hung from.\n *\n * `null` for no selection, a collapsed one, whitespace only, or one that\n * starts or ends outside `container` -- a drag that ran off the transcript and\n * into the page is not a quotation from the transcript.\n */\nexport function quotableSelection(\n container: HTMLElement,\n roots: readonly ShadowRoot[] = [],\n near?: Point,\n): QuotableSelection | null {\n for (const endpoints of endpointCandidates(roots)) {\n if (!container.contains(endpoints.startContainer)) {\n continue;\n }\n if (!container.contains(endpoints.endContainer)) {\n continue;\n }\n // A live `Range` regardless of what the engine handed back: `getComposedRanges`\n // returns `StaticRange`s, which carry endpoints and nothing else -- no text,\n // no geometry. Both are what this is for.\n const range = document.createRange();\n range.setStart(endpoints.startContainer, endpoints.startOffset);\n range.setEnd(endpoints.endContainer, endpoints.endOffset);\n const text = renderedText(range).trim();\n if (text === \"\") {\n continue;\n }\n return { text, rect: lineToHangFrom(range, near) };\n }\n return null;\n}\n\n/**\n * Wrap `text` as a markdown blockquote, ready to be followed by a question.\n *\n * Markdown rather than a bespoke fence because the transcript renders markdown\n * and the server reads markdown: a quotation that survives both ends without a\n * convention to agree on first. The trailing blank line is what leaves the\n * caret on a fresh paragraph, which is the whole point of quoting into a\n * composer rather than sending straight away.\n */\nexport function asQuote(text: string): string {\n const lines = tidy(text);\n if (lines.length === 0) {\n return \"\";\n }\n const capped = cap(lines.join(\"\\n\"));\n const quoted = capped\n .split(\"\\n\")\n // `trimEnd` so a blank line inside the selection becomes a bare \">\" rather\n // than \"> \" -- trailing whitespace markdown treats as a line break.\n .map((line) => `> ${line}`.trimEnd())\n .join(\"\\n\");\n return `${quoted}\\n\\n`;\n}\n\n/**\n * The selection's lines, with the *markup's* whitespace taken back out.\n *\n * A selection crossing block elements carries the source's own layout with it:\n * every newline and every run of indentation between one element and the next\n * is a text node like any other. Quoting a form as marked up produced twenty-\n * four lines of which twelve were a bare \">\", the rest indented by wherever\n * they happened to sit in the HTML. That is not a quotation of anything.\n *\n * Two rules, and deliberately only two. Runs of blank lines collapse to one,\n * because the gap between two blocks is one gap however it was written. And the\n * indentation every line shares is removed, not each line's own -- a quotation\n * from a code block keeps its shape, which trimming each line would flatten.\n */\nfunction tidy(text: string): readonly string[] {\n const lines = text.split(/\\r\\n?|\\n/).map((line) => line.trimEnd());\n const indents = lines.filter((line) => line !== \"\").map(indentOf);\n const shared = indents.length === 0 ? 0 : Math.min(...indents);\n const kept: string[] = [];\n for (const line of lines) {\n const dedented = line.slice(shared);\n // No leading blank lines, and never two in a row.\n if (dedented === \"\" && (kept.length === 0 || kept[kept.length - 1] === \"\")) {\n continue;\n }\n kept.push(dedented);\n }\n while (kept[kept.length - 1] === \"\") {\n kept.pop();\n }\n return kept;\n}\n\n/** How many spaces of indentation `line` opens with. */\nfunction indentOf(line: string): number {\n return line.length - line.trimStart().length;\n}\n\n/** `text`, cut to {@link MAX_QUOTE_CHARS} if it runs past it. */\nfunction cap(text: string): string {\n return text.length > MAX_QUOTE_CHARS ? `${text.slice(0, MAX_QUOTE_CHARS).trimEnd()}...` : text;\n}\n\n/**\n * The selected text **as rendered**, which is not what `Range.toString()` says.\n *\n * `toString()` concatenates the text nodes in the range and asks no questions\n * about CSS, so a drag across an ordinary form quotes back the values of every\n * `<option>` in a closed `<select>` -- words the user has never seen, presented\n * to the model as something they pointed at. `checkVisibility()` is the\n * platform's own answer to \"is this actually rendered\", and it reports exactly\n * those options as hidden.\n *\n * Older engines without it keep the previous behaviour rather than a guess:\n * quoting a few invisible words is a smaller failure than dropping visible ones\n * because a hand-rolled visibility test was wrong.\n */\nfunction renderedText(range: Range): string {\n let text = \"\";\n for (const node of textNodesIn(range)) {\n // The element carries the styles; the text node has none of its own.\n const parent = node.parentElement as HTMLElement;\n if (!isRendered(parent)) {\n continue;\n }\n // The end nodes are only partly inside the range; everything between them\n // is wholly inside it.\n const from = node === range.startContainer ? range.startOffset : 0;\n const to = node === range.endContainer ? range.endOffset : node.data.length;\n text += collapse(node.data.slice(from, to), parent);\n }\n return text;\n}\n\n/**\n * Squeeze the runs of spaces the renderer squeezes, and keep the ones it keeps.\n *\n * Indentation between block elements is markup, not content: it is in the DOM\n * as text nodes and it is on screen as nothing at all, because a collapsing\n * `white-space` reduces it. Carrying it into a quotation is not merely untidy --\n * four leading spaces inside a blockquote is a markdown **code block**, so a\n * form quoted as marked up renders as source listing.\n *\n * Newlines survive on purpose, where CSS would collapse those too. They are the\n * only record left of where one block ended and the next began, and a quotation\n * of six form rows run together on one line is worse than one that keeps them\n * apart. Preformatted text is passed through untouched: there the indentation\n * *is* the content.\n */\nfunction collapse(text: string, parent: HTMLElement): string {\n if (PREFORMATTED.has(whiteSpaceOf(parent))) {\n return text;\n }\n return (\n text\n // Whitespace *around* a newline goes with it. Leaving a space behind\n // would indent every line of the quotation by one, for nothing.\n .replace(/[^\\S\\n]*\\n[^\\S\\n]*/g, \"\\n\")\n .replace(/[^\\S\\n]+/g, \" \")\n );\n}\n\n/** The `white-space` values under which every space is content. */\nconst PREFORMATTED = new Set([\"pre\", \"pre-wrap\", \"break-spaces\"]);\n\n/** The computed `white-space` of `element`, or `\"\"` where it cannot be read. */\nfunction whiteSpaceOf(element: HTMLElement): string {\n return window.getComputedStyle(element).whiteSpace;\n}\n\n/** Every text node the range touches, in document order. */\nfunction textNodesIn(range: Range): readonly Text[] {\n const root = range.commonAncestorContainer;\n // A selection inside a single text node has that node as its own common\n // ancestor, and a `TreeWalker` never visits its root.\n if (root.nodeType === Node.TEXT_NODE) {\n return [root as Text];\n }\n const found: Text[] = [];\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {\n // The walker covers the whole subtree, which reaches past both ends of the\n // range -- a sibling paragraph above the selection is in it too.\n if (range.intersectsNode(node)) {\n found.push(node as Text);\n }\n }\n return found;\n}\n\n/** Whether `element` is actually drawn, where the engine will say. */\nfunction isRendered(element: HTMLElement): boolean {\n if (typeof element.checkVisibility !== \"function\") {\n return true;\n }\n return element.checkVisibility({\n contentVisibilityAuto: true,\n opacityProperty: true,\n visibilityProperty: true,\n });\n}\n\n/**\n * The line of the selection to hang the offer from.\n *\n * **Not the bounding box.** A drag from a narrow column of a form down to a\n * full-width line running under the chat panel beside it produced a union\n * reaching from the column's left edge to the far end of that line -- and its\n * centre landed most of the way across the page, behind the panel, on a line\n * the user had not been looking at, while the pointer had let go by the column.\n *\n * Note what the fix is *not*: that centre was over selected text. It was over\n * selected text nobody could see. A union is a shape the selection does not\n * have, so no point derived from it belongs to any particular line.\n *\n * `near` is where the pointer let go. The line under it is where the user is\n * looking, and it needs no engine-specific way to ask which end of the\n * selection is its focus -- which the shadow-aware read does not carry anyway.\n * Without a pointer -- a keyboard selection -- the first line is the one that\n * exists whichever way the selection was made.\n *\n * The bounding box remains the fallback for a range that reports no line boxes\n * at all, which is what a DOM with no layout does.\n */\nfunction lineToHangFrom(range: Range, near: Point | undefined): DOMRect {\n const lines = [...range.getClientRects()];\n if (lines.length === 0) {\n return range.getBoundingClientRect();\n }\n if (near === undefined) {\n return lines[0] as DOMRect;\n }\n let closest = lines[0] as DOMRect;\n let shortest = distanceTo(closest, near);\n for (const line of lines.slice(1)) {\n const distance = distanceTo(line, near);\n if (distance < shortest) {\n shortest = distance;\n closest = line;\n }\n }\n return closest;\n}\n\n/** How far `point` is from the nearest edge of `rect`, or 0 inside it. */\nfunction distanceTo(rect: DOMRect, point: Point): number {\n const dx = Math.max(rect.left - point.x, 0, point.x - rect.right);\n const dy = Math.max(rect.top - point.y, 0, point.y - rect.bottom);\n return Math.hypot(dx, dy);\n}\n\n/**\n * Endpoint pairs to consider, best first.\n *\n * Both reads are offered rather than one being chosen, because which is correct\n * is a property of the engine *and* of where the user dragged: an engine that\n * rescopes to the host returns endpoints outside the transcript, and the caller\n * rejects those on the same test it uses for a selection that genuinely ran off\n * the transcript. One rule, no engine sniffing.\n */\nfunction endpointCandidates(roots: readonly ShadowRoot[]): readonly AbstractRange[] {\n const selection = window.getSelection();\n if (selection === null) {\n return [];\n }\n const candidates = [...composedRanges(selection, roots)];\n if (selection.rangeCount > 0) {\n candidates.push(selection.getRangeAt(0));\n }\n return candidates;\n}\n\n/** The shadow-aware read, or nothing on an engine that does not have it. */\nfunction composedRanges(\n selection: Selection,\n roots: readonly ShadowRoot[],\n): readonly AbstractRange[] {\n const composed = (selection as ComposedSelection).getComposedRanges;\n if (composed === undefined) {\n return [];\n }\n try {\n return composed.call(selection, { shadowRoots: roots });\n } catch {\n // The method shipped first with the shadow roots as rest parameters and\n // only later as a dictionary member, and the earlier form rejects the\n // options object outright rather than ignoring it. Lexical resolves the\n // same split the same way, by trying both shapes at runtime.\n return composed.call(selection, ...roots);\n }\n}\n", "/** Pixels between a selection and the offer to quote it. */\nconst GAP = 6;\n\n/** The box an offer is positioned in: its top-left corner and width, in viewport pixels. */\nexport interface OfferBox {\n readonly top: number;\n readonly left: number;\n readonly width: number;\n}\n\n/** Float the offer beside `rect`, above it when there is room and inside `box` horizontally. */\nexport function placeOffer(button: HTMLButtonElement, rect: DOMRect, box: OfferBox): void {\n // Unhidden first: a hidden element measures zero, and its own size decides both\n // whether it fits above the selection and how far to pull it left.\n button.hidden = false;\n const top = rect.top - box.top;\n // Selecting the first line is the ordinary case, and an offer clipped above is one nobody takes.\n const below = top < GAP + button.offsetHeight;\n button.dataset[\"below\"] = String(below);\n button.style.top = `${below ? rect.bottom - box.top + GAP : top - GAP}px`;\n const half = button.offsetWidth / 2;\n const centre = rect.left + rect.width / 2 - box.left;\n button.style.left = `${Math.min(Math.max(centre, half), box.width - half)}px`;\n}\n", "import { placeOffer } from \"./place_offer.js\";\nimport { quotableSelection } from \"./quote_selection.js\";\n\n/**\n * The same select-then-offer gesture the transcript has, in the **host page**.\n *\n * This exists because the recipe version of it is a trap, and a specific one.\n * Chrome reports the internal selection of an `<input>` or `<textarea>` through\n * `document.getSelection()` as an ordinary `Range` whose endpoints are the\n * field's *wrapper* -- not the field. So the text reads back perfectly and the\n * range is indistinguishable from a selection over the surrounding prose: a\n * host listening for a page selection quotes the user's own half-typed form\n * field back at them, and nothing about the selection says why. The only signal\n * is `document.activeElement`, which is not where anyone looks.\n *\n * That, plus \"do not fire for the widget's own transcript, which already offers\n * this\", plus \"a fixed-position affordance strands itself on the first scroll\",\n * is three non-obvious guards. Three guards is a component feature, not a\n * documentation snippet.\n */\n\n/**\n * The offer's own appearance.\n *\n * Deliberately plain and deliberately overridable: this element lands in the\n * host's page, not in our shadow tree, so it has no theme to inherit and no\n * business imposing one. Everything here is a single class a host stylesheet\n * outranks by adding one more selector.\n */\nconst OFFER_CSS = `\n.ag-ui-quote-offer {\n position: fixed;\n z-index: 2147483000;\n transform: translate(-50%, -100%);\n margin: 0;\n padding: 0.25em 0.7em;\n border: 1px solid rgb(0 0 0 / 0.15);\n border-radius: 999px;\n background: Canvas;\n color: CanvasText;\n font: inherit;\n font-size: 0.8rem;\n line-height: 1.6;\n white-space: nowrap;\n cursor: pointer;\n box-shadow: 0 2px 10px rgb(0 0 0 / 0.18);\n}\n\n.ag-ui-quote-offer[data-below=\"true\"] {\n transform: translate(-50%, 0);\n}\n`;\n\n/** A live page-side offer. */\nexport interface PageQuoteOffer {\n /** The button itself, for a host that wants to style or inspect it. */\n readonly element: HTMLButtonElement;\n /** Stop offering: every listener removed, the button and its styles gone. */\n detach(): void;\n}\n\n/** What {@link attachQuoteOffer} needs to know. */\nexport interface PageQuoteOfferOptions {\n /** Where a selection is worth offering to quote. */\n within: HTMLElement;\n /** What the offer says. */\n label: string;\n /**\n * A subtree to stay out of -- the chat widget itself.\n *\n * Its transcript runs this same gesture on the inside, so without this a\n * selection there would be offered twice and quoted twice.\n */\n exclude: Node;\n /** Take the offer. */\n onQuote: (text: string) => void;\n}\n\n/**\n * Offer to quote what the user selects inside `within`.\n *\n * Nothing is quoted until the offer is taken -- which is the whole point. An\n * automatic version of this is easy to write and horrible to use: every drag\n * made to read, to copy, or to fix a typo silently appends to whatever the user\n * was in the middle of typing.\n */\nexport function attachQuoteOffer(options: PageQuoteOfferOptions): PageQuoteOffer {\n const { within, exclude, onQuote } = options;\n\n // A constructed sheet rather than an injected `<style>`: a host with a strict\n // `style-src` drops the second one silently, leaving an unstyled pill in the\n // middle of their page. Per attachment rather than at module scope, which\n // this package forbids.\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(OFFER_CSS);\n document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];\n\n const button = document.createElement(\"button\");\n button.type = \"button\";\n button.className = \"ag-ui-quote-offer\";\n button.textContent = options.label;\n button.hidden = true;\n document.body.append(button);\n\n let quoting = \"\";\n\n const hide = (): void => {\n button.hidden = true;\n quoting = \"\";\n };\n\n const settled = (event: Event): void => {\n // The widget's own gesture, tested on the **event path** rather than on the\n // selection. The path crosses shadow boundaries and the selection does not:\n // `Node.contains` is false for a node in a shadow tree, and the shadow-aware\n // read, given no roots, hands back endpoints rescoped up into the page --\n // so both selection-side tests would let a transcript drag through here and\n // quote it a second time.\n if (event.composedPath().includes(exclude)) {\n hide();\n return;\n }\n if (fieldHasFocus()) {\n // The user is selecting inside their own form, to edit or to copy. See\n // the module comment: nothing about the range itself says so.\n hide();\n return;\n }\n // The pointer's own coordinates, where there was one: they decide which\n // line of a multi-line selection the offer hangs from.\n const near = event instanceof MouseEvent ? { x: event.clientX, y: event.clientY } : undefined;\n const selected = quotableSelection(within, [], near);\n if (selected === null) {\n hide();\n return;\n }\n quoting = selected.text;\n placeOffer(button, selected.rect, {\n top: 0,\n left: 0,\n width: document.documentElement.clientWidth,\n });\n };\n\n const onMouseDown = (event: MouseEvent): void => {\n if (!button.contains(event.target as Node)) {\n hide();\n }\n };\n\n within.addEventListener(\"mouseup\", settled);\n within.addEventListener(\"keyup\", settled);\n within.addEventListener(\"mousedown\", onMouseDown);\n // Capture, so a scrolling pane counts and not only the window: the offer is\n // positioned in viewport coordinates, so anything that moves the words out\n // from under it leaves it pointing at the wrong thing.\n document.addEventListener(\"scroll\", hide, true);\n window.addEventListener(\"resize\", hide);\n\n // Without this the press collapses the selection before the click reads it.\n button.addEventListener(\"mousedown\", (event) => {\n event.preventDefault();\n });\n button.addEventListener(\"click\", () => {\n const text = quoting;\n window.getSelection()?.removeAllRanges();\n hide();\n onQuote(text);\n });\n\n return {\n element: button,\n detach(): void {\n within.removeEventListener(\"mouseup\", settled);\n within.removeEventListener(\"keyup\", settled);\n within.removeEventListener(\"mousedown\", onMouseDown);\n document.removeEventListener(\"scroll\", hide, true);\n window.removeEventListener(\"resize\", hide);\n button.remove();\n document.adoptedStyleSheets = document.adoptedStyleSheets.filter((each) => each !== sheet);\n },\n };\n}\n\n/**\n * Whether focus is in something the user types into.\n *\n * `activeElement` rather than the selection, because the selection does not\n * say. A focused shadow host reports as the host, which is why the widget's own\n * composer is caught by the `exclude` subtree test instead -- the two guards\n * each cover the other's blind spot.\n */\nfunction fieldHasFocus(): boolean {\n const active = document.activeElement;\n if (active === null) {\n return false;\n }\n return (\n active.tagName === \"INPUT\" ||\n active.tagName === \"TEXTAREA\" ||\n (active as HTMLElement).isContentEditable === true\n );\n}\n", "/**\n * The flat table of every user-facing string the chat shell renders \u2014 labels,\n * placeholders, `aria-label`s, and `title` tooltips. A localizable seam, not a\n * framework: a host overrides any subset (via the element's `strings` property\n * or its `data-strings` JSON attribute) and the rest fall back to the English\n * defaults.\n *\n * Some values are templates carrying `{token}` placeholders the call site fills\n * in; the token names are noted on each key, and a translation must keep them\n * verbatim.\n */\nexport interface UiStrings {\n // \u2500\u2500 Header \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** Default header title (the `title-text` attribute overrides per element). */\n title: string;\n /** History button + drawer dialog label. */\n chatHistory: string;\n /** Dismiss the chat-history list and return to the conversation. */\n closeHistory: string;\n /** Placeholder in the conversation-list filter. */\n searchConversations: string;\n /** Names the row of messages waiting for the run to finish. */\n queued: string;\n /** Drops one waiting message. `{text}` is the message. */\n removeQueued: string;\n /** Shown when a filter matches nothing, unlike having no conversations. */\n noMatches: string;\n /** Heading over the conversations last active today. */\n threadsToday: string;\n /** Heading over the conversations last active in the seven days before today. */\n threadsPreviousWeek: string;\n /** Heading over every older conversation, and any with no readable date. */\n threadsOlder: string;\n /** Notice text when the agent moved its own panel out of the way. */\n chatMoved: string;\n /** Notice text when the agent collapsed its own panel. */\n chatMinimised: string;\n /** The one control a run notice may carry. */\n undo: string;\n /** New-chat button (header + drawer). */\n newChat: string;\n /** Collapse button. */\n collapse: string;\n /** Expand affordance (the launcher, and the sidebar rail). */\n expand: string;\n /** Header control that grows the open panel; apart from {@link expand}, which opens it. */\n maximize: string;\n /** The same control while the panel is maximized. */\n restore: string;\n /**\n * The launcher's label while unread answers wait behind it. Token: `{count}`.\n * Replaces {@link expand} rather than appending to it, so a translation can\n * order the two parts as its language needs.\n */\n expandUnread: string;\n /** Built-in header theme toggle (light \u21C4 dark). */\n toggleTheme: string;\n\n // \u2500\u2500 Messages region \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /**\n * The greeting over an empty conversation under `placement=\"page\"` (or an\n * `embedded` panel that opted in). Token: `{name}`, the `user-name` attribute.\n */\n greeting: string;\n /** The same greeting when the host named nobody: no `user-name`, or a blank one. */\n greetingNoName: string;\n /** `aria-label` of the scrolling message log. */\n conversation: string;\n /** The button offering to return to the foot of the transcript. */\n jumpToLatest: string;\n /** Announced when a turn starts. Screen-reader only; never rendered. */\n announceResponding: string;\n /** Announced when the answer has finished arriving. Screen-reader only. */\n announceAnswerReady: string;\n /** Announced when a card is waiting for the user's decision. Token: `{count}`. */\n announceAwaitingDecision: string;\n /** Announced when the user stopped the run. Screen-reader only. */\n announceStopped: string;\n /** Announced when the run failed. Screen-reader only. */\n announceFailed: string;\n /** `aria-label` of the \"thinking\" pending indicator, and the thoughts region's\n * header while the model is still reasoning. */\n thinking: string;\n /** The thoughts region's header once reasoning has ended, and its fallback\n * when the reasoning took under a second, too short to time. */\n thoughts: string;\n /** The thoughts region's header once reasoning has ended, naming how long it\n * took in whole seconds. Token: `{seconds}`. */\n thoughtFor: string;\n /** The muted note after a cancelled run. */\n stopped: string;\n /** Error shown when the stream drops without a terminal AG-UI event. */\n connectionLost: string;\n /**\n * Tool-result content (and card text) for a call that never produced a result\n * and that nobody refused: the run was stopped or failed first, the page\n * reloaded, or no tool here answered it. Sent to the agent, so it must not say\n * a person declined.\n */\n callNotFinished: string;\n /** Tool-result content when the user declines a confirmed action. */\n declinedAction: string;\n /** Tool-result content (and card text) when `confirmPredicate` threw, so the call was refused. */\n confirmCheckFailed: string;\n /** A navigating tool's card text while the page reloads. */\n navigating: string;\n /** Notice shown when the server replaced the conversation wholesale. */\n historyReplaced: string;\n /** Notice shown when a pushed chart could not be drawn and was removed. */\n chartUndrawable: string;\n /** Missing-placeholder skill hint. Tokens: `{title}`, `{fields}`. */\n skillNeeds: string;\n /** Notice shown when the agent condensed earlier turns. Token: `{count}`. */\n historyCompacted: string;\n /** Notice shown when the agent loads an agent skill. Token: `{name}`. */\n usingSkill: string;\n /** Notice shown on mount when the previous run never produced a response. */\n runInterrupted: string;\n /** Tool-result content (and card text) when the page moved mid-run. */\n pageMoved: string;\n /** Notice when Send ran while a file was still uploading. Token: `{n}`. */\n attachmentsStillUploading: string;\n /** Notice shown when a message was typed at an element with no `endpoint`. */\n notConnected: string;\n /** Composer hint when a run continuation was picked with an empty composer. */\n continueNeedsTurn: string;\n /** Composer hint when a run continuation was picked while a run is in flight. */\n continueWhileRunning: string;\n /**\n * Composer hint when a run continuation was picked while the stored\n * conversation is still loading.\n */\n continueWhileLoading: string;\n\n // \u2500\u2500 Composer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** `aria-label` of the message textarea. */\n message: string;\n /** Placeholder of the message textarea. */\n inputPlaceholder: string;\n /** Send button (idle composer). */\n send: string;\n /** Stop button (composer while a run is in flight). */\n stop: string;\n /** Attach-files button. */\n attachFiles: string;\n /** Mic button while idle (start recording). */\n recordVoice: string;\n /** Mic button while recording (stop + transcribe). */\n stopRecording: string;\n /** Mic button while the clip is being transcribed. */\n transcribing: string;\n /** Mic button fallback message when transcription fails. */\n transcriptionFailed: string;\n /**\n * Mic button message after a recording hit its length cap and stopped itself.\n * The clip is kept and transcribed, so this explains the silence rather than\n * reporting a loss. Token: `{n}` (the cap, in minutes).\n */\n recordingLimit: string;\n /** The place chip's tooltip while the place is sent. Token: `{label}`. */\n placeShared: string;\n /** The place chip's tooltip while the user withholds it. Token: `{label}`. */\n placeWithheld: string;\n /** The place toggle while the place is sent: pressing it withholds it. */\n placeStopSharing: string;\n /** The place toggle while the place is withheld: pressing it sends it again. */\n placeShareAgain: string;\n\n // \u2500\u2500 Tool-call card \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** Status pill while the call runs. */\n toolRunning: string;\n /** Status pill on a gated call the run deferred, waiting on a person. */\n toolDeferred: string;\n /** Status pill on success. */\n toolDone: string;\n /** Status pill on error. */\n toolError: string;\n /** Status pill on a declined call. */\n toolDeclined: string;\n /** Status pill on a call that ended without a result nobody refused. */\n toolInterrupted: string;\n /** Accessible label on the panel resize handle. */\n resizePanel: string;\n /** Note on a tool card whose call a human approved. */\n decisionApproved: string;\n /** Note on a tool card whose call a human declined. */\n decisionDeclined: string;\n /** Heading over a tool card's arguments region. */\n argumentsLabel: string;\n /** Heading over a tool card's result region when the call succeeded. */\n resultLabel: string;\n /** Heading over a tool card's result region when the call failed. */\n errorLabel: string;\n /** Heading over a tool card's result region when the call was declined. */\n declinedLabel: string;\n /** Heading over a tool card's result region when the call did not finish. */\n interruptedLabel: string;\n /** Label on the toggle that expands a tool card's body. */\n details: string;\n\n // \u2500\u2500 Tool-step group \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // The row a run's consecutive calls fold into under the default\n // data-tool-display. A group of one shows that call's own label instead, so\n // the three labels are filled with 2 or more; the notes count from 1.\n /** The group's label while a step waits on the user. Token: `{count}` (steps). */\n toolGroupSteps: string;\n /** The group's label while a step runs. Token: `{count}` (steps). */\n toolGroupWorking: string;\n /** The group's label once every step has settled. Token: `{count}` (steps). */\n toolGroupWorked: string;\n /** Note on the group's row: steps waiting on the user. Token: `{count}`. */\n toolGroupWaiting: string;\n /** Note on the group's row: steps that failed. Token: `{count}`. */\n toolGroupFailed: string;\n /** Note on the group's row: steps that were declined. Token: `{count}`. */\n toolGroupDeclined: string;\n /**\n * Set after a step's label when an earlier step in its group has the same\n * one, so two \"Fill field\" steps read \"Fill field\" and \"Fill field (2)\".\n * Grouped mode only. Token: `{n}` (which occurrence, from 2).\n */\n toolStepRepeat: string;\n\n // \u2500\u2500 Delegated sub-agent \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /**\n * The delegation row's text before the server's own status line lands.\n *\n * A fallback, not a state: every announcement carries a pre-rendered `status`,\n * and this only shows if one arrives unusable. The row is the expander, so it\n * must never be blank.\n */\n subAgentWorking: string;\n /**\n * The row's line while a delegation is running. Token: `{agent}`.\n *\n * Worded here rather than on the wire, unlike the two step phases. The\n * protocol's `SUBAGENT_STARTED` carries the sub-agent's `name` and no rendered\n * status -- which is the better shape for a localised UI, and the reason this\n * string exists at all.\n */\n subAgentDelegatedTo: string;\n /** The row's line once a delegation completed. Token: `{agent}`. */\n subAgentFinished: string;\n /**\n * The row's line for a delegation that failed and named no agent.\n *\n * A fallback only: `SUBAGENT_ERROR` carries a required `message`, which the\n * server fills with the sub-agent's name and nothing else, and that text is\n * what the row shows. This covers a server that sent an empty one.\n */\n subAgentFailed: string;\n /** `aria-label` of the region holding the sub-agent's own tool calls. */\n subAgentSteps: string;\n\n // \u2500\u2500 Confirmation card \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** `aria-label` of the editable arguments field on an approval card. */\n approvalEditArgs: string;\n /** Shown when the edited arguments are not valid JSON. */\n approvalArgsInvalid: string;\n /** Shown when the edited arguments parse but are not a JSON object. */\n approvalArgsNotAnObject: string;\n /** `aria-label` of the follow-up suggestion chips row. */\n suggestions: string;\n /** `aria-label` of a message's action row. */\n messageActions: string;\n /** The offer that floats beside a selection in the transcript. */\n quoteSelection: string;\n /** Copy this message (button `title` / `aria-label`). Its confirmation and\n * failure text are the code block's `copied` / `copyFailed`, which say the\n * same thing about the same clipboard. */\n copyMessage: string;\n /** Ask for a different answer to the same question. */\n retryMessage: string;\n /** Rate this answer as good. */\n feedbackUp: string;\n /** Rate this answer as poor. */\n feedbackDown: string;\n /** `aria-label` of the inline confirmation card. */\n confirmAction: string;\n /** Waive confirmation for this tool for the rest of the session. Token: `{tool}`. */\n confirmAlways: string;\n /** Generic confirmation prompt when a tool has no `x-confirm`. Token: `{tool}`. */\n confirmRun: string;\n /** Confirm button. */\n confirm: string;\n /** Cancel button (confirmation + delete confirm). */\n cancel: string;\n\n // \u2500\u2500 Approval card (server-side tool gate) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** `aria-label` of the inline server-side-tool approval card. */\n approveAction: string;\n /** Fallback approval prompt when the interrupt carries no message. */\n approvalPrompt: string;\n /** Approve button (runs the gated server-side tool). */\n approve: string;\n /** Deny button (declines the gated server-side tool). */\n deny: string;\n\n // \u2500\u2500 Question card (the `ask_user` frontend tool) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** `aria-label` of the inline question card. */\n askUserAction: string;\n /** Radio label for the free-text \"other\" choice (when custom answers are allowed). */\n otherOption: string;\n /** Placeholder for the free-text answer field. */\n answerPlaceholder: string;\n /** Submit button for the question card. */\n submit: string;\n\n // \u2500\u2500 Chat-history drawer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** Drawer heading. */\n chats: string;\n /** Empty-state line when there are no threads. */\n noConversations: string;\n /** Rename row button (`title`). */\n rename: string;\n /** Rename row button `aria-label`. */\n renameConversation: string;\n /** Delete row button (`title`) + the inline-confirm action. */\n delete: string;\n /** Delete row button `aria-label`. */\n deleteConversation: string;\n /** Inline delete-confirm prompt. */\n deletePrompt: string;\n\n // \u2500\u2500 Attachments \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** Oversize rejection. Token: `{size}`. */\n tooLarge: string;\n /** Disallowed-type rejection. */\n fileTypeNotAllowed: string;\n /** Generic upload failure (when the error carries no message). */\n uploadFailed: string;\n /** Retry-upload button (`title`). */\n retry: string;\n /** Retry-upload button `aria-label`. */\n retryUpload: string;\n /** Remove-attachment button (`title`). */\n remove: string;\n /** Remove-attachment button `aria-label`. */\n removeAttachment: string;\n\n // \u2500\u2500 Code blocks \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** Label on a code block's copy button. */\n copyCode: string;\n /** Shown on the copy button after the code reached the clipboard. */\n copied: string;\n /** Shown when the clipboard was unavailable or refused the write. */\n copyFailed: string;\n\n // \u2500\u2500 Checkpoint panel (continue a run) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** Title of the checkpoint panel. */\n checkpoints: string;\n /** Empty state when no run can be continued. */\n noCheckpoints: string;\n /** Action: continue a run from its last checkpoint. */\n resumeRun: string;\n /** Action: branch a run without touching the original. */\n forkRun: string;\n /** Badge on a run that branched from another. */\n forkedRun: string;\n\n // \u2500\u2500 Relative time (drawer rows) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n /** Under a minute ago. */\n justNow: string;\n /** Minutes ago. Token: `{n}`. */\n minutesAgo: string;\n /** Hours ago. Token: `{n}`. */\n hoursAgo: string;\n /** Days ago. Token: `{n}`. */\n daysAgo: string;\n /** Weeks ago. Token: `{n}`. */\n weeksAgo: string;\n}\n\n/** The built-in English strings \u2014 the fallback every override merges over. */\nexport const DEFAULT_UI_STRINGS: UiStrings = {\n title: \"Assistant\",\n chatHistory: \"Chat history\",\n closeHistory: \"Close history\",\n searchConversations: \"Search conversations\",\n queued: \"Waiting to send\",\n removeQueued: 'Do not send \"{text}\"',\n noMatches: \"No conversations match that.\",\n threadsToday: \"Today\",\n threadsPreviousWeek: \"Previous 7 days\",\n threadsOlder: \"Older\",\n chatMoved: \"Moved this panel out of the way\",\n chatMinimised: \"Minimised this panel\",\n undo: \"Undo\",\n newChat: \"New chat\",\n collapse: \"Collapse\",\n expand: \"Expand\",\n maximize: \"Maximize\",\n restore: \"Restore\",\n expandUnread: \"Expand \u2014 {count} unread\",\n toggleTheme: \"Toggle theme\",\n copyCode: \"Copy\",\n copied: \"Copied\",\n copyFailed: \"Copy failed\",\n checkpoints: \"Continue a run\",\n noCheckpoints: \"Nothing to continue yet.\",\n resumeRun: \"Resume\",\n forkRun: \"Fork\",\n forkedRun: \"branched\",\n\n greeting: \"Hello, {name}\",\n greetingNoName: \"Hello there\",\n conversation: \"Conversation\",\n jumpToLatest: \"Jump to latest\",\n announceResponding: \"Assistant is responding\",\n announceAnswerReady: \"Assistant answered\",\n announceAwaitingDecision: \"{count} action is waiting for your approval\",\n announceStopped: \"Response stopped\",\n announceFailed: \"The response failed\",\n thinking: \"Assistant is thinking\u2026\",\n thoughts: \"Thoughts\",\n thoughtFor: \"Thought for {seconds}s\",\n stopped: \"\u23F9 Stopped\",\n connectionLost: \"Connection lost\",\n callNotFinished:\n \"Not finished: the run ended or moved on before this tool call returned a result.\",\n declinedAction: \"User declined the action.\",\n confirmCheckFailed:\n \"Not run: the check that decides whether this action needs the user's confirmation failed.\",\n navigating: \"Navigating\u2026\",\n historyReplaced:\n \"The server replaced this conversation's history. Reload to see the updated transcript.\",\n chartUndrawable: \"A chart could not be drawn from the data sent, so it was removed.\",\n historyCompacted: \"Earlier turns condensed to fit the context window ({count} removed)\",\n usingSkill: \"Using skill {name}\",\n runInterrupted: \"The previous response didn\u2019t finish \u2014 the page changed before it arrived.\",\n pageMoved:\n \"The page changed since you last looked at it. Call read_page to see the current page, then retry.\",\n attachmentsStillUploading:\n \"{n} file still uploading \u2014 it was not sent with this message and is still attached.\",\n notConnected: \"This chat isn\u2019t connected to an agent, so the message wasn\u2019t sent.\",\n continueNeedsTurn: \"Type the next turn in the composer first, then pick a run to continue.\",\n continueWhileRunning: \"Wait for the current answer or stop it, then pick a run to continue.\",\n continueWhileLoading: \"Wait for the conversation to finish loading, then pick a run to continue.\",\n skillNeeds: \"\u201C{title}\u201D needs {fields} \u2014 fill it in below, then send.\",\n\n message: \"Message\",\n inputPlaceholder: \"Ask anything\u2026\",\n send: \"Send\",\n stop: \"Stop\",\n attachFiles: \"Attach files\",\n recordVoice: \"Record voice\",\n stopRecording: \"Stop recording\",\n transcribing: \"Transcribing\u2026\",\n transcriptionFailed: \"Transcription failed\",\n recordingLimit: \"Stopped at the {n}-minute limit \u2014 transcribing what was recorded.\",\n placeShared: \"The agent is told you are on {label}\",\n placeWithheld: \"{label} is not sent with your next message\",\n placeStopSharing: \"Stop sharing this page\",\n placeShareAgain: \"Share this page again\",\n\n toolRunning: \"running\u2026\",\n toolDeferred: \"waiting for you\",\n toolDone: \"\u2713 done\",\n toolError: \"\u26A0 error\",\n toolDeclined: \"\u2298 declined\",\n toolInterrupted: \"\u25CC not finished\",\n resizePanel: \"Resize the chat panel\",\n decisionApproved: \"approved by you\",\n decisionDeclined: \"declined by you\",\n argumentsLabel: \"Arguments\",\n resultLabel: \"Result\",\n errorLabel: \"Error\",\n declinedLabel: \"Declined\",\n interruptedLabel: \"Not finished\",\n details: \"Details\",\n\n toolGroupSteps: \"{count} steps\",\n toolGroupWorking: \"Working through {count} steps\",\n toolGroupWorked: \"Worked through {count} steps\",\n toolGroupWaiting: \"{count} waiting for you\",\n toolGroupFailed: \"{count} failed\",\n toolGroupDeclined: \"{count} declined\",\n toolStepRepeat: \"({n})\",\n\n subAgentWorking: \"Working\u2026\",\n subAgentDelegatedTo: \"Delegated to {agent}\",\n subAgentFinished: \"{agent} finished\",\n subAgentFailed: \"The sub-agent failed\",\n subAgentSteps: \"Steps the sub-agent took\",\n\n approvalEditArgs: \"Edit the arguments before approving\",\n approvalArgsInvalid: \"That is not valid JSON, so nothing was sent.\",\n approvalArgsNotAnObject: \"Arguments have to be a JSON object.\",\n suggestions: \"Suggested follow-ups\",\n messageActions: \"Message actions\",\n quoteSelection: \"Quote\",\n copyMessage: \"Copy message\",\n retryMessage: \"Try again\",\n feedbackUp: \"Good answer\",\n feedbackDown: \"Poor answer\",\n confirmAction: \"Confirm action\",\n confirmAlways: \"Always allow\",\n confirmRun: \"Run \u201C{tool}\u201D?\",\n confirm: \"Confirm\",\n cancel: \"Cancel\",\n\n approveAction: \"Approve action\",\n approvalPrompt: \"Approve this action?\",\n approve: \"Approve\",\n deny: \"Deny\",\n\n askUserAction: \"Question\",\n otherOption: \"Other\u2026\",\n answerPlaceholder: \"Type your answer\u2026\",\n submit: \"Submit\",\n\n chats: \"Chats\",\n noConversations: \"No conversations yet.\",\n rename: \"Rename\",\n renameConversation: \"Rename conversation\",\n delete: \"Delete\",\n deleteConversation: \"Delete conversation\",\n deletePrompt: \"Delete?\",\n\n tooLarge: \"Too large (max {size})\",\n fileTypeNotAllowed: \"File type not allowed\",\n uploadFailed: \"upload failed\",\n retry: \"Retry\",\n retryUpload: \"Retry upload\",\n remove: \"Remove\",\n removeAttachment: \"Remove attachment\",\n\n justNow: \"just now\",\n minutesAgo: \"{n}m ago\",\n hoursAgo: \"{n}h ago\",\n daysAgo: \"{n}d ago\",\n weeksAgo: \"{n}w ago\",\n};\n\n/**\n * Merge a partial set of overrides over {@link DEFAULT_UI_STRINGS}, yielding a\n * complete {@link UiStrings}. Keys whose override is `undefined` keep the\n * default (so a `data-strings` JSON with only a few keys \u2014 or a property carrying\n * explicit `undefined` \u2014 leaves the rest English).\n */\nexport function mergeUiStrings(overrides: Partial<UiStrings>): UiStrings {\n const merged: UiStrings = { ...DEFAULT_UI_STRINGS };\n for (const key of Object.keys(overrides) as (keyof UiStrings)[]) {\n const value = overrides[key];\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n return merged;\n}\n", "/** A `{token}` placeholder, named the way every key in the string table names one. */\nconst TOKEN_RE = /\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g;\n\n/**\n * Fill the `{token}` placeholders of a string-table template.\n *\n * Every string-table template goes through here rather than through\n * `template.replace(\"{token}\", value)`, which was wrong in two ways at once:\n *\n * - **A string replacement interprets dollar patterns in the value.** `$&`\n * inserts the matched token, and `` $` `` and `$'` the text either side of it,\n * so a queued message reading `costs $& more` was labelled\n * `Do not send \"costs {text} more\"`. Several of these values are text a user\n * or a server wrote -- a queued message, a tool name, a skill title, an\n * agent name -- so the value has to land verbatim. A replacer function's\n * return value is never interpreted, which is the whole fix.\n * - **A string pattern replaces only the first occurrence**, so a translation\n * that uses a token twice was left half filled.\n *\n * One pass over the template, so a value that itself contains a `{token}` is\n * inserted as written rather than filled in turn: a skill titled\n * `Fill {fields}` stays that, where chained replacements filled it twice.\n *\n * A token with no entry in `values` is left as written. Every call site passes\n * the tokens its key documents, so that is a translation carrying a token the\n * call site does not know, and printing it is more honest than dropping it.\n * `skills/fill_template.ts` is the prompt-side counterpart, and its contract is\n * different on purpose: a prompt reports what it could not fill so a send can\n * be refused.\n *\n * @param template - A string-table value, e.g. `strings.removeQueued`.\n * @param values - The value for each token the template's key documents.\n */\nexport function fillUiString(\n template: string,\n values: Readonly<Record<string, string | number>>,\n): string {\n return template.replace(TOKEN_RE, (token, key: string) =>\n Object.hasOwn(values, key) ? String(values[key]) : token,\n );\n}\n", "import { fillUiString } from \"../fill_ui_string.js\";\nimport { DEFAULT_UI_STRINGS, type UiStrings } from \"../ui_strings.js\";\n\n/**\n * A compact relative timestamp for a thread row \u2014 e.g. `\"just now\"`, `\"5m ago\"`,\n * `\"3h ago\"`, `\"2d ago\"`, `\"4w ago\"`.\n *\n * `now` is injectable so callers and tests can pin the reference point. A\n * future timestamp (clock skew) and a non-finite one (an unparseable or missing\n * `updated_at`, arriving as `NaN`) both read as `justNow`, rather than\n * rendering a nonsense age. Unit words come from {@link UiStrings} with `{n}`\n * filled in here; the bucketing stays integer-rounded and locale-neutral.\n */\nexport function relativeTime(\n timestamp: number,\n now: number = Date.now(),\n strings: UiStrings = DEFAULT_UI_STRINGS,\n): string {\n if (!Number.isFinite(timestamp)) {\n return strings.justNow;\n }\n const seconds = Math.round((now - timestamp) / 1000);\n if (seconds < 60) {\n return strings.justNow;\n }\n const minutes = Math.round(seconds / 60);\n if (minutes < 60) {\n return fillUiString(strings.minutesAgo, { n: minutes });\n }\n const hours = Math.round(minutes / 60);\n if (hours < 24) {\n return fillUiString(strings.hoursAgo, { n: hours });\n }\n const days = Math.round(hours / 24);\n if (days < 7) {\n return fillUiString(strings.daysAgo, { n: days });\n }\n return fillUiString(strings.weeksAgo, { n: Math.round(days / 7) });\n}\n\n/**\n * A host's replacement for {@link relativeTime}.\n *\n * Takes an epoch-milliseconds timestamp and returns the text a row shows.\n * `Intl.RelativeTimeFormat` is the obvious implementation and is deliberately\n * *not* the default: a component that guessed a locale would disagree with the\n * host page's own formatting, and being wrong in a second language is worse\n * than being neutral in one.\n */\nexport type RelativeTimeFormatter = (timestamp: number) => string;\n", "export function openerElement(root: Document | ShadowRoot): Element | null {\n const inside = root.activeElement;\n if (inside !== null) {\n return inside;\n }\n let active: Element | null = document.activeElement;\n while (active?.shadowRoot?.activeElement) {\n active = active.shadowRoot.activeElement;\n }\n return active === document.body ? null : active;\n}\n", "import type { RunRow } from \"../../core/run_index.js\";\nimport { DEFAULT_UI_STRINGS, type UiStrings } from \"../ui_strings.js\";\nimport { type RelativeTimeFormatter, relativeTime } from \"./relative_time.js\";\nimport { openerElement } from \"./utils.js\";\n\n/** How the host continues a picked run. */\nexport type CheckpointVerb = \"resume\" | \"fork\";\n\n/** The run's first message, or `null` where the row has no words to show. */\nfunction previewOf(run: RunRow): string | null {\n return run.preview !== undefined && run.preview !== null && run.preview !== \"\"\n ? run.preview\n : null;\n}\n\n/**\n * A preview reduced to what the row puts on screen, for comparing two rows.\n *\n * Whitespace is collapsed because the rendered row collapses it anyway, so two\n * previews that differ only there are one label to the eye. Case is kept: two\n * spellings a person can tell apart are two labels, and an id beside them would\n * answer a question nobody asked.\n */\nfunction asShown(preview: string): string {\n return preview.replace(/\\s+/g, \" \").trim();\n}\n\n/**\n * The checkpoint panel: continuable runs, each offering **resume** or **fork**.\n *\n * Deliberately separate from the thread drawer: a thread is a conversation you\n * switch to, a checkpoint is a run you continue from, and one thread holds\n * many. One list would make \"resume\" read as \"open\", when resuming starts a new\n * run seeded from a snapshot.\n *\n * The host feeds only rows the server marked `continuable`, a run without a\n * snapshot having nothing to resume from. Pure DOM, like {@link SkillsMenu}:\n * append {@link element}, toggle it, feed {@link setRuns}, act on\n * {@link onPick}.\n */\nexport class CheckpointMenu {\n /** The panel root. Append to the chat shell; hidden until opened. */\n readonly element: HTMLDivElement;\n\n readonly #onPick: (runId: string, verb: CheckpointVerb) => void;\n readonly #list: HTMLDivElement;\n readonly #heading: HTMLSpanElement;\n /** What had focus before the panel opened, restored on close. */\n #lastFocused: HTMLElement | null = null;\n #formatRelativeTime: RelativeTimeFormatter | null = null;\n #strings: UiStrings;\n #runs: readonly RunRow[] = [];\n\n constructor(\n onPick: (runId: string, verb: CheckpointVerb) => void,\n strings: UiStrings = DEFAULT_UI_STRINGS,\n ) {\n this.#onPick = onPick;\n this.#strings = strings;\n\n this.element = document.createElement(\"div\");\n this.element.className = \"checkpoints\";\n this.element.setAttribute(\"part\", \"checkpoints\");\n this.element.setAttribute(\"role\", \"dialog\");\n this.element.setAttribute(\"aria-label\", strings.checkpoints);\n // Focusable as a fallback: with no continuable runs the panel holds no\n // controls at all, and a dialog that cannot take focus strands the\n // keyboard user outside it with no way back except Tab-ing blind.\n this.element.tabIndex = -1;\n this.element.hidden = true;\n\n const header = document.createElement(\"div\");\n header.className = \"checkpoints-header\";\n header.setAttribute(\"part\", \"checkpoints-header\");\n this.#heading = document.createElement(\"span\");\n this.#heading.className = \"checkpoints-title\";\n this.#heading.setAttribute(\"part\", \"checkpoints-title\");\n this.#heading.textContent = strings.checkpoints;\n header.append(this.#heading);\n\n this.#list = document.createElement(\"div\");\n this.#list.className = \"checkpoints-list\";\n this.#list.setAttribute(\"part\", \"checkpoints-list\");\n\n this.element.append(header, this.#list);\n this.element.addEventListener(\"keydown\", (event) => this.#onKeydown(event));\n }\n\n /** Replace the rows. The host passes only `continuable` runs. */\n setRuns(runs: readonly RunRow[]): void {\n this.#runs = runs;\n this.#render();\n }\n\n /** Re-localize a panel built before the host's strings resolved. */\n /**\n * Replace the timestamp formatter, or restore the built-in with `null`.\n *\n * The built-in is deliberately locale-neutral -- there is no `Intl` anywhere\n * in this component, so it never disagrees with a host's own formatting by\n * guessing a locale. That is a defensible default and a poor requirement, so\n * this is the way out.\n */\n setRelativeTimeFormatter(format: RelativeTimeFormatter | null): void {\n this.#formatRelativeTime = format;\n }\n\n /** This row's timestamp, through the host's formatter when it set one. */\n #formatTime(timestamp: number): string {\n return this.#formatRelativeTime !== null\n ? this.#formatRelativeTime(timestamp)\n : relativeTime(timestamp, Date.now(), this.#strings);\n }\n\n setStrings(strings: UiStrings): void {\n this.#strings = strings;\n this.element.setAttribute(\"aria-label\", strings.checkpoints);\n this.#heading.textContent = strings.checkpoints;\n this.#render();\n }\n\n open(): void {\n if (this.open_) {\n return;\n }\n // Remember what had focus so it is restored on close, then move focus into\n // the panel so a keyboard user lands inside the dialog rather than being\n // left behind it. The thread drawer already does this; a dialog that takes\n // no focus is one a keyboard user cannot reach and a screen reader does not\n // announce, however correct its role and label.\n this.#lastFocused = openerElement(\n this.element.getRootNode() as Document | ShadowRoot,\n ) as HTMLElement | null;\n this.element.hidden = false;\n (this.#focusables()[0] ?? this.element).focus();\n }\n\n close(): void {\n if (!this.open_) {\n return;\n }\n this.element.hidden = true;\n this.#lastFocused?.focus();\n this.#lastFocused = null;\n }\n\n /** The focused element within this panel's root (shadow-aware). */\n #activeElement(): Element | null {\n return (this.element.getRootNode() as Document | ShadowRoot).activeElement;\n }\n\n /** The panel's tabbable controls, in document order. */\n #focusables(): HTMLElement[] {\n return Array.from(this.element.querySelectorAll<HTMLElement>(\"button, [tabindex]\")).filter(\n (el) => !el.hidden,\n );\n }\n\n /** Escape closes; Tab is trapped so focus cannot wander behind the dialog. */\n #onKeydown(event: KeyboardEvent): void {\n if (event.key === \"Escape\") {\n event.stopPropagation();\n this.close();\n return;\n }\n if (event.key !== \"Tab\") {\n return;\n }\n const focusables = this.#focusables();\n const first = focusables[0];\n const last = focusables[focusables.length - 1];\n const active = this.#activeElement();\n if (event.shiftKey && active === first) {\n event.preventDefault();\n last?.focus();\n } else if (!event.shiftKey && active === last) {\n event.preventDefault();\n first?.focus();\n }\n }\n\n get open_(): boolean {\n return !this.element.hidden;\n }\n\n #render(): void {\n this.#list.replaceChildren();\n if (this.#runs.length === 0) {\n const empty = document.createElement(\"div\");\n empty.className = \"checkpoints-empty\";\n empty.setAttribute(\"part\", \"checkpoints-empty\");\n empty.textContent = this.#strings.noCheckpoints;\n this.#list.append(empty);\n return;\n }\n const repeated = this.#repeatedPreviews();\n for (const run of this.#runs) {\n this.#list.append(this.#row(run, repeated));\n }\n }\n\n /**\n * The previews more than one row shows.\n *\n * A preview identifies a run only while it is that run's alone. A real index\n * answered with five runs opening on the same sentence, so those rows read\n * alike, as bare timestamps do. Where the words repeat the short id comes\n * back, and where they do not the row is left as it is.\n */\n #repeatedPreviews(): ReadonlySet<string> {\n const seen = new Set<string>();\n const repeated = new Set<string>();\n for (const run of this.#runs) {\n const preview = previewOf(run);\n if (preview === null) {\n continue;\n }\n const shown = asShown(preview);\n if (seen.has(shown)) {\n repeated.add(shown);\n }\n seen.add(shown);\n }\n return repeated;\n }\n\n #row(run: RunRow, repeated: ReadonlySet<string>): HTMLDivElement {\n const row = document.createElement(\"div\");\n row.className = \"checkpoint-row\";\n row.setAttribute(\"part\", \"checkpoint-row\");\n\n const preview = previewOf(run);\n const time = run.started_at === null ? null : this.#formatTime(Date.parse(run.started_at));\n\n const label = document.createElement(\"span\");\n label.className = \"checkpoint-label\";\n label.setAttribute(\"part\", \"checkpoint-label\");\n // What the run was about, if the server says. Otherwise the time, and only\n // then the id \u2014 a person recognises the first, reads the second, and\n // recognises nothing at all in the third.\n label.textContent = preview ?? time ?? run.run_id;\n row.append(label);\n\n if (preview !== null && time !== null) {\n // Demoted to a chip: with words in the label the time is no longer what\n // identifies the run, but it still orders it.\n const when = document.createElement(\"span\");\n when.className = \"checkpoint-time\";\n when.setAttribute(\"part\", \"checkpoint-time\");\n when.textContent = time;\n row.append(when);\n }\n\n // The id, for a row whose label does not identify the run on its own: two\n // runs a few seconds apart both read \"just now\", and words another row also\n // opens with name neither of them. Picking between either pair is picking\n // blind. Shown rather than left in a tooltip, since a hover is not an\n // identity either \u2014 and eight characters beats a full id on the row. A\n // label that already is the id needs no second copy, and a run that arrived\n // without one has nothing better to offer than the words it shares.\n const ambiguous = preview === null ? time !== null : repeated.has(asShown(preview));\n if (ambiguous && run.run_id !== \"\") {\n const short = document.createElement(\"span\");\n short.className = \"checkpoint-id\";\n short.setAttribute(\"part\", \"checkpoint-id\");\n short.textContent = run.run_id.slice(0, 8);\n short.title = run.run_id;\n row.append(short);\n }\n\n if (run.parent_run_id !== null) {\n // Lineage, so a branch doesn't read as a duplicate of its parent.\n const branch = document.createElement(\"span\");\n branch.className = \"checkpoint-branch\";\n branch.setAttribute(\"part\", \"checkpoint-branch\");\n branch.textContent = this.#strings.forkedRun;\n branch.title = run.parent_run_id;\n row.append(branch);\n }\n\n row.append(\n this.#action(run.run_id, \"resume\", this.#strings.resumeRun),\n this.#action(run.run_id, \"fork\", this.#strings.forkRun),\n );\n return row;\n }\n\n #action(runId: string, verb: CheckpointVerb, label: string): HTMLButtonElement {\n const button = document.createElement(\"button\");\n button.type = \"button\";\n button.className = `checkpoint-action checkpoint-${verb}`;\n button.setAttribute(\"part\", `checkpoint-action checkpoint-${verb}`);\n button.textContent = label;\n button.addEventListener(\"click\", () => {\n this.close();\n this.#onPick(runId, verb);\n });\n return button;\n }\n}\n", "import { DEFAULT_UI_STRINGS, type UiStrings } from \"../ui_strings.js\";\n\n/** What the inline approval card displays for one server-side-tool interrupt. */\nexport interface ApprovalRequest {\n /**\n * Human-readable prompt from the AG-UI interrupt (e.g.\n * `Approve delete_thing({\u2026})?`). Falls back to the generic\n * {@link UiStrings.approvalPrompt} when the interrupt carries no message.\n */\n message?: string;\n /** Tool name, surfaced as a `data-tool-name` attribute for styling/tests. */\n toolName?: string;\n /**\n * The call's arguments, shown for editing when {@link ApprovalOptions.onEdit}\n * is set. Omitted when the interrupt names no call whose arguments are known.\n */\n args?: Record<string, unknown>;\n}\n\n/** Build a labelled action button. */\nfunction actionButton(modifier: string, label: string): HTMLButtonElement {\n const button = document.createElement(\"button\");\n button.type = \"button\";\n button.className = `approval-btn approval-btn--${modifier}`;\n button.setAttribute(\"part\", `approval-button approval-${modifier}`);\n button.textContent = label;\n return button;\n}\n\n/** Options for {@link requestApproval}. */\nexport interface ApprovalOptions {\n /**\n * Aborting this signal resolves the card as denied, with buttons disabled and\n * `data-resolved=\"denied\"` \u2014 how a Stop control dismisses a pending approval.\n */\n signal?: AbortSignal;\n /** Localized strings; defaults to the English {@link DEFAULT_UI_STRINGS}. */\n strings?: UiStrings;\n /**\n * Offer the call's arguments for editing, and receive what the user approved.\n *\n * Called **only** on approval, and only when the text parses and differs from\n * what was proposed -- an untouched call resolves as a plain approval, so a\n * server sees `editedArgs` exactly when something was actually edited.\n *\n * Absent means no editor, which is deliberate: AG-UI gates this on the\n * agent's own `approveWithEdits` capability, and a card that let a user\n * rewrite arguments a server will discard is worse than one that does not\n * offer to.\n */\n onEdit?: (args: Record<string, unknown>) => void;\n}\n\n/**\n * A fully custom renderer for a server-side-tool approval, set via\n * `AgUiChat.approvalRenderer`. Receives the {@link ApprovalRequest} and an\n * `AbortSignal` that fires when the run is stopped, and resolves `true` to\n * approve or `false` to deny. Replaces the built-in {@link requestApproval}\n * card entirely, the host owning the DOM; to restyle the built-in card instead,\n * use the `strings` and `::part()` seams.\n */\nexport type ApprovalRenderer = (\n request: ApprovalRequest,\n options: { signal: AbortSignal },\n) => Promise<boolean>;\n\n/**\n * Append an inline approval card to `host` and resolve `true` to run a gated\n * server-side tool or `false` to deny it.\n *\n * Distinct from the client-tool confirmation card\n * ({@link requestConfirmation}): a gated server tool defers instead of\n * executing, so the run finishes on an AG-UI interrupt the client answers with\n * `resume[]`, and this is the browser half of that loop. Unlike the\n * confirmation card, this one stays in the transcript as a resolved record,\n * buttons disabled and `data-resolved` set.\n */\nexport function requestApproval(\n host: Node & ParentNode,\n request: ApprovalRequest,\n options: ApprovalOptions = {},\n): Promise<boolean> {\n const strings = options.strings ?? DEFAULT_UI_STRINGS;\n return new Promise<boolean>((resolve) => {\n const card = document.createElement(\"div\");\n card.className = \"approval\";\n card.setAttribute(\"part\", \"approval\");\n if (request.toolName !== undefined) {\n card.setAttribute(\"data-tool-name\", request.toolName);\n }\n card.setAttribute(\"role\", \"group\");\n card.setAttribute(\"aria-label\", strings.approveAction);\n\n const body = document.createElement(\"div\");\n body.className = \"approval-body\";\n body.setAttribute(\"part\", \"approval-body\");\n body.textContent = request.message ?? strings.approvalPrompt;\n\n const editor = buildEditor(request, options, strings);\n\n const actions = document.createElement(\"div\");\n actions.className = \"approval-actions\";\n actions.setAttribute(\"part\", \"approval-actions\");\n\n const deny = actionButton(\"deny\", strings.deny);\n const approve = actionButton(\"approve\", strings.approve);\n\n let settled = false;\n const close = (approved: boolean): void => {\n if (settled) {\n return;\n }\n settled = true;\n deny.disabled = true;\n approve.disabled = true;\n card.setAttribute(\"data-resolved\", approved ? \"approved\" : \"denied\");\n resolve(approved);\n };\n\n deny.addEventListener(\"click\", () => close(false));\n approve.addEventListener(\"click\", () => {\n if (editor !== null && !editor.commit()) {\n // Unparseable JSON: say so on the card and stay open. Approving what\n // the user did not write -- the original arguments -- would be the one\n // outcome they cannot see coming.\n return;\n }\n close(true);\n });\n options.signal?.addEventListener(\"abort\", () => close(false), { once: true });\n\n actions.append(deny, approve);\n card.append(body, ...(editor === null ? [] : [editor.root]), actions);\n host.appendChild(card);\n if (options.signal?.aborted === true) {\n // The run was cancelled before the card could ask; record the denial.\n close(false);\n return;\n }\n approve.focus();\n });\n}\n\n/** The editable-arguments region, or `null` when this card does not offer one. */\nfunction buildEditor(\n request: ApprovalRequest,\n options: ApprovalOptions,\n strings: UiStrings,\n): { root: HTMLElement; commit: () => boolean } | null {\n const { onEdit } = options;\n if (onEdit === undefined || request.args === undefined) {\n return null;\n }\n const original = JSON.stringify(request.args, null, 2);\n const root = document.createElement(\"div\");\n root.className = \"approval-edit\";\n root.setAttribute(\"part\", \"approval-edit\");\n\n const field = document.createElement(\"textarea\");\n field.className = \"approval-args\";\n field.setAttribute(\"part\", \"approval-args\");\n field.setAttribute(\"aria-label\", strings.approvalEditArgs);\n field.rows = Math.min(10, original.split(\"\\n\").length);\n field.value = original;\n\n const error = document.createElement(\"div\");\n error.className = \"approval-error\";\n error.setAttribute(\"part\", \"approval-error\");\n // A live region: it appears in response to pressing Approve, and a message\n // that only exists visually leaves a screen-reader user with a button that\n // silently did nothing.\n error.setAttribute(\"role\", \"alert\");\n error.hidden = true;\n\n root.append(field, error);\n return {\n root,\n commit: () => {\n if (field.value === original) {\n return true;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(field.value);\n } catch {\n error.textContent = strings.approvalArgsInvalid;\n error.hidden = false;\n field.focus();\n return false;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n error.textContent = strings.approvalArgsNotAnObject;\n error.hidden = false;\n field.focus();\n return false;\n }\n error.hidden = true;\n onEdit(parsed as Record<string, unknown>);\n return true;\n },\n };\n}\n", "import { fillUiString } from \"../fill_ui_string.js\";\nimport { DEFAULT_UI_STRINGS, type UiStrings } from \"../ui_strings.js\";\n\n/** What the inline confirmation card displays. */\nexport interface ConfirmationRequest {\n toolName: string;\n args: Record<string, unknown>;\n /**\n * Human-readable prompt (from the tool's `x-confirm` metadata), e.g.\n * \"Activate this project?\". Falls back to the generic `confirmRun` template.\n */\n message?: string;\n}\n\n/** Build a labelled action button. */\nfunction actionButton(modifier: string, label: string): HTMLButtonElement {\n const button = document.createElement(\"button\");\n button.type = \"button\";\n button.className = `confirm-btn confirm-btn--${modifier}`;\n button.setAttribute(\"part\", `confirm-button confirm-${modifier}`);\n button.textContent = label;\n return button;\n}\n\n/** Options for {@link requestConfirmation}. */\nexport interface ConfirmationOptions {\n /**\n * Aborting this signal resolves the card as declined, with buttons disabled\n * and `data-resolved=\"declined\"` \u2014 how a Stop control dismisses a pending\n * confirmation.\n */\n signal?: AbortSignal;\n /** Localized strings; defaults to the English {@link DEFAULT_UI_STRINGS}. */\n strings?: UiStrings;\n /**\n * Offer a third button \u2014 \"always allow, this session\" \u2014 and call this when\n * the user picks it. The card still resolves `true`: the extra decision is\n * *in addition to* approving this call, not instead of it.\n *\n * Absent means no button, which is deliberate: presence of the handler is\n * what enables it, so the affordance can never be rendered with nothing\n * listening. A caller that cannot honour the waiver simply does not pass one.\n */\n onAlwaysAllow?: () => void;\n}\n\n/**\n * Append an inline confirmation card to `host` (the chat message list) and\n * resolve `true` on confirm, `false` on cancel.\n *\n * The card lives in the transcript rather than in a modal overlay, so it reads\n * after the assistant's explanation and never steals focus from the page.\n *\n * Answering it removes it: the record of the decision belongs to the tool card\n * this gates, which settles to `done` or `declined` and carries it. A spent\n * form left in place reads as still outstanding.\n *\n * With `onAlwaysAllow` set the card offers a third button. A prompt that is\n * approved nearly every time is not a decision, it is a speed bump \u2014 and the\n * reflex it trains is what makes the rare refusal easy to miss. Letting the\n * user say \"not this one again, this session\" is the affordance that keeps the\n * remaining prompts meaningful.\n */\nexport function requestConfirmation(\n host: Node & ParentNode,\n request: ConfirmationRequest,\n options: ConfirmationOptions = {},\n): Promise<boolean> {\n const strings = options.strings ?? DEFAULT_UI_STRINGS;\n return new Promise<boolean>((resolve) => {\n const card = document.createElement(\"div\");\n card.className = \"confirm\";\n card.setAttribute(\"part\", \"confirm\");\n card.setAttribute(\"data-tool-name\", request.toolName);\n card.setAttribute(\"role\", \"group\");\n card.setAttribute(\"aria-label\", strings.confirmAction);\n\n const body = document.createElement(\"div\");\n body.className = \"confirm-body\";\n body.setAttribute(\"part\", \"confirm-body\");\n body.textContent =\n request.message ?? fillUiString(strings.confirmRun, { tool: request.toolName });\n\n const args = document.createElement(\"pre\");\n args.className = \"confirm-args\";\n args.setAttribute(\"part\", \"confirm-args\");\n args.textContent = JSON.stringify(request.args, null, 2);\n // A call with no arguments rendered the string \"{}\" in a box of its own.\n args.hidden = Object.keys(request.args).length === 0;\n\n const actions = document.createElement(\"div\");\n actions.className = \"confirm-actions\";\n actions.setAttribute(\"part\", \"confirm-actions\");\n\n const cancel = actionButton(\"cancel\", strings.cancel);\n const always =\n options.onAlwaysAllow === undefined\n ? null\n : actionButton(\"always\", fillUiString(strings.confirmAlways, { tool: request.toolName }));\n const confirm = actionButton(\"confirm\", strings.confirm);\n\n let settled = false;\n const close = (accepted: boolean): void => {\n if (settled) {\n return;\n }\n settled = true;\n // The prompt leaves once it has been answered. What stays is the tool\n // card next to it, which settles to the outcome and scrolls with the rest\n // of the transcript -- a record of the action rather than a spent form\n // sitting there as a standing reminder of one.\n card.remove();\n resolve(accepted);\n };\n\n cancel.addEventListener(\"click\", () => close(false));\n confirm.addEventListener(\"click\", () => close(true));\n always?.addEventListener(\"click\", () => {\n // Recorded before resolving, so a caller that reads its own allowlist\n // synchronously on the next call already sees this one.\n options.onAlwaysAllow?.();\n close(true);\n });\n options.signal?.addEventListener(\"abort\", () => close(false), { once: true });\n\n // Confirm stays last, and rightmost: the waiver is the wider decision, and\n // putting it where the eye lands for \"yes\" is how it gets taken by accident.\n actions.append(cancel, ...(always === null ? [] : [always]), confirm);\n card.append(body, args, actions);\n host.appendChild(card);\n if (options.signal?.aborted === true) {\n // The run was cancelled before the card could ask; record the decline.\n close(false);\n return;\n }\n confirm.focus();\n });\n}\n", "import { DEFAULT_UI_STRINGS, type UiStrings } from \"../ui_strings.js\";\n\n/** What the inline question card asks (the `ask_user` frontend tool's args). */\nexport interface QuestionRequest {\n /** The question shown to the user. */\n question: string;\n /**\n * Preset choices rendered as radios. When empty/omitted the card is a plain\n * free-text prompt.\n */\n options?: readonly string[];\n /**\n * Whether the user may type a custom answer. With `options`, adds an \"other\"\n * radio revealing a text field; without options the card is free-text anyway.\n */\n allowCustom?: boolean;\n}\n\n/** Options for {@link requestQuestion}. */\nexport interface QuestionOptions {\n /**\n * Aborting this signal resolves the card with an empty answer and disabled\n * fields \u2014 how a Stop control dismisses an open question.\n */\n signal?: AbortSignal;\n /** Localized strings; defaults to the English {@link DEFAULT_UI_STRINGS}. */\n strings?: UiStrings;\n}\n\n/**\n * A fully custom renderer for the `ask_user` question, set via\n * `AgUiChat.askUserRenderer`. Receives the parsed {@link QuestionRequest} and an\n * `AbortSignal` that fires when the run is stopped, and resolves with the user's\n * answer; an empty string means no answer. Replaces the built-in\n * {@link requestQuestion} card entirely \u2014 see {@link ApprovalRenderer} for the\n * same seam on approvals.\n */\nexport type QuestionRenderer = (\n request: QuestionRequest,\n options: { signal: AbortSignal },\n) => Promise<string>;\n\n/** A single custom-answer text field. */\nfunction answerInput(placeholder: string): HTMLInputElement {\n const input = document.createElement(\"input\");\n input.type = \"text\";\n input.className = \"question-input\";\n input.setAttribute(\"part\", \"question-input\");\n input.placeholder = placeholder;\n return input;\n}\n\n/**\n * Append an inline question card to `host` and resolve with the user's answer \u2014\n * the browser half of the built-in `ask_user` frontend tool.\n *\n * Collects a typed answer rather than the yes/no the confirmation and approval\n * cards return: a radio pick from `options`, or free text when `allowCustom` is\n * set or no `options` are given. Stays in the transcript as a resolved record,\n * controls disabled and `data-resolved` set; a Stop while it is open resolves\n * it with an empty string.\n */\nexport function requestQuestion(\n host: Node & ParentNode,\n request: QuestionRequest,\n options: QuestionOptions = {},\n): Promise<string> {\n const strings = options.strings ?? DEFAULT_UI_STRINGS;\n const choices = request.options ?? [];\n const hasChoices = choices.length > 0;\n // Free text is offered when there are no preset choices, or when custom\n // answers are explicitly allowed alongside them (via an \"other\" radio).\n const allowsText = !hasChoices || request.allowCustom === true;\n\n return new Promise<string>((resolve) => {\n const card = document.createElement(\"div\");\n card.className = \"question\";\n card.setAttribute(\"part\", \"question\");\n card.setAttribute(\"role\", \"group\");\n card.setAttribute(\"aria-label\", strings.askUserAction);\n\n const body = document.createElement(\"div\");\n body.className = \"question-body\";\n body.setAttribute(\"part\", \"question-body\");\n body.textContent = request.question;\n\n const form = document.createElement(\"div\");\n form.className = \"question-options\";\n form.setAttribute(\"part\", \"question-options\");\n\n // `name` scopes the radio group to this card so multiple open cards don't\n // interfere; a per-card token keeps it unique without module state.\n const group = `q-${choices.length}-${request.question.length}`;\n const radios: HTMLInputElement[] = [];\n for (const choice of choices) {\n const label = document.createElement(\"label\");\n label.className = \"question-choice\";\n label.setAttribute(\"part\", \"question-choice\");\n const radio = document.createElement(\"input\");\n radio.type = \"radio\";\n radio.name = group;\n radio.value = choice;\n radio.setAttribute(\"part\", \"question-radio\");\n const text = document.createElement(\"span\");\n text.setAttribute(\"part\", \"question-choice-text\");\n text.textContent = choice;\n label.append(radio, text);\n form.appendChild(label);\n radios.push(radio);\n }\n\n // The \"other\" radio (only alongside choices) toggles the free-text field.\n let otherRadio: HTMLInputElement | null = null;\n let input: HTMLInputElement | null = null;\n if (allowsText) {\n input = answerInput(strings.answerPlaceholder);\n if (hasChoices) {\n const label = document.createElement(\"label\");\n label.className = \"question-choice\";\n label.setAttribute(\"part\", \"question-choice\");\n otherRadio = document.createElement(\"input\");\n otherRadio.type = \"radio\";\n otherRadio.name = group;\n otherRadio.value = \"\";\n otherRadio.setAttribute(\"part\", \"question-radio\");\n const text = document.createElement(\"span\");\n text.setAttribute(\"part\", \"question-choice-text\");\n text.textContent = strings.otherOption;\n label.append(otherRadio, text);\n form.appendChild(label);\n input.disabled = true;\n }\n form.appendChild(input);\n }\n\n const actions = document.createElement(\"div\");\n actions.className = \"question-actions\";\n actions.setAttribute(\"part\", \"question-actions\");\n const submit = document.createElement(\"button\");\n submit.type = \"button\";\n submit.className = \"question-btn\";\n submit.setAttribute(\"part\", \"question-button\");\n submit.textContent = strings.submit;\n actions.appendChild(submit);\n\n let settled = false;\n const answerFor = (): string | null => {\n const picked = radios.find((r) => r.checked);\n if (picked !== undefined) {\n return picked.value;\n }\n if (input !== null && (otherRadio === null || otherRadio.checked)) {\n const typed = input.value.trim();\n return typed === \"\" ? null : typed;\n }\n return null;\n };\n const refresh = (): void => {\n if (input !== null && otherRadio !== null) {\n input.disabled = !otherRadio.checked;\n }\n submit.disabled = answerFor() === null;\n };\n const close = (answer: string): void => {\n if (settled) {\n return;\n }\n settled = true;\n submit.disabled = true;\n for (const radio of radios) {\n radio.disabled = true;\n }\n if (otherRadio !== null) {\n otherRadio.disabled = true;\n }\n if (input !== null) {\n input.disabled = true;\n }\n card.setAttribute(\"data-resolved\", answer === \"\" ? \"cancelled\" : \"answered\");\n resolve(answer);\n };\n\n for (const radio of [...radios, ...(otherRadio !== null ? [otherRadio] : [])]) {\n radio.addEventListener(\"change\", refresh);\n }\n input?.addEventListener(\"input\", refresh);\n input?.addEventListener(\"keydown\", (event) => {\n if (event.key === \"Enter\") {\n event.preventDefault();\n const answer = answerFor();\n if (answer !== null) {\n close(answer);\n }\n }\n });\n submit.addEventListener(\"click\", () => {\n const answer = answerFor();\n if (answer !== null) {\n close(answer);\n }\n });\n options.signal?.addEventListener(\"abort\", () => close(\"\"), { once: true });\n\n card.append(body, form, actions);\n host.appendChild(card);\n if (options.signal?.aborted === true) {\n close(\"\");\n return;\n }\n refresh();\n (hasChoices ? radios[0] : input)?.focus();\n });\n}\n", "import { TOOL_CALL_STATUS, type TOOL_DISPLAY } from \"../../constants.js\";\nimport { DEFAULT_UI_STRINGS, type UiStrings } from \"../ui_strings.js\";\n\n/** Any state a tool-call card can be in. */\nexport type ToolCallStatus = (typeof TOOL_CALL_STATUS)[keyof typeof TOOL_CALL_STATUS];\n\n/** How much detail a card renders. */\nexport type ToolDisplayMode = (typeof TOOL_DISPLAY)[keyof typeof TOOL_DISPLAY];\n\n/** The two states a card can sit in before an outcome exists. */\nexport type UnsettledStatus = typeof TOOL_CALL_STATUS.PENDING | typeof TOOL_CALL_STATUS.DEFERRED;\n\n/** The terminal states a card settles into (everything unsettled excluded). */\nexport type SettledStatus = Exclude<ToolCallStatus, UnsettledStatus>;\n\n/** Short pill text shown for each status, drawn from the string table. */\nfunction statusLabels(strings: UiStrings): Record<ToolCallStatus, string> {\n return {\n [TOOL_CALL_STATUS.PENDING]: strings.toolRunning,\n [TOOL_CALL_STATUS.DEFERRED]: strings.toolDeferred,\n [TOOL_CALL_STATUS.DONE]: strings.toolDone,\n [TOOL_CALL_STATUS.ERROR]: strings.toolError,\n [TOOL_CALL_STATUS.DECLINED]: strings.toolDeclined,\n [TOOL_CALL_STATUS.INTERRUPTED]: strings.toolInterrupted,\n };\n}\n\n/** Section-heading text for each settled outcome's result region. */\nfunction resultLabels(strings: UiStrings): Record<SettledStatus, string> {\n return {\n [TOOL_CALL_STATUS.DONE]: strings.resultLabel,\n [TOOL_CALL_STATUS.ERROR]: strings.errorLabel,\n [TOOL_CALL_STATUS.DECLINED]: strings.declinedLabel,\n [TOOL_CALL_STATUS.INTERRUPTED]: strings.interruptedLabel,\n };\n}\n\n/** Pretty-print a JSON payload; fall back to the raw text if it isn't JSON. */\nfunction formatPayload(text: string): string {\n try {\n return JSON.stringify(JSON.parse(text), null, 2);\n } catch {\n return text;\n }\n}\n\n/**\n * One region of a card's body, handed to a host {@link ToolPayloadFormatter}.\n *\n * A discriminated union rather than three positional parameters because the two\n * halves do not carry the same thing: arguments are the parsed record the call\n * was made with, and a result is the raw string the tool returned, which may not\n * be JSON at all. Flattening both into one `payload` parameter would force every\n * formatter to re-derive which it had before it could read it, and the\n * arguments would arrive re-serialised for no reason.\n *\n * `toolName` is the raw tool name, not the card's `x-summary` label -- a\n * formatter dispatches on identity, and the label is a display string a server\n * may change.\n */\nexport type ToolPayload =\n | {\n readonly kind: \"arguments\";\n readonly toolName: string;\n readonly args: Record<string, unknown>;\n }\n | {\n readonly kind: \"result\";\n readonly toolName: string;\n readonly status: SettledStatus;\n readonly text: string;\n };\n\n/**\n * Renders one region of a tool card's body, for a host that would rather show a\n * table or a summary line than a wall of pretty-printed JSON.\n *\n * Return a `Node` to take the region over, a `string` to replace its text, or\n * `null` to fall through to the built-in pretty-print -- so a formatter that\n * only cares about one tool, or only about results, declines the rest rather\n * than reimplementing them.\n *\n * **Presentation only.** The model reads the tool result from its own copy of\n * the message, which this never touches, so anything said here is said to the\n * person and not to the agent. Translating a value -- an enum constant into a\n * friendly label, an epoch into a date -- belongs on the server, where it also\n * reaches the model's prose; doing it here would make the card and the answer\n * beside it disagree about what happened.\n *\n * A returned string is set as text, never parsed as markup: this is not a\n * second HTML channel into the transcript, and a host that wants elements\n * builds them itself and returns the node.\n */\nexport type ToolPayloadFormatter = (payload: ToolPayload) => Node | string | null;\n\n/** Optional per-card wiring beyond the name, arguments, label and strings. */\nexport interface ToolCallCardOptions {\n /** Host presentation hook for both body regions. See {@link ToolPayloadFormatter}. */\n readonly formatPayload?: ToolPayloadFormatter;\n}\n\n/**\n * A live tool-call card for the chat transcript.\n *\n * Construction renders a status icon, the tool name, a status pill, and a body\n * of two separately-headed regions \u2014 arguments and result \u2014 each with its own\n * `part`. {@link settle} fills in the result and flips the pill. Both payloads\n * are pretty-printed and never concatenated into one block.\n *\n * The card renders one DOM shape in every display mode and lets CSS decide what\n * shows, selecting visibility from the host attribute rather than a value\n * copied onto the card at construction. That is what lets `data-tool-display`\n * be flipped on the host and re-read by every card already on screen; building\n * a different structure per mode would leave existing cards stale.\n *\n * The leading icon carries no text: the shadow CSS draws its glyph or spinner\n * from the card's `data-status`, so a host themes it through the\n * `--ag-ui-tool-icon-*` custom properties or the `tool-card-icon` part without\n * the card reaching into the host stylesheet.\n *\n * Either region may be drawn by the host instead: `options.formatPayload` is\n * asked about each one and pretty-prints as before whenever it declines. The\n * arguments are offered from the constructor and the result from {@link settle},\n * because that is when each exists -- so a formatter is asked twice per card,\n * potentially long apart.\n *\n * Pure DOM. The host appends {@link element} into its shadow root; all visible\n * text comes from {@link UiStrings}.\n */\nexport class ToolCallCard {\n /** The card's root element; append this into the message list. */\n readonly element: HTMLDivElement;\n\n /**\n * Where a question about *this* call renders \u2014 the approval prompt for a\n * server-side tool the run deferred.\n *\n * It belongs to the card rather than to the transcript because a run can defer\n * several calls at once, and a prompt written per *tool* (\"Add this event to\n * the board?\") is identical for every one of them. Rendered into the answer\n * group they were three anonymous copies of one question, below the three\n * cards they gated; rendered here, position identifies them and the arguments\n * are already on screen above the question.\n *\n * Empty until used, and hidden while empty by the shadow CSS.\n */\n readonly approvalSlot: HTMLDivElement;\n\n /**\n * Where a *nested* run's progress renders \u2014 the sub-agent this call delegated\n * to, narrating itself while the card waits.\n *\n * A slot rather than a rendered thing, on the same reasoning as\n * {@link approvalSlot}: the card owns the position and something else owns the\n * content. What makes the position right is that the wire keys a delegation on\n * this card's own `toolCallId`, so the run being narrated is the one this card\n * already stands for.\n *\n * Placed above the Details toggle rather than inside the body, because the\n * body is what the display modes hide \u2014 and a progress line that only appears\n * in `full` mode would leave exactly the stall it exists to end. Empty on every\n * card that delegated nothing, and hidden while empty by the shadow CSS.\n */\n readonly subagentSlot: HTMLDivElement;\n\n readonly #status: HTMLSpanElement;\n readonly #decision: HTMLSpanElement;\n readonly #toggle: HTMLButtonElement;\n readonly #resultSection: HTMLDivElement;\n readonly #resultLabel: HTMLSpanElement;\n readonly #resultBody: HTMLPreElement;\n readonly #strings: UiStrings;\n /**\n * The arguments this call was made with.\n *\n * Retained rather than only rendered, because an approval interrupt names a\n * `toolCallId` and nothing else -- so this card is the only place the args\n * still exist when the user is asked to approve, edit or deny the call.\n */\n readonly args: Record<string, unknown>;\n /** The raw tool name, kept for the payloads handed to {@link ToolPayloadFormatter}. */\n readonly #name: string;\n readonly #formatPayload: ToolPayloadFormatter | null;\n #settled = false;\n\n constructor(\n name: string,\n args: Record<string, unknown>,\n summary?: string,\n strings: UiStrings = DEFAULT_UI_STRINGS,\n options: ToolCallCardOptions = {},\n ) {\n this.#strings = strings;\n this.args = args;\n this.#name = name;\n this.#formatPayload = options.formatPayload ?? null;\n\n this.element = document.createElement(\"div\");\n this.element.className = \"tool-call\";\n this.element.setAttribute(\"data-tool-name\", name);\n this.element.setAttribute(\"data-expanded\", \"false\");\n\n const head = document.createElement(\"div\");\n head.className = \"tool-call-head\";\n head.setAttribute(\"part\", \"tool-card-head\");\n\n // Left empty in the DOM on purpose: the shadow CSS draws the spinner or\n // settled mark from `data-status`, keeping the glyphs themeable.\n const icon = document.createElement(\"span\");\n icon.className = \"tool-call-icon\";\n icon.setAttribute(\"part\", \"tool-card-icon\");\n icon.setAttribute(\"aria-hidden\", \"true\");\n\n const label = document.createElement(\"span\");\n label.className = \"tool-call-name\";\n label.setAttribute(\"part\", \"tool-card-name\");\n // A server-provided `x-summary` label reads better than the raw tool name.\n label.textContent = summary ?? name;\n\n this.#status = document.createElement(\"span\");\n this.#status.className = \"tool-call-status\";\n this.#setStatus(TOOL_CALL_STATUS.PENDING);\n\n this.#decision = document.createElement(\"span\");\n this.#decision.className = \"tool-call-decision\";\n this.#decision.setAttribute(\"part\", \"tool-card-decision\");\n this.#decision.hidden = true;\n\n head.append(icon, label, this.#status, this.#decision);\n\n const argsSection = this.#section(\"args\", strings.argumentsLabel);\n this.#renderPayload(\n argsSection.body,\n { kind: \"arguments\", toolName: name, args },\n JSON.stringify(args, null, 2),\n );\n // Drop the region rather than frame an empty object. The marker is what\n // the shadow CSS reads to tell whether the toggle has anything to open:\n // in compact the arguments are behind it too.\n const hasArgs = Object.keys(args).length > 0;\n argsSection.root.hidden = !hasArgs;\n this.element.toggleAttribute(\"data-has-args\", hasArgs);\n\n const resultSection = this.#section(\"result\", strings.resultLabel);\n this.#resultSection = resultSection.root;\n this.#resultLabel = resultSection.label;\n this.#resultBody = resultSection.body;\n // Nothing to show until `settle` supplies it, or a pending card expands\n // onto an empty region.\n resultSection.root.hidden = true;\n\n this.#toggle = document.createElement(\"button\");\n this.#toggle.type = \"button\";\n this.#toggle.className = \"tool-call-toggle\";\n this.#toggle.setAttribute(\"part\", \"tool-card-toggle\");\n this.#toggle.setAttribute(\"aria-expanded\", \"false\");\n this.#toggle.textContent = strings.details;\n this.#toggle.addEventListener(\"click\", () => this.#setExpanded(!this.#expanded()));\n\n const body = document.createElement(\"div\");\n body.className = \"tool-call-body\";\n body.setAttribute(\"part\", \"tool-card-body\");\n body.append(argsSection.root, resultSection.root);\n\n this.approvalSlot = document.createElement(\"div\");\n this.approvalSlot.className = \"tool-call-approval\";\n this.approvalSlot.setAttribute(\"part\", \"tool-card-approval\");\n\n this.subagentSlot = document.createElement(\"div\");\n this.subagentSlot.className = \"tool-call-subagent\";\n this.subagentSlot.setAttribute(\"part\", \"tool-card-subagent\");\n\n this.element.append(head, this.subagentSlot, this.#toggle, body, this.approvalSlot);\n }\n\n /**\n * Move between the two states that are not an outcome \u2014 `pending` (running)\n * and `deferred` (gated, waiting on a person).\n *\n * Ignored once {@link settle} has run: a card that was declined must not be\n * talked back into looking live by a late event.\n */\n mark(status: UnsettledStatus): void {\n if (this.#settled) {\n return;\n }\n this.#setStatus(status);\n }\n\n /**\n * Say whether a prompt is open on this call, a question it asked or a\n * confirmation it needs. A flag of its own beside the status, which stays\n * `pending`: the call is still running as far as the status goes, and a card\n * display mode that reads the status draws it exactly as before. The step\n * group reads the flag to tell a call waiting on a person from one working.\n */\n setAsking(asking: boolean): void {\n this.element.toggleAttribute(\"data-asking\", asking);\n }\n\n /**\n * Record that a human approved or declined this call, as a line in the card.\n * The prompt disappears once answered, so this is the only lasting trace that\n * the call was gated at all.\n */\n recordDecision(kind: \"approved\" | \"declined\"): void {\n this.element.setAttribute(\"data-decision\", kind);\n this.#decision.textContent =\n kind === \"approved\" ? this.#strings.decisionApproved : this.#strings.decisionDeclined;\n this.#decision.hidden = false;\n }\n\n /** Whether {@link settle} has already run (so a terminal sweep can skip it). */\n get settled(): boolean {\n return this.#settled;\n }\n\n /**\n * Flip the status pill to `status` and fill in the result region, whose\n * heading names the outcome (result / error / declined).\n *\n * A blank `text` leaves the region out, as the constructor does for empty\n * arguments: the call settled with nothing to show, so the card stays a\n * status row and its toggle is not offered. The formatter is not asked about\n * a result that is not there.\n */\n settle(status: SettledStatus, text: string): void {\n // Idempotent: a duplicate `TOOL_CALL_RESULT`, or a replayed tool message\n // for an already-settled card, must not overwrite the first outcome.\n if (this.#settled) {\n return;\n }\n this.#settled = true;\n this.#setStatus(status);\n if (text.trim() === \"\") {\n return;\n }\n this.#resultLabel.textContent = resultLabels(this.#strings)[status];\n this.#renderPayload(\n this.#resultBody,\n { kind: \"result\", toolName: this.#name, status, text },\n formatPayload(text),\n );\n this.#resultSection.hidden = false;\n // Read by the shadow CSS, which offers the toggle only over something, and\n // by a step group, which offers its row on the same terms.\n this.element.setAttribute(\"data-has-result\", \"\");\n }\n\n /**\n * Write the status everywhere it is read from, in one place so they cannot\n * disagree: `data-status` for the shadow CSS, the pill's text, and the part\n * lists. `::part()` takes no attribute selector, so the card and its pill also\n * name the status as a part (`tool-card-error`, `tool-card-status-error`), the\n * modifier convention a run notice uses, and a host styles failures alone.\n * Setting the whole list replaces the previous modifier.\n */\n #setStatus(status: ToolCallStatus): void {\n this.element.setAttribute(\"data-status\", status);\n this.element.setAttribute(\"part\", `tool-card tool-card-${status}`);\n this.#status.setAttribute(\"part\", `tool-card-status tool-card-status-${status}`);\n this.#status.textContent = statusLabels(this.#strings)[status];\n }\n\n /**\n * Fill one body region, offering it to the host formatter first.\n *\n * `fallback` is computed by the caller rather than here because the two\n * regions build it differently -- arguments are already parsed, a result is a\n * string that may or may not be JSON -- and because a formatter that takes\n * the region over should not have paid for a pretty-print nobody sees. It is\n * cheap either way; the point is that the built-in rendering stays written\n * once, beside the payload it belongs to.\n *\n * The `data-formatted` marker is what the shadow CSS reads to relax the\n * preformatted whitespace on a region a host owns -- a table inherits it as\n * mangled cell spacing, a sentence as line breaks nobody typed. Marked for a\n * returned string too: one rule, and a summary line wants ordinary wrapping\n * as much as a table does.\n */\n #renderPayload(body: HTMLPreElement, payload: ToolPayload, fallback: string): void {\n const rendered = this.#formatPayload === null ? null : this.#formatPayload(payload);\n if (rendered === null) {\n body.textContent = fallback;\n return;\n }\n body.setAttribute(\"data-formatted\", \"true\");\n if (typeof rendered === \"string\") {\n body.textContent = rendered;\n return;\n }\n body.replaceChildren(rendered);\n }\n\n /** Build one labelled region of the body: a heading plus a payload block. */\n #section(\n kind: string,\n labelText: string,\n ): {\n root: HTMLDivElement;\n label: HTMLSpanElement;\n body: HTMLPreElement;\n } {\n const root = document.createElement(\"div\");\n root.className = `tool-call-section tool-call-section--${kind}`;\n root.setAttribute(\"part\", `tool-card-section tool-card-${kind}-section`);\n\n const label = document.createElement(\"span\");\n label.className = \"tool-call-section-label\";\n label.setAttribute(\"part\", `tool-card-section-label tool-card-${kind}-label`);\n label.textContent = labelText;\n\n const body = document.createElement(\"pre\");\n body.className = `tool-call-${kind}`;\n body.setAttribute(\"part\", `tool-card-${kind}`);\n\n root.append(label, body);\n return { root, label, body };\n }\n\n #expanded(): boolean {\n return this.element.getAttribute(\"data-expanded\") === \"true\";\n }\n\n #setExpanded(expand: boolean): void {\n this.element.setAttribute(\"data-expanded\", String(expand));\n this.#toggle.setAttribute(\"aria-expanded\", String(expand));\n }\n}\n", "import { ICON_COPY, ICON_THUMB_DOWN, ICON_THUMB_UP } from \"../../constants.js\";\nimport type { UiStrings } from \"../ui_strings.js\";\n\n/** How long a button shows its confirmation before reverting. */\nconst CONFIRM_MS = 1500;\n\n/** What an action bar can do, beyond copying. */\nexport interface MessageActionsOptions {\n /** Localized strings. */\n strings: UiStrings;\n /**\n * The text Copy puts on the clipboard. Absent means no copy button.\n *\n * A function rather than a string because a bubble's content is rewritten\n * while it streams. Each button's option is also the statement that the\n * button belongs, so no second flag can disagree with it.\n */\n text?: () => string;\n /**\n * The rich flavour to copy alongside `text`, as an HTML fragment. Absent\n * means plain text only.\n *\n * It is what makes a copied table paste as a table: a spreadsheet or a chat\n * client reads `text/html` when offered and falls back to the plain flavour.\n */\n html?: () => string;\n /**\n * Report a rating for this message. Absent means no feedback buttons.\n *\n * The component stores nothing: a rating is the host's to keep, and a\n * write-only table nobody reads is not worth a schema.\n */\n onFeedback?: (rating: \"up\" | \"down\") => void;\n}\n\n/**\n * Give one finished message bubble its row of actions.\n *\n * **Finished** is load-bearing. A streaming bubble reassigns its `innerHTML` on\n * every delta, so anything attached mid-stream is discarded and rebuilt for\n * each one -- the same constraint `attachCopyButtons` records, one level up.\n *\n * Retry is deliberately **not** here: it belongs to the last turn only, so the\n * element owns it and moves it as the transcript grows. Everything on this bar\n * is safe to offer on any message, however old.\n *\n * Idempotent -- a bubble already given a bar is skipped, so a re-render or a\n * second call cannot stack rows.\n *\n * Passing neither `text` nor `onFeedback` builds an empty row; the element\n * skips the call when a host has turned both off.\n */\nexport function attachMessageActions(bubble: HTMLElement, options: MessageActionsOptions): void {\n if (existingBar(bubble) !== null) {\n return;\n }\n const bar = messageActionBar(bubble, options.strings);\n const text = options.text;\n if (text !== undefined) {\n bar.appendChild(copyButton(options.strings, text, options.html));\n }\n if (options.onFeedback !== undefined) {\n bar.append(\n feedbackButton(\"up\", options.strings.feedbackUp, options.onFeedback),\n feedbackButton(\"down\", options.strings.feedbackDown, options.onFeedback),\n );\n }\n}\n\n/**\n * The empty action row on `bubble`, created if it has none yet.\n *\n * Shared so a bubble that wants *only* Retry -- a failed run, which has nothing\n * worth copying and nothing to rate -- gets the same row, the same part name\n * and the same accessible grouping as every other message, rather than a\n * second thing that looks like one.\n */\nexport function messageActionBar(bubble: HTMLElement, strings: UiStrings): HTMLElement {\n const existing = existingBar(bubble);\n if (existing !== null) {\n return existing;\n }\n const bar = document.createElement(\"div\");\n bar.className = \"message-actions\";\n bar.setAttribute(\"part\", \"message-actions\");\n // A group rather than a toolbar: these are independent actions on the message\n // above, not a set the user arrows between.\n bar.setAttribute(\"role\", \"group\");\n bar.setAttribute(\"aria-label\", strings.messageActions);\n // A **sibling**, never a child. Inside the bubble the buttons join its\n // `textContent`, which is what Copy reads, what history persists and what\n // every existing assertion about a message's text compares against -- so an\n // answer would be copied back with the glyphs of the buttons that copied it.\n // The bubble must therefore already be in the tree when this is called.\n bubble.after(bar);\n return bar;\n}\n\n/** The action row belonging to `bubble`, if it has one. */\nfunction existingBar(bubble: HTMLElement): HTMLElement | null {\n const next = bubble.nextElementSibling;\n return next?.classList.contains(\"message-actions\") === true ? (next as HTMLElement) : null;\n}\n\n/**\n * Build one action button, labelled for screen readers rather than by glyph.\n *\n * `icon` is icon markup rather than a text glyph: the copy mark in particular\n * has no font behind it on most systems.\n *\n * The label is carried three ways, and each has a reader the others miss:\n * `aria-label` for assistive technology, `title` for the browser's own\n * tooltip, and `data-tooltip` for the one this component draws. The last is\n * not redundant with the second -- a `title` never appears on keyboard focus,\n * so without it a keyboard user has no way to see what the control does.\n *\n * The icon sits in its own part, so a host can restyle or replace it. A slot\n * would be the better channel and cannot be used here: these repeat once per\n * message, and a named slot can only be filled once.\n */\nexport function messageActionButton(\n modifier: string,\n label: string,\n icon: string,\n): HTMLButtonElement {\n const button = document.createElement(\"button\");\n button.type = \"button\";\n button.className = `message-action message-action--${modifier}`;\n button.setAttribute(\"part\", `message-action message-action-${modifier}`);\n setLabel(button, label);\n const holder = document.createElement(\"span\");\n holder.className = \"message-action-icon\";\n holder.setAttribute(\"part\", `message-action-icon message-action-icon-${modifier}`);\n holder.setAttribute(\"aria-hidden\", \"true\");\n // Author-written markup from constants, never message content.\n holder.innerHTML = icon;\n button.appendChild(holder);\n return button;\n}\n\n/** Put `label` on every channel that names this button. */\nfunction setLabel(button: HTMLButtonElement, label: string): void {\n button.title = label;\n button.setAttribute(\"aria-label\", label);\n button.dataset[\"tooltip\"] = label;\n}\n\nfunction copyButton(\n strings: UiStrings,\n text: () => string,\n html: (() => string) | undefined,\n): HTMLButtonElement {\n const button = messageActionButton(\"copy\", strings.copyMessage, ICON_COPY);\n button.addEventListener(\"click\", () => {\n void write(text(), html?.()).then((ok) => {\n // A denied clipboard permission is the common case, not an exception:\n // say so on the button rather than throwing into an unhandled rejection.\n flash(button, ok ? strings.copied : strings.copyFailed, strings.copyMessage);\n });\n });\n return button;\n}\n\n/**\n * Put the message on the clipboard, richest flavour first.\n *\n * Writing both flavours needs `ClipboardItem`, which not every engine that has\n * `writeText` also has -- and even where the constructor exists the write can\n * be refused. Neither is a failure worth reporting as one while the plain text\n * would still have landed, so both fall through to `writeText` and only that\n * decides what the button says.\n */\nasync function write(text: string, html: string | undefined): Promise<boolean> {\n const clipboard = navigator.clipboard;\n if (clipboard === undefined) {\n return false;\n }\n if (html !== undefined && typeof ClipboardItem === \"function\") {\n try {\n await clipboard.write([\n new ClipboardItem({\n \"text/plain\": new Blob([text], { type: \"text/plain\" }),\n \"text/html\": new Blob([html], { type: \"text/html\" }),\n }),\n ]);\n return true;\n } catch {\n // Fall through to the plain flavour.\n }\n }\n try {\n await clipboard.writeText(text);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction feedbackButton(\n rating: \"up\" | \"down\",\n label: string,\n report: (rating: \"up\" | \"down\") => void,\n): HTMLButtonElement {\n const button = messageActionButton(\n rating,\n label,\n rating === \"up\" ? ICON_THUMB_UP : ICON_THUMB_DOWN,\n );\n button.addEventListener(\"click\", () => {\n // Pressed rather than removed: the rating is a standing statement about the\n // message, and a button that vanishes leaves no record of what was said.\n const pressed = button.getAttribute(\"aria-pressed\") === \"true\";\n button.setAttribute(\"aria-pressed\", pressed ? \"false\" : \"true\");\n report(rating);\n });\n button.setAttribute(\"aria-pressed\", \"false\");\n return button;\n}\n\n/**\n * Flash `message` on the button, then restore `label`.\n *\n * The label to restore is passed rather than read back off the element: the\n * caller is the one that set it, and reading it would introduce a null arm that\n * cannot happen and cannot be covered.\n */\nfunction flash(button: HTMLButtonElement, message: string, label: string): void {\n setLabel(button, message);\n button.classList.add(\"message-action--confirmed\");\n setTimeout(() => {\n setLabel(button, label);\n button.classList.remove(\"message-action--confirmed\");\n }, CONFIRM_MS);\n}\n", "const {\n entries,\n setPrototypeOf,\n isFrozen,\n getPrototypeOf,\n getOwnPropertyDescriptor,\n} = Object;\n\nlet { freeze, seal, create } = Object; // eslint-disable-line import/no-mutable-exports\nlet { apply, construct } = typeof Reflect !== 'undefined' && Reflect;\n\nif (!freeze) {\n freeze = function <T>(x: T): T {\n return x;\n };\n}\n\nif (!seal) {\n seal = function <T>(x: T): T {\n return x;\n };\n}\n\nif (!apply) {\n apply = function <T>(\n func: (thisArg: any, ...args: any[]) => T,\n thisArg: any,\n ...args: any[]\n ): T {\n return func.apply(thisArg, args);\n };\n}\n\nif (!construct) {\n construct = function <T>(Func: new (...args: any[]) => T, ...args: any[]): T {\n return new Func(...args);\n };\n}\n\nconst arrayForEach = unapply(Array.prototype.forEach);\nconst arrayIndexOf = unapply(Array.prototype.indexOf);\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nconst arraySlice = unapply(Array.prototype.slice);\nconst arraySplice = unapply(Array.prototype.splice);\nconst arrayIsArray = Array.isArray;\n\nconst setCreate = unconstruct(Set) as () => Set<unknown>;\nconst setAdd = unapply(Set.prototype.add);\nconst setHas = unapply(Set.prototype.has);\n\nconst stringToLowerCase = unapply(String.prototype.toLowerCase);\nconst stringToString = unapply(String.prototype.toString);\nconst stringMatch = unapply(String.prototype.match);\nconst stringReplace = unapply(String.prototype.replace);\nconst stringIndexOf = unapply(String.prototype.indexOf);\nconst stringTrim = unapply(String.prototype.trim);\n\nconst numberToString = unapply(Number.prototype.toString);\nconst booleanToString = unapply(Boolean.prototype.toString);\nconst bigintToString =\n typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);\nconst symbolToString =\n typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);\n\nconst objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\nconst objectToString = unapply(Object.prototype.toString);\n\nconst regExpTest = unapply(RegExp.prototype.test);\n\nconst typeErrorCreate = unconstruct(TypeError);\n\n/**\n * Creates a new function that calls the given function with a specified thisArg and arguments.\n *\n * @param func - The function to be wrapped and called.\n * @returns A new function that calls the given function with a specified thisArg and arguments.\n */\nfunction unapply<T>(\n func: (thisArg: any, ...args: any[]) => T\n): (thisArg: any, ...args: any[]) => T {\n return (thisArg: any, ...args: any[]): T => {\n if (thisArg instanceof RegExp) {\n thisArg.lastIndex = 0;\n }\n\n return apply(func, thisArg, args);\n };\n}\n\n/**\n * Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n *\n * @param func - The constructor function to be wrapped and called.\n * @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n */\nfunction unconstruct<T>(\n Func: new (...args: any[]) => T\n): (...args: any[]) => T {\n return (...args: any[]): T => construct(Func, args);\n}\n\n/**\n * Add properties to a lookup table\n *\n * @param set - The set to which elements will be added.\n * @param array - The array containing elements to be added to the set.\n * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n * @returns The modified set with added elements.\n */\nfunction addToSet(\n set: Record<string, boolean>,\n array: readonly unknown[],\n transformCaseFunc: ReturnType<typeof unapply<string>> = stringToLowerCase\n): Record<string, boolean> {\n if (setPrototypeOf) {\n // Make 'in' and truthy checks like Boolean(set.constructor)\n // independent of any properties defined on Object.prototype.\n // Prevent prototype setters from intercepting set as a this value.\n setPrototypeOf(set, null);\n }\n\n if (!arrayIsArray(array)) {\n return set;\n }\n\n let l = array.length;\n while (l--) {\n let element = array[l];\n\n if (typeof element === 'string') {\n const lcElement = transformCaseFunc(element);\n\n if (lcElement !== element) {\n // Config presets (e.g. tags.js, attrs.js) are immutable.\n if (!isFrozen(array)) {\n (array as unknown[])[l] = lcElement;\n }\n\n element = lcElement;\n }\n }\n\n set[element as string] = true;\n }\n\n return set;\n}\n\n/**\n * Clean up an array to harden against CSPP\n *\n * @param array - The array to be cleaned.\n * @returns The cleaned version of the array\n */\nfunction cleanArray<T>(array: T[]): Array<T | null> {\n for (let index = 0; index < array.length; index++) {\n const isPropertyExist = objectHasOwnProperty(array, index);\n\n if (!isPropertyExist) {\n array[index] = null;\n }\n }\n\n return array;\n}\n\n/**\n * Shallow clone an object\n *\n * @param object - The object to be cloned.\n * @returns A new object that copies the original.\n */\nfunction clone<T extends Record<string, any>>(object: T): T {\n const newObject = create(null);\n\n for (const [property, value] of entries(object)) {\n const isPropertyExist = objectHasOwnProperty(object, property);\n\n if (isPropertyExist) {\n if (arrayIsArray(value)) {\n newObject[property] = cleanArray(value);\n } else if (\n value &&\n typeof value === 'object' &&\n value.constructor === Object\n ) {\n newObject[property] = clone(value);\n } else {\n newObject[property] = value;\n }\n }\n }\n\n return newObject;\n}\n\n/**\n * Convert non-node values into strings without depending on direct property access.\n *\n * @param value - The value to stringify.\n * @returns A string representation of the provided value.\n */\nfunction stringifyValue(value: unknown): string {\n switch (typeof value) {\n case 'string': {\n return value;\n }\n\n case 'number': {\n return numberToString(value);\n }\n\n case 'boolean': {\n return booleanToString(value);\n }\n\n case 'bigint': {\n return bigintToString ? bigintToString(value) : '0';\n }\n\n case 'symbol': {\n return symbolToString ? symbolToString(value) : 'Symbol()';\n }\n\n case 'undefined': {\n return objectToString(value);\n }\n\n case 'function':\n case 'object': {\n if (value === null) {\n return objectToString(value);\n }\n\n const valueAsRecord = value as Record<string, any>;\n const valueToString = lookupGetter(valueAsRecord, 'toString');\n\n if (typeof valueToString === 'function') {\n const stringified = valueToString(valueAsRecord);\n\n return typeof stringified === 'string'\n ? stringified\n : objectToString(stringified);\n }\n\n return objectToString(value);\n }\n\n default: {\n return objectToString(value);\n }\n }\n}\n\n/**\n * This method automatically checks if the prop is function or getter and behaves accordingly.\n *\n * @param object - The object to look up the getter function in its prototype chain.\n * @param prop - The property name for which to find the getter function.\n * @returns The getter function found in the prototype chain or a fallback function.\n */\nfunction lookupGetter<T extends Record<string, any>>(\n object: T,\n prop: string\n): ReturnType<typeof unapply<any>> | (() => null) {\n while (object !== null) {\n const desc = getOwnPropertyDescriptor(object, prop);\n\n if (desc) {\n if (desc.get) {\n return unapply(desc.get);\n }\n\n if (typeof desc.value === 'function') {\n return unapply(desc.value);\n }\n }\n\n object = getPrototypeOf(object);\n }\n\n function fallbackValue(): null {\n return null;\n }\n\n return fallbackValue;\n}\n\n/**\n * Like lookupGetter, but for accessor properties only, and returns null\n * instead of a null-returning fallback when no getter exists on the chain.\n * Lets a caller fall back to a direct property read in environments that\n * lack the getter, where a fallback returning null would be indistinguishable\n * from a legitimate null value (e.g. namespaceURI of a no-namespace element).\n *\n * @param object - The object (usually a prototype) to start the lookup at.\n * @param prop - The accessor property name.\n * @returns The unapplied getter, or null if none was found.\n */\nfunction lookupAccessor<T extends Record<string, any>>(\n object: T,\n prop: string\n): ReturnType<typeof unapply<any>> | null {\n while (object !== null) {\n const desc = getOwnPropertyDescriptor(object, prop);\n\n if (desc) {\n return desc.get ? unapply(desc.get) : null;\n }\n\n object = getPrototypeOf(object);\n }\n\n return null;\n}\n\nfunction isRegex(value: unknown): value is RegExp {\n try {\n regExpTest(value as RegExp, '');\n return true;\n } catch {\n return false;\n }\n}\n\nexport {\n // Array\n arrayForEach,\n arrayIndexOf,\n arrayIsArray,\n arrayLastIndexOf,\n arrayPop,\n arrayPush,\n arraySlice,\n arraySplice,\n // Object\n entries,\n freeze,\n getPrototypeOf,\n getOwnPropertyDescriptor,\n isFrozen,\n setPrototypeOf,\n seal,\n clone,\n create,\n objectHasOwnProperty,\n objectToString,\n // RegExp\n regExpTest,\n setAdd,\n setCreate,\n setHas,\n isRegex,\n // String\n stringIndexOf,\n stringMatch,\n stringReplace,\n stringToLowerCase,\n stringToString,\n stringTrim,\n // Other conversion\n stringifyValue,\n // Errors\n typeErrorCreate,\n // Other\n lookupAccessor,\n lookupGetter,\n addToSet,\n // Reflect\n unapply,\n unconstruct,\n};\n", "import { freeze } from './utils.js';\n\nexport const html = freeze([\n 'a',\n 'abbr',\n 'acronym',\n 'address',\n 'area',\n 'article',\n 'aside',\n 'audio',\n 'b',\n 'bdi',\n 'bdo',\n 'big',\n 'blink',\n 'blockquote',\n 'body',\n 'br',\n 'button',\n 'canvas',\n 'caption',\n 'center',\n 'cite',\n 'code',\n 'col',\n 'colgroup',\n 'content',\n 'data',\n 'datalist',\n 'dd',\n 'decorator',\n 'del',\n 'details',\n 'dfn',\n 'dialog',\n 'dir',\n 'div',\n 'dl',\n 'dt',\n 'element',\n 'em',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'font',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'head',\n 'header',\n 'hgroup',\n 'hr',\n 'html',\n 'i',\n 'img',\n 'input',\n 'ins',\n 'kbd',\n 'label',\n 'legend',\n 'li',\n 'main',\n 'map',\n 'mark',\n 'marquee',\n 'menu',\n 'menuitem',\n 'meter',\n 'nav',\n 'nobr',\n 'ol',\n 'optgroup',\n 'option',\n 'output',\n 'p',\n 'picture',\n 'pre',\n 'progress',\n 'q',\n 'rp',\n 'rt',\n 'ruby',\n 's',\n 'samp',\n 'search',\n 'section',\n 'select',\n 'shadow',\n 'slot',\n 'small',\n 'source',\n 'spacer',\n 'span',\n 'strike',\n 'strong',\n 'style',\n 'sub',\n 'summary',\n 'sup',\n 'table',\n 'tbody',\n 'td',\n 'template',\n 'textarea',\n 'tfoot',\n 'th',\n 'thead',\n 'time',\n 'tr',\n 'track',\n 'tt',\n 'u',\n 'ul',\n 'var',\n 'video',\n 'wbr',\n] as const);\n\nexport const svg = freeze([\n 'svg',\n 'a',\n 'altglyph',\n 'altglyphdef',\n 'altglyphitem',\n 'animatecolor',\n 'animatemotion',\n 'animatetransform',\n 'circle',\n 'clippath',\n 'defs',\n 'desc',\n 'ellipse',\n 'enterkeyhint',\n 'exportparts',\n 'filter',\n 'font',\n 'g',\n 'glyph',\n 'glyphref',\n 'hkern',\n 'image',\n 'inputmode',\n 'line',\n 'lineargradient',\n 'marker',\n 'mask',\n 'metadata',\n 'mpath',\n 'part',\n 'path',\n 'pattern',\n 'polygon',\n 'polyline',\n 'radialgradient',\n 'rect',\n 'stop',\n 'style',\n 'switch',\n 'symbol',\n 'text',\n 'textpath',\n 'title',\n 'tref',\n 'tspan',\n 'view',\n 'vkern',\n] as const);\n\nexport const svgFilters = freeze([\n 'feBlend',\n 'feColorMatrix',\n 'feComponentTransfer',\n 'feComposite',\n 'feConvolveMatrix',\n 'feDiffuseLighting',\n 'feDisplacementMap',\n 'feDistantLight',\n 'feDropShadow',\n 'feFlood',\n 'feFuncA',\n 'feFuncB',\n 'feFuncG',\n 'feFuncR',\n 'feGaussianBlur',\n 'feImage',\n 'feMerge',\n 'feMergeNode',\n 'feMorphology',\n 'feOffset',\n 'fePointLight',\n 'feSpecularLighting',\n 'feSpotLight',\n 'feTile',\n 'feTurbulence',\n] as const);\n\n// List of SVG elements that are disallowed by default.\n// We still need to know them so that we can do namespace\n// checks properly in case one wants to add them to\n// allow-list.\nexport const svgDisallowed = freeze([\n 'animate',\n 'color-profile',\n 'cursor',\n 'discard',\n 'font-face',\n 'font-face-format',\n 'font-face-name',\n 'font-face-src',\n 'font-face-uri',\n 'foreignobject',\n 'hatch',\n 'hatchpath',\n 'mesh',\n 'meshgradient',\n 'meshpatch',\n 'meshrow',\n 'missing-glyph',\n 'script',\n 'set',\n 'solidcolor',\n 'unknown',\n 'use',\n] as const);\n\nexport const mathMl = freeze([\n 'math',\n 'menclose',\n 'merror',\n 'mfenced',\n 'mfrac',\n 'mglyph',\n 'mi',\n 'mlabeledtr',\n 'mmultiscripts',\n 'mn',\n 'mo',\n 'mover',\n 'mpadded',\n 'mphantom',\n 'mroot',\n 'mrow',\n 'ms',\n 'mspace',\n 'msqrt',\n 'mstyle',\n 'msub',\n 'msup',\n 'msubsup',\n 'mtable',\n 'mtd',\n 'mtext',\n 'mtr',\n 'munder',\n 'munderover',\n 'mprescripts',\n] as const);\n\n// Similarly to SVG, we want to know all MathML elements,\n// even those that we disallow by default.\nexport const mathMlDisallowed = freeze([\n 'maction',\n 'maligngroup',\n 'malignmark',\n 'mlongdiv',\n 'mscarries',\n 'mscarry',\n 'msgroup',\n 'mstack',\n 'msline',\n 'msrow',\n 'semantics',\n 'annotation',\n 'annotation-xml',\n 'mprescripts',\n 'none',\n] as const);\n\nexport const text = freeze(['#text'] as const);\n", "import { freeze } from './utils.js';\n\nexport const html = freeze([\n 'accept',\n 'action',\n 'align',\n 'alt',\n 'autocapitalize',\n 'autocomplete',\n 'autopictureinpicture',\n 'autoplay',\n 'background',\n 'bgcolor',\n 'border',\n 'capture',\n 'cellpadding',\n 'cellspacing',\n 'checked',\n 'cite',\n 'class',\n 'clear',\n 'color',\n 'cols',\n 'colspan',\n 'command',\n 'commandfor',\n 'controls',\n 'controlslist',\n 'coords',\n 'crossorigin',\n 'datetime',\n 'decoding',\n 'default',\n 'dir',\n 'disabled',\n 'disablepictureinpicture',\n 'disableremoteplayback',\n 'download',\n 'draggable',\n 'enctype',\n 'enterkeyhint',\n 'exportparts',\n 'face',\n 'for',\n 'headers',\n 'height',\n 'hidden',\n 'high',\n 'href',\n 'hreflang',\n 'id',\n 'inert',\n 'inputmode',\n 'integrity',\n 'ismap',\n 'kind',\n 'label',\n 'lang',\n 'list',\n 'loading',\n 'loop',\n 'low',\n 'max',\n 'maxlength',\n 'media',\n 'method',\n 'min',\n 'minlength',\n 'multiple',\n 'muted',\n 'name',\n 'nonce',\n 'noshade',\n 'novalidate',\n 'nowrap',\n 'open',\n 'optimum',\n 'part',\n 'pattern',\n 'placeholder',\n 'playsinline',\n 'popover',\n 'popovertarget',\n 'popovertargetaction',\n 'poster',\n 'preload',\n 'pubdate',\n 'radiogroup',\n 'readonly',\n 'rel',\n 'required',\n 'rev',\n 'reversed',\n 'role',\n 'rows',\n 'rowspan',\n 'spellcheck',\n 'scope',\n 'selected',\n 'shape',\n 'size',\n 'sizes',\n 'slot',\n 'span',\n 'srclang',\n 'start',\n 'src',\n 'srcset',\n 'step',\n 'style',\n 'summary',\n 'tabindex',\n 'title',\n 'translate',\n 'type',\n 'usemap',\n 'valign',\n 'value',\n 'width',\n 'wrap',\n 'xmlns',\n] as const);\n\nexport const svg = freeze([\n 'accent-height',\n 'accumulate',\n 'additive',\n 'alignment-baseline',\n 'amplitude',\n 'ascent',\n 'attributename',\n 'attributetype',\n 'azimuth',\n 'basefrequency',\n 'baseline-shift',\n 'begin',\n 'bias',\n 'by',\n 'class',\n 'clip',\n 'clippathunits',\n 'clip-path',\n 'clip-rule',\n 'color',\n 'color-interpolation',\n 'color-interpolation-filters',\n 'color-profile',\n 'color-rendering',\n 'cx',\n 'cy',\n 'd',\n 'dx',\n 'dy',\n 'diffuseconstant',\n 'direction',\n 'display',\n 'divisor',\n 'dominant-baseline',\n 'dur',\n 'edgemode',\n 'elevation',\n 'end',\n 'exponent',\n 'fill',\n 'fill-opacity',\n 'fill-rule',\n 'filter',\n 'filterunits',\n 'flood-color',\n 'flood-opacity',\n 'font-family',\n 'font-size',\n 'font-size-adjust',\n 'font-stretch',\n 'font-style',\n 'font-variant',\n 'font-weight',\n 'fx',\n 'fy',\n 'g1',\n 'g2',\n 'glyph-name',\n 'glyphref',\n 'gradientunits',\n 'gradienttransform',\n 'height',\n 'href',\n 'id',\n 'image-rendering',\n 'in',\n 'in2',\n 'intercept',\n 'k',\n 'k1',\n 'k2',\n 'k3',\n 'k4',\n 'kerning',\n 'keypoints',\n 'keysplines',\n 'keytimes',\n 'lang',\n 'lengthadjust',\n 'letter-spacing',\n 'kernelmatrix',\n 'kernelunitlength',\n 'lighting-color',\n 'local',\n 'marker-end',\n 'marker-mid',\n 'marker-start',\n 'markerheight',\n 'markerunits',\n 'markerwidth',\n 'maskcontentunits',\n 'maskunits',\n 'max',\n 'mask',\n 'mask-type',\n 'media',\n 'method',\n 'mode',\n 'min',\n 'name',\n 'numoctaves',\n 'offset',\n 'operator',\n 'opacity',\n 'order',\n 'orient',\n 'orientation',\n 'origin',\n 'overflow',\n 'paint-order',\n 'path',\n 'pathlength',\n 'patterncontentunits',\n 'patterntransform',\n 'patternunits',\n 'pointer-events',\n 'points',\n 'preservealpha',\n 'preserveaspectratio',\n 'primitiveunits',\n 'r',\n 'rx',\n 'ry',\n 'radius',\n 'refx',\n 'refy',\n 'repeatcount',\n 'repeatdur',\n 'restart',\n 'result',\n 'rotate',\n 'scale',\n 'seed',\n 'shape-rendering',\n 'slope',\n 'specularconstant',\n 'specularexponent',\n 'spreadmethod',\n 'startoffset',\n 'stddeviation',\n 'stitchtiles',\n 'stop-color',\n 'stop-opacity',\n 'stroke-dasharray',\n 'stroke-dashoffset',\n 'stroke-linecap',\n 'stroke-linejoin',\n 'stroke-miterlimit',\n 'stroke-opacity',\n 'stroke',\n 'stroke-width',\n 'style',\n 'surfacescale',\n 'systemlanguage',\n 'tabindex',\n 'tablevalues',\n 'targetx',\n 'targety',\n 'transform',\n 'transform-origin',\n 'text-anchor',\n 'text-decoration',\n 'text-orientation',\n 'text-rendering',\n 'textlength',\n 'type',\n 'u1',\n 'u2',\n 'unicode',\n 'values',\n 'vector-effect',\n 'viewbox',\n 'visibility',\n 'version',\n 'vert-adv-y',\n 'vert-origin-x',\n 'vert-origin-y',\n 'width',\n 'word-spacing',\n 'wrap',\n 'writing-mode',\n 'xchannelselector',\n 'ychannelselector',\n 'x',\n 'x1',\n 'x2',\n 'xmlns',\n 'y',\n 'y1',\n 'y2',\n 'z',\n 'zoomandpan',\n] as const);\n\nexport const mathMl = freeze([\n 'accent',\n 'accentunder',\n 'align',\n 'bevelled',\n 'close',\n 'columnalign',\n 'columnlines',\n 'columnspacing',\n 'columnspan',\n 'denomalign',\n 'depth',\n 'dir',\n 'display',\n 'displaystyle',\n 'encoding',\n 'fence',\n 'frame',\n 'height',\n 'href',\n 'id',\n 'largeop',\n 'length',\n 'linethickness',\n 'lquote',\n 'lspace',\n 'mathbackground',\n 'mathcolor',\n 'mathsize',\n 'mathvariant',\n 'maxsize',\n 'minsize',\n 'movablelimits',\n 'notation',\n 'numalign',\n 'open',\n 'rowalign',\n 'rowlines',\n 'rowspacing',\n 'rowspan',\n 'rspace',\n 'rquote',\n 'scriptlevel',\n 'scriptminsize',\n 'scriptsizemultiplier',\n 'selection',\n 'separator',\n 'separators',\n 'stretchy',\n 'subscriptshift',\n 'supscriptshift',\n 'symmetric',\n 'voffset',\n 'width',\n 'xmlns',\n]);\n\nexport const xml = freeze([\n 'xlink:href',\n 'xml:id',\n 'xlink:title',\n 'xml:space',\n 'xmlns:xlink',\n] as const);\n", "import { seal } from './utils.js';\n\nexport const MUSTACHE_EXPR = seal(/{{[\\w\\W]*|^[\\w\\W]*}}/g);\nexport const ERB_EXPR = seal(/<%[\\w\\W]*|^[\\w\\W]*%>/g);\nexport const TMPLIT_EXPR = seal(/\\${[\\w\\W]*/g);\nexport const DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/); // eslint-disable-line no-useless-escape\nexport const ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\nexport const IS_ALLOWED_URI = seal(\n /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n);\nexport const IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nexport const ATTR_WHITESPACE = seal(\n /[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n);\nexport const DOCTYPE_NAME = seal(/^html$/i);\nexport const CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\n\n// Markup-significant character probes used by _sanitizeElements.\n// Shared module-level instances are safe despite the sticky /g flags:\n// unapply() resets lastIndex for RegExp receivers before every call.\nexport const ELEMENT_MARKUP_PROBE = seal(/<[/\\w!]/g);\nexport const COMMENT_MARKUP_PROBE = seal(/<[/\\w]/g);\nexport const FALLBACK_TAG_CLOSE = seal(/<\\/no(script|embed|frames)/i);\nexport const SELF_CLOSING_TAG = seal(/\\/>/i);\n", "import type { Config, UseProfilesConfig } from './config';\nimport type { DOMPurify, HooksMap, HookFunction, WindowLike } from './types';\nimport * as TAGS from './tags.js';\nimport * as ATTRS from './attrs.js';\nimport * as EXPRESSIONS from './regexp.js';\nimport {\n addToSet,\n clone,\n entries,\n freeze,\n seal,\n arrayForEach,\n arrayIsArray,\n arrayLastIndexOf,\n arrayPop,\n arrayPush,\n arraySlice,\n arraySplice,\n stringMatch,\n stringReplace,\n stringToLowerCase,\n stringToString,\n stringIndexOf,\n stringTrim,\n regExpTest,\n setAdd,\n setCreate,\n setHas,\n isRegex,\n typeErrorCreate,\n lookupAccessor,\n lookupGetter,\n create,\n objectHasOwnProperty,\n stringifyValue,\n} from './utils.js';\n\nexport type { Config } from './config';\n\nexport type {\n DOMPurify,\n RemovedElement,\n RemovedAttribute,\n HookName,\n NodeHook,\n ElementHook,\n DocumentFragmentHook,\n UponSanitizeElementHook,\n UponSanitizeAttributeHook,\n UponSanitizeElementHookEvent,\n UponSanitizeAttributeHookEvent,\n WindowLike,\n} from './types';\n\ndeclare const VERSION: string;\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\nconst NODE_TYPE = {\n element: 1,\n attribute: 2,\n text: 3,\n cdataSection: 4,\n entityReference: 5, // Deprecated\n entityNode: 6, // Deprecated\n processingInstruction: 7,\n comment: 8,\n document: 9,\n documentType: 10,\n documentFragment: 11,\n notation: 12, // Deprecated\n};\n\n/* HTML-namespace elements whose child text nodes are serialized *literally*\n (unescaped) by the HTML fragment-serialization algorithm. Two reparse-mXSS\n shapes ride on that literal serialization:\n (a) an element child - a tree the HTML parser can never build, but the DOM\n API and an XML/XHTML parse can - after which a `</tag>`-bearing text\n sibling breaks the element open on reparse; and\n (b) text-only content that already carries the element's OWN end tag, e.g.\n `<style>...</style><img onerror=x>` built as a node, which the literal\n serializer emits verbatim for the HTML parser to re-open.\n Shape (a) is handled by the firstElementChild branch in _isUnsafeNode; shape\n (b), and any other markup in the text, by the ELEMENT_MARKUP_PROBE branch next\n to it. Both read textContent (the raw-serialized form for these elements)\n rather than innerHTML, because an XML/XHTML working document serializes\n innerHTML with `<` escaped, which silently blinds the innerHTML-based probes\n (rule 1's second probe and FALLBACK_TAG_CLOSE) there.\n `script` is never allow-listed, but is kept here so the guard matches the\n serializer's own literal-text list exactly. */\nconst LITERAL_TEXT_ELEMENT_NAMES = [\n 'style',\n 'script',\n 'xmp',\n 'iframe',\n 'noembed',\n 'noframes',\n 'plaintext',\n 'noscript',\n];\nconst LITERAL_TEXT_ELEMENTS = freeze(addToSet({}, LITERAL_TEXT_ELEMENT_NAMES));\n\nconst getGlobal = function (): WindowLike {\n return typeof window === 'undefined' ? null : window;\n};\n\n/**\n * Creates a no-op policy for internal use only.\n * Don't export this function outside this module!\n * @param trustedTypes The policy factory.\n * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).\n * @return The policy created (or null, if Trusted Types\n * are not supported or creating the policy failed).\n */\nconst _createTrustedTypesPolicy = function (\n trustedTypes: TrustedTypePolicyFactory,\n purifyHostElement: HTMLScriptElement\n) {\n if (\n typeof trustedTypes !== 'object' ||\n typeof trustedTypes.createPolicy !== 'function'\n ) {\n return null;\n }\n\n // Allow the callers to control the unique policy name\n // by adding a data-tt-policy-suffix to the script element with the DOMPurify.\n // Policy creation with duplicate names throws in Trusted Types.\n let suffix = null;\n const ATTR_NAME = 'data-tt-policy-suffix';\n if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {\n suffix = purifyHostElement.getAttribute(ATTR_NAME);\n }\n\n const policyName = 'dompurify' + (suffix ? '#' + suffix : '');\n\n try {\n return trustedTypes.createPolicy(policyName, {\n createHTML(html) {\n return html;\n },\n createScriptURL(scriptUrl) {\n return scriptUrl;\n },\n });\n } catch (_) {\n // Policy creation failed (most likely another DOMPurify script has\n // already run). Skip creating the policy, as this will only cause errors\n // if TT are enforced.\n console.warn(\n 'TrustedTypes policy ' + policyName + ' could not be created.'\n );\n return null;\n }\n};\n\nconst _createHooksMap = function (): HooksMap {\n return {\n afterSanitizeAttributes: [],\n afterSanitizeElements: [],\n afterSanitizeShadowDOM: [],\n beforeSanitizeAttributes: [],\n beforeSanitizeElements: [],\n beforeSanitizeShadowDOM: [],\n uponSanitizeAttribute: [],\n uponSanitizeElement: [],\n uponSanitizeShadowNode: [],\n };\n};\n\n/**\n * Resolve a set-valued configuration option: a fresh set built from\n * cfg[key] when it is an own array property (seeded with a clone of\n * options.base when given, case-normalized via options.transform),\n * the fallback set otherwise.\n *\n * @param cfg the cloned, prototype-free configuration object\n * @param key the configuration property to read\n * @param fallback the set to use when the option is absent or not an array\n * @param options transform and optional base set to merge into\n * @returns the resolved set\n */\nconst _resolveSetOption = function (\n cfg: Config,\n key: keyof Config,\n fallback: Record<string, boolean>,\n options: {\n transform: Parameters<typeof addToSet>[2];\n base?: Record<string, boolean>;\n }\n): Record<string, boolean> {\n return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key])\n ? addToSet(\n options.base ? clone(options.base) : {},\n cfg[key] as readonly unknown[],\n options.transform\n )\n : fallback;\n};\n\n/**\n * Resolve an object-valued configuration option: a prototype-free clone\n * of cfg[key] when it is an own, truthy object property, else a fresh\n * fallback built by makeFallback (fresh on every parse, so a previous\n * parse can never leak state into the next one).\n *\n * @param cfg the cloned, prototype-free configuration object\n * @param key the configuration property to read\n * @param makeFallback builds the fallback value when the option is absent\n * @returns the resolved object\n */\nconst _resolveObjectOption = function <T extends Record<string, any>>(\n cfg: Config,\n key: keyof Config,\n makeFallback: () => T\n): T {\n const value = objectHasOwnProperty(cfg, key) ? cfg[key] : undefined;\n return value && typeof value === 'object'\n ? clone(value as T)\n : makeFallback();\n};\n\nfunction createDOMPurify(window: WindowLike = getGlobal()): DOMPurify {\n const DOMPurify: DOMPurify = (root: WindowLike) => createDOMPurify(root);\n\n DOMPurify.version = VERSION;\n\n DOMPurify.removed = [];\n\n if (\n !window ||\n !window.document ||\n window.document.nodeType !== NODE_TYPE.document ||\n !window.Element\n ) {\n // Not running in a browser, provide a factory function\n // so that you can pass your own Window\n DOMPurify.isSupported = false;\n\n return DOMPurify;\n }\n\n let { document } = window;\n\n const originalDocument = document;\n const currentScript: HTMLScriptElement =\n originalDocument.currentScript as HTMLScriptElement;\n const {\n DocumentFragment,\n HTMLTemplateElement,\n Node,\n Element,\n NodeFilter,\n NamedNodeMap = window.NamedNodeMap || (window as any).MozNamedAttrMap,\n HTMLFormElement,\n DOMParser,\n trustedTypes,\n } = window;\n\n const ElementPrototype = Element.prototype;\n\n const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');\n const remove = lookupGetter(ElementPrototype, 'remove');\n // Clobber-safe Attr-node removal. On an HTMLFormElement a descendant named\n // \"removeAttributeNode\" shadows the prototype method via\n // [LegacyOverrideBuiltIns], so element.removeAttributeNode(attr) throws.\n // Calling the cached Element.prototype method with the element as the\n // receiver removes the exact live Attr node regardless of the shadowing.\n const removeAttributeNode = lookupGetter(\n ElementPrototype,\n 'removeAttributeNode'\n );\n const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');\n const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');\n const getParentNode = lookupGetter(ElementPrototype, 'parentNode');\n const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');\n const getAttributes = lookupGetter(ElementPrototype, 'attributes');\n const getNodeType =\n Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;\n const getNodeName =\n Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;\n const getOwnerDocument =\n Node && Node.prototype\n ? lookupGetter(Node.prototype, 'ownerDocument')\n : null;\n\n /* Clobber-safe nodeType / nodeName reads through the cached Node.prototype\n getters, with a direct-property fallback for environments that lack\n Node.prototype. Sites that need a different fallback (e.g. _isClobbered\n returns early on a null name) intentionally keep their own reads. */\n const _readNodeType = function (node: Node): number {\n return getNodeType ? getNodeType(node) : (node as any).nodeType;\n };\n\n const _readNodeName = function (node: Node): string {\n return getNodeName ? getNodeName(node) : (node as any).nodeName;\n };\n\n /* Element namespace through the cached Element.prototype getter, so a live\n node's own-property override (Object.defineProperty) cannot steer\n namespace decisions; direct read where the getter does not exist. Only\n call this on Elements - the getter throws on other node types. */\n const getNamespaceURI = lookupAccessor(ElementPrototype, 'namespaceURI');\n const _readNamespaceURI = function (element: Element): string | null {\n return getNamespaceURI\n ? getNamespaceURI(element)\n : (element as any).namespaceURI;\n };\n\n // As per issue #47, the web-components registry is inherited by a\n // new document created via createHTMLDocument. As per the spec\n // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)\n // a new empty registry is used when creating a template contents owner\n // document, so we use that as our parent document to ensure nothing\n // is inherited.\n if (typeof HTMLTemplateElement === 'function') {\n const template = document.createElement('template');\n if (template.content && template.content.ownerDocument) {\n document = template.content.ownerDocument;\n }\n }\n\n let trustedTypesPolicy;\n let emptyHTML = '';\n\n // The instance's own internal Trusted Types policy. Unlike a caller-supplied\n // `TRUSTED_TYPES_POLICY`, this is created at most once \u2014 Trusted Types throws\n // on duplicate policy names \u2014 and is the only policy allowed to persist\n // across configurations and survive `clearConfig()`.\n let defaultTrustedTypesPolicy;\n let defaultTrustedTypesPolicyResolved = false;\n\n // Tracks whether we are already inside a call to the configured Trusted Types\n // policy (`createHTML` or `createScriptURL`). If a supplied policy callback\n // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would\n // re-enter the policy and recurse until the stack overflows. We detect that\n // re-entry and throw a clear, actionable error instead. The guard is shared\n // across both callbacks, because either one re-entering `sanitize` triggers\n // the same unbounded recursion.\n let IN_TRUSTED_TYPES_POLICY = 0;\n const _assertNotInTrustedTypesPolicy = function (): void {\n if (IN_TRUSTED_TYPES_POLICY > 0) {\n throw typeErrorCreate(\n 'A configured TRUSTED_TYPES_POLICY callback (createHTML or ' +\n 'createScriptURL) must not call DOMPurify.sanitize, as that causes ' +\n 'infinite recursion. Do not pass a policy whose callbacks wrap ' +\n 'DOMPurify as TRUSTED_TYPES_POLICY; see the \"DOMPurify and Trusted ' +\n 'Types\" section of the README.'\n );\n }\n };\n\n const _createTrustedHTML = function (html: string): string {\n _assertNotInTrustedTypesPolicy();\n\n IN_TRUSTED_TYPES_POLICY++;\n try {\n return trustedTypesPolicy.createHTML(html);\n } finally {\n IN_TRUSTED_TYPES_POLICY--;\n }\n };\n\n const _createTrustedScriptURL = function (scriptUrl: string): string {\n _assertNotInTrustedTypesPolicy();\n\n IN_TRUSTED_TYPES_POLICY++;\n try {\n return trustedTypesPolicy.createScriptURL(scriptUrl);\n } finally {\n IN_TRUSTED_TYPES_POLICY--;\n }\n };\n\n // Lazily resolve (and cache) the instance's internal default policy.\n // Resolution is attempted at most once: a successful `createPolicy` cannot be\n // repeated (Trusted Types throws on duplicate names), and a failed or\n // unsupported attempt must not be retried on every parse.\n const _getDefaultTrustedTypesPolicy = function () {\n if (!defaultTrustedTypesPolicyResolved) {\n defaultTrustedTypesPolicy = _createTrustedTypesPolicy(\n trustedTypes,\n currentScript\n );\n defaultTrustedTypesPolicyResolved = true;\n }\n\n return defaultTrustedTypesPolicy;\n };\n\n const {\n implementation,\n createNodeIterator,\n createDocumentFragment,\n getElementsByTagName,\n } = document;\n const { importNode } = originalDocument;\n\n let hooks = _createHooksMap();\n\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n DOMPurify.isSupported =\n typeof entries === 'function' &&\n typeof getParentNode === 'function' &&\n implementation &&\n implementation.createHTMLDocument !== undefined;\n\n const {\n MUSTACHE_EXPR,\n ERB_EXPR,\n TMPLIT_EXPR,\n DATA_ATTR,\n ARIA_ATTR,\n IS_SCRIPT_OR_DATA,\n ATTR_WHITESPACE,\n CUSTOM_ELEMENT,\n } = EXPRESSIONS;\n\n let { IS_ALLOWED_URI } = EXPRESSIONS;\n\n /**\n * We consider the elements and attributes below to be safe. Ideally\n * don't add any new ones but feel free to remove unwanted ones.\n */\n\n /* allowed element names */\n let ALLOWED_TAGS = null;\n const DEFAULT_ALLOWED_TAGS = addToSet({}, [\n ...TAGS.html,\n ...TAGS.svg,\n ...TAGS.svgFilters,\n ...TAGS.mathMl,\n ...TAGS.text,\n ]);\n\n /* Allowed attribute names */\n let ALLOWED_ATTR = null;\n const DEFAULT_ALLOWED_ATTR = addToSet({}, [\n ...ATTRS.html,\n ...ATTRS.svg,\n ...ATTRS.mathMl,\n ...ATTRS.xml,\n ]);\n\n /*\n * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.\n * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)\n * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)\n * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.\n */\n let CUSTOM_ELEMENT_HANDLING = Object.seal(\n create(null, {\n tagNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null,\n },\n attributeNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null,\n },\n allowCustomizedBuiltInElements: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: false,\n },\n })\n );\n\n /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */\n let FORBID_TAGS = null;\n\n /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */\n let FORBID_ATTR = null;\n\n /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */\n const EXTRA_ELEMENT_HANDLING = Object.seal(\n create(null, {\n tagCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null,\n },\n attributeCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null,\n },\n })\n );\n\n /* Decide if ARIA attributes are okay */\n let ALLOW_ARIA_ATTR = true;\n\n /* Decide if custom data attributes are okay */\n let ALLOW_DATA_ATTR = true;\n\n /* Decide if unknown protocols are okay */\n let ALLOW_UNKNOWN_PROTOCOLS = false;\n\n /* Decide if self-closing tags in attributes are allowed.\n * Usually removed due to a mXSS issue in jQuery 3.0 */\n let ALLOW_SELF_CLOSE_IN_ATTR = true;\n\n /* Output should be safe for common template engines.\n * This means, DOMPurify removes data attributes, mustaches and ERB\n */\n let SAFE_FOR_TEMPLATES = false;\n\n /* Output should be safe even for XML used within HTML and alike.\n * This means, DOMPurify removes comments when containing risky content.\n */\n let SAFE_FOR_XML = true;\n\n /* Decide if document with <html>... should be returned */\n let WHOLE_DOCUMENT = false;\n\n /* Track whether config is already set on this instance of DOMPurify. */\n let SET_CONFIG = false;\n\n /* Pristine allowlist bindings captured at setConfig() time. On the\n * persistent-config path sanitize() restores the sets from these before\n * the per-walk hook clone-guard, so a hook's in-call widening cannot\n * carry across calls. Null until setConfig() is called; reset by\n * clearConfig(). */\n let SET_CONFIG_ALLOWED_TAGS = null;\n let SET_CONFIG_ALLOWED_ATTR = null;\n\n /* Decide if all elements (e.g. style, script) must be children of\n * document.body. By default, browsers might move them to document.head */\n let FORCE_BODY = false;\n\n /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported).\n * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead\n */\n let RETURN_DOM = false;\n\n /* Decide if a DOM `DocumentFragment` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported) */\n let RETURN_DOM_FRAGMENT = false;\n\n /* Try to return a Trusted Type object instead of a string, return a string in\n * case Trusted Types are not supported */\n let RETURN_TRUSTED_TYPE = false;\n\n /* Output should be free from DOM clobbering attacks?\n * This sanitizes markups named with colliding, clobberable built-in DOM APIs.\n */\n let SANITIZE_DOM = true;\n\n /* Achieve full DOM Clobbering protection by isolating the namespace of named\n * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.\n *\n * HTML/DOM spec rules that enable DOM Clobbering:\n * - Named Access on Window (\u00A77.3.3)\n * - DOM Tree Accessors (\u00A73.1.5)\n * - Form Element Parent-Child Relations (\u00A74.10.3)\n * - Iframe srcdoc / Nested WindowProxies (\u00A74.8.5)\n * - HTMLCollection (\u00A74.2.10.2)\n *\n * Namespace isolation is implemented by prefixing `id` and `name` attributes\n * with a constant string, i.e., `user-content-`\n */\n let SANITIZE_NAMED_PROPS = false;\n const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';\n\n /* Keep element content when removing element? */\n let KEEP_CONTENT = true;\n\n /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead\n * of importing it into a new Document and returning a sanitized copy */\n let IN_PLACE = false;\n\n /* IN_PLACE: nodes processed during the current call */\n let IN_PLACE_VISITED: Set<unknown> | null = null;\n\n /* Allow usage of profiles like html, svg and mathMl */\n let USE_PROFILES: UseProfilesConfig | false = {};\n\n /* Tags to ignore content of when KEEP_CONTENT is true */\n let FORBID_CONTENTS = null;\n const DEFAULT_FORBID_CONTENTS = addToSet({}, [\n 'annotation-xml',\n 'audio',\n 'colgroup',\n 'desc',\n 'foreignobject',\n 'head',\n 'iframe',\n 'math',\n 'mi',\n 'mn',\n 'mo',\n 'ms',\n 'mtext',\n 'noembed',\n 'noframes',\n 'noscript',\n 'plaintext',\n 'script',\n // <selectedcontent> mirrors the selected <option>'s subtree, cloned by\n // the UA (customizable <select>) \u2014 including any on* handlers \u2014 and the\n // engine re-mirrors synchronously whenever a removal changes which\n // option/selectedcontent is current, even inside DOMPurify's inert\n // DOMParser document. Hoisting its children on removal re-inserts a fresh\n // mirror target ahead of the walk, which the engine refills, looping\n // forever (DoS) and amplifying output. Dropping its content on removal\n // (rather than hoisting) breaks that cascade; the content is a duplicate\n // of the option, which is sanitized on its own. See campaign-3 F1/F6.\n 'selectedcontent',\n 'style',\n 'svg',\n 'template',\n 'thead',\n 'title',\n 'video',\n 'xmp',\n ]);\n\n /* Tags that are safe for data: URIs */\n let DATA_URI_TAGS = null;\n const DEFAULT_DATA_URI_TAGS = addToSet({}, [\n 'audio',\n 'video',\n 'img',\n 'source',\n 'image',\n 'track',\n ]);\n\n /* Attributes safe for values like \"javascript:\" */\n let URI_SAFE_ATTRIBUTES = null;\n const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, [\n 'alt',\n 'class',\n 'for',\n 'id',\n 'label',\n 'name',\n 'pattern',\n 'placeholder',\n 'role',\n 'summary',\n 'title',\n 'value',\n 'style',\n 'xmlns',\n ]);\n\n const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n /* Document namespace */\n let NAMESPACE = HTML_NAMESPACE;\n let IS_EMPTY_INPUT = false;\n\n /* Allowed XHTML+XML namespaces */\n let ALLOWED_NAMESPACES = null;\n const DEFAULT_ALLOWED_NAMESPACES = addToSet(\n {},\n [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE],\n stringToString\n );\n\n const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze([\n 'mi',\n 'mo',\n 'mn',\n 'ms',\n 'mtext',\n ]);\n let MATHML_TEXT_INTEGRATION_POINTS = addToSet(\n {},\n DEFAULT_MATHML_TEXT_INTEGRATION_POINTS\n );\n\n const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);\n let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);\n\n // Certain elements are allowed in both SVG and HTML\n // namespace. We need to specify them explicitly\n // so that they don't get erroneously deleted from\n // HTML namespace.\n const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, [\n 'title',\n 'style',\n 'font',\n 'a',\n 'script',\n ]);\n\n /* Parsing of strict XHTML documents */\n let PARSER_MEDIA_TYPE: null | DOMParserSupportedType = null;\n const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];\n const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';\n let transformCaseFunc: null | Parameters<typeof addToSet>[2] = null;\n\n /* Keep a reference to config to pass to hooks */\n let CONFIG: Config | null = null;\n\n /* Ideally, do not touch anything below this line */\n /* ______________________________________________ */\n\n const formElement = document.createElement('form');\n\n const isRegexOrFunction = function (\n testValue: unknown\n ): testValue is Function | RegExp {\n return testValue instanceof RegExp || testValue instanceof Function;\n };\n\n /**\n * _parseConfig\n *\n * @param cfg optional config literal\n */\n // eslint-disable-next-line complexity\n const _parseConfig = function (cfg: Config = {}): void {\n if (CONFIG && CONFIG === cfg) {\n return;\n }\n\n /* Shield configuration object from tampering */\n if (!cfg || typeof cfg !== 'object') {\n cfg = {};\n }\n\n /* Shield configuration object from prototype pollution */\n cfg = clone(cfg);\n\n PARSER_MEDIA_TYPE =\n // eslint-disable-next-line unicorn/prefer-includes\n SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1\n ? DEFAULT_PARSER_MEDIA_TYPE\n : cfg.PARSER_MEDIA_TYPE;\n\n // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.\n transformCaseFunc =\n PARSER_MEDIA_TYPE === 'application/xhtml+xml'\n ? stringToString\n : stringToLowerCase;\n\n /* Set configuration parameters */\n ALLOWED_TAGS = _resolveSetOption(\n cfg,\n 'ALLOWED_TAGS',\n DEFAULT_ALLOWED_TAGS,\n { transform: transformCaseFunc }\n );\n ALLOWED_ATTR = _resolveSetOption(\n cfg,\n 'ALLOWED_ATTR',\n DEFAULT_ALLOWED_ATTR,\n { transform: transformCaseFunc }\n );\n ALLOWED_NAMESPACES = _resolveSetOption(\n cfg,\n 'ALLOWED_NAMESPACES',\n DEFAULT_ALLOWED_NAMESPACES,\n { transform: stringToString }\n );\n URI_SAFE_ATTRIBUTES = _resolveSetOption(\n cfg,\n 'ADD_URI_SAFE_ATTR',\n DEFAULT_URI_SAFE_ATTRIBUTES,\n { transform: transformCaseFunc, base: DEFAULT_URI_SAFE_ATTRIBUTES }\n );\n DATA_URI_TAGS = _resolveSetOption(\n cfg,\n 'ADD_DATA_URI_TAGS',\n DEFAULT_DATA_URI_TAGS,\n { transform: transformCaseFunc, base: DEFAULT_DATA_URI_TAGS }\n );\n FORBID_CONTENTS = _resolveSetOption(\n cfg,\n 'FORBID_CONTENTS',\n DEFAULT_FORBID_CONTENTS,\n { transform: transformCaseFunc }\n );\n FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {\n transform: transformCaseFunc,\n });\n FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {\n transform: transformCaseFunc,\n });\n USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES')\n ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object'\n ? clone(cfg.USE_PROFILES)\n : cfg.USE_PROFILES\n : false;\n\n ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true\n ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true\n ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false\n ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true\n SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false\n SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true\n WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false\n RETURN_DOM = cfg.RETURN_DOM || false; // Default false\n RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false\n RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false\n FORCE_BODY = cfg.FORCE_BODY || false; // Default false\n SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true\n SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false\n KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true\n IN_PLACE = cfg.IN_PLACE || false; // Default false\n IS_ALLOWED_URI = isRegex(cfg.ALLOWED_URI_REGEXP)\n ? cfg.ALLOWED_URI_REGEXP\n : EXPRESSIONS.IS_ALLOWED_URI; // Default regexp\n\n NAMESPACE =\n typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace\n\n MATHML_TEXT_INTEGRATION_POINTS = _resolveObjectOption(\n cfg,\n 'MATHML_TEXT_INTEGRATION_POINTS',\n () => addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS) // Default built-in map\n );\n\n HTML_INTEGRATION_POINTS = _resolveObjectOption(\n cfg,\n 'HTML_INTEGRATION_POINTS',\n () => addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS) // Default built-in map\n );\n\n const customElementHandling = _resolveObjectOption(\n cfg,\n 'CUSTOM_ELEMENT_HANDLING',\n () => create(null)\n );\n\n CUSTOM_ELEMENT_HANDLING = create(null);\n\n if (\n objectHasOwnProperty(customElementHandling, 'tagNameCheck') &&\n isRegexOrFunction(customElementHandling.tagNameCheck)\n ) {\n CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined\n }\n\n if (\n objectHasOwnProperty(customElementHandling, 'attributeNameCheck') &&\n isRegexOrFunction(customElementHandling.attributeNameCheck)\n ) {\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck =\n customElementHandling.attributeNameCheck; // Default undefined\n }\n\n if (\n objectHasOwnProperty(\n customElementHandling,\n 'allowCustomizedBuiltInElements'\n ) &&\n typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean'\n ) {\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements =\n customElementHandling.allowCustomizedBuiltInElements; // Default undefined\n }\n\n seal(CUSTOM_ELEMENT_HANDLING);\n\n if (SAFE_FOR_TEMPLATES) {\n ALLOW_DATA_ATTR = false;\n }\n\n if (RETURN_DOM_FRAGMENT) {\n RETURN_DOM = true;\n }\n\n /* Parse profile info */\n if (USE_PROFILES) {\n ALLOWED_TAGS = addToSet({}, TAGS.text);\n ALLOWED_ATTR = create(null);\n if (USE_PROFILES.html === true) {\n addToSet(ALLOWED_TAGS, TAGS.html);\n addToSet(ALLOWED_ATTR, ATTRS.html);\n }\n\n if (USE_PROFILES.svg === true) {\n addToSet(ALLOWED_TAGS, TAGS.svg);\n addToSet(ALLOWED_ATTR, ATTRS.svg);\n addToSet(ALLOWED_ATTR, ATTRS.xml);\n }\n\n if (USE_PROFILES.svgFilters === true) {\n addToSet(ALLOWED_TAGS, TAGS.svgFilters);\n addToSet(ALLOWED_ATTR, ATTRS.svg);\n addToSet(ALLOWED_ATTR, ATTRS.xml);\n }\n\n if (USE_PROFILES.mathMl === true) {\n addToSet(ALLOWED_TAGS, TAGS.mathMl);\n addToSet(ALLOWED_ATTR, ATTRS.mathMl);\n addToSet(ALLOWED_ATTR, ATTRS.xml);\n }\n }\n\n /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent\n * leaking across calls when switching from function to array config */\n EXTRA_ELEMENT_HANDLING.tagCheck = null;\n EXTRA_ELEMENT_HANDLING.attributeCheck = null;\n\n /* Merge configuration parameters */\n if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {\n if (typeof cfg.ADD_TAGS === 'function') {\n EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;\n } else if (arrayIsArray(cfg.ADD_TAGS)) {\n if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n\n addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);\n }\n }\n\n if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {\n if (typeof cfg.ADD_ATTR === 'function') {\n EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;\n } else if (arrayIsArray(cfg.ADD_ATTR)) {\n if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n\n addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);\n }\n }\n\n if (\n objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') &&\n arrayIsArray(cfg.ADD_FORBID_CONTENTS)\n ) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n\n addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);\n }\n\n /* Add #text in case KEEP_CONTENT is set to true */\n if (KEEP_CONTENT) {\n ALLOWED_TAGS['#text'] = true;\n }\n\n /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */\n if (WHOLE_DOCUMENT) {\n addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);\n }\n\n /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */\n if (ALLOWED_TAGS.table) {\n addToSet(ALLOWED_TAGS, ['tbody']);\n delete FORBID_TAGS.tbody;\n }\n\n // Re-derive the active Trusted Types policy from this configuration on\n // every parse. The active policy must never be sticky closure state that\n // outlives the config that set it: a caller-supplied policy left in place\n // after `clearConfig()` \u2014 or after a later call that supplied none, or\n // `TRUSTED_TYPES_POLICY: null` \u2014 could sign a subsequent \"default\"\n // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.\n // See GHSA-vxr8-fq34-vvx9.\n if (cfg.TRUSTED_TYPES_POLICY) {\n if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {\n throw typeErrorCreate(\n 'TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.'\n );\n }\n\n if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {\n throw typeErrorCreate(\n 'TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.'\n );\n }\n\n // A caller-supplied policy applies to this configuration only.\n const previousTrustedTypesPolicy = trustedTypesPolicy;\n trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;\n\n // Sign local variables required by `sanitize`. If the supplied policy's\n // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this\n // throws via the re-entrancy guard. Restore the previous policy first so\n // the instance is not left in a poisoned state. See #1422.\n try {\n emptyHTML = _createTrustedHTML('');\n } catch (error) {\n trustedTypesPolicy = previousTrustedTypesPolicy;\n throw error;\n }\n } else if (cfg.TRUSTED_TYPES_POLICY === null) {\n // Explicit opt-out for this call: perform no Trusted Types signing and\n // create nothing (so a strict `trusted-types` CSP that disallows a\n // `dompurify` policy can still call `sanitize` from inside its own\n // policy \u2014 see #1422). Resetting to `undefined` rather than a sticky\n // `null` also drops any previously retained caller policy, so it cannot\n // resurface on a later call, while still allowing the next config-less\n // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.\n trustedTypesPolicy = undefined;\n emptyHTML = '';\n } else {\n // No policy supplied: keep the currently active policy if one is set \u2014 a\n // previously supplied policy is intentionally sticky across config-less\n // calls \u2014 otherwise fall back to the instance's own internal policy,\n // created at most once. (A policy supplied for a *single* call still\n // lingers by design; what must not linger is a policy whose configuration\n // has been torn down via `clearConfig()`, which restores the default.)\n if (trustedTypesPolicy === undefined) {\n trustedTypesPolicy = _getDefaultTrustedTypesPolicy();\n }\n\n // Sign internal variables only when a policy is active. A falsy policy\n // (Trusted Types unsupported, creation failed, or an explicit opt-out)\n // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on\n // a non-policy and throw. See #1422.\n if (trustedTypesPolicy && typeof emptyHTML === 'string') {\n emptyHTML = _createTrustedHTML('');\n }\n }\n\n // Prevent further manipulation of configuration.\n // Not available in IE8, Safari 5, etc.\n if (freeze) {\n freeze(cfg);\n }\n\n CONFIG = cfg;\n };\n\n /* Keep track of all possible SVG and MathML tags\n * so that we can perform the namespace checks\n * correctly. */\n const ALL_SVG_TAGS = addToSet({}, [\n ...TAGS.svg,\n ...TAGS.svgFilters,\n ...TAGS.svgDisallowed,\n ]);\n const ALL_MATHML_TAGS = addToSet({}, [\n ...TAGS.mathMl,\n ...TAGS.mathMlDisallowed,\n ]);\n\n /**\n * Namespace rules for an element in the SVG namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkSvgNamespace = function (\n tagName: string,\n parent: { namespaceURI?: string },\n parentTagName: string\n ): boolean {\n // The only way to switch from HTML namespace to SVG\n // is via <svg>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'svg';\n }\n\n // The only way to switch from MathML to SVG is via <svg>\n // if the parent is either <annotation-xml> or a MathML\n // text integration point.\n if (parent.namespaceURI === MATHML_NAMESPACE) {\n return (\n tagName === 'svg' &&\n (parentTagName === 'annotation-xml' ||\n MATHML_TEXT_INTEGRATION_POINTS[parentTagName])\n );\n }\n\n // We only allow elements that are defined in SVG\n // spec. All others are disallowed in SVG namespace.\n return Boolean(ALL_SVG_TAGS[tagName]);\n };\n\n /**\n * Namespace rules for an element in the MathML namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkMathMlNamespace = function (\n tagName: string,\n parent: { namespaceURI?: string },\n parentTagName: string\n ): boolean {\n // The only way to switch from HTML namespace to MathML\n // is via <math>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'math';\n }\n\n // The only way to switch from SVG to MathML is via\n // <math> and HTML integration points\n if (parent.namespaceURI === SVG_NAMESPACE) {\n return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];\n }\n\n // We only allow elements that are defined in MathML\n // spec. All others are disallowed in MathML namespace.\n return Boolean(ALL_MATHML_TAGS[tagName]);\n };\n\n /**\n * Namespace rules for an element in the HTML namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkHtmlNamespace = function (\n tagName: string,\n parent: { namespaceURI?: string },\n parentTagName: string\n ): boolean {\n // The only way to switch from SVG to HTML is via\n // HTML integration points, and from MathML to HTML\n // is via MathML text integration points\n if (\n parent.namespaceURI === SVG_NAMESPACE &&\n !HTML_INTEGRATION_POINTS[parentTagName]\n ) {\n return false;\n }\n\n if (\n parent.namespaceURI === MATHML_NAMESPACE &&\n !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]\n ) {\n return false;\n }\n\n // We disallow tags that are specific for MathML\n // or SVG and should never appear in HTML namespace\n return (\n !ALL_MATHML_TAGS[tagName] &&\n (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName])\n );\n };\n\n /**\n * @param element a DOM element whose namespace is being checked\n * @returns Return false if the element has a\n * namespace that a spec-compliant parser would never\n * return. Return true otherwise.\n */\n const _checkValidNamespace = function (element: Element): boolean {\n /* Read names and namespaces through the cached prototype getters, never\n the instance properties. A live IN_PLACE node can carry own-property\n overrides of tagName / namespaceURI (Object.defineProperty) that would\n otherwise steer the classification below: a namespace-confused node\n posing as a plain HTML element, or a parent posing as an integration\n point. Same root cause as GHSA-x4vx-rjvf-j5p4 (nodeName); for elements\n nodeName is the tagName. */\n const elementNamespace = _readNamespaceURI(element);\n const tagName = stringToLowerCase(_readNodeName(element));\n\n // A missing parent (JSDOM inside shadow DOM) or a non-element parent\n // (DocumentFragment, ShadowRoot, Document) is simulated as a <template>\n // in the configured namespace, as before.\n const parentNode = getParentNode(element);\n let parent: { namespaceURI: string | null };\n let parentTagName: string;\n if (parentNode && _readNodeType(parentNode) === NODE_TYPE.element) {\n parent = { namespaceURI: _readNamespaceURI(parentNode) };\n parentTagName = stringToLowerCase(_readNodeName(parentNode));\n } else {\n parent = { namespaceURI: NAMESPACE };\n parentTagName = 'template';\n }\n\n if (!ALLOWED_NAMESPACES[elementNamespace]) {\n return false;\n }\n\n if (elementNamespace === SVG_NAMESPACE) {\n return _checkSvgNamespace(tagName, parent, parentTagName);\n }\n\n if (elementNamespace === MATHML_NAMESPACE) {\n return _checkMathMlNamespace(tagName, parent, parentTagName);\n }\n\n if (elementNamespace === HTML_NAMESPACE) {\n return _checkHtmlNamespace(tagName, parent, parentTagName);\n }\n\n // For XHTML and XML documents that support custom namespaces\n if (\n PARSER_MEDIA_TYPE === 'application/xhtml+xml' &&\n ALLOWED_NAMESPACES[elementNamespace]\n ) {\n return true;\n }\n\n // The code should never reach this place (this means\n // that the element somehow got namespace that is not\n // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).\n // Return false just in case.\n return false;\n };\n\n /**\n * _forceRemove\n *\n * @param node a DOM node\n */\n const _forceRemove = function (node: Node): void {\n arrayPush(DOMPurify.removed, { element: node });\n\n try {\n // eslint-disable-next-line unicorn/prefer-dom-node-remove\n getParentNode(node).removeChild(node);\n } catch (_) {\n /* The normal detach failed \u2014 this is reached for a parentless node\n (getParentNode() is null, so .removeChild throws). Element.prototype\n .remove() is itself a spec no-op on a parentless node, so a recorded\n \"removal\" would otherwise hand the caller back an intact,\n payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or\n the style-with-element-child rule decided to kill). Fail closed by\n throwing \u2014 exactly as a clobbered root does at the IN_PLACE entry \u2014\n rather than trying to \"neutralize\" the node via its own methods.\n Neutralizing would mean calling getAttributeNames()/removeAttribute()\n on the node, both of which a <form> root can clobber via a named child\n (and _isClobbered does not even probe getAttributeNames), so the\n neutralize step could itself be silently defeated, leaving the payload\n intact. A throw touches only the cached, clobber-safe remove() and\n getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)\n to every root-kill reason. REPORT-3.\n\n This lives inside the catch, so it never fires for a normally-removed\n in-tree node: those have a parent, removeChild() succeeds, and the\n catch is not entered. Only a kept (parentless) root reaches here. */\n remove(node);\n\n if (!getParentNode(node)) {\n throw typeErrorCreate(\n 'a node selected for removal could not be detached from its tree ' +\n 'and cannot be safely returned; refusing to sanitize in place'\n );\n }\n }\n };\n\n /**\n * _stripAttributeNode\n *\n * Remove a single Attr node case/namespace-exactly on an attribute-teardown\n * path. Name-based removeAttribute() ASCII-lowercases its lookup key for an\n * HTML element in an HTML document and so silently misses a case-preserved\n * handler (e.g. `ONERROR` off an XML/XHTML import) - the same defect\n * _removeAttribute() was fixed for, which a name-based call would reintroduce\n * on these IN_PLACE teardown paths. Unlike _removeAttribute this does not\n * record into DOMPurify.removed: the neutralize passes intentionally do not\n * book-keep. A clobbered/detached node falls back to best-effort name-based\n * removal.\n *\n * @param element the element to strip the attribute from\n * @param attribute the Attr node to remove\n * @param name the attribute's name, for the fallback path\n */\n const _stripAttributeNode = function (\n element: Element,\n attribute: Attr,\n name: string\n ): void {\n try {\n removeAttributeNode(element, attribute);\n } catch (_) {\n try {\n element.removeAttribute(name);\n } catch (_) {}\n }\n };\n\n /**\n * Fail-closed teardown of an in-place root: strip every disallowed attribute\n * in the subtree first, so nothing armed is left behind, then remove all\n * children and the root's own attributes.\n *\n * @param root the in-place root to empty\n */\n const _neutralizeRoot = function (root: Node): void {\n _neutralizeSubtree(root);\n\n const childNodes = getChildNodes(root);\n if (childNodes) {\n arrayForEach(arraySlice(childNodes), (child: Node) => {\n try {\n remove(child);\n } catch (_) {\n /* Best effort */\n }\n });\n }\n\n // Only elements have attributes; the root may be a rejected fragment\n const attributes =\n _readNodeType(root) === NODE_TYPE.element ? getAttributes(root) : null;\n if (attributes) {\n for (let i = attributes.length - 1; i >= 0; --i) {\n const attribute = attributes[i];\n const name = attribute && attribute.name;\n if (typeof name === 'string') {\n _stripAttributeNode(root as Element, attribute, name);\n }\n }\n }\n };\n\n /**\n * Removes an attribute, preferably as its exact Attr node: name-based\n * removal lowercases the name in HTML documents and misses case-preserved\n * names, e.g. from imported XHTML.\n *\n * @param name an Attribute name\n * @param element a DOM node\n * @param attr the exact Attr node to remove, when the caller has it\n */\n const _removeAttribute = function (\n name: string,\n element: Element,\n attr?: Attr | null\n ): void {\n if (!attr) {\n try {\n attr = element.getAttributeNode(name);\n } catch (_) {\n attr = null;\n }\n }\n\n arrayPush(DOMPurify.removed, {\n attribute: attr || null,\n from: element,\n });\n\n try {\n if (attr) {\n removeAttributeNode(element, attr);\n } else {\n element.removeAttribute(name);\n }\n } catch (_) {\n /* Clobbered or detached node: fall back to name-based removal */\n try {\n element.removeAttribute(name);\n } catch (_) {}\n }\n\n // We void attribute values for unremovable \"is\" attributes\n if (name === 'is') {\n if (RETURN_DOM || RETURN_DOM_FRAGMENT) {\n try {\n _forceRemove(element);\n } catch (_) {}\n } else {\n try {\n element.setAttribute(name, '');\n } catch (_) {}\n }\n }\n };\n\n /**\n * Removes every attribute the configuration does not allow. Used to\n * neutralize nodes discarded from an in-place tree.\n *\n * @param element the element to strip\n */\n const _stripDisallowedAttributes = function (element: Element): void {\n const attributes = getAttributes(element);\n if (!attributes) {\n return;\n }\n\n for (let i = attributes.length - 1; i >= 0; --i) {\n const attribute = attributes[i];\n const name = attribute && attribute.name;\n if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {\n continue;\n }\n\n _stripAttributeNode(element, attribute, name);\n }\n };\n\n /**\n * Iterative depth-first walk, so deep trees cannot overflow the call stack,\n * reading through the cached getters, so clobbering cannot hide children.\n * When `visit` returns false, the node's children are skipped. With\n * `intoShadow`, open shadow roots are walked after their host's children.\n *\n * @param root where to start\n * @param visit called for every node\n * @param intoShadow whether to enter open shadow roots\n */\n const _walkTree = function (\n root: Node,\n visit: (node: Node) => boolean | void,\n intoShadow = false\n ): void {\n const stack: Node[] = [root];\n\n while (stack.length > 0) {\n const node = stack.pop();\n if (visit(node) === false) {\n continue;\n }\n\n if (intoShadow && _readNodeType(node) === NODE_TYPE.element) {\n const shadowRoot = getShadowRoot(node);\n if (_isDocumentFragment(shadowRoot)) {\n stack.push(shadowRoot);\n }\n }\n\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push(childNodes[i]);\n }\n }\n }\n };\n\n /**\n * Strips disallowed attributes from every element of a discarded subtree,\n * so a handler that is already queued (a loading image) cannot fire.\n *\n * @param root the root of a removed subtree\n */\n const _neutralizeSubtree = function (root: Node): void {\n _walkTree(root, (node) => {\n if (_readNodeType(node) === NODE_TYPE.element) {\n _stripDisallowedAttributes(node as Element);\n }\n });\n };\n\n /**\n * All nodes under `root`, root first, including open shadow roots. Template\n * content is not entered, it is inert.\n *\n * @param root the in-place root\n * @return the nodes\n */\n const _collectLiveNodes = function (root: Node): Node[] {\n const nodes: Node[] = [];\n _walkTree(\n root,\n (node) => {\n nodes.push(node);\n },\n true\n );\n return nodes;\n };\n\n /**\n * Strips disallowed attributes from every element that was under the\n * in-place root when the call started and no longer is, whatever removed\n * or moved it.\n *\n * @param root the in-place root\n * @param before the root's nodes, collected before the walk\n */\n const _neutralizeEscapedElements = function (\n root: Node,\n before: Node[]\n ): void {\n const reachable = setCreate();\n arrayForEach(_collectLiveNodes(root), (node: Node) => {\n if (_readNodeType(node) === NODE_TYPE.element) {\n setAdd(reachable, node);\n }\n });\n arrayForEach(before, (node: Node) => {\n if (\n _readNodeType(node) === NODE_TYPE.element &&\n !setHas(reachable, node)\n ) {\n _stripDisallowedAttributes(node as Element);\n }\n });\n };\n\n /**\n * Neutralizes everything that left the in-place tree during the call: what\n * DOMPurify removed, and what hooks or custom elements removed or moved out.\n *\n * @param root the in-place root\n * @param before the root's nodes, collected before the walk\n * @return true if the root itself was removed\n */\n const _neutralizeDiscarded = function (root: Node, before: Node[]): boolean {\n let rootRemoved = false;\n arrayForEach(DOMPurify.removed, (entry) => {\n if (entry.element) {\n rootRemoved = rootRemoved || entry.element === root;\n _neutralizeSubtree(entry.element as Node);\n }\n });\n _neutralizeEscapedElements(root, before);\n return rootRemoved;\n };\n\n const MAX_UNVISITED_ROUNDS = 8;\n\n /**\n * The walk only moves forward, so a node moved to a position it already\n * passed is never visited. Give every original node that is still in the\n * tree but unvisited the normal treatment, hooks included. Nodes created\n * during the call are left alone. Fails closed if the tree keeps changing.\n *\n * @param root the in-place root\n * @param before the root's nodes, collected before the walk\n */\n const _sanitizeUnvisitedNodes = function (root: Node, before: Node[]): void {\n const visited = IN_PLACE_VISITED;\n /* Built lazily: usually every live node was visited */\n let original: Set<unknown> | null = null;\n const getOriginal = (): Set<unknown> => {\n if (!original) {\n original = setCreate();\n arrayForEach(before, (beforeNode: Node) => {\n setAdd(original, beforeNode);\n });\n }\n\n return original;\n };\n\n for (let round = 0; ; round++) {\n const live = _collectLiveNodes(root);\n const containers: Node[] = [root];\n let pending = false;\n\n arrayForEach(live, (node: Node) => {\n if (_readNodeType(node) === NODE_TYPE.documentFragment) {\n /* An open shadow root under the root */\n arrayPush(containers, node);\n } else if (!pending && !setHas(visited, node)) {\n pending = setHas(getOriginal(), node);\n }\n });\n\n if (!pending) {\n return;\n }\n\n if (round >= MAX_UNVISITED_ROUNDS) {\n throw typeErrorCreate(\n 'the tree kept changing during in-place sanitization; ' +\n 'refusing to return it'\n );\n }\n\n arrayForEach(containers, (container: Node, index: number) => {\n _sanitizeUnvisitedIn(container, index > 0, root, getOriginal());\n });\n }\n };\n\n /**\n * One _sanitizeUnvisitedNodes pass over the root or an open shadow root.\n *\n * @param container the root or an open shadow root\n * @param inShadow whether container is a shadow root\n * @param root the in-place root\n * @param original the root's nodes collected before the walk, as a set\n */\n const _sanitizeUnvisitedIn = function (\n container: Node,\n inShadow: boolean,\n root: Node,\n original: Set<unknown>\n ): void {\n const iterator = _createNodeIterator(container);\n let node: Node | null;\n while ((node = iterator.nextNode())) {\n if (!setHas(original, node) || setHas(IN_PLACE_VISITED, node)) {\n continue;\n }\n\n if (inShadow) {\n _executeHooks(hooks.uponSanitizeShadowNode, node, null);\n }\n\n _sanitizeElements(node, root);\n _sanitizeAttributes(node as Element, root);\n if (_isDocumentFragment((node as HTMLTemplateElement).content)) {\n _sanitizeShadowDOM((node as HTMLTemplateElement).content);\n }\n }\n };\n\n /**\n * Records that _sanitizeElements processed `node`. No-op outside IN_PLACE.\n *\n * @param node the node being processed\n */\n const _markVisited = function (node: Node): void {\n if (IN_PLACE_VISITED) {\n setAdd(IN_PLACE_VISITED, node);\n }\n };\n\n /**\n * Patch-linkage attributes (declarative partial updates): `patchsrc`\n * always, `for` everywhere except on <label> and <output>. Gated on\n * SAFE_FOR_XML. Shared by the IN_PLACE pre-pass and _isValidAttribute.\n *\n * @param lcName the transformCaseFunc'd attribute name\n * @param lcTag the transformCaseFunc'd tag name of the carrying element\n * @return true if the attribute is patch linkage and must be dropped\n */\n const _isPatchLinkageAttribute = function (\n lcName: string,\n lcTag: string\n ): boolean {\n if (!SAFE_FOR_XML) {\n return false;\n }\n\n if (lcName === 'patchsrc') {\n return true;\n }\n\n return lcName === 'for' && lcTag !== 'label' && lcTag !== 'output';\n };\n\n /**\n * IN_PLACE pre-pass: sever all patch linkage before the walk, so no patch\n * can fire mid-walk into a part of the tree the walker already passed.\n * Removes range markers (processing instructions, comments with markup)\n * and strips linkage attributes. It cannot undo a patch that already fired.\n *\n * TODO: if the shipped feature can patch through `for` on <label>/<output>,\n * drop that pair here too (see test/declarative-patch-probe.html).\n *\n * @param root the in-place root to sweep\n */\n const _neutralizePatchLinkage = function (root: Node): void {\n if (!SAFE_FOR_XML) {\n return;\n }\n\n _walkTree(root, (node) => {\n const nodeType = _readNodeType(node);\n\n // Range markers: processing instructions, comments with markup\n if (\n nodeType === NODE_TYPE.processingInstruction ||\n (nodeType === NODE_TYPE.comment &&\n regExpTest(EXPRESSIONS.COMMENT_MARKUP_PROBE, (node as any).data))\n ) {\n try {\n remove(node);\n } catch (_) {\n /* Best effort */\n }\n\n return false;\n }\n\n // Linkage attributes\n if (nodeType === NODE_TYPE.element) {\n const element = node as Element;\n const lcTag = transformCaseFunc(_readNodeName(node));\n try {\n if (element.hasAttribute && element.hasAttribute('patchsrc')) {\n element.removeAttribute('patchsrc');\n }\n\n if (\n element.hasAttribute &&\n element.hasAttribute('for') &&\n _isPatchLinkageAttribute('for', lcTag)\n ) {\n element.removeAttribute('for');\n }\n } catch (_) {\n /* Clobbered methods on a doomed node */\n }\n }\n\n return true;\n });\n };\n\n /**\n * _initDocument\n *\n * @param dirty - a string of dirty markup\n * @return a DOM, filled with the dirty markup\n */\n const _initDocument = function (dirty: string): Document {\n /* Create a HTML document */\n let doc = null;\n let leadingWhitespace = null;\n\n if (FORCE_BODY) {\n dirty = '<remove></remove>' + dirty;\n } else {\n /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */\n const matches = stringMatch(dirty, /^[\\r\\n\\t ]+/);\n leadingWhitespace = matches && matches[0];\n }\n\n if (\n PARSER_MEDIA_TYPE === 'application/xhtml+xml' &&\n NAMESPACE === HTML_NAMESPACE\n ) {\n // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)\n dirty =\n '<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body>' +\n dirty +\n '</body></html>';\n }\n\n const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;\n /*\n * Use the DOMParser API by default, fallback later if needs be\n * DOMParser not work for svg when has multiple root element.\n */\n if (NAMESPACE === HTML_NAMESPACE) {\n try {\n doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);\n } catch (_) {}\n }\n\n /* Use createHTMLDocument in case DOMParser is not available */\n if (!doc || !doc.documentElement) {\n doc = implementation.createDocument(NAMESPACE, 'template', null);\n try {\n doc.documentElement.innerHTML = IS_EMPTY_INPUT\n ? emptyHTML\n : dirtyPayload;\n } catch (_) {\n // Syntax error if dirtyPayload is invalid xml\n }\n }\n\n const body = doc.body || doc.documentElement;\n\n if (dirty && leadingWhitespace) {\n body.insertBefore(\n document.createTextNode(leadingWhitespace),\n body.childNodes[0] || null\n );\n }\n\n /* Work on whole document or just its body */\n if (NAMESPACE === HTML_NAMESPACE) {\n return getElementsByTagName.call(\n doc,\n WHOLE_DOCUMENT ? 'html' : 'body'\n )[0];\n }\n\n return WHOLE_DOCUMENT ? doc.documentElement : body;\n };\n\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n *\n * @param root The root element or node to start traversing on.\n * @return The created NodeIterator\n */\n const _createNodeIterator = function (root: Node): NodeIterator {\n /* Read ownerDocument through the cached Node.prototype getter, never the\n direct property. HTMLFormElement has [LegacyOverrideBuiltIns], so a\n clobbering child (<input name=\"ownerDocument\"> or a form-associated\n external input) shadows the prototype getter and makes a direct read\n return that <input>. createNodeIterator.call(<input>, ...) then throws\n \"Illegal invocation\", and on the IN_PLACE path that throw lands before\n the walk's fail-closed barrier - leaving the caller's live tree, with\n any already-armed handler in it, un-neutralized. The cached getter\n returns the real Document regardless of the clobber. */\n const doc = getOwnerDocument ? getOwnerDocument(root) : root.ownerDocument;\n return createNodeIterator.call(\n doc || root,\n root,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_ELEMENT |\n NodeFilter.SHOW_COMMENT |\n NodeFilter.SHOW_TEXT |\n NodeFilter.SHOW_PROCESSING_INSTRUCTION |\n NodeFilter.SHOW_CDATA_SECTION,\n null\n );\n };\n\n /**\n * Replace template expression syntax (mustache, ERB, template\n * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub\n * sites. Order matters: mustache, then ERB, then template literal.\n *\n * @param value the string to scrub\n * @returns the scrubbed string\n */\n const _stripTemplateExpressions = function (value: string): string {\n value = stringReplace(value, MUSTACHE_EXPR, ' ');\n value = stringReplace(value, ERB_EXPR, ' ');\n value = stringReplace(value, TMPLIT_EXPR, ' ');\n return value;\n };\n\n /**\n * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the\n * character data of an element subtree. Used as the final safety net for\n * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions\n * which only form after text-node normalization (e.g. fragments split across\n * stripped elements) cannot survive into a template-evaluating framework.\n *\n * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`\n * in place rather than round-tripping through innerHTML. This preserves\n * descendant node references (important for IN_PLACE callers), avoids a\n * serialize/reparse cycle, and reads literal character data \u2014 which means\n * `<%...%>` in text content matches the ERB regex against its real bytes\n * instead of the HTML-entity-escaped form innerHTML would produce.\n *\n * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for\n * attributes is performed during the per-node `_sanitizeAttributes` pass.\n *\n * @param node The root element whose character data should be scrubbed.\n */\n const _scrubTemplateExpressions = function (node: Element): void {\n _scrubOwnCharacterData(node);\n\n // NodeIterator does not descend into <template>.content per the DOM spec,\n // so we must explicitly recurse into each template's content fragment,\n // mirroring the approach used by _sanitizeShadowDOM.\n const templates = node.querySelectorAll?.('template');\n if (templates) {\n arrayForEach(templates, (tmpl: HTMLTemplateElement) => {\n if (_isDocumentFragment(tmpl.content)) {\n _scrubTemplateExpressions(tmpl.content as unknown as Element);\n }\n });\n }\n };\n\n /**\n * _scrubOwnCharacterData\n *\n * Non-recursive core of _scrubTemplateExpressions: normalize `node` and\n * strip template expressions from its own character data only. Does not\n * enter <template>.content or attached shadow roots (NodeIterator never\n * does). Used by _sanitizeShadowDOM, where every nested template content\n * and shadow root is already walked - and therefore scrubbed - by its own\n * recursive _sanitizeShadowDOM call; recursing here as well would rescrub\n * each nested fragment once per ancestor, which is quadratic in nesting\n * depth.\n *\n * @param node The root whose own character data should be scrubbed.\n */\n const _scrubOwnCharacterData = function (node: Element): void {\n node.normalize();\n /* Clobber-safe ownerDocument read, same reasoning as _createNodeIterator:\n under SAFE_FOR_TEMPLATES this runs on the live IN_PLACE root, which may\n carry a form-named-getter override of ownerDocument. */\n const doc = getOwnerDocument ? getOwnerDocument(node) : node.ownerDocument;\n const walker = createNodeIterator.call(\n doc || node,\n node,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_TEXT |\n NodeFilter.SHOW_COMMENT |\n NodeFilter.SHOW_CDATA_SECTION |\n NodeFilter.SHOW_PROCESSING_INSTRUCTION,\n null\n );\n\n let currentNode = walker.nextNode() as CharacterData | null;\n while (currentNode) {\n currentNode.data = _stripTemplateExpressions(currentNode.data);\n currentNode = walker.nextNode() as CharacterData | null;\n }\n };\n\n /**\n * _isClobbered\n *\n * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML\n * interface with [LegacyOverrideBuiltIns]; a descendant element with a\n * `name` attribute matching a prototype property shadows that property\n * on direct reads. We use this check at the IN_PLACE entry-point and\n * during attribute sanitization to refuse clobbered forms.\n *\n * @param element element to check for clobbering attacks\n * @return true if clobbered, false if safe\n */\n const _isClobbered = function (element: Element): boolean {\n // Realm-independent tag-name probe. If we can't determine the tag\n // name at all, we can't reason about clobbering \u2014 return false\n // (the caller's other defences still apply).\n const realTagName = getNodeName ? getNodeName(element) : null;\n if (typeof realTagName !== 'string') {\n return false;\n }\n\n if (transformCaseFunc(realTagName) !== 'form') {\n return false;\n }\n\n return (\n typeof element.nodeName !== 'string' ||\n typeof element.textContent !== 'string' ||\n typeof element.removeChild !== 'function' ||\n // Realm-safe NamedNodeMap detection: equality against the cached\n // prototype getter. Clobbered .attributes (e.g. <input name=\"attributes\">)\n // makes the direct read diverge from the cached read; a clean form\n // (same-realm OR foreign-realm) has both reads pointing at the same\n // canonical NamedNodeMap.\n element.attributes !== getAttributes(element) ||\n typeof element.removeAttribute !== 'function' ||\n // A form descendant named \"removeAttributeNode\" or \"getAttributeNode\"\n // shadows these Attr-node methods via [LegacyOverrideBuiltIns].\n // _removeAttribute() / _stripAttributeNode() reach for\n // element.removeAttributeNode(attr) first; when it is shadowed the call\n // throws and the name-based fallback element.removeAttribute(name)\n // ASCII-lowercases its lookup key in an HTML document, silently missing\n // a case-preserved event-handler attribute (e.g. an ONANIMATIONSTART\n // that reached the sanitizer through an XML/XHTML parse). Flag the form\n // so it is removed wholesale, exactly as for the other shadowed methods.\n typeof element.removeAttributeNode !== 'function' ||\n typeof element.getAttributeNode !== 'function' ||\n typeof element.setAttribute !== 'function' ||\n typeof element.namespaceURI !== 'string' ||\n typeof element.insertBefore !== 'function' ||\n typeof element.hasChildNodes !== 'function' ||\n // NodeType clobbering probe. Cached Node.prototype.nodeType getter\n // returns the integer 1 for any Element regardless of realm; direct\n // read on a clobbered form (e.g. <input name=\"nodeType\">) returns\n // the named child element. Cheap addition \u2014 nodeType is read from\n // an internal slot, no serialization cost \u2014 and removes a residual\n // clobbering surface used by several mXSS / PI / comment branches\n // in _sanitizeElements that compare currentNode.nodeType directly.\n element.nodeType !== getNodeType(element) ||\n // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named\n // \"childNodes\" shadows the prototype getter. Direct reads of\n // form.childNodes from a clobbered form return the named child\n // instead of the real NodeList, so any walk that reads it directly\n // skips the form's real children. Compare the direct read to the\n // cached Node.prototype getter \u2014 when the form's named-property\n // getter intercepts the read, the two values differ and we flag\n // the form. This catches every clobbering child type (input,\n // select, etc.) regardless of whether the named child happens to\n // carry a numeric .length, which a typeof-based probe would miss\n // (e.g. HTMLSelectElement.length is a defined unsigned-long).\n element.childNodes !== getChildNodes(element)\n );\n };\n\n /**\n * Checks whether the given value is a DocumentFragment from any realm.\n *\n * The realm-independent replacement reads `nodeType` through the cached\n * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE\n * constant (11). nodeType is a numeric value resolved from the node's\n * internal slot, identical across realms for the same kind of node.\n *\n * @param value object to check\n * @return true if value is a DocumentFragment-shaped node from any realm\n */\n const _isDocumentFragment = function (value: unknown): boolean {\n if (!getNodeType || typeof value !== 'object' || value === null) {\n return false;\n }\n\n try {\n return getNodeType(value as Node) === NODE_TYPE.documentFragment;\n } catch (_) {\n return false;\n }\n };\n\n /**\n * Checks whether the given object is a DOM node, including nodes that\n * originate from a different window/realm (e.g. an iframe's\n * contentDocument). The previous `value instanceof Node` check was\n * realm-bound: nodes from a different window failed it, causing\n * sanitize() to silently stringify them and reset IN_PLACE to false,\n * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.\n *\n * @param value object to check whether it's a DOM node\n * @return true if value is a DOM node from any realm\n */\n const _isNode = function (value: unknown): value is Node {\n if (!getNodeType || typeof value !== 'object' || value === null) {\n return false;\n }\n\n try {\n return typeof getNodeType(value) === 'number';\n } catch (_) {\n return false;\n }\n };\n\n function _executeHooks<T extends HookFunction>(\n hooks: HookFunction[],\n currentNode: Parameters<T>[0],\n data: Parameters<T>[1]\n ): void {\n if (hooks.length === 0) {\n return;\n }\n\n arrayForEach(hooks, (hook: T) => {\n hook.call(DOMPurify, currentNode, data, CONFIG);\n });\n }\n\n /**\n * Structural-threat checks that condemn a node regardless of the\n * allowlists: mXSS via namespace confusion, risky CSS construction,\n * processing instructions, markup-bearing comments. Pure predicate;\n * the caller removes. Check order is load-bearing.\n *\n * @param currentNode the node to inspect\n * @param tagName the node's transformCaseFunc'd tag name\n * @return true if the node must be removed\n */\n const _isUnsafeNode = function (currentNode: any, tagName: string): boolean {\n /* Detect mXSS attempts abusing namespace confusion */\n if (\n SAFE_FOR_XML &&\n currentNode.hasChildNodes() &&\n !_isNode(currentNode.firstElementChild) &&\n regExpTest(EXPRESSIONS.ELEMENT_MARKUP_PROBE, currentNode.textContent) &&\n regExpTest(EXPRESSIONS.ELEMENT_MARKUP_PROBE, currentNode.innerHTML)\n ) {\n return true;\n }\n\n /* Remove rawtext/literal-text elements whose literal serialization\n re-opens markup on an HTML reparse - shapes (a) and (b) documented at\n LITERAL_TEXT_ELEMENTS. Both are invisible to rule 1 above (which\n self-disables once there is an element child, and whose second probe\n reads the innerHTML an XML/XHTML document serializes escaped), which\n is why both probes here read textContent instead. Previously only\n `style`-with-element-child was covered; every element in\n LITERAL_TEXT_ELEMENTS shares this literal serialization and is\n equally affected.\n\n The text probe is rule 1's ELEMENT_MARKUP_PROBE, not just the element's\n own end tag. For these elements textContent is exactly what an HTML\n serializer emits, so in an HTML working document this is the same\n decision rule 1 already makes there (markup-like text is removed). Only\n matching the own end tag let an XML/XHTML-sourced literal-text element\n keep markup such as `</style><img onerror>` that the same input loses in\n HTML mode, and that breaks out once the output is placed in another\n raw-text context.\n\n Namespace through the cached getter (see _checkValidNamespace), and only\n for Elements: a processing instruction's nodeName is its target, which\n can collide with a name in LITERAL_TEXT_ELEMENTS. */\n if (\n SAFE_FOR_XML &&\n LITERAL_TEXT_ELEMENTS[tagName] &&\n _readNodeType(currentNode) === NODE_TYPE.element &&\n _readNamespaceURI(currentNode) === HTML_NAMESPACE &&\n (_isNode(currentNode.firstElementChild) ||\n (typeof currentNode.textContent === 'string' &&\n regExpTest(\n EXPRESSIONS.ELEMENT_MARKUP_PROBE,\n currentNode.textContent\n )))\n ) {\n return true;\n }\n\n /* Remove any occurrence of processing instructions */\n if (currentNode.nodeType === NODE_TYPE.processingInstruction) {\n return true;\n }\n\n /* Remove any kind of possibly harmful comments */\n if (\n SAFE_FOR_XML &&\n currentNode.nodeType === NODE_TYPE.comment &&\n regExpTest(EXPRESSIONS.COMMENT_MARKUP_PROBE, currentNode.data)\n ) {\n return true;\n }\n\n return false;\n };\n\n /**\n * Evaluate a CUSTOM_ELEMENT_HANDLING check (a RegExp or a predicate\n * function, per the validation in _parseConfig) against a name.\n * Additional arguments are forwarded to predicate functions - the\n * attributeNameCheck predicate receives the tag name as its second\n * argument. A null/absent check never matches.\n *\n * @param check the configured tagNameCheck / attributeNameCheck value\n * @param name the name to test\n * @param args extra arguments forwarded to a predicate function\n * @return true if the check matches the name\n */\n const _matchesNameCheck = function (\n check: unknown,\n name: string,\n ...args: unknown[]\n ): boolean {\n if (check instanceof RegExp) {\n return regExpTest(check, name);\n }\n\n if (check instanceof Function) {\n return Boolean(check(name, ...args));\n }\n\n return false;\n };\n\n /**\n * Handle a node whose tag is forbidden or not allowlisted: keep\n * allowed custom elements (false return exits _sanitizeElements\n * early - the namespace and fallback-tag removal checks are\n * intentionally skipped for kept custom elements), else hoist\n * content per KEEP_CONTENT and remove.\n *\n * A kept custom element is the ONLY case in which this function\n * returns false, so the caller uses that return value to run the\n * afterSanitizeElements hook on the kept element and keep the\n * element-hook lifecycle consistent with normal allowlisted\n * elements (GHSA-c2j3-45gr-mqc4).\n *\n * @param currentNode the disallowed node\n * @param tagName the node's transformCaseFunc'd tag name\n * @return true if the node was removed, false if kept\n */\n const _sanitizeDisallowedNode = function (\n currentNode: any,\n tagName: string,\n root: Node\n ): boolean {\n /* Check if we have a custom element to handle */\n if (\n !FORBID_TAGS[tagName] &&\n _isBasicCustomElement(tagName) &&\n _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)\n ) {\n return false;\n }\n\n /* Keep content except for bad-listed elements.\n Use the cached prototype getters exclusively \u2014 the previous code\n had `|| currentNode.parentNode` / `|| currentNode.childNodes`\n fallbacks, but the cached getters always return the canonical\n value (or null for a real parent-less node), so the fallback\n path was dead in safe cases and a clobbering surface in unsafe\n ones. Falsy cached results stay falsy; the `if (childNodes &&\n parentNode)` check already gates correctly. */\n if (\n KEEP_CONTENT &&\n !FORBID_CONTENTS[tagName] &&\n /* The default list is lowercase, but in application/xhtml+xml mode\n tagName keeps its case, so `foreignObject` would miss its\n `foreignobject` entry and have its content hoisted instead of\n dropped, unlike in HTML mode. Also consult the lowercased name; this\n can only drop more content, never keep more. */\n !FORBID_CONTENTS[stringToLowerCase(tagName)]\n ) {\n const parentNode = getParentNode(currentNode);\n const childNodes = getChildNodes(currentNode);\n\n if (childNodes && parentNode) {\n const childCount = childNodes.length;\n\n /* Hoist by moving each child up one level rather than deep-cloning\n it. Moving transfers every descendant exactly once, so a chain of\n nested disallowed elements costs O(n) instead of the O(n^2) that\n re-cloning the shrinking subtree at each level produced; it also\n empties the removed original, so `DOMPurify.removed` no longer\n pins whole subtrees. Moving preserves the in-place guarantee too:\n an original carrying already-queued resource events (`<img\n onerror>`, `<video>`/`<audio>` error, lazy/`onload`, \u2026) is\n relocated and sanitised rather than left detached but still armed.\n\n The sole case that must clone is removing the walk root itself.\n The result is serialised from the root's subtree, so a restrictive\n ALLOWED_TAGS that strips the root (`body` on the string path) must\n leave the content inside it, which only cloning does. In IN_PLACE\n the root is pre-validated as an allowed tag and so is never removed\n here, so that path always takes the move branch.\n\n `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`\n valid whether we move (drops the trailing entry) or clone (leaves\n the list intact). */\n for (let i = childCount - 1; i >= 0; --i) {\n const hoisted =\n currentNode === root\n ? cloneNode(childNodes[i], true)\n : childNodes[i];\n parentNode.insertBefore(hoisted, getNextSibling(currentNode));\n }\n }\n }\n\n _forceRemove(currentNode);\n return true;\n };\n\n /**\n * Fork a hook-mutable allowlist off its shared binding the first time a\n * (possibly lazily-installed) uponSanitize* hook is about to see it, so the\n * hook cannot widen the per-instance default or the setConfig binding by\n * reference and leak past the call. Returns the set unchanged once it is\n * already call-local, so repeated calls across elements are idempotent.\n *\n * @param hookList the uponSanitize* hook array for this event\n * @param set the current ALLOWED_TAGS / ALLOWED_ATTR binding\n * @param defaultSet the per-instance DEFAULT_ALLOWED_* constant\n * @param setConfigSet the captured setConfig() binding, or null\n * @return a call-local clone if a hook is present and set is still shared,\n * else set unchanged\n */\n const _forkSharedAllowlist = function <T extends Record<string, any>>(\n hookList: unknown[],\n set: T,\n defaultSet: T,\n setConfigSet: T | null\n ): T {\n if (hookList.length === 0) {\n return set;\n }\n\n return set === defaultSet || set === setConfigSet ? clone(set) : set;\n };\n\n /**\n * A hook may have detached the node it was called for. If so, treat it as\n * removed and stop processing it; the walk root is exempt. On the IN_PLACE\n * path the detached subtree is neutralized right away.\n *\n * @param currentNode the node a hook may have detached\n * @param root the current walk root\n * @return true if the node was detached\n */\n const _handleHookDetachedNode = function (\n currentNode: Node,\n root: Node\n ): boolean {\n if (currentNode === root || getParentNode(currentNode) !== null) {\n return false;\n }\n\n if (IN_PLACE) {\n _neutralizeSubtree(currentNode);\n }\n\n return true;\n };\n\n /**\n * _sanitizeElements\n *\n * @protect nodeName\n * @protect textContent\n * @protect removeChild\n * @param currentNode to check for permission to exist\n * @return true if node was killed, false if left alive\n */\n const _sanitizeElements = function (currentNode: any, root: Node): boolean {\n /* IN_PLACE: remember the node was processed (see _sanitizeUnvisitedNodes). */\n _markVisited(currentNode);\n\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeElements, currentNode, null);\n\n /* A hook may have detached the node - treat it as removed (see\n _handleHookDetachedNode for the full rationale). */\n if (_handleHookDetachedNode(currentNode, root)) {\n return true;\n }\n\n /* Check if element is clobbered or can clobber */\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Now let's check the element's type and name */\n const tagName = transformCaseFunc(_readNodeName(currentNode));\n\n /* Close the pre-walk clone-guard's timing gap: an uponSanitizeElement\n hook may have been installed after that guard sampled the hook arrays\n (e.g. lazily from beforeSanitizeElements), leaving ALLOWED_TAGS still\n aliasing a shared binding that a widening hook would mutate by\n reference. Fork it before exposing it to the hook. */\n ALLOWED_TAGS = _forkSharedAllowlist(\n hooks.uponSanitizeElement,\n ALLOWED_TAGS,\n DEFAULT_ALLOWED_TAGS,\n SET_CONFIG_ALLOWED_TAGS\n );\n\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeElement, currentNode, {\n tagName,\n allowedTags: ALLOWED_TAGS,\n });\n\n /* The uponSanitizeElement hook may have detached the node, exactly as\n above (see _handleHookDetachedNode for the full rationale). */\n if (_handleHookDetachedNode(currentNode, root)) {\n return true;\n }\n\n /* Remove mXSS vectors, processing instructions and risky comments */\n if (_isUnsafeNode(currentNode, tagName)) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Remove element if anything forbids its presence */\n if (\n FORBID_TAGS[tagName] ||\n (!(\n EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function &&\n EXTRA_ELEMENT_HANDLING.tagCheck(tagName)\n ) &&\n !ALLOWED_TAGS[tagName])\n ) {\n const removed = _sanitizeDisallowedNode(currentNode, tagName, root);\n\n /* A false return means the node is a custom element kept via\n CUSTOM_ELEMENT_HANDLING - the only keep path through\n _sanitizeDisallowedNode. Run afterSanitizeElements on it so the\n element-hook lifecycle matches normal allowlisted elements: a\n security policy applied in this hook (e.g. stripping an attribute\n from every surviving element) must not silently skip kept custom\n elements (GHSA-c2j3-45gr-mqc4). This mirrors the normal-element\n tail below - the hook runs, then the walker's subsequent\n _sanitizeAttributes pass sanitizes the element's attributes. The\n deliberately skipped namespace and fallback-tag removal checks stay\n skipped; they are removal decisions, not the hook contract. */\n if (removed === false) {\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n\n /* The hook may have detached the kept custom element. Same\n IN_PLACE hazard as the before/upon sites: neutralize the\n detached subtree before the walker skips past it (see\n _handleHookDetachedNode). */\n if (_handleHookDetachedNode(currentNode, root)) {\n return true;\n }\n }\n\n return removed;\n }\n\n /* Check whether element has a valid namespace.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype\n nodeType getter rather than `instanceof Element`, which is realm-\n bound and short-circuits to false for any node minted in a different\n realm \u2014 letting a foreign-realm element with a forbidden namespace\n slip past the namespace check entirely. */\n const nt = _readNodeType(currentNode);\n if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Make sure that older browsers don't get fallback-tag mXSS */\n if (\n (tagName === 'noscript' ||\n tagName === 'noembed' ||\n tagName === 'noframes') &&\n regExpTest(EXPRESSIONS.FALLBACK_TAG_CLOSE, currentNode.innerHTML)\n ) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Sanitize element content to be template-safe */\n if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {\n /* Get the element's text content */\n const content = _stripTemplateExpressions(currentNode.textContent);\n\n if (currentNode.textContent !== content) {\n arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });\n currentNode.textContent = content;\n }\n }\n\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n\n /* The afterSanitizeElements hook is the documented place for\n node.remove() policies, and a detach here is invisible to every later\n pass: the iterator advances past the detached subtree, so its\n descendants are never visited, and hook-detached nodes are not in\n DOMPurify.removed, so the post-walk IN_PLACE pass does not reach them\n either. Apply the same detach-neutralization invariant as the\n before/upon sites: true (removed) if the hook detached the node. */\n return _handleHookDetachedNode(currentNode, root);\n };\n\n /**\n * _isValidAttribute\n *\n * @param lcTag Lowercase tag name of containing element.\n * @param lcName Lowercase attribute name.\n * @param value Attribute value.\n * @return Returns true if `value` is valid, otherwise false.\n */\n // eslint-disable-next-line complexity\n const _isValidAttribute = function (\n lcTag: string,\n lcName: string,\n value: string\n ): boolean {\n /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */\n if (FORBID_ATTR[lcName]) {\n return false;\n }\n\n /* Reject declarative-partial-updates patch-linkage attributes\n (https://github.com/WICG/declarative-partial-updates).\n\n Empirical note (Chrome 150, verified \u2014 see\n test/declarative-patch-probe-v3.html): expansion is NOT applied after\n sanitization. For the string path it fires during sanitize()'s own\n parse, so the walk sees and sanitizes the fully materialized expanded\n tree \u2014 teleports into MathML/SVG integration points included; a\n weaponized `<template for>`->`<img onerror>` comes back with the handler\n stripped. For the IN_PLACE path it fires on connection, before the walk.\n Either way DOMPurify is NOT blind to the patch.\n\n This removal is therefore defense-in-depth rather than the sole barrier:\n it prevents live linkage from surviving into the OUTPUT and re-expanding\n in the caller's context, and keeps behaviour deterministic if a future\n engine defers expansion. `for` is legitimate only on <label>/<output>;\n anywhere else (notably <template for>) it links the element to a patch\n target and teleports or removes an arbitrary DOM range by id/marker name.\n `patchsrc` fetches remote markup and is treated as a script-loading\n mechanism (CSP). Gated on SAFE_FOR_XML so the removal groups with the\n other structural-threat checks and stays overridable, consistent with\n the rest of the codebase. PI range markers are already removed by\n _isUnsafeNode. */\n if (_isPatchLinkageAttribute(lcName, lcTag)) {\n return false;\n }\n\n /* Make sure attribute cannot clobber */\n if (\n SANITIZE_DOM &&\n (lcName === 'id' || lcName === 'name') &&\n (value in document || value in formElement)\n ) {\n return false;\n }\n\n const nameIsPermitted =\n ALLOWED_ATTR[lcName] ||\n (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function &&\n EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag));\n\n /* Allow valid data-* attributes: At least one character after \"-\"\n (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)\n XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)\n We don't need to check the value; it's always URI safe. */\n if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR, lcName)) {\n return true;\n }\n\n /* Allow valid aria-* attributes, the value is always URI safe */\n if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) {\n return true;\n }\n\n /* A name outside the allowlist is acceptable on custom-element terms\n only. The value checks below are intentionally skipped in that case:\n if the user supplied a tagNameCheck we also allow derived custom\n elements using the same test, and attributes passing the configured\n attributeNameCheck are allowed as custom elements define these at\n their own discretion. */\n if (!nameIsPermitted) {\n return (\n // Condition a) covers a basically valid custom element tag name whose\n // tag passes the configured tagNameCheck and whose attribute name\n // passes the configured attributeNameCheck ...\n (_isBasicCustomElement(lcTag) &&\n _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) &&\n _matchesNameCheck(\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck,\n lcName,\n lcTag\n )) ||\n // Condition b) covers an `is` attribute whose value passes the\n // configured tagNameCheck while customized built-in elements are\n // allowed.\n (lcName === 'is' &&\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements &&\n _matchesNameCheck(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value))\n );\n }\n\n /* Check value is safe. First, is attr inert? If so, is safe */\n if (URI_SAFE_ATTRIBUTES[lcName]) {\n return true;\n }\n\n /* Check no script, data or unknown possibly unsafe URI\n unless we know URI values are safe for that attribute */\n if (regExpTest(IS_ALLOWED_URI, stringReplace(value, ATTR_WHITESPACE, ''))) {\n return true;\n }\n\n /* Keep image data URIs alive if src/xlink:href is allowed */\n /* Further prevent gadget XSS for dynamically built script tags */\n if (\n (lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') &&\n lcTag !== 'script' &&\n stringIndexOf(value, 'data:') === 0 &&\n DATA_URI_TAGS[lcTag]\n ) {\n return true;\n }\n\n /* Allow unknown protocols: This provides support for links that\n are handled by protocol handlers which may be unknown ahead of\n time, e.g. fb:, spotify: */\n if (\n ALLOW_UNKNOWN_PROTOCOLS &&\n !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))\n ) {\n return true;\n }\n\n /* Only an empty (binary) value remains safe at this point;\n anything else is presumed unsafe, do not add it back */\n return !value;\n };\n\n /* Names the HTML spec reserves from valid-custom-element-name; these must\n * never be treated as basic custom elements even when a permissive\n * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */\n const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, [\n 'annotation-xml',\n 'color-profile',\n 'font-face',\n 'font-face-format',\n 'font-face-name',\n 'font-face-src',\n 'font-face-uri',\n 'missing-glyph',\n ]);\n\n /**\n * _isBasicCustomElement\n * checks if at least one dash is included in tagName, and it's not the first char\n * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name\n *\n * @param tagName name of the tag of the node to sanitize\n * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.\n */\n const _isBasicCustomElement = function (tagName: string): boolean {\n return (\n !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] &&\n regExpTest(CUSTOM_ELEMENT, tagName)\n );\n };\n\n /**\n * Wrap an attribute value in the matching Trusted Types object when\n * the active policy requires it. Namespaced attributes pass through\n * unchanged (no TT support yet, see\n * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).\n *\n * @param lcTag lowercase tag name of the containing element\n * @param lcName lowercase attribute name\n * @param namespaceURI the attribute's namespace, if any\n * @param value the attribute value to wrap\n * @return the value, wrapped when Trusted Types demand it\n */\n const _applyTrustedTypesToAttribute = function (\n lcTag: string,\n lcName: string,\n namespaceURI: string | null,\n value: string\n ): string {\n if (\n trustedTypesPolicy &&\n typeof trustedTypes === 'object' &&\n typeof trustedTypes.getAttributeType === 'function' &&\n !namespaceURI\n ) {\n switch (trustedTypes.getAttributeType(lcTag, lcName)) {\n case 'TrustedHTML': {\n return _createTrustedHTML(value);\n }\n\n case 'TrustedScriptURL': {\n return _createTrustedScriptURL(value);\n }\n\n default: {\n break;\n }\n }\n }\n\n return value;\n };\n\n /**\n * Write a modified attribute value back onto the element. On\n * success, re-probe for clobbering introduced by the new value and\n * remove the element when found; otherwise, when this writeback is the\n * recreate half of the SANITIZE_NAMED_PROPS remove-and-recreate, pop the\n * removal entry that path recorded so it does not show as removed. On\n * failure, remove the attribute instead.\n *\n * Returns true only on a clean write (the value was set and the new value\n * introduced no clobbering). The caller uses that, together with its own\n * knowledge of whether this attribute pushed a DOMPurify.removed record, to\n * decide whether to pop that record. The pop must happen ONLY for the\n * named-prop remove-and-recreate; popping on any other value change (trim,\n * template scrubbing, Trusted Types) would consume an unrelated _forceRemove\n * subtree-cleanup record and let that detached subtree keep a live event\n * handler through the IN_PLACE neutralization pass (SO-001).\n *\n * @param currentNode the element carrying the attribute\n * @param name the attribute name as present on the element\n * @param namespaceURI the attribute's namespace, if any\n * @param value the new attribute value\n * @return true if the value was written without introducing clobbering\n */\n const _setAttributeValue = function (\n currentNode: Element,\n name: string,\n namespaceURI: string | null,\n value: string\n ): boolean {\n try {\n if (namespaceURI) {\n currentNode.setAttributeNS(namespaceURI, name, value);\n } else {\n /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. \"x-schema\". */\n currentNode.setAttribute(name, value);\n }\n\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n return false;\n }\n\n return true;\n } catch (_) {\n _removeAttribute(name, currentNode);\n return false;\n }\n };\n\n /**\n * _isUnsafeAttributeValue\n *\n * Value-based attribute checks that the attribute walk applies before any\n * hook can force-keep an attribute, shared with the public\n * isValidAttribute() so that it never approves a value sanitize() would\n * strip.\n *\n * @param name the attribute name as found on the node (case preserved)\n * @param value the attribute value\n * @returns true if the attribute must be removed because of its value\n */\n const _isUnsafeAttributeValue = function (\n name: string,\n value: string\n ): boolean {\n /* Work around a security issue with comments inside attributes, and\n raw-text closers that re-contextualize the value on a later reparse */\n if (\n SAFE_FOR_XML &&\n regExpTest(\n /((--!?|])>)|<\\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,\n value\n )\n ) {\n return true;\n }\n\n /* Make sure we cannot easily use animated hrefs, even if animations are\n allowed. Compared case-insensitively on purpose: in\n application/xhtml+xml mode names keep their case, and the real SVG\n attribute is spelled attributeName, which 'attributename' would\n never match (GHSA-c6gr-qvv4-5v3f). In XHTML a lowercase\n `attributename` is not the SMIL attribute, so also stripping it\n there costs nothing. */\n return (\n stringToLowerCase(name) === 'attributename' &&\n stringMatch(value, 'href') !== null\n );\n };\n\n /**\n * _sanitizeAttributes\n *\n * @protect attributes\n * @protect nodeName\n * @protect removeAttribute\n * @protect setAttribute\n *\n * @param currentNode to sanitize\n * @param root the current walk root\n */\n const _sanitizeAttributes = function (\n currentNode: Element,\n root: Node\n ): void {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);\n\n /* A hook may have detached the node - the attribute hooks can detach\n exactly like the element hooks can, and the walker will not revisit\n the detached subtree. Treat it as removed and, on the IN_PLACE path,\n neutralize it (see _handleHookDetachedNode for the full rationale). */\n if (_handleHookDetachedNode(currentNode, root)) {\n return;\n }\n\n const { attributes } = currentNode;\n\n /* Check if we have attributes; if not we might have a text node */\n if (!attributes || _isClobbered(currentNode)) {\n return;\n }\n\n /* Same lazy-install guard as uponSanitizeElement (see there): fork the\n attribute allowlist off its shared binding before a hook can see it. */\n ALLOWED_ATTR = _forkSharedAllowlist(\n hooks.uponSanitizeAttribute,\n ALLOWED_ATTR,\n DEFAULT_ALLOWED_ATTR,\n SET_CONFIG_ALLOWED_ATTR\n );\n\n const hookEvent = {\n attrName: '',\n attrValue: '',\n keepAttr: true,\n allowedAttributes: ALLOWED_ATTR,\n forceKeepAttr: undefined,\n };\n let l = attributes.length;\n const lcTag = transformCaseFunc(currentNode.nodeName);\n\n /* Go backwards over all attributes; safely remove bad ones */\n while (l--) {\n const attr = attributes[l];\n const { name, namespaceURI, value: attrValue } = attr;\n const lcName = transformCaseFunc(name);\n\n const initValue = attrValue;\n let value = name === 'value' ? initValue : stringTrim(initValue);\n\n /* Tracks whether this specific attribute pushed a DOMPurify.removed\n record that a later _setAttributeValue() writeback is expected to pop\n back off (the SANITIZE_NAMED_PROPS remove-and-recreate below is the\n only path that does). A value that merely changed via trim, template\n scrubbing, or Trusted Types pushes no such record, so its writeback\n must NOT pop \u2014 otherwise it consumes an unrelated _forceRemove subtree\n record and that detached subtree escapes the IN_PLACE handler-\n neutralization pass (SO-001). */\n let recreatedNamedProp = false;\n\n /* Execute a hook if present */\n hookEvent.attrName = lcName;\n hookEvent.attrValue = value;\n hookEvent.keepAttr = true;\n hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set\n _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);\n value = hookEvent.attrValue;\n\n /* Full DOM Clobbering protection via namespace isolation,\n * Prefix id and name attributes with `user-content-`\n */\n if (\n SANITIZE_NAMED_PROPS &&\n (lcName === 'id' || lcName === 'name') &&\n stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0\n ) {\n // Remove the attribute with this value\n _removeAttribute(name, currentNode, attr);\n // Prefix the value and later re-create the attribute with the sanitized value\n value = SANITIZE_NAMED_PROPS_PREFIX + value;\n // This attribute owns the record just pushed; its recreate writeback\n // is the one allowed to pop it back off.\n recreatedNamedProp = true;\n }\n // Else: already prefixed, leave the attribute alone \u2014 the prefix is\n // itself the clobbering protection, and re-applying it is incorrect.\n\n /* Value checks that apply regardless of hooks (comment / raw-text\n closers in the value, animated hrefs); see _isUnsafeAttributeValue. */\n if (_isUnsafeAttributeValue(name, value)) {\n _removeAttribute(name, currentNode, attr);\n continue;\n }\n\n /* Did the hooks force-keep the attribute? */\n if (hookEvent.forceKeepAttr) {\n continue;\n }\n\n /* Did the hooks approve of the attribute? */\n if (!hookEvent.keepAttr) {\n _removeAttribute(name, currentNode, attr);\n continue;\n }\n\n /* Work around a security issue in jQuery 3.0 */\n if (\n !ALLOW_SELF_CLOSE_IN_ATTR &&\n regExpTest(EXPRESSIONS.SELF_CLOSING_TAG, value)\n ) {\n _removeAttribute(name, currentNode, attr);\n continue;\n }\n\n /* Sanitize attribute content to be template-safe */\n if (SAFE_FOR_TEMPLATES) {\n value = _stripTemplateExpressions(value);\n }\n\n /* Is `value` valid for this attribute? */\n if (!_isValidAttribute(lcTag, lcName, value)) {\n _removeAttribute(name, currentNode, attr);\n continue;\n }\n\n /* Handle attributes that require Trusted Types */\n value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);\n\n /* Handle invalid data-* attribute set by try-catching it */\n if (value !== initValue) {\n const cleanWrite = _setAttributeValue(\n currentNode,\n name,\n namespaceURI,\n value\n );\n\n /* Only the named-prop remove-and-recreate owns a DOMPurify.removed\n record to pop; a plain trim/template/Trusted-Types writeback owns\n none, so popping here would drop an unrelated subtree's cleanup\n record (SO-001). */\n if (cleanWrite && recreatedNamedProp) {\n arrayPop(DOMPurify.removed);\n }\n }\n }\n\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);\n\n /* Same detach re-check as after beforeSanitizeAttributes: this is the\n last hook that runs for the node, so a detach here would otherwise\n hand the caller a live, handler-bearing subtree. */\n _handleHookDetachedNode(currentNode, root);\n };\n\n /**\n * _sanitizeShadowDOM\n *\n * @param fragment to iterate over recursively\n */\n const _sanitizeShadowDOM = function (fragment: DocumentFragment): void {\n let shadowNode = null;\n const shadowIterator = _createNodeIterator(fragment);\n\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);\n\n while ((shadowNode = shadowIterator.nextNode())) {\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);\n\n /* Sanitize tags and elements */\n _sanitizeElements(shadowNode, fragment);\n\n /* Check attributes next */\n _sanitizeAttributes(shadowNode, fragment);\n\n /* Deep shadow DOM detected.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the\n DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we\n recurse into <template>.content from foreign realms too. */\n if (_isDocumentFragment(shadowNode.content)) {\n _sanitizeShadowDOM(shadowNode.content);\n }\n\n /* An element iterated here may itself host an attached\n shadow root. The default NodeIterator does not enter shadow\n trees, so a shadow root nested inside template.content was\n previously reached by no walk at all (the pre-pass at\n _sanitizeAttachedShadowRoots descends via childNodes, which\n doesn't enter template.content; the template-content recursion\n above iterates the content but never inspected shadowRoot).\n Walk it explicitly. The nodeType guard avoids reading\n shadowRoot off text / comment / CDATA / PI nodes that the\n iterator also surfaces. */\n if (_readNodeType(shadowNode) === NODE_TYPE.element) {\n const innerSr = getShadowRoot(shadowNode);\n if (_isDocumentFragment(innerSr)) {\n _sanitizeAttachedShadowRoots(innerSr);\n _sanitizeShadowDOM(innerSr);\n }\n }\n }\n\n /* Post-walk template-expression safety net, mirroring the light-DOM\n passes on `dirty` / `body`. The per-node strip above (via\n _sanitizeElements) only sees each text node in isolation, so an\n expression split across text siblings by a disallowed separator element\n (e.g. `$` <object> `{alert(1)}`) survives: each fragment matches no\n delimiter regex on its own, and once the separator is removed the\n fragments become adjacent and serialize as one complete expression.\n The light-DOM net catches exactly this, but NodeIterator does not\n descend into shadow trees and node.normalize() does not merge text\n across the shadow boundary, so the fragments were never re-examined as\n a merged unit. normalize() here (inside _scrubTemplateExpressions)\n merges them and re-strips. Deliberately the non-recursive variant: each\n nested shadow root and template content is walked by its own\n _sanitizeShadowDOM call above and scrubbed there, so every fragment is\n scrubbed exactly once (the recursive variant would make this quadratic\n in nesting depth). Gated on SAFE_FOR_TEMPLATES like the light-DOM\n passes, and placed before the afterSanitizeShadowDOM hook so that hook\n observes the finalized fragment. */\n if (SAFE_FOR_TEMPLATES) {\n _scrubOwnCharacterData(fragment as unknown as Element);\n }\n\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n };\n\n /**\n * Sanitizes every attached shadow root under `root`, since the node\n * iterator does not enter shadow trees. Needed for IN_PLACE input and for\n * DOM input whose clonable shadow roots were copied by importNode().\n *\n * @param root the subtree root to walk for attached shadow roots\n */\n const _sanitizeAttachedShadowRoots = function (root: Node): void {\n /* Explicit stack, so deep trees cannot overflow the call stack. An item is\n a node to walk or a shadow root to sanitize. Items are processed in\n reverse push order: a shadow root is walked first (finding nested\n roots), then sanitized, then template content, then the children. */\n const stack: Array<{ node: Node | null; shadow: DocumentFragment | null }> =\n [{ node: root, shadow: null }];\n\n while (stack.length > 0) {\n const item = stack.pop();\n\n if (item.shadow) {\n _sanitizeShadowDOM(item.shadow);\n continue;\n }\n\n const node = item.node;\n const nodeType = _readNodeType(node);\n const isElement = nodeType === NODE_TYPE.element;\n\n // Children, copied now since hooks may detach siblings mid-walk\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push({ node: childNodes[i], shadow: null });\n }\n }\n\n // Template content\n if (isElement) {\n const rootName = getNodeName ? getNodeName(node) : null;\n if (\n typeof rootName === 'string' &&\n transformCaseFunc(rootName) === 'template'\n ) {\n const content = (node as HTMLTemplateElement).content;\n if (_isDocumentFragment(content)) {\n stack.push({ node: content, shadow: null });\n }\n }\n }\n\n // Shadow root: walk it, then sanitize it (realm-safe nodeType check)\n if (isElement) {\n const sr = getShadowRoot(node);\n if (_isDocumentFragment(sr)) {\n stack.push({ node: null, shadow: sr }, { node: sr, shadow: null });\n }\n }\n }\n };\n\n // eslint-disable-next-line complexity\n DOMPurify.sanitize = function (dirty, cfg = {}) {\n let body = null;\n let importedNode = null;\n let currentNode = null;\n let returnNode = null;\n /* Make sure we have a string to sanitize.\n DO NOT return early, as this will return the wrong type if\n the user has requested a DOM object rather than a string */\n IS_EMPTY_INPUT = !dirty;\n if (IS_EMPTY_INPUT) {\n dirty = '<!-->';\n }\n\n /* Stringify, in case dirty is an object */\n if (typeof dirty !== 'string' && !_isNode(dirty)) {\n dirty = stringifyValue(dirty);\n\n if (typeof dirty !== 'string') {\n throw typeErrorCreate('dirty is not a string, aborting');\n }\n }\n\n /* Return dirty HTML if DOMPurify cannot run */\n if (!DOMPurify.isSupported) {\n return dirty;\n }\n\n /* Assign config vars */\n if (SET_CONFIG) {\n /* Persistent setConfig() path: _parseConfig is skipped, so the sets are\n * not re-derived per call. Restore them from the pristine bindings\n * captured at setConfig() time so a previous call's hook clone (mutated\n * below) does not carry over. */\n ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;\n ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;\n } else {\n _parseConfig(cfg);\n }\n\n /* Clone the hook-mutable allowlists before the walk whenever an\n * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS\n * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so\n * a hook that widens them would otherwise mutate the shared set\n * permanently: across later calls and across every element. Cloning per\n * walk keeps documented in-call widening working while scoping it to the\n * call. A single guard for both config paths - the per-call path rebinds\n * the sets in _parseConfig each call, the persistent path restores them\n * from the captured bindings just above - so the two cannot diverge. */\n if (\n hooks.uponSanitizeElement.length > 0 ||\n hooks.uponSanitizeAttribute.length > 0\n ) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n\n if (hooks.uponSanitizeAttribute.length > 0) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n\n /* Clean up removed elements */\n DOMPurify.removed = [];\n\n /* Resolved per call: setConfig() skips _parseConfig, so writing IN_PLACE\n here would leak into later calls (REPORT-2). */\n const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);\n /* IN_PLACE: the caller's nodes before any hook or custom element can run,\n and the visit tracking of an outer call this one may be nested in */\n let inPlaceNodes: Node[] = [];\n const outerVisited = IN_PLACE_VISITED;\n\n if (inPlace) {\n _neutralizePatchLinkage(dirty as Node);\n\n /* The root must be an allowed tag and not clobbered: a parentless root\n cannot be removed, so it would come back unsanitized. Its name is read\n through the cached getter, a clobbering child could shadow it. */\n const nn = _readNodeName(dirty as Node);\n if (typeof nn === 'string') {\n const tagName = transformCaseFunc(nn);\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n _neutralizeRoot(dirty as Node);\n throw typeErrorCreate(\n 'root node is forbidden and cannot be sanitized in-place'\n );\n }\n }\n\n if (_isClobbered(dirty as Element)) {\n _neutralizeRoot(dirty as Node);\n throw typeErrorCreate(\n 'root node is clobbered and cannot be sanitized in-place'\n );\n }\n\n inPlaceNodes = _collectLiveNodes(dirty as Node);\n IN_PLACE_VISITED = setCreate();\n } else if (_isNode(dirty)) {\n /* If dirty is a DOM element, append to an empty document to avoid\n elements being stripped by the parser */\n body = _initDocument('<!---->');\n importedNode = body.ownerDocument.importNode(dirty, true);\n if (\n importedNode.nodeType === NODE_TYPE.element &&\n importedNode.nodeName === 'BODY'\n ) {\n /* Node is already a body, use as is */\n body = importedNode;\n } else if (importedNode.nodeName === 'HTML') {\n body = importedNode;\n } else {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n body.appendChild(importedNode);\n }\n\n /* Clonable shadow roots are deep-cloned by importNode(); sanitize\n them before the main iterator runs, since the iterator does not\n descend into shadow trees. The walk routes every read through a\n cached prototype getter so clobbering descendants on a form root\n cannot hide a shadow host from this pass.\n\n Traverse from `body`, not `importedNode`: when importedNode is a\n DocumentFragment, the appendChild() above moves its children into\n `body` and leaves the fragment empty, so walking importedNode would\n scan nothing and miss every attached shadow host now under `body`\n (SO-003). In the BODY/HTML branches `body === importedNode`, so this\n is equivalent there; in the element branch `body` contains the\n appended element and its descendants. `body` covers all three. */\n _sanitizeAttachedShadowRoots(body);\n } else {\n /* Exit directly if we have nothing to do */\n if (\n !RETURN_DOM &&\n !SAFE_FOR_TEMPLATES &&\n !WHOLE_DOCUMENT &&\n // eslint-disable-next-line unicorn/prefer-includes\n dirty.indexOf('<') === -1\n ) {\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE\n ? _createTrustedHTML(dirty)\n : dirty;\n }\n\n /* Initialize the document to work on */\n body = _initDocument(dirty);\n\n /* Check we have a DOM node from the data */\n if (!body) {\n return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';\n }\n }\n\n /* Remove first element node (ours) if FORCE_BODY is set */\n if (body && FORCE_BODY) {\n _forceRemove(body.firstChild);\n }\n\n /* Get node iterator */\n const walkRoot: Node = inPlace ? (dirty as Node) : body;\n\n /* If anything throws, an in-place tree is stripped bare before the error\n propagates, never left half-sanitized. */\n try {\n if (inPlace) {\n _sanitizeAttachedShadowRoots(dirty as Node);\n }\n\n const nodeIterator = _createNodeIterator(walkRoot);\n while ((currentNode = nodeIterator.nextNode())) {\n _sanitizeElements(currentNode, walkRoot);\n _sanitizeAttributes(currentNode, walkRoot);\n\n // Template content (realm-safe nodeType check)\n if (_isDocumentFragment(currentNode.content)) {\n _sanitizeShadowDOM(currentNode.content);\n }\n }\n\n if (inPlace) {\n _sanitizeUnvisitedNodes(dirty as Node, inPlaceNodes);\n }\n } catch (error) {\n if (inPlace) {\n _neutralizeRoot(dirty as Node);\n _neutralizeDiscarded(dirty as Node, inPlaceNodes);\n }\n\n throw error;\n } finally {\n IN_PLACE_VISITED = outerVisited;\n }\n\n if (inPlace) {\n // A removed root has no safe state to return\n if (_neutralizeDiscarded(dirty as Node, inPlaceNodes)) {\n throw typeErrorCreate(\n 'a node selected for removal could not be safely returned; ' +\n 'refusing to sanitize in place'\n );\n }\n\n if (SAFE_FOR_TEMPLATES) {\n _scrubTemplateExpressions(dirty as Element);\n }\n\n return dirty;\n }\n\n /* Return sanitized string or DOM */\n if (RETURN_DOM) {\n if (SAFE_FOR_TEMPLATES) {\n _scrubTemplateExpressions(body);\n }\n\n if (RETURN_DOM_FRAGMENT) {\n returnNode = createDocumentFragment.call(body.ownerDocument);\n\n while (body.firstChild) {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n returnNode.appendChild(body.firstChild);\n }\n } else {\n returnNode = body;\n }\n\n if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {\n /*\n AdoptNode() is not used because internal state is not reset\n (e.g. the past names map of a HTMLFormElement), this is safe\n in theory but we would rather not risk another attack vector.\n The state that is cloned by importNode() is explicitly defined\n by the specs.\n */\n returnNode = importNode.call(originalDocument, returnNode, true);\n }\n\n return returnNode;\n }\n\n let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n\n /* Serialize doctype if allowed */\n if (\n WHOLE_DOCUMENT &&\n ALLOWED_TAGS['!doctype'] &&\n body.ownerDocument &&\n body.ownerDocument.doctype &&\n body.ownerDocument.doctype.name &&\n regExpTest(EXPRESSIONS.DOCTYPE_NAME, body.ownerDocument.doctype.name)\n ) {\n serializedHTML =\n '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\\n' + serializedHTML;\n }\n\n /* Sanitize final string template-safe */\n if (SAFE_FOR_TEMPLATES) {\n serializedHTML = _stripTemplateExpressions(serializedHTML);\n }\n\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE\n ? _createTrustedHTML(serializedHTML)\n : serializedHTML;\n };\n\n DOMPurify.setConfig = function (cfg = {}) {\n _parseConfig(cfg);\n SET_CONFIG = true;\n SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;\n SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;\n };\n\n DOMPurify.clearConfig = function () {\n CONFIG = null;\n SET_CONFIG = false;\n SET_CONFIG_ALLOWED_TAGS = null;\n SET_CONFIG_ALLOWED_ATTR = null;\n\n // Drop any caller-supplied Trusted Types policy so it cannot poison later\n // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and\n // never recreated \u2014 Trusted Types throws on duplicate names) is restored by\n // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.\n trustedTypesPolicy = defaultTrustedTypesPolicy;\n emptyHTML = '';\n };\n\n DOMPurify.isValidAttribute = function (tag, attr, value) {\n /* Initialize shared config vars if necessary. */\n if (!CONFIG) {\n _parseConfig({});\n }\n\n const lcTag = transformCaseFunc(tag);\n const lcName = transformCaseFunc(attr);\n\n /* Apply the same value checks sanitize() applies to an attribute when no\n hook intervenes, so a value approved here is one sanitize() would also\n keep: comment / raw-text closers, animated hrefs, and the jQuery 3.0\n self-closing-tag pattern. */\n if (\n typeof value === 'string' &&\n (_isUnsafeAttributeValue(attr, value) ||\n (!ALLOW_SELF_CLOSE_IN_ATTR &&\n regExpTest(EXPRESSIONS.SELF_CLOSING_TAG, value)))\n ) {\n return false;\n }\n\n return _isValidAttribute(lcTag, lcName, value);\n };\n\n DOMPurify.addHook = function (\n entryPoint: keyof HooksMap,\n hookFunction: HookFunction\n ) {\n if (typeof hookFunction !== 'function') {\n return;\n }\n\n /* Reject unknown entry points. Without this, a non-hook key (e.g.\n * '__proto__') indexes off the prototype chain rather than a real\n * hook array, and arrayPush then writes to Object.prototype. Guard\n * with an own-property check against the known hook names. */\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return;\n }\n\n arrayPush(hooks[entryPoint], hookFunction);\n };\n\n DOMPurify.removeHook = function (\n entryPoint: keyof HooksMap,\n hookFunction: HookFunction\n ) {\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return undefined;\n }\n\n if (hookFunction !== undefined) {\n const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);\n\n return index === -1\n ? undefined\n : arraySplice(hooks[entryPoint], index, 1)[0];\n }\n\n return arrayPop(hooks[entryPoint]);\n };\n\n DOMPurify.removeHooks = function (entryPoint: keyof HooksMap) {\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return;\n }\n\n hooks[entryPoint] = [];\n };\n\n DOMPurify.removeAllHooks = function () {\n hooks = _createHooksMap();\n };\n\n return DOMPurify;\n}\n\nexport default createDOMPurify();\n", "import type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Gets the original marked default options.\n */\nexport function _getDefaults<ParserOutput = string, RendererOutput = string>(): MarkedOptions<ParserOutput, RendererOutput> {\n return {\n async: false,\n breaks: false,\n extensions: null,\n gfm: true,\n hooks: null,\n pedantic: false,\n renderer: null,\n silent: false,\n tokenizer: null,\n walkTokens: null,\n };\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport let _defaults: MarkedOptions<any, any> = _getDefaults();\n\nexport function changeDefaults<ParserOutput = string, RendererOutput = string>(newDefaults: MarkedOptions<ParserOutput, RendererOutput>) {\n _defaults = newDefaults;\n}\n", "const noopTest = { exec: () => null } as unknown as RegExp;\n\nfunction cachedIndentRegex(createRegex: (indent: number) => RegExp) {\n const cache: RegExp[] = [];\n return (indent: number) => {\n const cacheIndex = Math.max(0, Math.min(3, indent - 1));\n let regex = cache[cacheIndex];\n if (!regex) {\n regex = createRegex(cacheIndex);\n cache[cacheIndex] = regex;\n }\n return regex;\n };\n}\n\nfunction edit(regex: string | RegExp, opt = '') {\n let source = typeof regex === 'string' ? regex : regex.source;\n const obj = {\n replace: (name: string | RegExp, val: string | RegExp) => {\n let valSource = typeof val === 'string' ? val : val.source;\n valSource = valSource.replace(other.caret, '$1');\n source = source.replace(name, valSource);\n return obj;\n },\n getRegex: () => {\n return new RegExp(source, opt);\n },\n };\n return obj;\n}\n\n// use a default variable to ensure the regex is evaluated on client an not removed by minifiers\nconst supportsLookbehind = ((a = '') => {\ntry {\n return !!new RegExp('(?<=1)(?<!1)' + a);\n} catch {\n // See browser support here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion\n return false;\n}\n})();\n\nexport const other = {\n codeRemoveIndent: /^(?: {0,3}\\t| {1,4})/gm,\n outputLinkReplace: /\\\\([\\[\\]])/g,\n indentCodeCompensation: /^(\\s+)(?:```)/,\n beginningSpace: /^\\s+/,\n endingHash: /#$/,\n startingSpaceChar: /^ /,\n endingSpaceChar: / $/,\n endingSpaceTabChar: /[ \\t]$/,\n nonSpaceChar: /[^ ]/,\n newLineCharGlobal: /\\n/g,\n tabCharGlobal: /\\t/g,\n leadingSpaceTab: /^[ \\t]+/,\n multipleSpaceGlobal: /\\s+/g,\n blankLine: /^[ \\t]*$/,\n doubleBlankLine: /\\n[ \\t]*\\n[ \\t]*$/,\n blockquoteStart: /^ {0,3}>/,\n // Neutralize a lazy setext underline, including one with trailing tabs.\n // CommonMark \u00A74.3 allows those tabs on a real underline, so the same class\n // has to be recognized here or a lazy `===\\t` becomes a heading.\n blockquoteSetextReplace: /\\n {0,3}((?:=+|-+)[ \\t]*)(?=\\n|$)/g,\n blockquoteSetextReplace2: /^ {0,3}>[ \\t]?/gm,\n blockquoteMarkerWhitespace: /^( {0,3}>)([ \\t]+)/gm,\n listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,\n listIsTask: /^\\[[ xX]\\][ \\t]+\\S/,\n listReplaceTask: /^\\[[ xX]\\][ \\t]+/,\n listTaskCheckbox: /\\[[ xX]\\]/,\n anyLine: /\\n.*\\n/,\n hrefBrackets: /^<(.*)>$/,\n tableDelimiter: /[:|]/,\n tableAlignChars: /^\\||\\| *$/g,\n tableRowBlankLine: /\\n[ \\t]*$/,\n tableAlignRight: /^ *-+: *$/,\n tableAlignCenter: /^ *:-+: *$/,\n tableAlignLeft: /^ *:-+ *$/,\n startATag: /^<a /i,\n endATag: /^<\\/a>/i,\n startPreScriptTag: /^<(pre|code|kbd|script)(\\s|>)/i,\n endPreScriptTag: /^<\\/(pre|code|kbd|script)(\\s|>)/i,\n startAngleBracket: /^</,\n endAngleBracket: />$/,\n pedanticHrefTitle: /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,\n unicodeAlphaNumeric: /[\\p{L}\\p{N}]/u,\n numericCharacterReference: /&#(?:(\\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,\n numericCharacterReferenceOrAmpersand: /&#(?:(\\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,\n escapeTest: /[&<>\"']/,\n escapeReplace: /[&<>\"']/g,\n escapeTestNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,\n escapeReplaceNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,\n caret: /(^|[^\\[])\\^/g,\n percentDecode: /%25/g,\n findPipe: /\\|/g,\n splitPipe: / \\|/,\n slashPipe: /\\\\\\|/g,\n carriageReturn: /\\r\\n|\\r/g,\n spaceLine: /^ +$/gm,\n notSpaceStart: /^\\S*/,\n endingNewline: /\\n$/,\n listItemRegex: (bull: string) => new RegExp(`^( {0,3}${bull})((?:[\\t ][^\\\\n]*)?(?:\\\\n|$))`),\n nextBulletRegex: cachedIndentRegex((indent: number) => new RegExp(`^ {0,${indent}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \\t][^\\\\n]*)?(?:\\\\n|$))`)),\n hrRegex: cachedIndentRegex((indent: number) => new RegExp(`^ {0,${indent}}((?:-[ \\t]*){3,}|(?:_[ \\t]*){3,}|(?:\\\\*[ \\t]*){3,})(?:\\\\n+|$)`)),\n fencesBeginRegex: cachedIndentRegex((indent: number) => new RegExp(`^ {0,${indent}}(?:\\`\\`\\`|~~~)`)),\n // an ATX heading needs a space (or the end of the line) after the hashes, so a line\n // like `#tag` does not end a list item; pedantic mode accepts it as a heading\n headingBeginRegex: cachedIndentRegex((indent: number) => new RegExp(`^ {0,${indent}}#{1,6}(?:\\\\s|$)`)),\n pedanticHeadingBeginRegex: cachedIndentRegex((indent: number) => new RegExp(`^ {0,${indent}}#`)),\n // a list item ends where a paragraph would be interrupted, so this mirrors the\n // html start conditions in the paragraph rule below; type 7 is excluded there\n htmlBeginRegex: cachedIndentRegex((indent: number) => new RegExp(`^ {0,${indent}}(?:</?(?:${_tag})(?: +|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\\\s>]|$)|!--)|<\\\\?|<![A-Za-z]|<!\\\\[CDATA\\\\[)`, 'i')),\n blockquoteBeginRegex: cachedIndentRegex((indent: number) => new RegExp(`^ {0,${indent}}>`)),\n};\n\n/**\n * Block-Level Grammar\n */\n\nconst newline = /^(?:[ \\t]*(?:\\n|$))+/;\nconst blockCode = /^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/;\nconst fences = /^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}(?:(?=`)\\1`*|(?=~)\\1~*) *(?=\\n|$)|$)/;\nconst hr = /^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/;\nconst heading = /^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/;\nconst bullet = / {0,3}(?:[*+-]|\\d{1,9}[.)])/;\n// The underline may end with spaces or tabs (CommonMark \u00A74.3). Internal\n// spaces or tabs still fail to match, and more than three spaces of indent\n// still do not.\nconst lheadingCore = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |fences|blockquote|heading|hr|html|table))+?)\\n {0,3}(=+|-+)[ \\t]*(?:\\n+|$)/;\nconst lheading = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code can start a block but cannot interrupt a paragraph\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}(?:\\s|$)/) // ATX heading can interrupt\n .replace(/hr/g, / {0,3}(?:(?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/) // thematic break can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .replace(/\\|table/g, '') // table not in commonmark\n .getRegex();\nconst lheadingGfm = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code can start a block but cannot interrupt a paragraph\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}(?:\\s|$)/) // ATX heading can interrupt\n .replace(/hr/g, / {0,3}(?:(?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/) // thematic break can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .replace(/table/g, / {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/) // table can interrupt\n .getRegex();\nconst _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \\t]+\\n)[^\\n]+)*)/;\nconst blockText = /^[^\\n]+/;\nconst _blockLabel = /(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\\\n]|\\n(?![ \\t]*\\n))+/;\nconst def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/)\n .replace('label', _blockLabel)\n // An escaped delimiter is part of the title, so a backslash must consume the\n // next character. An optional closer (`\\\"?`) lets that character backtrack\n // into the closing quote (`[foo]: /url \"t\\\"` is not a title).\n .replace('title', /(?:\"(?:\\\\[\\s\\S]|[^\"\\\\])*\"|'(?:\\\\[\\s\\S]|[^'\\\\\\n]|\\n(?!\\n))*'|\\((?:\\\\[\\s\\S]|[^()\\\\])*\\))/)\n .getRegex();\n\nconst list = edit(/^(bull)([ \\t][^\\n]*?)?(?:\\n|$)/)\n .replace(/bull/g, bullet)\n .getRegex();\n\nconst _tag = 'address|article|aside|base|basefont|blockquote|body|caption'\n + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'\n + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'\n + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'\n + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'\n + '|tr|track|ul';\nconst _comment = /<!--(?:-?>|[\\s\\S]*?(?:-->|$))/;\nconst html = edit(\n '^ {0,3}(?:' // optional indentation\n+ '<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:</\\\\1>[^\\\\n]*\\\\n*|$)' // (1)\n+ '|comment[^\\\\n]*(\\\\n+|$)' // (2)\n+ '|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>[^\\\\n]*\\\\n*|$)' // (3)\n+ '|<![A-Z][\\\\s\\\\S]*?(?:>[^\\\\n]*\\\\n*|$)' // (4)\n+ '|<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?(?:\\\\]\\\\]>[^\\\\n]*\\\\n*|$)' // (5)\n+ '|</?(tag)(?:[ \\\\t]+|\\\\n|/?>|$)[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (6)\n+ '|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) open tag\n+ '|</[a-z][a-z0-9-]*\\\\s*>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) closing tag\n+ ')', 'i')\n .replace('comment', _comment)\n .replace('tag', _tag)\n .replace('attribute', / +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/)\n .getRegex();\n\nconst createParagraph = (listInterrupt: RegExp) => edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*(?:\\\\n|$))|~~~)[^\\\\n]*(?:\\\\n|$)')\n .replace('list', listInterrupt)\n .replace('html', ' {0,3}(?:</?(?:tag)(?: +|\\\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\\\s>]|$)|!--)|<\\\\?|<![A-Za-z]|<!\\\\[CDATA\\\\[)')\n .replace('tag', _tag) // pars can be interrupted by html blocks of types (1) to (6)\n .getRegex();\n\n// only non-empty lists starting from 1 can interrupt paragraphs\nconst paragraph = createParagraph(/ {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]/);\n// inside a blockquote a bare list marker (any number) starts a sibling list,\n// so it must not be lazily continued as paragraph text (unlike a top level\n// paragraph, where an empty list cannot interrupt)\nconst blockquoteParagraph = createParagraph(/ {0,3}(?:[*+-]|\\d{1,9}[.)])(?:[ \\t]|\\n|$)/);\n\n// a line with only whitespace after the marker is blank, so it must not start a\n// paragraph that lazily continues onto the next line\nconst blockquote = edit(/^( {0,3}> ?(?:(?![ \\t]*(?:\\n|$))(paragraph)|[^\\n]*)(?:\\n|$))+/)\n .replace('paragraph', blockquoteParagraph)\n .getRegex();\n\n/**\n * Normal Block Grammar\n */\n\nconst blockNormal = {\n blockquote,\n code: blockCode,\n def,\n fences,\n heading,\n hr,\n html,\n lheading,\n list,\n newline,\n paragraph,\n table: noopTest,\n text: blockText,\n};\n\ntype BlockKeys = keyof typeof blockNormal;\n\n/**\n * GFM Block Grammar\n */\n\nconst gfmTable = edit(\n '^ *([^\\\\n ].*)\\\\n' // Header\n+ ' {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)' // Align\n+ '(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)') // Cells\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('blockquote', ' {0,3}>')\n .replace('code', '(?: {4}| {0,3}\\t)[^\\\\n]')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*(?:\\\\n|$))|~~~)[^\\\\n]*(?:\\\\n|$)')\n .replace('list', ' {0,3}(?:[*+-]|1[.)])[ \\\\t]') // any bullet ends the table rows\n .replace('html', ' {0,3}(?:</?(?:tag)(?: +|\\\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\\\s>]|$)|!--)|<\\\\?|<![A-Za-z]|<!\\\\[CDATA\\\\[)')\n .replace('tag', _tag) // tables can be interrupted by html blocks of types (1) to (6)\n .getRegex();\n\nconst blockGfm: Record<BlockKeys, RegExp> = {\n ...blockNormal,\n lheading: lheadingGfm,\n table: gfmTable,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('table', gfmTable) // interrupt paragraphs with table\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*(?:\\\\n|$))|~~~)[^\\\\n]*(?:\\\\n|$)')\n .replace('list', ' {0,3}(?:[*+-]|1[.)])[ \\\\t]+[^ \\\\t\\\\n]') // only non-empty lists starting from 1 can interrupt\n .replace('html', ' {0,3}(?:</?(?:tag)(?: +|\\\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\\\s>]|$)|!--)|<\\\\?|<![A-Za-z]|<!\\\\[CDATA\\\\[)')\n .replace('tag', _tag) // pars can be interrupted by html blocks of types (1) to (6)\n .getRegex(),\n};\n\n/**\n * Pedantic grammar (original John Gruber's loose markdown specification)\n */\n\nconst blockPedantic: Record<BlockKeys, RegExp> = {\n ...blockNormal,\n html: edit(\n '^ *(?:comment(?: *\\\\n|\\\\s*$)'\n + '|<(tag)[\\\\s\\\\S]+?</\\\\1>(?: *\\\\n{2,}|\\\\s*$)' // closed tag\n + '|<tag(?:\"[^\"]*\"|\\'[^\\']*\\'|\\\\s[^\\'\"/>\\\\s]*)*?/?>(?: *\\\\n{2,}|\\\\s*$))')\n .replace('comment', _comment)\n .replace(/tag/g, '(?!(?:'\n + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'\n + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'\n + '\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b')\n .getRegex(),\n def: /^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,\n heading: /^(#{1,6})(.*)(?:\\n+|$)/,\n fences: noopTest, // fences not supported\n lheading: /^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' *#{1,6} *[^\\n]')\n .replace('lheading', lheading)\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('|fences', '')\n .replace('|list', '')\n .replace('|html', '')\n .replace('|tag', '')\n .getRegex(),\n};\n\n/**\n * Inline-Level Grammar\n */\n\nconst escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nconst inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nconst br = /^( {2,}|\\\\)\\n(?!\\s*$)[ \\t]*/;\nconst inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/;\n\n// list of unicode punctuation marks, plus any missing characters from CommonMark spec\nconst _punctuation = /[\\p{P}\\p{S}]/u;\nconst _punctuationOrSpace = /[\\s\\p{P}\\p{S}]/u;\nconst _notPunctuationOrSpace = /[^\\s\\p{P}\\p{S}]/u;\nconst punctuation = edit(/^((?![*_])punctSpace)/, 'u')\n .replace(/punctSpace/g, _punctuationOrSpace).getRegex();\n\n/**\n * Opening punct/quotes excluded from pedantic LDelim nextChar so\n * `aa**\"A\"**bb` / `aa**(A)**bb` can start strong (Pi + Ps + ASCII straight quotes).\n */\nconst _openQuote = /[\\p{Pi}\\p{Ps}\"']/u;\n\n// GFM allows ~ inside strong and em for strikethrough\nconst _punctuationGfmStrongEm = /(?!~)[\\p{P}\\p{S}]/u;\nconst _punctuationOrSpaceGfmStrongEm = /(?!~)[\\s\\p{P}\\p{S}]/u;\nconst _notPunctuationOrSpaceGfmStrongEm = /(?:[^\\s\\p{P}\\p{S}]|~)/u;\n\n// sequences em should skip over [title](link), `code`, <html>\nconst blockSkip = edit(/link|precode-code|html/, 'g')\n .replace('link', /\\[(?:[^\\[\\]`]|(?<a>`+)[^`]+\\k<a>(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/)\n .replace('precode-', supportsLookbehind ? '(?<!`)()' : '(^^|[^`])')\n .replace('code', /(?<b>`+)[^`]+\\k<b>(?!`)/)\n .replace('html', /<(?! )[^<>]*?>/)\n .getRegex();\n\nconst emStrongLDelimCore = /^(?:\\*+(?:((?!\\*)punct)|([^\\s*]))?)|^_+(?:((?!_)punct)|([^\\s_]))?/;\n\nconst emStrongLDelim = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongLDelimGfm = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\n// Pedantic: do not treat opening punct/quotes as left-delim punct (e.g. **( / **\").\nconst emStrongLDelimPedanticCore = /^(?:\\*+(?:((?!\\*)(?!openQuote)punct)|([^\\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\\s_]))?/;\n\nconst emStrongLDelimPedantic = edit(emStrongLDelimPedanticCore, 'u')\n .replace(/openQuote/g, _openQuote)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongRDelimAstCore =\n '^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n+ '|[^*]+(?=[^*])' // Consume to delim\n+ '|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter\n+ '|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)' // (3) #***a, ***a can only be Left Delimiter\n+ '|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)' // (4) ***# can only be Left Delimiter\n+ '|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter\n\nconst emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm)\n .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm)\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\n// Pedantic: rule 3 requires whitespace before left delim; rule 6 allows punct before close (e.g. `:**bar`).\nconst emStrongRDelimAstPedanticCore =\n '^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n+ '|[^*]+(?=[^*])' // Consume to delim\n+ '|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter\n+ '|(?!\\\\*)[\\\\s](\\\\*+)(?=notPunctSpace)' // (3) ***a can only be Left Delimiter (whitespace required; not #***a)\n+ '|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)' // (4) ***# can only be Left Delimiter\n+ '|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter\n+ '|(?:(?!\\\\*)punct|notPunctSpace)(\\\\*+)(?!\\\\*)(?=notPunctSpace)'; // (6) a***a, #***a, and :** (e.g. **foo:**bar)\n\nconst emStrongRDelimAstPedantic = edit(emStrongRDelimAstPedanticCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\n// Normal: no rule 6 for _ (a___a cannot close as emphasis).\nconst emStrongRDelimUnd = edit(\n '^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n+ '|[^_]+(?=[^_])' // Consume to delim\n+ '|(?!_)punct(_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n+ '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter\n+ '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (3) #___a, ___a can only be Left Delimiter\n+ '|[\\\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter\n+ '|(?!_)punct(_+)(?!_)(?=punct)', 'gu') // (5) #___# can be either Left or Right Delimiter\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\n// Pedantic: same rule 3/6 adjustments as emStrongRDelimAstPedantic (e.g. `_foo:_bar`).\nconst emStrongRDelimUndPedanticCore =\n '^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n+ '|[^_]+(?=[^_])' // Consume to delim\n+ '|(?!_)punct(_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n+ '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter\n+ '|(?!_)[\\\\s](_+)(?=notPunctSpace)' // (3) ___a can only be Left Delimiter (whitespace required; not #___a)\n+ '|[\\\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter\n+ '|(?!_)punct(_+)(?!_)(?=punct)' // (5) #___# can be either Left or Right Delimiter\n+ '|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)'; // (6) a___a, #___a, and :__ (e.g. _foo:_bar)\n\nconst emStrongRDelimUndPedantic = edit(emStrongRDelimUndPedanticCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\n// Tilde left delimiter for strikethrough (similar to emStrongLDelim for asterisk)\nconst delLDelim = edit(/^~~?(?:((?!~)punct)|[^\\s~])/, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\n// Tilde delimiter patterns for strikethrough (similar to asterisk)\nconst delRDelimCore =\n '^[^~]+(?=[^~])' // Consume to delim\n+ '|(?!~)punct(~~?)(?=[\\\\s]|$)' // (1) #~~ can only be a Right Delimiter\n+ '|notPunctSpace(~~?)(?!~)(?=punctSpace|$)' // (2) a~~#, a~~ can only be a Right Delimiter\n+ '|(?!~)punctSpace(~~?)(?=notPunctSpace)' // (3) #~~a, ~~a can only be Left Delimiter\n+ '|[\\\\s](~~?)(?!~)(?=punct)' // (4) ~~# can only be Left Delimiter\n+ '|(?!~)punct(~~?)(?!~)(?=punct)' // (5) #~~# can be either Left or Right Delimiter\n+ '|notPunctSpace(~~?)(?=notPunctSpace)'; // (6) a~~a can be either Left or Right Delimiter\n\nconst delRDelim = edit(delRDelimCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst anyPunctuation = edit(/\\\\(punct)/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\n// `anyPunctuation` for the em/strong mask. A backslash is literal inside a code\n// span, so a code span (matched like `inline.code`), or a backtick run that\n// opens none, is matched whole and kept; only the escapes outside code spans\n// are masked.\nconst anyPunctuationOutsideCode = edit(/(`+)(?:[^`]|[^`][\\s\\S]*?[^`])\\1(?!`)|`+|\\\\(punct)/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst autolink = edit(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/)\n .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)\n .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)\n .getRegex();\n\nconst _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();\nconst tag = edit(\n '^comment'\n + '|^</[a-zA-Z][a-zA-Z0-9-]*\\\\s*>' // self-closing tag\n + '|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\\\s*/?>' // open tag\n + '|^<\\\\?[\\\\s\\\\S]*?\\\\?>' // processing instruction, e.g. <?php ?>\n + '|^<![a-zA-Z]+\\\\s[\\\\s\\\\S]*?>' // declaration, e.g. <!DOCTYPE html>\n + '|^<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>') // CDATA section\n .replace('comment', _inlineComment)\n .replace('attribute', /\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/)\n .getRegex();\n\n// One matched pair of brackets, holding no bracket of its own.\nconst _inlineLabelBrackets = /\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]/;\n// CommonMark lets the brackets in a link label nest to any depth, which a regex\n// cannot follow, so it stops at a fixed one. Two levels is what the spec suite\n// asks for: a third and a fourth flip no further example.\nconst _inlineLabel = edit(/(?:\\[(?:brackets|\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\\])|[^\\[\\]\\\\`])*?/)\n .replace('brackets', _inlineLabelBrackets)\n .getRegex();\n\nconst link = edit(/^!?\\[(label)\\]\\([ \\t\\n]*(href)(?:(?:[ \\t]+(?:\\n[ \\t]*)?|\\n[ \\t]*)(title))?[ \\t\\n]*\\)/)\n .replace('label', _inlineLabel)\n .replace('href', /<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]+|(?=\\))/)\n // Same as the definition title: the escaped character is not the closer.\n .replace('title', /\"(?:\\\\[\\s\\S]|[^\"\\\\])*\"|'(?:\\\\[\\s\\S]|[^'\\\\])*'|\\((?:\\\\[\\s\\S]|[^)\\\\])*\\)/)\n .getRegex();\n\nconst reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _inlineLabel)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _blockLabel)\n .getRegex();\n\n// `reflink` and `nolink` are anchored, so the tokenizer tries each of them at a\n// single position. `reflinkSearch` drops the anchors and runs with the global\n// flag, which makes every '[' in the source a start position. A label crosses a\n// bracket only by escaping it, and nothing caps how often it does, so a\n// candidate that can never match still scans to the end of the source and the\n// whole pass costs O(n^2).\n//\n// The labels below bound that scan. `_boundedInlineLabel` limits how many\n// escapes, code spans and nested brackets a link text may hold, leaving runs of\n// ordinary characters unbounded so link text of any length is still found.\n// `_boundedBlockLabel` limits the label itself to 999 items, which is every\n// label CommonMark allows: \"A link label can have at most 999 characters\n// inside the square brackets.\"\nconst _boundedBlockLabel = /(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\]){1,999}/;\nconst _boundedInlineLabel = edit(/(?:[^\\[\\]\\\\`]*(?:\\[(?:brackets|\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\\]))){0,999}?[^\\[\\]\\\\`]*?/)\n .replace('brackets', _inlineLabelBrackets)\n .getRegex();\n\nconst reflinkSearch = edit('reflink|nolink(?!\\\\()', 'g')\n .replace('reflink', edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _boundedInlineLabel)\n .replace('ref', _boundedBlockLabel)\n .getRegex())\n .replace('nolink', edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _boundedBlockLabel)\n .getRegex())\n .getRegex();\n\nconst _caseInsensitiveProtocol = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/;\nconst _extendedEmail = /[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\\w-])/;\nconst _extendedEmailProtocol = edit(/(?:mailto:email|xmpp:email(?:\\/[A-Za-z0-9@.]+)?)/)\n .replace(/email/g, _extendedEmail)\n .getRegex();\n\n/**\n * Normal Inline Grammar\n */\n\nconst inlineNormal = {\n _backpedal: noopTest, // only used for GFM url\n anyPunctuation,\n anyPunctuationOutsideCode,\n autolink,\n blockSkip,\n br,\n code: inlineCode,\n del: noopTest,\n delLDelim: noopTest,\n delRDelim: noopTest,\n emStrongLDelim,\n emStrongRDelimAst,\n emStrongRDelimUnd,\n escape,\n link,\n nolink,\n punctuation,\n reflink,\n reflinkSearch,\n tag,\n text: inlineText,\n url: noopTest,\n};\n\ntype InlineKeys = keyof typeof inlineNormal;\n\n/**\n * Pedantic Inline Grammar\n */\n\nconst inlinePedantic: Record<InlineKeys, RegExp> = {\n ...inlineNormal,\n emStrongLDelim: emStrongLDelimPedantic,\n emStrongRDelimAst: emStrongRDelimAstPedantic,\n emStrongRDelimUnd: emStrongRDelimUndPedantic,\n link: edit(/^!?\\[(label)\\]\\((.*?)\\)/)\n .replace('label', _inlineLabel)\n .getRegex(),\n reflink: edit(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/)\n .replace('label', _inlineLabel)\n .getRegex(),\n};\n\n/**\n * GFM Inline Grammar\n */\n\nconst inlineGfm: Record<InlineKeys, RegExp> = {\n ...inlineNormal,\n emStrongRDelimAst: emStrongRDelimAstGfm,\n emStrongLDelim: emStrongLDelimGfm,\n delLDelim,\n delRDelim,\n url: edit(/^emailProtocol|^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/)\n .replace('emailProtocol', _extendedEmailProtocol)\n .replace('protocol', _caseInsensitiveProtocol)\n .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\\w-])/)\n .getRegex(),\n _backpedal: /(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,\n del: /^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,\n text: edit(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*~_]|\\b_|protocol:\\/\\/|wwwStart|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-](?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@))))/)\n .replace('protocol', _caseInsensitiveProtocol)\n .replace(/emailProtocol/g, /(?:mailto|xmpp):/)\n // GFM: a www autolink starts only at the beginning of a line, after whitespace or after\n // `*`, `_`, `~` or `(`. Without lookbehind support, keep stopping at every `www.`.\n .replace('wwwStart', supportsLookbehind ? '(?<![^\\\\s*_~(])www\\\\.' : 'www\\\\.')\n .getRegex(),\n};\n\n/**\n * GFM + Line Breaks Inline Grammar\n */\n\nconst inlineBreaks: Record<InlineKeys, RegExp> = {\n ...inlineGfm,\n br: edit(br).replace('{2,}', '*').getRegex(),\n text: edit(inlineGfm.text)\n .replace('\\\\b_', '\\\\b_| {2,}\\\\n')\n .replace(/\\{2,\\}/g, '*')\n .getRegex(),\n};\n\n/**\n * exports\n */\n\nexport const block = {\n normal: blockNormal,\n gfm: blockGfm,\n pedantic: blockPedantic,\n};\n\nexport const inline = {\n normal: inlineNormal,\n gfm: inlineGfm,\n breaks: inlineBreaks,\n pedantic: inlinePedantic,\n};\n\nexport interface Rules {\n other: typeof other\n block: Record<BlockKeys, RegExp>\n inline: Record<InlineKeys, RegExp>\n}\n", "import { other } from './rules.ts';\n\n/**\n * Helpers\n */\nconst escapeReplacements: { [index: string]: string } = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n};\nconst getEscapeReplacement = (ch: string) => escapeReplacements[ch];\n\nexport function escapeHtmlEntities(html: string, encode?: boolean) {\n if (encode) {\n if (other.escapeTest.test(html)) {\n return html.replace(other.escapeReplace, getEscapeReplacement);\n }\n } else {\n if (other.escapeTestNoEncode.test(html)) {\n return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n\n return html;\n}\n\n/**\n * Numeric character references are recognized outside code and are equivalent to the\n * character they name. Values that are zero, out of range, or a surrogate become the\n * replacement character.\n */\nexport function decodeNumericCharacterReferences(text: string) {\n if (!other.numericCharacterReference.test(text)) {\n return text;\n }\n // A decoded character must not join its neighbours into a new reference,\n // so every `&` that is not already one is escaped here.\n return text.replace(other.numericCharacterReferenceOrAmpersand, (ref: string, dec?: string, hex?: string) => {\n if (dec === undefined && hex === undefined) {\n return '&';\n }\n const code = dec === undefined ? Number.parseInt(hex!, 16) : Number.parseInt(dec, 10);\n if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) {\n return '\uFFFD';\n }\n return code === 38 ? '&' : String.fromCodePoint(code);\n });\n}\n\nexport function cleanUrl(href: string) {\n try {\n href = encodeURI(href).replace(other.percentDecode, '%');\n } catch {\n return null;\n }\n return href;\n}\n\nexport function splitCells(tableRow: string, count?: number) {\n // ensure that every cell-delimiting pipe has a space\n // before it to distinguish it from an escaped pipe\n const row = tableRow.replace(other.findPipe, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === '\\\\') escaped = !escaped;\n if (escaped) {\n // odd number of slashes means | is escaped\n // so we leave it alone\n return '|';\n } else {\n // add space before unescaped |\n return ' |';\n }\n }),\n cells = row.split(other.splitPipe);\n let i = 0;\n\n // First/last cell in a row cannot be empty if it has no leading/trailing pipe\n if (!cells[0].trim()) {\n cells.shift();\n }\n if (cells.length > 0 && !cells.at(-1)?.trim()) {\n cells.pop();\n }\n\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n } else {\n while (cells.length < count) cells.push('');\n }\n }\n\n for (; i < cells.length; i++) {\n // leading or trailing whitespace is ignored per the gfm spec\n cells[i] = cells[i].trim().replace(other.slashPipe, '|');\n }\n return cells;\n}\n\n/**\n * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').\n * /c*$/ is vulnerable to REDOS.\n *\n * @param str\n * @param c\n * @param invert Remove suffix of non-c chars instead. Default falsey.\n */\nexport function rtrim(str: string, c: string, invert?: boolean) {\n const l = str.length;\n if (l === 0) {\n return '';\n }\n\n // Length of suffix matching the invert condition.\n let suffLen = 0;\n\n // Step left until we fail to match the invert condition.\n while (suffLen < l) {\n const currChar = str.charAt(l - suffLen - 1);\n if (currChar === c && !invert) {\n suffLen++;\n } else if (currChar !== c && invert) {\n suffLen++;\n } else {\n break;\n }\n }\n\n return str.slice(0, l - suffLen);\n}\n\nexport function trimTrailingBlankLines(str: string) {\n const lines = str.split('\\n');\n let end = lines.length - 1;\n while (end >= 0 && other.blankLine.test(lines[end])) {\n end--;\n }\n if (lines.length - end <= 2) {\n // we want to keep single trailing blank lines\n return str;\n }\n\n return lines.slice(0, end + 1).join('\\n');\n}\n\n/**\n * Normalizes a link label so definitions and references can be matched.\n * CommonMark asks for a Unicode case fold, which `toLowerCase()` does not\n * reach: `\u1E9E` lowercases to `\u00DF` and so never meets `SS`. Round-tripping\n * through upper case does, as in commonmark.js; the final `toLowerCase()`\n * keeps the folded label lower case, the form `def.tag` has always used.\n */\nexport function normalizeLabel(label: string) {\n // The spec also asks for leading and trailing spaces, tabs and line endings\n // to be stripped, and for internal runs of them to collapse to one space.\n // Doing it here keeps every call site in agreement: the definition and the\n // reference have to normalize to the same key.\n return label.trim().replace(other.multipleSpaceGlobal, ' ').toLowerCase().toUpperCase().toLowerCase();\n}\n\nexport function findClosingBracket(str: string, b: string) {\n // an opening bracket on its own is still unbalanced, so both have to be absent\n if (str.indexOf(b[0]) === -1 && str.indexOf(b[1]) === -1) {\n return -1;\n }\n\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '\\\\') {\n i++;\n } else if (str[i] === b[0]) {\n level++;\n } else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n if (level > 0) {\n return -2;\n }\n\n return -1;\n}\n\ninterface LastPossibleEmStrongCloserIndex {\n /** Last `*` run that can close emphasis or strong. `-1` if none. */\n '*': number;\n /** Last `_` run that can close emphasis or strong. `-1` if none. */\n _: number;\n}\n\n/**\n * Closer hints for one inline `maskedSrc`. Held only while that pass runs.\n */\ninterface EmStrongDelCloserHintFrame {\n maskedSrc: string;\n lastPossibleEmStrongCloserIndex: LastPossibleEmStrongCloserIndex;\n /** Last `~` run that can close strikethrough. `-1` if none. */\n lastPossibleDelCloserIndex: number;\n}\n\n/**\n * Hint stacks for inline passes currently running. Keyed by the tokenizer\n * instance so parses do not share frames. Nested `inlineTokens` calls push\n * a frame. The entry is removed when the outermost pass ends, so\n * `maskedSrc` is not retained once parsing returns (#4099).\n */\nconst emStrongDelCloserHintStacks = new WeakMap<object, EmStrongDelCloserHintFrame[]>();\n\n/**\n * Last indexes of `*` / `_` runs that can close emphasis or strong, and of\n * a `~` run that can close strikethrough.\n *\n * A run can close only when it is not preceded by ASCII whitespace or the\n * start of the string. The right-delim regexes accept a closer only in\n * groups 1, 2, 5, and 6, and each of those requires that predecessor. When\n * the opener's window has no such run, the regex scan cannot succeed.\n * Finding one only means \"keep looking\": CommonMark rules 9\u201310 and mid-run\n * openers are still applied in the loop (#4099).\n */\nfunction scanLastPossibleEmStrongDelClosers(src: string): EmStrongDelCloserHintFrame {\n const lastPossibleEmStrongCloserIndex: LastPossibleEmStrongCloserIndex = { '*': -1, _: -1 };\n let lastPossibleDelCloserIndex = -1;\n const len = src.length;\n for (let i = 0; i < len; i++) {\n const ch = src[i];\n if (ch !== '*' && ch !== '_' && ch !== '~') {\n continue;\n }\n // A leading run has no predecessor, same as one after a line break.\n const prev = i === 0 ? '\\n' : src[i - 1];\n let j = i + 1;\n while (j < len && src[j] === ch) {\n j++;\n }\n if (prev !== ' ' && prev !== '\\t' && prev !== '\\n' && prev !== '\\r' && prev !== '\\f') {\n if (ch === '~') {\n lastPossibleDelCloserIndex = i;\n } else {\n lastPossibleEmStrongCloserIndex[ch] = i;\n }\n }\n i = j - 1;\n }\n return {\n maskedSrc: src,\n lastPossibleEmStrongCloserIndex,\n lastPossibleDelCloserIndex,\n };\n}\n\n/**\n * Scan `maskedSrc` once for the last `*` / `_` run that can close emphasis\n * or strong and the last `~` run that can close strikethrough.\n * `endEmStrongDelCloserScan` drops this frame when the inline pass ends.\n */\nexport function beginEmStrongDelCloserScan(tokenizer: object, maskedSrc: string): void {\n const frame = scanLastPossibleEmStrongDelClosers(maskedSrc);\n const stack = emStrongDelCloserHintStacks.get(tokenizer);\n if (stack) {\n stack.push(frame);\n } else {\n emStrongDelCloserHintStacks.set(tokenizer, [frame]);\n }\n}\n\n/**\n * Drop the closer-hint frame for the inline pass that just finished.\n * Removing the last frame drops the tokenizer's `maskedSrc` reference.\n */\nexport function endEmStrongDelCloserScan(tokenizer: object): void {\n const stack = emStrongDelCloserHintStacks.get(tokenizer);\n if (!stack) {\n return;\n }\n stack.pop();\n if (stack.length === 0) {\n emStrongDelCloserHintStacks.delete(tokenizer);\n }\n}\n\n/**\n * Index in `maskedSrc` of the last `*` or `_` run that can close emphasis\n * or strong. Uses the active inline-pass scan when `maskedSrc` is that\n * pass's source; otherwise scans this string and discards the result.\n */\nexport function cachedLastPossibleEmStrongCloserIndex(tokenizer: object, maskedSrc: string, delim: '*' | '_'): number {\n const frame = emStrongDelCloserHintStacks.get(tokenizer)?.at(-1);\n if (frame && frame.maskedSrc === maskedSrc) {\n return frame.lastPossibleEmStrongCloserIndex[delim];\n }\n return scanLastPossibleEmStrongDelClosers(maskedSrc).lastPossibleEmStrongCloserIndex[delim];\n}\n\n/**\n * Index in `maskedSrc` of the last `~` run that can close strikethrough.\n * Uses the active inline-pass scan when `maskedSrc` is that pass's\n * source; otherwise scans this string and discards the result.\n */\nexport function cachedLastPossibleDelCloserIndex(tokenizer: object, maskedSrc: string): number {\n const frame = emStrongDelCloserHintStacks.get(tokenizer)?.at(-1);\n if (frame && frame.maskedSrc === maskedSrc) {\n return frame.lastPossibleDelCloserIndex;\n }\n return scanLastPossibleEmStrongDelClosers(maskedSrc).lastPossibleDelCloserIndex;\n}\n\nexport function expandTabs(line: string, indent = 0) {\n let col = indent;\n let expanded = '';\n for (const char of line) {\n if (char === '\\t') {\n const added = 4 - (col % 4);\n expanded += ' '.repeat(added);\n col += added;\n } else {\n expanded += char;\n col++;\n }\n }\n\n return expanded;\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n rtrim,\n splitCells,\n findClosingBracket,\n expandTabs,\n normalizeLabel,\n decodeNumericCharacterReferences,\n trimTrailingBlankLines,\n cachedLastPossibleEmStrongCloserIndex,\n cachedLastPossibleDelCloserIndex,\n} from './helpers.ts';\nimport type { Rules } from './rules.ts';\nimport type { _Lexer } from './Lexer.ts';\nimport type { Links, Tokens, Token } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\nfunction outputLink(cap: string[], link: Pick<Tokens.Link, 'href' | 'title'>, raw: string, lexer: _Lexer, rules: Rules): Tokens.Link | Tokens.Image | undefined {\n const href = link.href;\n const title = link.title || null;\n const text = cap[1].replace(rules.other.outputLinkReplace, '$1');\n const isImage = cap[0].charAt(0) === '!';\n\n const outerInLink = lexer.state.inLink;\n const outerLinkEmitted = lexer.state.linkEmitted;\n const outerInRawBlock = lexer.state.inRawBlock;\n lexer.state.inLink = true;\n lexer.state.linkEmitted = false;\n const tokens = lexer.inlineTokens(text);\n const textHasLink = lexer.state.linkEmitted;\n lexer.state.linkEmitted = outerLinkEmitted;\n lexer.state.inLink = outerInLink;\n\n if (!isImage) {\n // CommonMark: \"Links may not contain other links, at any level of nesting.\"\n // Bail so the caller falls through to text and the inner link is the one kept.\n // Images are exempt: their text is flattened into an alt attribute.\n if (textHasLink) {\n // these tokens are discarded, so undo the raw-block state they opened;\n // leaving it set would suppress escaping for the text that is re-scanned\n lexer.state.inRawBlock = outerInRawBlock;\n return;\n }\n lexer.state.linkEmitted = true;\n }\n\n return {\n type: isImage ? 'image' : 'link',\n raw,\n href,\n title,\n text,\n tokens,\n };\n}\n\nfunction indentCodeCompensation(raw: string, text: string, rules: Rules) {\n const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);\n\n if (matchIndentToCode === null) {\n return text;\n }\n\n const indentToCode = matchIndentToCode[1];\n\n return text\n .split('\\n')\n .map(node => {\n const matchIndentInNode = node.match(rules.other.beginningSpace);\n if (matchIndentInNode === null) {\n return node;\n }\n\n const [indentInNode] = matchIndentInNode;\n\n // Up to the fence's own indentation is removed from each line, so a line\n // indented less than the fence loses whatever indentation it has.\n return node.slice(Math.min(indentInNode.length, indentToCode.length));\n })\n .join('\\n');\n}\n\nfunction isLabelEndInsideToken(src: string, label: string, labelStart: number, rules: Rules) {\n if (!label.includes('<')) {\n return false;\n }\n\n for (let i = 0; i < label.length; i++) {\n if (label[i] === '\\\\') {\n i++;\n continue;\n }\n\n if (label[i] === '`') {\n const code = rules.inline.code.exec(label.slice(i));\n if (code) {\n i += code[0].length - 1;\n continue;\n }\n }\n\n if (label[i] !== '<') {\n continue;\n }\n\n const tokenSrc = src.slice(labelStart + i);\n const token = rules.inline.tag.exec(tokenSrc) || rules.inline.autolink.exec(tokenSrc);\n if (!token) {\n continue;\n }\n\n if (token[0].length > label.length - i) {\n return true;\n }\n i += token[0].length - 1;\n }\n return false;\n}\n\n/**\n * Tokenizer\n */\nexport class _Tokenizer<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n rules!: Rules; // set by the lexer\n lexer!: _Lexer<ParserOutput, RendererOutput>; // set by the lexer\n\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n }\n\n space(src: string): Tokens.Space | undefined {\n const cap = this.rules.block.newline.exec(src);\n if (cap && cap[0].length > 0) {\n return {\n type: 'space',\n raw: cap[0],\n };\n }\n }\n\n code(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const raw = this.options.pedantic\n ? cap[0]\n : trimTrailingBlankLines(cap[0]);\n const text = raw.replace(this.rules.other.codeRemoveIndent, '');\n return {\n type: 'code',\n raw,\n codeBlockStyle: 'indented',\n text,\n };\n }\n }\n\n fences(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || '', this.rules);\n\n return {\n type: 'code',\n raw,\n lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],\n text,\n };\n }\n }\n\n heading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n\n // remove trailing #s\n if (this.rules.other.endingHash.test(text)) {\n const trimmed = rtrim(text, '#');\n if (this.options.pedantic) {\n text = trimmed.trim();\n } else if (!trimmed || this.rules.other.endingSpaceTabChar.test(trimmed)) {\n // CommonMark requires a space or tab before trailing #s\n text = trimmed.trim();\n }\n }\n\n return {\n type: 'heading',\n raw: rtrim(cap[0], '\\n'),\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n hr(src: string): Tokens.Hr | undefined {\n const cap = this.rules.block.hr.exec(src);\n if (cap) {\n return {\n type: 'hr',\n raw: rtrim(cap[0], '\\n'),\n };\n }\n }\n\n blockquote(src: string): Tokens.Blockquote | undefined {\n const cap = this.rules.block.blockquote.exec(src);\n if (cap) {\n let lines = rtrim(cap[0], '\\n').split('\\n');\n let raw = '';\n let text = '';\n const tokens: Token[] = [];\n\n while (lines.length > 0) {\n let inBlockquote = false;\n const currentLines = [];\n\n let i;\n for (i = 0; i < lines.length; i++) {\n // get lines up to a continuation\n if (this.rules.other.blockquoteStart.test(lines[i])) {\n currentLines.push(lines[i]);\n inBlockquote = true;\n } else if (!inBlockquote) {\n currentLines.push(lines[i]);\n } else {\n break;\n }\n }\n lines = lines.slice(i);\n\n const currentRaw = currentLines.join('\\n');\n const currentText = currentRaw\n // a tab after the block quote marker runs to the next tab stop, and\n // the marker only consumes one space of it; the rest is content\n .replace(\n this.rules.other.blockquoteMarkerWhitespace,\n (_, marker: string, whitespace: string) => marker + expandTabs(whitespace, marker.length),\n )\n // precede setext continuation with 4 spaces so it isn't a setext\n .replace(this.rules.other.blockquoteSetextReplace, '\\n $1')\n .replace(this.rules.other.blockquoteSetextReplace2, '');\n raw = raw ? `${raw}\\n${currentRaw}` : currentRaw;\n text = text ? `${text}\\n${currentText}` : currentText;\n\n // parse blockquote lines as top level tokens\n // merge paragraphs if this is a continuation\n const top = this.lexer.state.top;\n this.lexer.state.top = true;\n this.lexer.blockTokens(currentText, tokens, true);\n this.lexer.state.top = top;\n\n // if there is no continuation then we are done\n if (lines.length === 0) {\n break;\n }\n\n const lastToken = tokens.at(-1);\n\n if (lastToken?.type === 'code' || lastToken?.type === 'heading' || lastToken?.type === 'hr' || lastToken?.type === 'html' || lastToken?.type === 'table') {\n // blockquote continuation cannot be preceded by a code block, heading, hr, html block or table\n break;\n } else if (lastToken?.type === 'blockquote') {\n // include continuation in nested blockquote\n const oldToken = lastToken as Tokens.Blockquote;\n // The continuation lines belong to the same nesting frame as the\n // nested blockquote, which already had one '>' marker stripped, so\n // strip one marker from them too. Otherwise a restated marker after a\n // lazy line is re-parsed as a spurious deeper blockquote.\n const continuation = lines.join('\\n');\n const newText = oldToken.raw + '\\n' + continuation.replace(this.rules.other.blockquoteSetextReplace2, '');\n const newToken = this.blockquote(newText)!;\n tokens[tokens.length - 1] = newToken;\n\n // Only include continuation lines the nested blockquote actually\n // consumed. Unconsumed trailing lines must stay out of `raw` so the\n // lexer can still tokenize them (paragraph, next blockquote, etc.).\n const leftover = newText.substring(newToken.raw.length).replace(/^\\n/, '');\n const leftoverCount = leftover ? leftover.split('\\n').length : 0;\n const consumed = leftoverCount ? lines.slice(0, -leftoverCount) : lines;\n if (consumed.length > 0) {\n raw = `${raw}\\n${consumed.join('\\n')}`;\n }\n text = text.substring(0, text.length - oldToken.text.length) + newToken.text;\n\n // A leftover line that starts with '>' still belongs to this\n // blockquote; any other leftover line ends it.\n lines = lines.slice(consumed.length);\n if (lines.length > 0 && this.rules.other.blockquoteStart.test(lines[0])) {\n continue;\n }\n break;\n } else if (lastToken?.type === 'list') {\n // include continuation in nested list\n const oldToken = lastToken as Tokens.List;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.list(newText)!;\n tokens[tokens.length - 1] = newToken;\n\n // The list raw has no '>' markers, so it cannot be cut out of `raw`.\n // Count the continuation lines the list took and add those lines instead.\n const consumedCount = newToken.raw.length > oldToken.raw.length\n ? newText.slice(oldToken.raw.length + 1, newToken.raw.length).split('\\n').length\n : 0;\n if (consumedCount > 0) {\n const consumed = lines.slice(0, consumedCount).join('\\n');\n raw = `${raw}\\n${consumed}`;\n text = `${text}\\n${consumed}`;\n }\n lines = lines.slice(consumedCount);\n continue;\n }\n }\n\n return {\n type: 'blockquote',\n raw,\n tokens,\n text,\n };\n }\n }\n\n list(src: string): Tokens.List | undefined {\n let cap = this.rules.block.list.exec(src);\n if (cap) {\n // src is only consumed from the front, so every raw below is a slice of\n // listSrc rather than a string built up line by line\n const listSrc = src;\n const taken = () => listSrc.length - src.length;\n let bull = cap[1].trim();\n const isordered = bull.length > 1;\n\n const list: Tokens.List = {\n type: 'list',\n raw: '',\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : '',\n loose: false,\n items: [],\n };\n\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n\n if (this.options.pedantic) {\n bull = isordered ? bull : '[*+-]';\n }\n\n // Get next list item\n const itemRegex = this.rules.other.listItemRegex(bull);\n let endsWithBlankLine = false;\n // Check if current bullet point can start a new List Item\n while (src) {\n let endEarly = false;\n let itemContents = '';\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n\n if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)\n break;\n }\n\n const itemStart = taken();\n src = src.substring(cap[0].length);\n\n const firstLine = cap[2].split('\\n', 1)[0];\n const bulletIndent = cap[1].length;\n let line = this.options.pedantic\n ? expandTabs(firstLine, bulletIndent)\n : firstLine.replace(this.rules.other.leadingSpaceTab, whitespace => expandTabs(whitespace, bulletIndent));\n let nextLine = src.split('\\n', 1)[0];\n let blankLine = !line.trim();\n\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n } else if (blankLine) {\n indent = bulletIndent + 1;\n } else {\n indent = line.search(this.rules.other.nonSpaceChar); // Find first non-space char\n indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent\n itemContents = line.slice(indent);\n indent += bulletIndent;\n }\n\n if (blankLine && this.rules.other.blankLine.test(nextLine)) { // Items begin with at most one blank line\n src = src.substring(nextLine.length + 1);\n endEarly = true;\n }\n\n if (!endEarly) {\n const nextBulletRegex = this.rules.other.nextBulletRegex(indent);\n const hrRegex = this.rules.other.hrRegex(indent);\n const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);\n const headingBeginRegex = this.options.pedantic\n ? this.rules.other.pedanticHeadingBeginRegex(indent)\n : this.rules.other.headingBeginRegex(indent);\n const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);\n const blockquoteBeginRegex = this.rules.other.blockquoteBeginRegex(indent);\n\n // Check if following lines should be included in List Item\n while (src) {\n const rawLine = src.split('\\n', 1)[0];\n let nextLineWithoutTabs;\n nextLine = rawLine;\n\n // Re-align to follow commonmark nesting rules\n if (this.options.pedantic) {\n nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' ');\n nextLineWithoutTabs = nextLine;\n } else {\n nextLineWithoutTabs = nextLine.replace(this.rules.other.leadingSpaceTab, whitespace => expandTabs(whitespace));\n }\n\n // End list item if found code fences\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new heading\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of html block\n if (htmlBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of blockquote\n if (blockquoteBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new bullet\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n\n // Horizontal rule found\n if (hrRegex.test(nextLine)) {\n break;\n }\n\n if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible\n itemContents += '\\n' + nextLineWithoutTabs.slice(indent);\n } else {\n // not enough indentation\n if (blankLine) {\n break;\n }\n\n // paragraph continuation unless last line was a different block level element\n if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 4) { // indented code block\n break;\n }\n if (fencesBeginRegex.test(line)) {\n break;\n }\n if (headingBeginRegex.test(line)) {\n break;\n }\n if (htmlBeginRegex.test(line)) {\n break;\n }\n if (hrRegex.test(line)) {\n break;\n }\n\n // A lazy continuation can look like a setext underline after\n // list indentation is removed. Keep it in the paragraph.\n const setextContinuation = !this.options.pedantic\n && /^ {0,3}(?:=+|-+) *$/.test(nextLine)\n && this.rules.block.lheading.test(`${line}\\n${nextLine}`);\n const continuation = setextContinuation\n ? ` ${nextLineWithoutTabs.replace(/^ {0,3}/, '')}`\n : nextLine;\n itemContents += '\\n' + continuation;\n }\n\n blankLine = !nextLine.trim();\n\n src = src.substring(rawLine.length + 1);\n line = nextLineWithoutTabs.slice(indent);\n }\n }\n\n // The loops above appended a '\\n' the source may not have had. It could\n // only land on the item that exhausts src, whose raw is trimmed below,\n // and after which nothing reads endsWithBlankLine\n const raw = listSrc.slice(itemStart, taken());\n\n if (!list.loose) {\n // If the previous item ended with a blank line, the list is loose\n if (endsWithBlankLine) {\n list.loose = true;\n } else if (this.rules.other.doubleBlankLine.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n\n list.items.push({\n type: 'list_item',\n raw,\n task: !!this.options.gfm && this.rules.other.listIsTask.test(itemContents),\n loose: false,\n text: itemContents,\n tokens: [],\n });\n }\n\n // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic\n const lastItem = list.items.at(-1);\n if (lastItem) {\n lastItem.raw = lastItem.raw.trimEnd();\n lastItem.text = lastItem.text.trimEnd();\n } else {\n // not a list since there were no items\n return;\n }\n list.raw = listSrc.slice(0, taken()).trimEnd();\n\n // Item child tokens handled here at end because we needed to have the final item to trim it first\n // First pass: tokenize items and finalize list.loose from spacers before placing checkboxes\n for (const item of list.items) {\n this.lexer.state.top = false;\n item.tokens = this.lexer.blockTokens(item.text, []);\n\n if (!list.loose) {\n // Check if list should be loose\n const spacers = item.tokens.filter(t => t.type === 'space');\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw));\n\n list.loose = hasMultipleLineBreaks;\n }\n }\n\n // Second pass: place task checkboxes using the final list.loose\n for (const item of list.items) {\n const itemToken = item.tokens[0];\n if (item.task && (itemToken?.type === 'text' || itemToken?.type === 'paragraph')) {\n // Remove checkbox markdown from item tokens\n item.text = item.text.replace(this.rules.other.listReplaceTask, '');\n itemToken.raw = itemToken.raw.replace(this.rules.other.listReplaceTask, '');\n itemToken.text = itemToken.text.replace(this.rules.other.listReplaceTask, '');\n for (let i = this.lexer.inlineQueue.length - 1; i >= 0; i--) {\n if (this.rules.other.listIsTask.test(this.lexer.inlineQueue[i].src)) {\n this.lexer.inlineQueue[i].src = this.lexer.inlineQueue[i].src.replace(this.rules.other.listReplaceTask, '');\n break;\n }\n }\n\n const taskRaw = this.rules.other.listTaskCheckbox.exec(item.raw);\n if (taskRaw) {\n const checkboxToken: Tokens.Checkbox = {\n type: 'checkbox',\n raw: taskRaw[0] + ' ',\n checked: taskRaw[0] !== '[ ]',\n };\n item.checked = checkboxToken.checked;\n if (list.loose) {\n if (item.tokens[0] && ['paragraph', 'text'].includes(item.tokens[0].type) && 'tokens' in item.tokens[0] && item.tokens[0].tokens) {\n item.tokens[0].raw = checkboxToken.raw + item.tokens[0].raw;\n item.tokens[0].text = checkboxToken.raw + item.tokens[0].text;\n item.tokens[0].tokens.unshift(checkboxToken);\n } else {\n item.tokens.unshift({\n type: 'paragraph',\n raw: checkboxToken.raw,\n text: checkboxToken.raw,\n tokens: [checkboxToken],\n });\n }\n } else {\n item.tokens.unshift(checkboxToken);\n }\n }\n } else if (item.task) {\n item.task = false;\n }\n }\n\n // Set all items to loose if list is loose\n if (list.loose) {\n for (const item of list.items) {\n item.loose = true;\n for (const token of item.tokens) {\n if (token.type === 'text') {\n token.type = 'paragraph';\n }\n }\n }\n }\n\n return list;\n }\n }\n\n html(src: string): Tokens.HTML | undefined {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const raw = trimTrailingBlankLines(cap[0]);\n const token: Tokens.HTML = {\n type: 'html',\n block: true,\n raw,\n pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',\n text: raw,\n };\n return token;\n }\n }\n\n def(src: string): Tokens.Def | undefined {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n // outside angle brackets a link destination holds only balanced parentheses\n if (!this.rules.other.startAngleBracket.test(cap[2]) && findClosingBracket(cap[2], '()') !== -1) {\n return;\n }\n\n const tag = normalizeLabel(cap[1]);\n const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';\n const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];\n return {\n type: 'def',\n tag,\n raw: rtrim(cap[0], '\\n'),\n href,\n title,\n };\n }\n }\n\n table(src: string): Tokens.Table | undefined {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n\n if (!this.rules.other.tableDelimiter.test(cap[2])) {\n // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading\n return;\n }\n\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|');\n const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\\n') : [];\n\n const item: Tokens.Table = {\n type: 'table',\n raw: rtrim(cap[0], '\\n'),\n header: [],\n align: [],\n rows: [],\n };\n\n if (headers.length !== aligns.length) {\n // header and align columns must be equal, rows can be different.\n return;\n }\n\n for (const align of aligns) {\n if (this.rules.other.tableAlignRight.test(align)) {\n item.align.push('right');\n } else if (this.rules.other.tableAlignCenter.test(align)) {\n item.align.push('center');\n } else if (this.rules.other.tableAlignLeft.test(align)) {\n item.align.push('left');\n } else {\n item.align.push(null);\n }\n }\n\n for (let i = 0; i < headers.length; i++) {\n item.header.push({\n text: headers[i],\n tokens: this.lexer.inline(headers[i]),\n header: true,\n align: item.align[i],\n });\n }\n\n for (const row of rows) {\n item.rows.push(splitCells(row, item.header.length).map((cell, i) => {\n return {\n text: cell,\n tokens: this.lexer.inline(cell),\n header: false,\n align: item.align[i],\n };\n }));\n }\n\n return item;\n }\n\n lheading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n const text = cap[1].trim();\n return {\n type: 'heading',\n raw: rtrim(cap[0], '\\n'),\n depth: cap[2].charAt(0) === '=' ? 1 : 2,\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n paragraph(src: string): Tokens.Paragraph | undefined {\n const cap = this.rules.block.paragraph.exec(src);\n if (cap) {\n const text = cap[1].charAt(cap[1].length - 1) === '\\n'\n ? cap[1].slice(0, -1)\n : cap[1];\n return {\n type: 'paragraph',\n raw: cap[0],\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n text(src: string): Tokens.Text | undefined {\n const cap = this.rules.block.text.exec(src);\n if (cap) {\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n tokens: this.lexer.inline(cap[0]),\n };\n }\n }\n\n escape(src: string): Tokens.Escape | undefined {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: 'escape',\n raw: cap[0],\n text: cap[1],\n };\n }\n }\n\n tag(src: string): Tokens.Tag | undefined {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {\n this.lexer.state.inLink = true;\n } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\n\n return {\n type: 'html',\n raw: cap[0],\n inLink: this.lexer.state.inLink,\n inRawBlock: this.lexer.state.inRawBlock,\n block: false,\n text: cap[0],\n };\n }\n }\n\n link(src: string): Tokens.Link | Tokens.Image | undefined {\n // The link regex backtracks quadratically over unterminated-link inputs\n // like '[a](b'.repeat(n): at every '[' its greedy unquoted-href run\n // re-partitions the whole remainder while hunting for a ')' that never\n // comes. inlineTokens anchors one paren scan per run in\n // state.linkParenPossible; when it is false the regex cannot match, so\n // bail out before running it.\n if (this.lexer.state.linkParenPossible === false) {\n return undefined;\n }\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const labelStart = cap[0].charAt(0) === '!' ? 2 : 1;\n if (!this.options.pedantic && isLabelEndInsideToken(src, cap[1], labelStart, this.rules)) {\n return;\n }\n\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {\n // commonmark requires matching angle brackets\n if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n return;\n }\n\n // ending angle bracket cannot be escaped\n const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\\\');\n if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {\n return;\n }\n } else {\n // find closing parenthesis\n const lastParenIndex = findClosingBracket(cap[2], '()');\n if (lastParenIndex === -2) {\n // more open parens than closed\n return;\n }\n\n if (lastParenIndex > -1) {\n const start = cap[0].indexOf('!') === 0 ? 5 : 4;\n const linkLen = start + cap[1].length + lastParenIndex;\n cap[2] = cap[2].substring(0, lastParenIndex);\n cap[0] = cap[0].substring(0, linkLen).trim();\n cap[3] = '';\n }\n }\n // The ')' that ends the match is the link closer only when it is not\n // escaped. `[foo](/url\\)` has no closer; that paren is destination text.\n const unescaped = rtrim(cap[0].slice(0, -1), '\\\\');\n if ((cap[0].length - unescaped.length) % 2 === 0) {\n return;\n }\n let href = cap[2];\n let title = '';\n if (this.options.pedantic) {\n // split pedantic href and title\n const link = this.rules.other.pedanticHrefTitle.exec(href);\n\n if (link) {\n href = link[1];\n title = link[3];\n }\n } else {\n title = cap[3] ? cap[3].slice(1, -1) : '';\n }\n\n href = href.trim();\n if (this.rules.other.startAngleBracket.test(href)) {\n if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n // pedantic allows starting angle bracket without ending angle bracket\n href = href.slice(1);\n } else {\n href = href.slice(1, -1);\n }\n }\n return outputLink(cap, {\n href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,\n title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title,\n }, cap[0], this.lexer, this.rules);\n }\n }\n\n reflink(src: string, links: Links): Tokens.Link | Tokens.Image | Tokens.Text | undefined {\n let cap;\n if ((cap = this.rules.inline.reflink.exec(src))\n || (cap = this.rules.inline.nolink.exec(src))) {\n const labelStart = cap[0].charAt(0) === '!' ? 2 : 1;\n if (!this.options.pedantic && isLabelEndInsideToken(src, cap[1], labelStart, this.rules)) {\n return;\n }\n\n const link = links[normalizeLabel(cap[2] || cap[1])];\n if (!link) {\n const text = cap[0].charAt(0);\n return {\n type: 'text',\n raw: text,\n text,\n };\n }\n return outputLink(cap, link, cap[0], this.lexer, this.rules);\n }\n }\n\n emStrong(src: string, maskedSrc: string, prevChar = ''): Tokens.Em | Tokens.Strong | undefined {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match) return;\n if (!match[1] && !match[2] && !match[3] && !match[4]) return;\n\n const delimChar = match[0][0];\n // A mid-run opener (for example the second star of an unmatched `**`) must\n // only pair with a delimiter that can only close, otherwise it steals the\n // opener of a later span (`**a*b*c` must be `**a<em>b</em>c`).\n const midRun = prevChar === delimChar;\n\n // The start of this delimiter run may already be behind src, either taken\n // as text after the whole run failed to match or used to close an earlier\n // span. Flanking and rules 9-10 are about the whole run, so find its start.\n // Pedantic follows markdown.pl, which has no such rules.\n const srcStart = maskedSrc.length - src.length;\n let runStart = srcStart;\n while (!this.options.pedantic && runStart > 0 && maskedSrc[runStart - 1] === delimChar) {\n runStart--;\n }\n const runPrevChar = [...maskedSrc.slice(Math.max(0, runStart - 2), runStart)].at(-1) ?? '';\n // The other delimiter character counts as punctuation here (`_**a*`)\n const runPrevPunct = runPrevChar === '*' || runPrevChar === '_' || !!this.rules.inline.punctuation.exec(runPrevChar);\n if (runStart < srcStart) {\n prevChar = runPrevChar;\n }\n const prevPunct = runStart < srcStart ? runPrevPunct : !!this.rules.inline.punctuation.exec(prevChar);\n\n // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n if (match[4] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) return;\n\n const nextChar = match[1] || match[3] || '';\n\n if (!nextChar || !prevChar || prevPunct) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;\n\n // Rules 9-10 count the whole run, and also apply when the opener could\n // close as well (`a*b**`, where `*` is both left- and right-flanking).\n const runLength = srcStart - runStart + lLength;\n const openerCanClose = !this.options.pedantic && !!runPrevChar.trim()\n && (!!nextChar || (delimChar === '*' && !runPrevPunct));\n if (delimChar !== '*' && delimChar !== '_') return;\n const endReg = delimChar === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n const lastPossibleEmStrongCloserIndex = cachedLastPossibleEmStrongCloserIndex(this, maskedSrc, delimChar);\n const emStrongCloserWindowStart = maskedSrc.length - src.length + lLength;\n if (lastPossibleEmStrongCloserIndex < emStrongCloserWindowStart) return;\n // Clip maskedSrc to same section of string as src (move to lexer?)\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n const lastPossibleEmStrongCloserIndexInWindow = lastPossibleEmStrongCloserIndex - emStrongCloserWindowStart;\n endReg.lastIndex = 0;\n\n while ((match = endReg.exec(maskedSrc)) !== null) {\n if (match.index > lastPossibleEmStrongCloserIndexInWindow) break;\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n\n if (!rDelim) continue; // skip single * in __abc*abc__\n\n rLength = [...rDelim].length;\n\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n } else if (match[5] || match[6] || openerCanClose) { // either Left or Right Delim\n if (midRun && (match[5] || match[6])) {\n // A mid-run opener cannot close against an ambiguous delimiter that\n // can also open; that delimiter opens its own emphasis span instead.\n break;\n }\n if (runLength % 3 && !((runLength + rLength) % 3)) {\n midDelimTotal += rLength;\n continue; // CommonMark Emphasis Rules 9-10\n }\n }\n\n delimTotal -= rLength;\n\n if (delimTotal > 0) continue; // Haven't found enough closing delimiters\n\n // Remove extra characters. *a*** -> *a*\n rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);\n // char length can be >1 for unicode characters;\n const lastCharLength = [...match[0]][0].length;\n const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);\n\n // Create `em` if smallest delimiter has odd char count. *a***\n if (Math.min(lLength, rLength) % 2) {\n const text = raw.slice(1, -1);\n return {\n type: 'em',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n\n // Create 'strong' if smallest delimiter has even char count. **a***\n const text = raw.slice(2, -2);\n return {\n type: 'strong',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n }\n }\n\n codespan(src: string): Tokens.Codespan | undefined {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' ');\n const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);\n const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n return {\n type: 'codespan',\n raw: cap[0],\n text,\n };\n }\n }\n\n br(src: string): Tokens.Br | undefined {\n const cap = this.rules.inline.br.exec(src);\n if (cap) {\n return {\n type: 'br',\n raw: cap[0],\n };\n }\n }\n\n del(src: string, maskedSrc: string, prevChar = ''): Tokens.Del | undefined {\n let match = this.rules.inline.delLDelim.exec(src);\n if (!match) return;\n\n const nextChar = match[1] || '';\n\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength;\n\n const endReg = this.rules.inline.delRDelim;\n const lastPossibleDelCloserIndex = cachedLastPossibleDelCloserIndex(this, maskedSrc);\n const delCloserWindowStart = maskedSrc.length - src.length + lLength;\n if (lastPossibleDelCloserIndex < delCloserWindowStart) return;\n // Clip maskedSrc to same section of string as src\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n const lastPossibleDelCloserIndexInWindow = lastPossibleDelCloserIndex - delCloserWindowStart;\n endReg.lastIndex = 0;\n\n while ((match = endReg.exec(maskedSrc)) !== null) {\n if (match.index > lastPossibleDelCloserIndexInWindow) break;\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n\n if (!rDelim) continue;\n\n rLength = [...rDelim].length;\n\n if (rLength !== lLength) continue;\n\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n }\n\n delimTotal -= rLength;\n\n if (delimTotal > 0) continue; // Haven't found enough closing delimiters\n\n // Remove extra characters\n rLength = Math.min(rLength, rLength + delimTotal);\n // char length can be >1 for unicode characters\n const lastCharLength = [...match[0]][0].length;\n const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);\n\n // Create del token - only single ~ or double ~~ supported\n const text = raw.slice(lLength, -lLength);\n return {\n type: 'del',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n }\n }\n\n autolink(src: string): Tokens.Link | undefined {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[1];\n href = 'mailto:' + text;\n } else {\n text = cap[1];\n href = text;\n }\n\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n autolink: true,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n\n url(src: string): Tokens.Link | undefined {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[0];\n href = 'mailto:' + text;\n } else {\n // do extended autolink path validation\n let prevCapZero;\n do {\n prevCapZero = cap[0];\n cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';\n } while (prevCapZero !== cap[0]);\n text = cap[0];\n if (cap[1] === 'www.') {\n href = 'http://' + cap[0];\n } else {\n href = cap[0];\n }\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n autolink: true,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n\n inlineText(src: string): Tokens.Text | undefined {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n const escaped = this.lexer.state.inRawBlock;\n return {\n type: 'text',\n raw: cap[0],\n // raw HTML keeps whatever it was written with, everywhere else a numeric\n // character reference stands for the character itself\n text: escaped ? cap[0] : decodeNumericCharacterReferences(cap[0]),\n escaped,\n };\n }\n }\n}\n", "import { _Tokenizer } from './Tokenizer.ts';\nimport { _defaults } from './defaults.ts';\nimport { other, block, inline } from './rules.ts';\nimport { beginEmStrongDelCloserScan, endEmStrongDelCloserScan, normalizeLabel } from './helpers.ts';\nimport type { Token, TokensList, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Block Lexer\n */\nexport class _Lexer<ParserOutput = string, RendererOutput = string> {\n tokens: TokensList;\n options: MarkedOptions<ParserOutput, RendererOutput>;\n state: {\n inLink: boolean;\n inRawBlock: boolean;\n /** a link was produced in the inline run currently being scanned */\n linkEmitted: boolean;\n /**\n * false while scanning an inline run whose source contains no ')',\n * letting Tokenizer.link bail out before its quadratic backtracking.\n * Anchored once per run by inlineTokens.\n */\n linkParenPossible: boolean;\n top: boolean;\n };\n\n public inlineQueue: { src: string, tokens: Token[] }[];\n\n private tokenizer: _Tokenizer<ParserOutput, RendererOutput>;\n\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n // TokenList cannot be created in one go\n this.tokens = [] as unknown as TokensList;\n this.tokens.links = Object.create(null);\n this.options = options || _defaults;\n this.options.tokenizer = this.options.tokenizer || new _Tokenizer<ParserOutput, RendererOutput>();\n this.tokenizer = this.options.tokenizer;\n this.tokenizer.options = this.options;\n this.tokenizer.lexer = this;\n this.inlineQueue = [];\n this.state = {\n inLink: false,\n inRawBlock: false,\n linkEmitted: false,\n linkParenPossible: true,\n top: true,\n };\n\n const rules = {\n other,\n block: block.normal,\n inline: inline.normal,\n };\n\n if (this.options.pedantic) {\n rules.block = block.pedantic;\n rules.inline = inline.pedantic;\n } else if (this.options.gfm) {\n rules.block = block.gfm;\n if (this.options.breaks) {\n rules.inline = inline.breaks;\n } else {\n rules.inline = inline.gfm;\n }\n }\n this.tokenizer.rules = rules;\n }\n\n /**\n * Expose Rules\n */\n static get rules() {\n return {\n block,\n inline,\n };\n }\n\n /**\n * Static Lex Method\n */\n static lex<ParserOutput = string, RendererOutput = string>(src: string, options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const lexer = new _Lexer<ParserOutput, RendererOutput>(options);\n return lexer.lex(src);\n }\n\n /**\n * Static Lex Inline Method\n */\n static lexInline<ParserOutput = string, RendererOutput = string>(src: string, options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const lexer = new _Lexer<ParserOutput, RendererOutput>(options);\n return lexer.inlineTokens(src);\n }\n\n /**\n * Preprocessing\n */\n lex(src: string) {\n src = src.replace(other.carriageReturn, '\\n');\n\n this.blockTokens(src, this.tokens);\n\n for (let i = 0; i < this.inlineQueue.length; i++) {\n const next = this.inlineQueue[i];\n // an inline <pre>, <code>, <kbd> or <script> left open ends with the block\n // holding it; carried over, it would stop every later block's text from\n // being escaped\n this.state.inRawBlock = false;\n this.inlineTokens(next.src, next.tokens);\n }\n this.inlineQueue = [];\n\n return this.tokens;\n }\n\n /**\n * Lexing\n */\n blockTokens(src: string, tokens?: Token[], lastParagraphClipped?: boolean): Token[];\n blockTokens(src: string, tokens?: TokensList, lastParagraphClipped?: boolean): TokensList;\n blockTokens(src: string, tokens: Token[] = [], lastParagraphClipped = false) {\n this.tokenizer.lexer = this;\n if (this.options.pedantic) {\n src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, '');\n }\n\n let srcLength = Infinity;\n while (src) {\n if (src.length < srcLength) {\n srcLength = src.length;\n } else {\n this.infiniteLoopError(src.charCodeAt(0));\n break;\n }\n\n let token: Tokens.Generic | undefined;\n\n if (this.options.extensions?.block?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n\n // newline\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.raw.length === 1 && lastToken !== undefined) {\n // if there's a single \\n as a spacer, it's terminating the last line,\n // so move it there so that we don't get unnecessary paragraph tags\n lastToken.raw += '\\n';\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // code\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n // An indented code block cannot interrupt a paragraph.\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // fences\n if (token = this.tokenizer.fences(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // heading\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // hr\n if (token = this.tokenizer.hr(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // blockquote\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // list\n if (token = this.tokenizer.list(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // html\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // def\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.raw;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n // The first definition of a label wins, but a later one still consumes its text\n if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title,\n };\n }\n tokens.push(token);\n }\n continue;\n }\n\n // table (gfm)\n if (token = this.tokenizer.table(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // lheading\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // top-level paragraph\n // prevent paragraph consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startBlock) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startBlock.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {\n const lastToken = tokens.at(-1);\n if (lastParagraphClipped && lastToken?.type === 'paragraph') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n lastParagraphClipped = cutSrc.length !== src.length;\n src = src.substring(token.raw.length);\n continue;\n }\n\n // text\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n if (src) {\n this.infiniteLoopError(src.charCodeAt(0));\n break;\n }\n }\n\n this.state.top = true;\n return tokens;\n }\n\n inline(src: string, tokens: Token[] = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n\n /**\n * Does this link text hold a link already? An image does not count: an image\n * may hold a link, a link may not.\n */\n private linkInText(text: string): boolean {\n if (!text.includes('[')) {\n return false;\n }\n\n const linkRule = this.tokenizer.rules.inline.link;\n for (const match of text.matchAll(this.tokenizer.rules.inline.blockSkip)) {\n // blockSkip also matches code spans and html, and the `!` of an image is\n // left out of the match, so read the character before it.\n if (linkRule.test(match[0]) && text.charAt(match.index - 1) !== '!') {\n return true;\n }\n }\n\n for (const match of text.matchAll(this.tokenizer.rules.inline.reflinkSearch)) {\n const match0 = match[0];\n const refStart = match0.lastIndexOf('[');\n if (match0.charAt(0) === '!' || !Object.hasOwn(this.tokens.links, normalizeLabel(match0.slice(refStart + 1, -1)))) {\n continue;\n }\n // a candidate holding a link is not a link either, so it does not count\n if (refStart > 1 && this.linkInText(match0.slice(1, refStart - 1))) {\n continue;\n }\n return true;\n }\n\n return false;\n }\n\n /**\n * Lexing/Compiling\n */\n inlineTokens(src: string, tokens: Token[] = []): Token[] {\n this.tokenizer.lexer = this;\n // One paren scan per inline run, shared with Tokenizer.link: without a\n // ')' ahead the link regex cannot match, and skipping it avoids its\n // quadratic backtracking over unterminated-link inputs like\n // `'[a](b'.repeat(n)`. A nested run receives a substring of the outer\n // run, so if the outer had no ')' neither does this substring \u2014 skip\n // the scan in that case.\n const prevLinkParenPossible = this.state.linkParenPossible;\n this.state.linkParenPossible = prevLinkParenPossible && src.includes(')');\n try {\n return this.#inlineTokensInner(src, tokens);\n } finally {\n // A nested run (e.g. a link label) anchored on its own substring;\n // restore the outer run's flag for the rest of its loop.\n this.state.linkParenPossible = prevLinkParenPossible;\n }\n }\n\n #inlineTokensInner(src: string, tokens: Token[]): Token[] {\n // The masked source is only read by emStrong and del, which need a *, _ or\n // ~ to start. Skip building it for a run without one, unless a custom\n // tokenizer or an emStrongMask hook may read it.\n const maskedSrc = src.includes('*') || src.includes('_') || src.includes('~')\n || this.options.hooks?.emStrongMask\n || this.tokenizer.emStrong !== _Tokenizer.prototype.emStrong\n || this.tokenizer.del !== _Tokenizer.prototype.del\n ? this.#maskSrc(src)\n : src;\n\n // One scan of this maskedSrc for the last emphasis, strong, and\n // strikethrough closers, shared by every opener in the pass. Popped\n // when the pass ends so the source is not retained (#4099).\n beginEmStrongDelCloserScan(this.tokenizer, maskedSrc);\n try {\n return this.#tokenizeInlines(src, maskedSrc, tokens);\n } finally {\n endEmStrongDelCloserScan(this.tokenizer);\n }\n }\n\n #tokenizeInlines(src: string, maskedSrc: string, tokens: Token[]): Token[] {\n let keepPrevChar = false;\n let prevChar = '';\n let srcLength = Infinity;\n while (src) {\n if (src.length < srcLength) {\n srcLength = src.length;\n } else {\n this.infiniteLoopError(src.charCodeAt(0));\n break;\n }\n\n if (!keepPrevChar) {\n prevChar = '';\n }\n keepPrevChar = false;\n\n let token: Tokens.Generic | undefined;\n\n // extensions\n if (this.options.extensions?.inline?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n\n // escape\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // tag\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // link\n if (token = this.tokenizer.link(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // reflink, nolink\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.type === 'text' && lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // em & strong\n if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // code\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // br\n if (token = this.tokenizer.br(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // del (gfm)\n if (token = this.tokenizer.del(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // autolink\n if (token = this.tokenizer.autolink(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // url (gfm)\n if (!this.state.inLink && (token = this.tokenizer.url(src))) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // text\n // prevent inlineText consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startInline) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startInline.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (token = this.tokenizer.inlineText(cutSrc)) {\n src = src.substring(token.raw.length);\n if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started\n prevChar = token.raw.slice(-1);\n }\n keepPrevChar = true;\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n if (src) {\n this.infiniteLoopError(src.charCodeAt(0));\n break;\n }\n }\n\n return tokens;\n }\n\n /**\n * Mask links, code, html and escapes so emStrong and del do not see their\n * delimiters inside them.\n */\n #maskSrc(src: string): string {\n // String with links masked to avoid interference with em and strong\n let maskedSrc = src;\n\n // Mask out reflinks\n if (this.tokens.links && src.includes('[')) {\n const reflinkSearch = this.tokenizer.rules.inline.reflinkSearch;\n const maskReflink = (match0: string): string => {\n const refStart = match0.lastIndexOf('[');\n if (!Object.hasOwn(this.tokens.links, normalizeLabel(match0.slice(refStart + 1, -1)))) {\n return match0;\n }\n // CommonMark: \"Links may not contain other links, at any level of\n // nesting.\" A candidate whose text already holds one never becomes a\n // link, so flattening the whole span would hide the emphasis that\n // does still apply inside it. Mask the links it holds instead.\n // Images are exempt: their text is flattened into an alt attribute.\n if (refStart > 1 && match0.charAt(0) !== '!') {\n const text = match0.slice(1, refStart - 1);\n if (this.linkInText(text)) {\n return '[' + text.replace(reflinkSearch, maskReflink)\n + '][' + 'a'.repeat(match0.length - refStart - 2) + ']';\n }\n }\n return '[' + 'a'.repeat(match0.length - 2) + ']';\n };\n maskedSrc = maskedSrc.replace(reflinkSearch, maskReflink);\n }\n\n // Mask out escaped characters.\n // Every mask must keep the length it replaces: emStrong and del line\n // maskedSrc up with src by slicing from the end. `anyPunctuation` matches\n // unicode punctuation, so an escaped astral character is 3 code units.\n // A backslash inside a code span is literal, not an escape. Mask the\n // backticks inside the span instead, so blockSkip still skips all of it.\n maskedSrc = maskedSrc.replace(this.tokenizer.rules.inline.anyPunctuationOutsideCode, (match0, code, punct) => {\n if (punct) {\n return '+'.repeat(match0.length);\n }\n if (code) {\n return code + match0.slice(code.length, -code.length).replace(/`/g, '+') + code;\n }\n return match0;\n });\n\n // Mask out other blocks\n maskedSrc = maskedSrc.replace(this.tokenizer.rules.inline.blockSkip, (match0, _link, context) => {\n const offset = context ? context.length : 0;\n return match0.slice(0, offset) + '[' + 'a'.repeat(match0.length - offset - 2) + ']';\n });\n\n // Mask out blocks from extensions\n maskedSrc = this.options.hooks?.emStrongMask?.call({ lexer: this }, maskedSrc) ?? maskedSrc;\n\n return maskedSrc;\n }\n\n private infiniteLoopError(byte: number) {\n const errMsg = 'Infinite loop on byte: ' + byte;\n if (this.options.silent) {\n console.error(errMsg);\n } else {\n throw new Error(errMsg);\n }\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n cleanUrl,\n escapeHtmlEntities,\n} from './helpers.ts';\nimport { other } from './rules.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Tokens } from './Tokens.ts';\nimport type { _Parser } from './Parser.ts';\n\n/**\n * Renderer\n */\nexport class _Renderer<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n parser!: _Parser<ParserOutput, RendererOutput>; // set by the parser\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n }\n\n space(token: Tokens.Space): RendererOutput {\n return '' as RendererOutput;\n }\n\n code({ text, lang, escaped }: Tokens.Code): RendererOutput {\n const langString = (lang || '').match(other.notSpaceStart)?.[0];\n\n // An empty code block has no content, so it must not gain a newline.\n const code = text ? text.replace(other.endingNewline, '') + '\\n' : '';\n\n if (!langString) {\n return '<pre><code>'\n + (escaped ? code : escapeHtmlEntities(code, true))\n + '</code></pre>\\n' as RendererOutput;\n }\n\n return '<pre><code class=\"language-'\n + escapeHtmlEntities(langString)\n + '\">'\n + (escaped ? code : escapeHtmlEntities(code, true))\n + '</code></pre>\\n' as RendererOutput;\n }\n\n blockquote({ tokens }: Tokens.Blockquote): RendererOutput {\n const body = this.parser.parse(tokens);\n return `<blockquote>\\n${body}</blockquote>\\n` as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n def(token: Tokens.Def): RendererOutput {\n return '' as RendererOutput;\n }\n\n heading({ tokens, depth }: Tokens.Heading): RendererOutput {\n return `<h${depth}>${this.parser.parseInline(tokens)}</h${depth}>\\n` as RendererOutput;\n }\n\n hr(token: Tokens.Hr): RendererOutput {\n return '<hr>\\n' as RendererOutput;\n }\n\n list(token: Tokens.List): RendererOutput {\n const ordered = token.ordered;\n const start = token.start;\n\n let body = '';\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n body += this.listitem(item);\n }\n\n const type = ordered ? 'ol' : 'ul';\n const startAttr = (ordered && start !== 1) ? (' start=\"' + start + '\"') : '';\n return '<' + type + startAttr + '>\\n' + body + '</' + type + '>\\n' as RendererOutput;\n }\n\n listitem(item: Tokens.ListItem): RendererOutput {\n return `<li>${this.parser.parse(item.tokens)}</li>\\n` as RendererOutput;\n }\n\n checkbox({ checked }: Tokens.Checkbox): RendererOutput {\n return '<input '\n + (checked ? 'checked=\"\" ' : '')\n + 'disabled=\"\" type=\"checkbox\"> ' as RendererOutput;\n }\n\n paragraph({ tokens }: Tokens.Paragraph): RendererOutput {\n return `<p>${this.parser.parseInline(tokens)}</p>\\n` as RendererOutput;\n }\n\n table(token: Tokens.Table): RendererOutput {\n let header = '';\n\n // header\n let cell = '';\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell(token.header[j]);\n }\n header += this.tablerow({ text: cell as ParserOutput });\n\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell(row[k]);\n }\n\n body += this.tablerow({ text: cell as ParserOutput });\n }\n if (body) body = `<tbody>${body}</tbody>`;\n\n return '<table>\\n'\n + '<thead>\\n'\n + header\n + '</thead>\\n'\n + body\n + '</table>\\n' as RendererOutput;\n }\n\n tablerow({ text }: Tokens.TableRow<ParserOutput>): RendererOutput {\n return `<tr>\\n${text}</tr>\\n` as RendererOutput;\n }\n\n tablecell(token: Tokens.TableCell): RendererOutput {\n const content = this.parser.parseInline(token.tokens);\n const type = token.header ? 'th' : 'td';\n const tag = token.align\n ? `<${type} align=\"${token.align}\">`\n : `<${type}>`;\n return tag + content + `</${type}>\\n` as RendererOutput;\n }\n\n /**\n * span level renderer\n */\n strong({ tokens }: Tokens.Strong): RendererOutput {\n return `<strong>${this.parser.parseInline(tokens)}</strong>` as RendererOutput;\n }\n\n em({ tokens }: Tokens.Em): RendererOutput {\n return `<em>${this.parser.parseInline(tokens)}</em>` as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return `<code>${escapeHtmlEntities(text, true)}</code>` as RendererOutput;\n }\n\n br(token: Tokens.Br): RendererOutput {\n return '<br>' as RendererOutput;\n }\n\n del({ tokens }: Tokens.Del): RendererOutput {\n return `<del>${this.parser.parseInline(tokens)}</del>` as RendererOutput;\n }\n\n link({ href, title, text, tokens, autolink }: Tokens.Link): RendererOutput {\n // References are not resolved inside an autolink, so every `&` there is\n // literal. Elsewhere only an `&` that cannot start one needs escaping.\n const parsedText = autolink\n ? escapeHtmlEntities(text, true)\n : this.parser.parseInline(tokens) as string;\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return parsedText as RendererOutput;\n }\n href = escapeHtmlEntities(cleanHref, autolink);\n let out = '<a href=\"' + href + '\"';\n if (title) {\n out += ' title=\"' + (escapeHtmlEntities(title)) + '\"';\n }\n out += '>' + parsedText + '</a>';\n return out as RendererOutput;\n }\n\n image({ href, title, text, tokens }: Tokens.Image): RendererOutput {\n if (tokens) {\n text = this.parser.parseInline(tokens, this.parser.textRenderer) as string;\n }\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return escapeHtmlEntities(text) as RendererOutput;\n }\n href = cleanHref;\n\n let out = `<img src=\"${escapeHtmlEntities(href)}\" alt=\"${escapeHtmlEntities(text)}\"`;\n if (title) {\n out += ` title=\"${escapeHtmlEntities(title)}\"`;\n }\n out += '>';\n return out as RendererOutput;\n }\n\n text(token: Tokens.Text | Tokens.Escape): RendererOutput {\n return 'tokens' in token && token.tokens\n ? this.parser.parseInline(token.tokens) as unknown as RendererOutput\n : ('escaped' in token && token.escaped ? token.text as RendererOutput : escapeHtmlEntities(token.text) as RendererOutput);\n }\n}\n", "import type { Tokens } from './Tokens.ts';\nimport type { _Parser } from './Parser.ts';\n\n/**\n * TextRenderer\n * returns only the textual part of the token\n */\nexport class _TextRenderer<RendererOutput = string> {\n parser!: _Parser<unknown, RendererOutput>;\n // no need for block level renderers\n strong({ text, tokens }: Tokens.Strong): RendererOutput {\n return (tokens ? this.parser.parseInline(tokens, this) : text) as RendererOutput;\n }\n\n em({ text, tokens }: Tokens.Em): RendererOutput {\n return (tokens ? this.parser.parseInline(tokens, this) : text) as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return text as RendererOutput;\n }\n\n del({ text, tokens }: Tokens.Del): RendererOutput {\n return (tokens ? this.parser.parseInline(tokens, this) : text) as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n text({ text }: Tokens.Text | Tokens.Escape | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n link({ text, tokens }: Tokens.Link): RendererOutput {\n return (tokens ? this.parser.parseInline(tokens, this) : text) as RendererOutput;\n }\n\n image({ text, tokens }: Tokens.Image): RendererOutput {\n return (tokens ? this.parser.parseInline(tokens, this) : text) as RendererOutput;\n }\n\n br(): RendererOutput {\n return '' as RendererOutput;\n }\n\n checkbox({ raw }: Tokens.Checkbox): RendererOutput {\n return raw as RendererOutput;\n }\n}\n", "import { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _defaults } from './defaults.ts';\nimport type { MarkedToken, Token, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Parsing & Compiling\n */\nexport class _Parser<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n renderer: _Renderer<ParserOutput, RendererOutput>;\n textRenderer: _TextRenderer<RendererOutput>;\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n this.options.renderer = this.options.renderer || new _Renderer<ParserOutput, RendererOutput>();\n this.renderer = this.options.renderer;\n this.renderer.options = this.options;\n this.renderer.parser = this;\n this.textRenderer = new _TextRenderer<RendererOutput>();\n this.textRenderer.parser = this;\n }\n\n /**\n * Static Parse Method\n */\n static parse<ParserOutput = string, RendererOutput = string>(tokens: Token[], options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const parser = new _Parser<ParserOutput, RendererOutput>(options);\n return parser.parse(tokens);\n }\n\n /**\n * Static Parse Inline Method\n */\n static parseInline<ParserOutput = string, RendererOutput = string>(tokens: Token[], options?: MarkedOptions<ParserOutput, RendererOutput>) {\n const parser = new _Parser<ParserOutput, RendererOutput>(options);\n return parser.parseInline(tokens);\n }\n\n /**\n * Parse Loop\n */\n parse(tokens: Token[]): ParserOutput {\n this.renderer.parser = this;\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const genericToken = anyToken as Tokens.Generic;\n const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);\n if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'checkbox', 'html', 'def', 'paragraph', 'text'].includes(genericToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'space': {\n out += this.renderer.space(token);\n break;\n }\n case 'hr': {\n out += this.renderer.hr(token);\n break;\n }\n case 'heading': {\n out += this.renderer.heading(token);\n break;\n }\n case 'code': {\n out += this.renderer.code(token);\n break;\n }\n case 'table': {\n out += this.renderer.table(token);\n break;\n }\n case 'blockquote': {\n out += this.renderer.blockquote(token);\n break;\n }\n case 'list': {\n out += this.renderer.list(token);\n break;\n }\n case 'checkbox': {\n out += this.renderer.checkbox(token);\n break;\n }\n case 'html': {\n out += this.renderer.html(token);\n break;\n }\n case 'def': {\n out += this.renderer.def(token);\n break;\n }\n case 'paragraph': {\n out += this.renderer.paragraph(token);\n break;\n }\n case 'text': {\n out += this.renderer.text(token);\n break;\n }\n\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n\n return out as ParserOutput;\n }\n\n /**\n * Parse Inline Tokens\n */\n parseInline(tokens: Token[], renderer: _Renderer<ParserOutput, RendererOutput> | _TextRenderer<RendererOutput> = this.renderer): ParserOutput {\n this.renderer.parser = this;\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);\n if (ret !== false || !['escape', 'html', 'link', 'image', 'checkbox', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'escape': {\n out += renderer.text(token);\n break;\n }\n case 'html': {\n out += renderer.html(token);\n break;\n }\n case 'link': {\n out += renderer.link(token);\n break;\n }\n case 'image': {\n out += renderer.image(token);\n break;\n }\n case 'checkbox': {\n out += renderer.checkbox(token);\n break;\n }\n case 'strong': {\n out += renderer.strong(token);\n break;\n }\n case 'em': {\n out += renderer.em(token);\n break;\n }\n case 'codespan': {\n out += renderer.codespan(token);\n break;\n }\n case 'br': {\n out += renderer.br(token);\n break;\n }\n case 'del': {\n out += renderer.del(token);\n break;\n }\n case 'text': {\n out += renderer.text(token);\n break;\n }\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n return out as ParserOutput;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\n\nexport class _Hooks<ParserOutput = string, RendererOutput = string> {\n options: MarkedOptions<ParserOutput, RendererOutput>;\n block?: boolean;\n\n constructor(options?: MarkedOptions<ParserOutput, RendererOutput>) {\n this.options = options || _defaults;\n }\n\n static passThroughHooks = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n 'emStrongMask',\n ]);\n\n static passThroughHooksRespectAsync = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n ]);\n\n /**\n * Process markdown before marked\n */\n preprocess(markdown: string) {\n return markdown;\n }\n\n /**\n * Process HTML after marked is finished\n */\n postprocess(html: ParserOutput) {\n return html;\n }\n\n /**\n * Process all tokens before walk tokens\n */\n processAllTokens(tokens: Token[] | TokensList) {\n return tokens;\n }\n\n /**\n * Mask contents that should not be interpreted as em/strong delimiters\n */\n emStrongMask(src: string) {\n return src;\n }\n\n /**\n * Provide function to tokenize markdown\n */\n provideLexer(block = this.block) {\n return block ? _Lexer.lex : _Lexer.lexInline;\n }\n\n /**\n * Provide function to parse tokens\n */\n provideParser(block = this.block) {\n return block ? _Parser.parse<ParserOutput, RendererOutput> : _Parser.parseInline<ParserOutput, RendererOutput>;\n }\n}\n", "import { _getDefaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { escapeHtmlEntities } from './helpers.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, Tokens, TokensList } from './Tokens.ts';\n\nexport type MaybePromise = void | Promise<void>;\n\ntype UnknownFunction = (...args: unknown[]) => unknown;\ntype GenericRendererFunction<RendererOutput> = (...args: unknown[]) => RendererOutput | false;\n\n/**\n * Append value(s) to values in place, flattening one level like concat\n */\nfunction pushValues(values: MaybePromise[], value: MaybePromise | MaybePromise[]) {\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n values.push(value[i]);\n }\n } else {\n values.push(value);\n }\n}\n\nexport class Marked<ParserOutput = string, RendererOutput = string> {\n defaults = _getDefaults<ParserOutput, RendererOutput>();\n options = this.setOptions;\n\n /**\n * Compiles markdown to HTML.\n *\n * To configure hooks, a renderer, or a tokenizer, create a separate `Marked`\n * instance and use `Marked#use` instead of passing them on each call.\n */\n parse = this.parseMarkdown(true);\n\n /**\n * Compiles inline markdown to HTML.\n *\n * To configure hooks, a renderer, or a tokenizer, create a separate `Marked`\n * instance and use `Marked#use` instead of passing them on each call.\n */\n parseInline = this.parseMarkdown(false);\n\n Parser = _Parser<ParserOutput, RendererOutput>;\n Renderer = _Renderer<ParserOutput, RendererOutput>;\n TextRenderer = _TextRenderer<RendererOutput>;\n Lexer = _Lexer;\n Tokenizer = _Tokenizer<ParserOutput, RendererOutput>;\n Hooks = _Hooks<ParserOutput, RendererOutput>;\n\n constructor(...args: MarkedExtension<ParserOutput, RendererOutput>[]) {\n this.use(...args);\n }\n\n /**\n * Run callback for every token\n */\n walkTokens(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n const values: MaybePromise[] = [];\n for (const token of tokens) {\n pushValues(values, callback.call(this, token));\n switch (token.type) {\n case 'table': {\n const tableToken = token as Tokens.Table;\n for (const cell of tableToken.header) {\n pushValues(values, this.walkTokens(cell.tokens, callback));\n }\n for (const row of tableToken.rows) {\n for (const cell of row) {\n pushValues(values, this.walkTokens(cell.tokens, callback));\n }\n }\n break;\n }\n case 'list': {\n const listToken = token as Tokens.List;\n pushValues(values, this.walkTokens(listToken.items, callback));\n break;\n }\n default: {\n const genericToken = token as Tokens.Generic;\n if (this.defaults.extensions?.childTokens?.[genericToken.type]) {\n this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {\n const tokens = genericToken[childTokens].flat(Infinity) as Token[] | TokensList;\n pushValues(values, this.walkTokens(tokens, callback));\n });\n } else if (genericToken.tokens) {\n pushValues(values, this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n\n /**\n * Registers extensions with this Marked instance.\n *\n * The `renderer`, `tokenizer`, and `hooks` objects may each contain only the\n * methods that should be overridden. Their methods are merged with built-in\n * behavior and extensions registered by earlier calls.\n *\n * Use this method when supplying only some hook methods.\n */\n use(...args: MarkedExtension<ParserOutput, RendererOutput>[]) {\n const extensions: MarkedOptions<ParserOutput, RendererOutput>['extensions'] = this.defaults.extensions || { renderers: Object.create(null), childTokens: Object.create(null) };\n\n args.forEach((pack) => {\n // copy options to new object\n const opts = { ...pack } as MarkedOptions<ParserOutput, RendererOutput>;\n\n // set async to true if it was set to true before\n opts.async = this.defaults.async || opts.async || false;\n\n // ==-- Parse \"addon\" extensions --== //\n if (pack.extensions) {\n pack.extensions.forEach((ext) => {\n if (!ext.name) {\n throw new Error('extension name required');\n }\n if ('renderer' in ext) { // Renderer extensions\n const prevRenderer = extensions.renderers[ext.name];\n if (prevRenderer) {\n // Replace extension with func to run new extension but fall back if false\n extensions.renderers[ext.name] = function(...args) {\n let ret = ext.renderer.apply(this, args);\n if (ret === false) {\n ret = prevRenderer.apply(this, args);\n }\n return ret;\n };\n } else {\n extensions.renderers[ext.name] = ext.renderer;\n }\n }\n if ('tokenizer' in ext) { // Tokenizer Extensions\n if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {\n throw new Error(\"extension level must be 'block' or 'inline'\");\n }\n const extLevel = extensions[ext.level];\n if (extLevel) {\n extLevel.unshift(ext.tokenizer);\n } else {\n extensions[ext.level] = [ext.tokenizer];\n }\n if (ext.start) { // Function to check for start of token\n if (ext.level === 'block') {\n if (extensions.startBlock) {\n extensions.startBlock.push(ext.start);\n } else {\n extensions.startBlock = [ext.start];\n }\n } else if (ext.level === 'inline') {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\n } else {\n extensions.startInline = [ext.start];\n }\n }\n }\n }\n if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens\n extensions.childTokens[ext.name] = ext.childTokens;\n }\n });\n opts.extensions = extensions;\n }\n\n // ==-- Parse \"overwrite\" extensions --== //\n if (pack.renderer) {\n const renderer = this.defaults.renderer || new _Renderer<ParserOutput, RendererOutput>(this.defaults);\n for (const prop in pack.renderer) {\n if (!(prop in renderer)) {\n throw new Error(`renderer '${prop}' does not exist`);\n }\n if (['options', 'parser'].includes(prop)) {\n // ignore options property\n continue;\n }\n const rendererProp = prop as Exclude<keyof _Renderer<ParserOutput, RendererOutput>, 'options' | 'parser'>;\n const rendererFunc = pack.renderer[rendererProp] as GenericRendererFunction<RendererOutput>;\n const prevRenderer = renderer[rendererProp] as GenericRendererFunction<RendererOutput>;\n // Replace renderer with func to run extension, but fall back if false\n renderer[rendererProp] = (...args: unknown[]) => {\n let ret = rendererFunc.apply(renderer, args);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args);\n }\n return (ret === false ? '' : ret ?? '') as RendererOutput;\n };\n }\n opts.renderer = renderer;\n }\n if (pack.tokenizer) {\n const tokenizer = this.defaults.tokenizer || new _Tokenizer<ParserOutput, RendererOutput>(this.defaults);\n for (const prop in pack.tokenizer) {\n if (!(prop in tokenizer)) {\n throw new Error(`tokenizer '${prop}' does not exist`);\n }\n if (['options', 'rules', 'lexer'].includes(prop)) {\n // ignore options, rules, and lexer properties\n continue;\n }\n const tokenizerProp = prop as Exclude<keyof _Tokenizer<ParserOutput, RendererOutput>, 'options' | 'rules' | 'lexer'>;\n const tokenizerFunc = pack.tokenizer[tokenizerProp] as UnknownFunction;\n const prevTokenizer = tokenizer[tokenizerProp] as UnknownFunction;\n // Replace tokenizer with func to run extension, but fall back if false\n // @ts-expect-error cannot type tokenizer function dynamically\n tokenizer[tokenizerProp] = (...args: unknown[]) => {\n let ret = tokenizerFunc.apply(tokenizer, args);\n if (ret === false) {\n ret = prevTokenizer.apply(tokenizer, args);\n }\n return ret;\n };\n }\n opts.tokenizer = tokenizer;\n }\n\n // ==-- Parse Hooks extensions --== //\n if (pack.hooks) {\n const hooks = this.defaults.hooks || new _Hooks<ParserOutput, RendererOutput>();\n for (const prop in pack.hooks) {\n if (!(prop in hooks)) {\n throw new Error(`hook '${prop}' does not exist`);\n }\n if (['options', 'block'].includes(prop)) {\n // ignore options and block properties\n continue;\n }\n const hooksProp = prop as Exclude<keyof _Hooks<ParserOutput, RendererOutput>, 'options' | 'block'>;\n const hooksFunc = pack.hooks[hooksProp] as UnknownFunction;\n const prevHook = hooks[hooksProp] as UnknownFunction;\n if (_Hooks.passThroughHooks.has(prop)) {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (arg: unknown) => {\n if (hooks.options.async && _Hooks.passThroughHooksRespectAsync.has(prop)) {\n return (async() => {\n const ret = await hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n })();\n }\n\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n } else {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (...args: unknown[]) => {\n if (hooks.options.async) {\n return (async() => {\n let ret = await hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = await prevHook.apply(hooks, args);\n }\n return ret;\n })();\n }\n\n let ret = hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = prevHook.apply(hooks, args);\n }\n return ret;\n };\n }\n }\n opts.hooks = hooks;\n }\n\n // ==-- Parse WalkTokens extensions --== //\n if (pack.walkTokens) {\n const walkTokens = this.defaults.walkTokens;\n const packWalktokens = pack.walkTokens;\n opts.walkTokens = function(token) {\n const values: MaybePromise[] = [];\n pushValues(values, packWalktokens.call(this, token));\n if (walkTokens) {\n pushValues(values, walkTokens.call(this, token));\n }\n return values;\n };\n }\n\n this.defaults = { ...this.defaults, ...opts };\n });\n\n return this;\n }\n\n setOptions(opt: MarkedOptions<ParserOutput, RendererOutput>) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n\n lexer(src: string, options?: MarkedOptions<ParserOutput, RendererOutput>) {\n return _Lexer.lex(src, options ?? this.defaults);\n }\n\n parser(tokens: Token[], options?: MarkedOptions<ParserOutput, RendererOutput>) {\n return _Parser.parse<ParserOutput, RendererOutput>(tokens, options ?? this.defaults);\n }\n\n private parseMarkdown(blockType: boolean) {\n type overloadedParse = {\n (src: string, options: MarkedOptions<ParserOutput, RendererOutput> & { async: true }): Promise<ParserOutput>;\n (src: string, options: MarkedOptions<ParserOutput, RendererOutput> & { async: false }): ParserOutput;\n (src: string, options?: MarkedOptions<ParserOutput, RendererOutput> | null): ParserOutput | Promise<ParserOutput>;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const parse: overloadedParse = (src: string, options?: MarkedOptions<ParserOutput, RendererOutput> | null): any => {\n const origOpt = { ...options };\n const opt = { ...this.defaults, ...origOpt };\n\n const throwError = this.onError(!!opt.silent, !!opt.async);\n\n // throw error if an extension set async to true but parse was called with async: false\n if (this.defaults.async === true && origOpt.async === false) {\n return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'));\n }\n\n // throw error in case of non string input\n if (typeof src === 'undefined' || src === null) {\n return throwError(new Error('marked(): input parameter is undefined or null'));\n }\n if (typeof src !== 'string') {\n return throwError(new Error('marked(): input parameter is of type '\n + Object.prototype.toString.call(src) + ', string expected'));\n }\n\n if (opt.hooks) {\n opt.hooks.options = opt;\n opt.hooks.block = blockType;\n }\n\n if (opt.async) {\n return (async() => {\n const processedSrc = opt.hooks ? await opt.hooks.preprocess(src) : src;\n const lexer = opt.hooks ? await opt.hooks.provideLexer(blockType) : (blockType ? _Lexer.lex : _Lexer.lexInline);\n const tokens = await lexer(processedSrc, opt);\n const processedTokens = opt.hooks ? await opt.hooks.processAllTokens(tokens) : tokens;\n if (opt.walkTokens) {\n await Promise.all(this.walkTokens(processedTokens, opt.walkTokens));\n }\n const parser = opt.hooks ? await opt.hooks.provideParser(blockType) : (blockType ? _Parser.parse : _Parser.parseInline);\n const html = await parser(processedTokens, opt);\n return opt.hooks ? await opt.hooks.postprocess(html) : html;\n })().catch(throwError);\n }\n\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src) as string;\n }\n const lexer = opt.hooks ? opt.hooks.provideLexer(blockType) : (blockType ? _Lexer.lex : _Lexer.lexInline);\n let tokens = lexer(src, opt);\n if (opt.hooks) {\n tokens = opt.hooks.processAllTokens(tokens);\n }\n if (opt.walkTokens) {\n this.walkTokens(tokens, opt.walkTokens);\n }\n const parser = opt.hooks ? opt.hooks.provideParser(blockType) : (blockType ? _Parser.parse : _Parser.parseInline);\n let html = parser(tokens, opt);\n if (opt.hooks) {\n html = opt.hooks.postprocess(html);\n }\n return html;\n } catch(e) {\n return throwError(e as Error);\n }\n };\n\n return parse;\n }\n\n private onError(silent: boolean, async: boolean) {\n return (e: Error): string | Promise<string> => {\n e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n\n if (silent) {\n const msg = '<p>An error occurred:</p><pre>'\n + escapeHtmlEntities(e.message + '', true)\n + '</pre>';\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\n\n if (async) {\n return Promise.reject(e);\n }\n throw e;\n };\n }\n}\n", "import { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { Marked } from './Instance.ts';\nimport {\n _getDefaults,\n changeDefaults,\n _defaults,\n} from './defaults.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\nimport type { MaybePromise } from './Instance.ts';\n\nconst markedInstance = new Marked();\n\n/**\n * Compiles markdown to HTML asynchronously.\n *\n * To configure hooks, a renderer, or a tokenizer, create a `Marked` instance\n * and use `Marked#use` instead of passing them as options on each call.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options, having async: true\n * @return Promise of string of compiled HTML\n */\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise<string>;\n\n/**\n * Compiles markdown to HTML.\n *\n * To configure hooks, a renderer, or a tokenizer, create a `Marked` instance\n * and use `Marked#use` instead of passing them as options on each call.\n *\n * @param src String of markdown source to be compiled\n * @param options Optional hash of options\n * @return String of compiled HTML. Will be a Promise of string if async is set to true by any extensions.\n */\nexport function marked(src: string, options: MarkedOptions & { async: false }): string;\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise<string>;\nexport function marked(src: string, options?: MarkedOptions | null): string | Promise<string>;\nexport function marked(src: string, opt?: MarkedOptions | null): string | Promise<string> {\n return markedInstance.parse(src, opt);\n}\n\nexport declare namespace marked {\n /**\n * Compiles inline markdown to HTML.\n *\n * To configure hooks, a renderer, or a tokenizer, create a `Marked` instance\n * and use `Marked#use` instead of passing them as options on each call.\n */\n let parseInline: typeof markedInstance.parseInline;\n\n /**\n * Registers extensions with the default Marked instance.\n *\n * The `renderer`, `tokenizer`, and `hooks` objects may each contain only the\n * methods that should be overridden. Their methods are merged with built-in\n * behavior and extensions registered by earlier calls.\n *\n * Use this function when supplying only some hook methods.\n */\n let use: (...args: MarkedExtension[]) => typeof marked;\n}\n\n/**\n * Sets the default options.\n *\n * @param options Hash of options\n */\nmarked.options =\n marked.setOptions = function(options: MarkedOptions) {\n markedInstance.setOptions(options);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n };\n\n/**\n * Gets the original marked default options.\n */\nmarked.getDefaults = _getDefaults;\n\nmarked.defaults = _defaults;\n\n/**\n * Registers extensions with the default Marked instance.\n *\n * The `renderer`, `tokenizer`, and `hooks` objects may each contain only the\n * methods that should be overridden. Their methods are merged with built-in\n * behavior and extensions registered by earlier calls.\n *\n * Use this function when supplying only some hook methods.\n *\n * @param args Extensions to register\n * @return The `marked` function\n */\nfunction useExtension(...args: MarkedExtension[]) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n}\n\nmarked.use = useExtension;\n\n/**\n * Run callback for every token\n */\n\nmarked.walkTokens = function(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n return markedInstance.walkTokens(tokens, callback);\n};\n\n/**\n * Compiles markdown to HTML without enclosing `p` tag.\n *\n * To configure hooks, a renderer, or a tokenizer, create a `Marked` instance\n * and use `Marked#use` instead of passing them as options on each call.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options\n * @return String of compiled HTML\n */\nmarked.parseInline = markedInstance.parseInline;\n\n/**\n * Expose\n */\nmarked.Parser = _Parser;\nmarked.parser = _Parser.parse;\nmarked.Renderer = _Renderer;\nmarked.TextRenderer = _TextRenderer;\nmarked.Lexer = _Lexer;\nmarked.lexer = _Lexer.lex;\nmarked.Tokenizer = _Tokenizer;\nmarked.Hooks = _Hooks;\nmarked.parse = marked;\n\nexport const options = marked.options;\nexport const setOptions = marked.setOptions;\nexport const walkTokens = marked.walkTokens;\n/**\n * Compiles inline markdown to HTML.\n *\n * To configure hooks, a renderer, or a tokenizer, create a `Marked` instance\n * and use `Marked#use` instead of passing them as options on each call.\n */\nexport const parseInline = marked.parseInline;\nexport const parse = marked;\nexport const parser = _Parser.parse;\nexport const lexer = _Lexer.lex;\nexport { _defaults as defaults, _getDefaults as getDefaults } from './defaults.ts';\nexport { _Lexer as Lexer } from './Lexer.ts';\nexport { _Parser as Parser } from './Parser.ts';\nexport { _Tokenizer as Tokenizer } from './Tokenizer.ts';\nexport { _Renderer as Renderer } from './Renderer.ts';\nexport { _TextRenderer as TextRenderer } from './TextRenderer.ts';\nexport { _Hooks as Hooks } from './Hooks.ts';\nexport { Marked } from './Instance.ts';\nexport { useExtension as use };\nexport type * from './MarkedOptions.ts';\nexport type * from './Tokens.ts';\n", "// Sanitisation is verified only in the `chromium` project: DOMPurify silently\n// sanitises nothing under happy-dom, so CLAUDE.md has the root cause.\nimport DOMPurify, { type Config, type DOMPurify as Purifier } from \"dompurify\";\nimport { Marked } from \"marked\";\n\n// A local instance, so configuration never leaks into a host's deduped `marked`.\n// Never mutated; per-call construction would re-pay setup on every streaming render.\nconst parser = new Marked({ gfm: true, breaks: true });\n\n// Conservative allowlist for assistant chat content. Rendering untrusted\n// model/tool output as HTML is an XSS surface and this sanitiser is the only\n// thing standing in front of it, so `iframe`, `style` and all scripting stay\n// out.\n//\n// `img` is excluded by default: a model-controlled image URL is fetched with no\n// user interaction, turning prompt-injected page data into a zero-click\n// exfiltration channel. Hosts that trust their content opt in via `allowImages`.\nconst ALLOWED_TAGS = [\n \"a\",\n \"p\",\n \"br\",\n \"strong\",\n \"em\",\n \"b\",\n \"i\",\n \"u\",\n \"s\",\n \"del\",\n \"code\",\n \"pre\",\n \"ul\",\n \"ol\",\n \"li\",\n \"blockquote\",\n \"h1\",\n \"h2\",\n \"h3\",\n \"h4\",\n \"h5\",\n \"h6\",\n \"hr\",\n \"span\",\n \"table\",\n \"thead\",\n \"tbody\",\n \"tr\",\n \"th\",\n \"td\",\n];\n\n// `target` and `rel` are on the list because {@link harden} writes them onto\n// every link. An attribute the returned markup carries but the config does not\n// name would be markup the sanitiser never approved \u2014 which is the whole defect\n// the hook exists to avoid.\n//\n// `class` is here only for marked's `language-*` code-fence hint, and `harden`\n// narrows it to exactly that. Left wide, it is a chrome-forgery channel: the\n// shadow stylesheet's component classes are unscoped selectors, so a `<span\n// class=\"approval-btn approval-btn--approve\">` in model output resolves to the\n// same pixels as the real human-in-the-loop approval button, inside the surface\n// where the user decides whether to approve.\nconst ALLOWED_ATTR = [\"href\", \"title\", \"class\", \"target\", \"rel\"];\n\n/**\n * The sanitiser's declared allowlist \u2014 and, because {@link harden} runs inside\n * the sanitiser rather than after it, its *effective* one too.\n *\n * `ALLOW_DATA_ATTR` and `ALLOW_ARIA_ATTR` default to `true`, which would admit\n * every `data-*` and `aria-*` attribute on top of the five named above. Both\n * matter here: the cards drive their resolved / expanded / status appearance off\n * `[data-resolved]`, `[data-status]` and `[data-expanded]`, and an `aria-label`\n * on model output makes a screen reader announce something other than what is on\n * screen. Turning them off is what makes the declared list the real one.\n *\n * Exported so a test can assert the returned markup is a fixed point of it.\n */\nexport const SANITIZE_CONFIG: Config = {\n ALLOWED_TAGS,\n ALLOWED_ATTR,\n ALLOW_DATA_ATTR: false,\n ALLOW_ARIA_ATTR: false,\n};\n\n/** {@link SANITIZE_CONFIG} plus the images a host opts into. */\nexport const SANITIZE_CONFIG_WITH_IMAGES: Config = {\n ...SANITIZE_CONFIG,\n ALLOWED_TAGS: [...ALLOWED_TAGS, \"img\"],\n ALLOWED_ATTR: [...ALLOWED_ATTR, \"src\", \"alt\", \"width\", \"height\"],\n};\n\n/** The one class value markdown is allowed to carry, and where it may sit. */\nconst LANGUAGE_CLASS = /^language-[A-Za-z0-9_+#.-]+$/;\nconst LANGUAGE_HOSTS = new Set([\"CODE\", \"PRE\"]);\n\n/**\n * Per-element hardening, run *inside* the sanitiser.\n *\n * It belongs here rather than in a pass over the finished string because\n * DOMPurify must be the last thing to touch the markup: anything edited in\n * afterwards is inserted into the document without the sanitiser ever having\n * seen it, and re-parsing sanitiser output is the shape every mXSS bypass takes.\n * Running as a hook means DOMPurify serialises the result of these edits, so\n * what the caller inserts is exactly what it approved.\n *\n * Two jobs:\n *\n * - links open in a new tab and never hand over their opener. `target`/`rel` are\n * this module's to write, so they are stripped from everything else rather\n * than inherited from the model's own markup;\n * - `class` is narrowed to the code-fence language hint on `code`/`pre`, the\n * only thing it is allowed for, and dropped everywhere else so model output\n * cannot adopt the component's own chrome.\n */\nfunction harden(node: Element): void {\n if (node.nodeName === \"A\" && node.hasAttribute(\"href\")) {\n node.setAttribute(\"target\", \"_blank\");\n node.setAttribute(\"rel\", \"noopener noreferrer\");\n } else {\n node.removeAttribute(\"target\");\n node.removeAttribute(\"rel\");\n }\n const classes = node.getAttribute(\"class\");\n if (classes === null) {\n return;\n }\n const kept = LANGUAGE_HOSTS.has(node.nodeName)\n ? classes.split(/\\s+/).filter((token) => LANGUAGE_CLASS.test(token))\n : [];\n if (kept.length === 0) {\n node.removeAttribute(\"class\");\n return;\n }\n node.setAttribute(\"class\", kept.join(\" \"));\n}\n\n// A memo, not state: DOMPurify's default export is a singleton that `addHook`\n// mutates for every caller sharing the copy, host app included, so this module\n// builds its own instance. The hook is added before the instance is published\n// and nothing touches it afterwards, so every element reads the same value.\n// Built on first render, because an instance made without a DOM has no\n// `addHook` and an eager one would make a server-side `import` throw.\nlet memo: Purifier | undefined;\n\nfunction sanitizer(): Purifier {\n if (memo === undefined) {\n const built = DOMPurify();\n built.addHook(\"afterSanitizeAttributes\", harden);\n memo = built;\n }\n return memo;\n}\n\n/** Options for {@link renderMarkdown}. */\nexport interface RenderMarkdownOptions {\n /**\n * Permit `<img>` tags (and their `src`/`alt`/`width`/`height` attributes) in\n * the sanitised output. Off by default; see the exfiltration note on the\n * allowlist above. Only enable for trusted content sources.\n */\n readonly allowImages?: boolean;\n}\n\n/**\n * Render markdown (and any embedded raw HTML) to a sanitised HTML string.\n *\n * Markdown syntax and literal HTML share one path: `marked` emits HTML, then\n * DOMPurify strips everything outside {@link SANITIZE_CONFIG} \u2014 scripts, event\n * handlers, `javascript:` URLs, `data-*`/`aria-*`, and every class but a code\n * fence's `language-*` hint. Links come out with `target=\"_blank\"` and\n * `rel=\"noopener noreferrer\"`.\n *\n * The returned string is the sanitiser's own output, trimmed. Nothing edits it\n * afterwards, so what a caller inserts is what DOMPurify approved.\n */\nexport function renderMarkdown(text: string, options?: RenderMarkdownOptions): string {\n const allowImages = options?.allowImages === true;\n const rendered = parser.parse(text, { async: false });\n return sanitizer()\n .sanitize(rendered, allowImages ? SANITIZE_CONFIG_WITH_IMAGES : SANITIZE_CONFIG)\n .trim();\n}\n", "import type { UiStrings } from \"../ui_strings.js\";\n\n/**\n * Most prompts one push may draw.\n *\n * **Keep in step with `MAX_SUGGESTIONS` in django-ag-ui's\n * `agent/suggestions_activity.py`**, which raises past it. Mirroring is the\n * whole point: this side silently draws no more than its limit and has no\n * channel to report the difference, so a producer that does not know the same\n * number ships suggestions that never appear. That is the hole the chart bounds\n * exist to close, and it was found there by shipping it.\n */\nexport const MAX_SUGGESTIONS = 4;\n\n/** Longest one prompt may be. Mirrored for the same reason as the count. */\nexport const MAX_SUGGESTION_CHARS = 120;\n\n/** The `prompts` a `suggestions` activity carries, or `null` when it carries none. */\nexport function suggestionPrompts(content: unknown): string[] | null {\n if (typeof content !== \"object\" || content === null) {\n return null;\n }\n const raw = (content as { prompts?: unknown }).prompts;\n if (!Array.isArray(raw)) {\n return null;\n }\n const prompts = raw\n .filter((prompt): prompt is string => typeof prompt === \"string\")\n .map((prompt) => prompt.trim())\n .filter((prompt) => prompt !== \"\" && prompt.length <= MAX_SUGGESTION_CHARS)\n .slice(0, MAX_SUGGESTIONS);\n return prompts.length === 0 ? null : prompts;\n}\n\n/**\n * Draw follow-up prompts as chips that send themselves when clicked.\n *\n * Returns `null` when nothing survives, which is the registry's signal to draw\n * nothing rather than an empty row -- the same contract the chart renderer uses\n * for a spec it cannot draw.\n *\n * Buttons rather than links or list items: each one performs an action in the\n * page, and the thing it sends is the label, so the accessible name is the\n * prompt itself and needs no `aria-label` restating it.\n */\nexport function renderSuggestionChips(\n content: unknown,\n strings: UiStrings,\n onPick: (prompt: string) => void,\n): HTMLElement | null {\n const prompts = suggestionPrompts(content);\n if (prompts === null) {\n return null;\n }\n const row = document.createElement(\"div\");\n row.className = \"suggestions\";\n row.setAttribute(\"part\", \"suggestions\");\n // A group, labelled: without it a screen reader meets a row of unrelated\n // buttons with no hint that they are the assistant's offer rather than the\n // page's own controls.\n row.setAttribute(\"role\", \"group\");\n row.setAttribute(\"aria-label\", strings.suggestions);\n for (const prompt of prompts) {\n const chip = document.createElement(\"button\");\n chip.type = \"button\";\n chip.className = \"suggestion-chip\";\n chip.setAttribute(\"part\", \"suggestion-chip\");\n chip.textContent = prompt;\n chip.addEventListener(\"click\", () => onPick(prompt));\n row.appendChild(chip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F,KAAKC,GAAG;AAGzB,UAAI,OAAOD,KAAKR,UAAU,WACxB,QAAO1E,QAAQkF,KAAKR,KAAK;IAE7B;AAEAN,aAAS1F,eAAe0F,MAAM;EAChC;AAEA,WAASgB,gBAAsB;AAC7B,WAAO;EACT;AAEA,SAAOA;AACT;AAaA,SAASC,eACPjB,QACAa,MACwC;AACxC,SAAOb,WAAW,MAAM;AACtB,UAAMc,OAAOvG,yBAAyByF,QAAQa,IAAI;AAElD,QAAIC,KACF,QAAOA,KAAKC,MAAMnF,QAAQkF,KAAKC,GAAG,IAAI;AAGxCf,aAAS1F,eAAe0F,MAAM;EAChC;AAEA,SAAO;AACT;AAEA,SAASkB,QAAQZ,OAAiC;AAChD,MAAI;AACF5B,eAAW4B,OAAiB,EAAE;AAC9B,WAAO;EACT,SAAEa,SAAM;AACN,WAAO;EACT;AACF;ACnUA,IAAaC,SAAO5G,OAAO;EACzB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AAAK,CACG;AAEV,IAAa6G,QAAM7G,OAAO;EACxB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AAAO,CACC;AAEV,IAAa8G,aAAa9G,OAAO;EAC/B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AAAc,CACN;AAMV,IAAa+G,gBAAgB/G,OAAO;EAClC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AAAK,CACG;AAEV,IAAagH,WAAShH,OAAO;EAC3B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AAAa,CACL;AAIV,IAAaiH,mBAAmBjH,OAAO;EACrC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AAAM,CACE;AAEV,IAAakH,QAAOlH,OAAO,CAAC,OAAO,CAAU;AC1R7C,IAAa4G,OAAO5G,OAAO;EACzB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AAAO,CACC;AAEV,IAAa6G,MAAM7G,OAAO;EACxB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;AAAY,CACJ;AAEV,IAAagH,SAAShH,OAAO;EAC3B;EACA;EACA;EACA;E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A,SAAO;AACT;",
|
|
6
|
+
"names": ["randomUUID", "randomUUID", "randomUUID", "randomUUID", "a", "text", "errorMessage", "r", "g", "b", "a", "el", "c", "x", "el", "el", "el", "write", "w", "svg", "entries", "text", "text", "el", "actionButton", "text", "text", "text", "html", "flash", "entries", "Object", "setPrototypeOf", "isFrozen", "getPrototypeOf", "getOwnPropertyDescriptor", "freeze", "seal", "create", "_ref", "Reflect", "apply", "construct", "x", "func", "thisArg", "_len", "arguments", "length", "args", "Array", "_key", "Func", "_len2", "_key2", "arrayForEach", "unapply", "prototype", "forEach", "indexOf", "arrayLastIndexOf", "lastIndexOf", "arrayPop", "pop", "arrayPush", "push", "arraySlice", "slice", "arraySplice", "splice", "arrayIsArray", "isArray", "setCreate", "unconstruct", "Set", "setAdd", "add", "setHas", "has", "stringToLowerCase", "String", "toLowerCase", "stringToString", "toString", "stringMatch", "match", "stringReplace", "replace", "stringIndexOf", "stringTrim", "trim", "numberToString", "Number", "booleanToString", "Boolean", "bigintToString", "BigInt", "symbolToString", "Symbol", "objectHasOwnProperty", "hasOwnProperty", "objectToString", "regExpTest", "RegExp", "test", "typeErrorCreate", "TypeError", "lastIndex", "_len3", "_key3", "_len4", "_key4", "addToSet", "set", "array", "transformCaseFunc", "undefined", "l", "element", "lcElement", "cleanArray", "index", "isPropertyExist", "clone", "object", "newObject", "_ref2", "_ref3", "_slicedToArray", "property", "value", "constructor", "stringifyValue", "valueAsRecord", "valueToString", "lookupGetter", "stringified", "prop", "desc", "get", "fallbackValue", "lookupAccessor", "isRegex", "_unused", "html", "svg", "svgFilters", "svgDisallowed", "mathMl", "mathMlDisallowed", "text", "xml", "MUSTACHE_EXPR", "ERB_EXPR", "TMPLIT_EXPR", "DATA_ATTR", "ARIA_ATTR", "IS_ALLOWED_URI", "IS_SCRIPT_OR_DATA", "ATTR_WHITESPACE", "DOCTYPE_NAME", "CUSTOM_ELEMENT", "ELEMENT_MARKUP_PROBE", "COMMENT_MARKUP_PROBE", "FALLBACK_TAG_CLOSE", "SELF_CLOSING_TAG", "NODE_TYPE", "attribute", "cdataSection", "entityReference", "entityNode", "processingInstruction", "comment", "document", "documentType", "documentFragment", "notation", "LITERAL_TEXT_ELEMENTS", "LITERAL_TEXT_ELEMENT_NAMES", "getGlobal", "window", "_createTrustedTypesPolicy", "trustedTypes", "purifyHostElement", "createPolicy", "suffix", "ATTR_NAME", "hasAttribute", "getAttribute", "policyName", "createHTML", "createScriptURL", "scriptUrl", "_", "console", "warn", "_createHooksMap", "afterSanitizeAttributes", "afterSanitizeElements", "afterSanitizeShadowDOM", "beforeSanitizeAttributes", "beforeSanitizeElements", "beforeSanitizeShadowDOM", "uponSanitizeAttribute", "uponSanitizeElement", "uponSanitizeShadowNode", "_resolveSetOption", "cfg", "key", "fallback", "options", "base", "transform", "_resolveObjectOption", "makeFallback", "createDOMPurify", "DOMPurify", "root", "version", "removed", "nodeType", "Element", "isSupported", "originalDocument", "currentScript", "DocumentFragment", "HTMLTemplateElement", "Node", "NodeFilter", "_window$NamedNodeMap", "NamedNodeMap", "MozNamedAttrMap", "HTMLFormElement", "DOMParser", "ElementPrototype", "cloneNode", "remove", "removeAttributeNode", "getNextSibling", "getChildNodes", "getParentNode", "getShadowRoot", "getAttributes", "getNodeType", "getNodeName", "getOwnerDocument", "_readNodeType", "node", "_readNodeName", "nodeName", "getNamespaceURI", "_readNamespaceURI", "namespaceURI", "template", "createElement", "content", "ownerDocument", "trustedTypesPolicy", "emptyHTML", "defaultTrustedTypesPolicy", "defaultTrustedTypesPolicyResolved", "IN_TRUSTED_TYPES_POLICY", "_assertNotInTrustedTypesPolicy", "_createTrustedHTML", "_createTrustedScriptURL", "_getDefaultTrustedTypesPolicy", "_document", "implementation", "createNodeIterator", "createDocumentFragment", "getElementsByTagName", "importNode", "hooks", "createHTMLDocument", "EXPRESSIONS", "ALLOWED_TAGS", "DEFAULT_ALLOWED_TAGS", "TAGS", "ALLOWED_ATTR", "DEFAULT_ALLOWED_ATTR", "ATTRS", "CUSTOM_ELEMENT_HANDLING", "tagNameCheck", "writable", "configurable", "enumerable", "attributeNameCheck", "allowCustomizedBuiltInElements", "FORBID_TAGS", "FORBID_ATTR", "EXTRA_ELEMENT_HANDLING", "tagCheck", "attributeCheck", "ALLOW_ARIA_ATTR", "ALLOW_DATA_ATTR", "ALLOW_UNKNOWN_PROTOCOLS", "ALLOW_SELF_CLOSE_IN_ATTR", "SAFE_FOR_TEMPLATES", "SAFE_FOR_XML", "WHOLE_DOCUMENT", "SET_CONFIG", "SET_CONFIG_ALLOWED_TAGS", "SET_CONFIG_ALLOWED_ATTR", "FORCE_BODY", "RETURN_DOM", "RETURN_DOM_FRAGMENT", "RETURN_TRUSTED_TYPE", "SANITIZE_DOM", "SANITIZE_NAMED_PROPS", "SANITIZE_NAMED_PROPS_PREFIX", "KEEP_CONTENT", "IN_PLACE", "IN_PLACE_VISITED", "USE_PROFILES", "FORBID_CONTENTS", "DEFAULT_FORBID_CONTENTS", "DATA_URI_TAGS", "DEFAULT_DATA_URI_TAGS", "URI_SAFE_ATTRIBUTES", "DEFAULT_URI_SAFE_ATTRIBUTES", "MATHML_NAMESPACE", "SVG_NAMESPACE", "HTML_NAMESPACE", "NAMESPACE", "IS_EMPTY_INPUT", "ALLOWED_NAMESPACES", "DEFAULT_ALLOWED_NAMESPACES", "DEFAULT_MATHML_TEXT_INTEGRATION_POINTS", "MATHML_TEXT_INTEGRATION_POINTS", "DEFAULT_HTML_INTEGRATION_POINTS", "HTML_INTEGRATION_POINTS", "COMMON_SVG_AND_HTML_ELEMENTS", "PARSER_MEDIA_TYPE", "SUPPORTED_PARSER_MEDIA_TYPES", "DEFAULT_PARSER_MEDIA_TYPE", "CONFIG", "formElement", "isRegexOrFunction", "testValue", "Function", "_parseConfig", "ALLOWED_URI_REGEXP", "customElementHandling", "ADD_TAGS", "ADD_ATTR", "ADD_FORBID_CONTENTS", "table", "tbody", "TRUSTED_TYPES_POLICY", "previousTrustedTypesPolicy", "error", "ALL_SVG_TAGS", "ALL_MATHML_TAGS", "_checkSvgNamespace", "tagName", "parent", "parentTagName", "_checkMathMlNamespace", "_checkHtmlNamespace", "_checkValidNamespace", "elementNamespace", "parentNode", "_forceRemove", "removeChild", "_stripAttributeNode", "name", "removeAttribute", "_neutralizeRoot", "_neutralizeSubtree", "childNodes", "child", "attributes", "i", "_removeAttribute", "attr", "getAttributeNode", "from", "setAttribute", "_stripDisallowedAttributes", "_walkTree", "visit", "intoShadow", "stack", "shadowRoot", "_isDocumentFragment", "_collectLiveNodes", "nodes", "_neutralizeEscapedElements", "before", "reachable", "_neutralizeDiscarded", "rootRemoved", "entry", "MAX_UNVISITED_ROUNDS", "_sanitizeUnvisitedNodes", "visited", "original", "getOriginal", "beforeNode", "round", "live", "containers", "pending", "container", "_sanitizeUnvisitedIn", "inShadow", "iterator", "_createNodeIterator", "nextNode", "_executeHooks", "_sanitizeElements", "_sanitizeAttributes", "_sanitizeShadowDOM", "_markVisited", "_isPatchLinkageAttribute", "lcName", "lcTag", "_neutralizePatchLinkage", "data", "_initDocument", "dirty", "doc", "leadingWhitespace", "matches", "dirtyPayload", "parseFromString", "documentElement", "createDocument", "innerHTML", "body", "insertBefore", "createTextNode", "call", "SHOW_ELEMENT", "SHOW_COMMENT", "SHOW_TEXT", "SHOW_PROCESSING_INSTRUCTION", "SHOW_CDATA_SECTION", "_stripTemplateExpressions", "_scrubTemplateExpressions", "_node$querySelectorAl", "_scrubOwnCharacterData", "templates", "querySelectorAll", "tmpl", "normalize", "walker", "currentNode", "_isClobbered", "realTagName", "textContent", "hasChildNodes", "_isNode", "hook", "_isUnsafeNode", "firstElementChild", "_matchesNameCheck", "check", "_sanitizeDisallowedNode", "_isBasicCustomElement", "childCount", "hoisted", "_forkSharedAllowlist", "hookList", "defaultSet", "setConfigSet", "_handleHookDetachedNode", "allowedTags", "nt", "_isValidAttribute", "nameIsPermitted", "RESERVED_CUSTOM_ELEMENT_NAMES", "_applyTrustedTypesToAttribute", "getAttributeType", "_setAttributeValue", "setAttributeNS", "_isUnsafeAttributeValue", "hookEvent", "attrName", "attrValue", "keepAttr", "allowedAttributes", "forceKeepAttr", "initValue", "recreatedNamedProp", "cleanWrite", "fragment", "shadowNode", "shadowIterator", "innerSr", "_sanitizeAttachedShadowRoots", "shadow", "item", "isElement", "rootName", "sr", "sanitize", "importedNode", "returnNode", "inPlace", "inPlaceNodes", "outerVisited", "nn", "appendChild", "firstChild", "walkRoot", "nodeIterator", "shadowroot", "shadowrootmode", "serializedHTML", "outerHTML", "doctype", "setConfig", "clearConfig", "isValidAttribute", "tag", "addHook", "entryPoint", "hookFunction", "removeHook", "removeHooks", "removeAllHooks", "_getDefaults", "_defaults", "changeDefaults", "newDefaults", "noopTest", "cachedIndentRegex", "createRegex", "cache", "indent", "cacheIndex", "regex", "edit", "opt", "source", "obj", "name", "val", "valSource", "other", "supportsLookbehind", "a", "bull", "_tag", "newline", "blockCode", "fences", "hr", "heading", "bullet", "lheadingCore", "lheading", "lheadingGfm", "_paragraph", "blockText", "_blockLabel", "def", "list", "_comment", "html", "createParagraph", "listInterrupt", "paragraph", "blockquoteParagraph", "blockquote", "blockNormal", "gfmTable", "blockGfm", "blockPedantic", "escape", "inlineCode", "br", "inlineText", "_punctuation", "_punctuationOrSpace", "_notPunctuationOrSpace", "punctuation", "_openQuote", "_punctuationGfmStrongEm", "_punctuationOrSpaceGfmStrongEm", "_notPunctuationOrSpaceGfmStrongEm", "blockSkip", "emStrongLDelimCore", "emStrongLDelim", "emStrongLDelimGfm", "emStrongLDelimPedanticCore", "emStrongLDelimPedantic", "emStrongRDelimAstCore", "emStrongRDelimAst", "emStrongRDelimAstGfm", "emStrongRDelimAstPedanticCore", "emStrongRDelimAstPedantic", "emStrongRDelimUnd", "emStrongRDelimUndPedanticCore", "emStrongRDelimUndPedantic", "delLDelim", "delRDelimCore", "delRDelim", "anyPunctuation", "anyPunctuationOutsideCode", "autolink", "_inlineComment", "tag", "_inlineLabelBrackets", "_inlineLabel", "link", "reflink", "nolink", "_boundedBlockLabel", "_boundedInlineLabel", "reflinkSearch", "_caseInsensitiveProtocol", "_extendedEmail", "_extendedEmailProtocol", "inlineNormal", "inlinePedantic", "inlineGfm", "inlineBreaks", "block", "inline", "escapeReplacements", "getEscapeReplacement", "ch", "escapeHtmlEntities", "encode", "decodeNumericCharacterReferences", "text", "ref", "dec", "hex", "code", "cleanUrl", "href", "splitCells", "tableRow", "count", "row", "match", "offset", "str", "escaped", "curr", "cells", "i", "rtrim", "c", "invert", "l", "suffLen", "currChar", "trimTrailingBlankLines", "lines", "end", "normalizeLabel", "label", "findClosingBracket", "b", "level", "emStrongDelCloserHintStacks", "scanLastPossibleEmStrongDelClosers", "src", "lastPossibleEmStrongCloserIndex", "lastPossibleDelCloserIndex", "len", "prev", "j", "beginEmStrongDelCloserScan", "tokenizer", "maskedSrc", "frame", "stack", "endEmStrongDelCloserScan", "cachedLastPossibleEmStrongCloserIndex", "delim", "cachedLastPossibleDelCloserIndex", "expandTabs", "line", "col", "expanded", "char", "added", "outputLink", "cap", "raw", "lexer", "rules", "title", "isImage", "outerInLink", "outerLinkEmitted", "outerInRawBlock", "tokens", "textHasLink", "indentCodeCompensation", "matchIndentToCode", "indentToCode", "node", "matchIndentInNode", "indentInNode", "isLabelEndInsideToken", "labelStart", "tokenSrc", "token", "_Tokenizer", "options", "trimmed", "inBlockquote", "currentLines", "currentRaw", "currentText", "_", "marker", "whitespace", "top", "lastToken", "oldToken", "continuation", "newText", "newToken", "leftover", "leftoverCount", "consumed", "consumedCount", "listSrc", "taken", "isordered", "itemRegex", "endsWithBlankLine", "endEarly", "itemContents", "itemStart", "firstLine", "bulletIndent", "nextLine", "blankLine", "nextBulletRegex", "hrRegex", "fencesBeginRegex", "headingBeginRegex", "htmlBeginRegex", "blockquoteBeginRegex", "rawLine", "nextLineWithoutTabs", "lastItem", "item", "spacers", "t", "hasMultipleLineBreaks", "itemToken", "taskRaw", "checkboxToken", "headers", "aligns", "rows", "align", "cell", "trimmedUrl", "rtrimSlash", "lastParenIndex", "linkLen", "unescaped", "links", "prevChar", "delimChar", "midRun", "srcStart", "runStart", "runPrevChar", "runPrevPunct", "prevPunct", "nextChar", "lLength", "rDelim", "rLength", "delimTotal", "midDelimTotal", "runLength", "openerCanClose", "endReg", "emStrongCloserWindowStart", "lastPossibleEmStrongCloserIndexInWindow", "lastCharLength", "hasNonSpaceChars", "hasSpaceCharsOnBothEnds", "delCloserWindowStart", "lastPossibleDelCloserIndexInWindow", "prevCapZero", "_Lexer", "__Lexer", "next", "lastParagraphClipped", "srcLength", "extTokenizer", "cutSrc", "startIndex", "tempSrc", "tempStart", "getStartIndex", "linkRule", "match0", "refStart", "prevLinkParenPossible", "#inlineTokensInner", "#maskSrc", "#tokenizeInlines", "keepPrevChar", "maskReflink", "punct", "_link", "context", "byte", "errMsg", "_Renderer", "lang", "langString", "depth", "ordered", "start", "body", "type", "startAttr", "checked", "header", "k", "content", "parsedText", "cleanHref", "out", "_TextRenderer", "_Parser", "__Parser", "anyToken", "genericToken", "ret", "renderer", "_Hooks", "markdown", "pushValues", "values", "value", "Marked", "args", "callback", "tableToken", "listToken", "childTokens", "extensions", "pack", "opts", "ext", "prevRenderer", "extLevel", "prop", "rendererProp", "rendererFunc", "tokenizerProp", "tokenizerFunc", "prevTokenizer", "hooks", "hooksProp", "hooksFunc", "prevHook", "arg", "walkTokens", "packWalktokens", "blockType", "origOpt", "throwError", "processedSrc", "processedTokens", "e", "silent", "async", "msg", "markedInstance", "marked", "useExtension", "setOptions", "parseInline", "parser", "_Parser", "lexer", "_Lexer", "text"]
|
|
7
|
+
}
|