sh3-server 0.13.3 → 0.13.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"mappings":";upDAAaA,GAAqB,EACrBC,GAAsB,EAEtBC,GAAqB,EACrBC,GAAmB,EACnBC,GAAsB,GAEtBC,GAAqB,EAErBC,GAAmB,EACnBC,GAAoB,EACpBC,GAAwB,GAExBC,GAAgB,EAChBC,GAAiB,EACjBC,GAAoB,EAEpBC,GAAoB,EACpBC,GAA2B,EAC3BC,GAAmB,EACnBC,GAAsB,EAEtBC,GAAkB,IAElBC,GAAuB,KAEvBC,GAAyB,KACzBC,GAAgB,IAChBC,GAAkB,GAMlBC,GAAgB,OAAM,EAGtBC,GAAW,OAAO,UAAU,EAC5BC,GAAM,OAAO,KAAK,EAElBC,GAAiB,+BACjBC,GAAgB,6BAChBC,GAAmB,qCAuBnBC,GAAiB,UCjE9BC,GAAe,GCER,IAAIC,GAAW,MAAM,QACjBC,GAAW,MAAM,UAAU,QAC3BC,GAAW,MAAM,UAAU,SAC3BC,GAAa,MAAM,KACnBC,GAAc,OAAO,KACrBC,GAAkB,OAAO,eACzBC,GAAiB,OAAO,yBACxBC,GAAkB,OAAO,0BACzBC,GAAmB,OAAO,UAC1BC,GAAkB,MAAM,UACxBC,GAAmB,OAAO,eAC1BC,GAAgB,OAAO,aACvBC,GAAmB,OAAO,UAAU,eAMxC,SAASC,GAAYC,EAAO,CAClC,OAAO,OAAOA,GAAU,UACzB,CAEO,MAAMC,GAAO,IAAM,CAAC,EAUpB,SAASC,GAAWC,EAAO,CACjC,OAAO,OAAOA,GAAO,MAAS,UAC/B,CAGO,SAASC,GAAIC,EAAI,CACvB,OAAOA,EAAE,CACV,CAGO,SAASC,GAAQC,EAAK,CAC5B,QAASC,EAAI,EAAGA,EAAID,EAAI,OAAQC,IAC/BD,EAAIC,CAAC,EAAC,CAER,CAMO,SAASC,IAAW,CAE1B,I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1Cp6B,CAAG,MAFPD,CAAG,IAFLiO,CAAO,MAAPA,CAAO,aADL8tB,CAAO,GAAArwB,EAAAC,CAAA,eAFJ,eC1BD,MAAMywB,GAAW,CACtB,WACA,kCACA,+BACA,iCACA,aACA,UACA,kBACA,UACA,MACA,aACA,MACA,aACA,QACA,WACA,SACA,QACA,eACA,gBACA,eACA,aACA,eACA,WACA,YACA,kBACA,QACA,UACA,YACA,OACA,MACA,OACA,YACA,QACA,cACA,WACA,UACA,SACA,OACA,gBACA,MACA,UACA,OACA,eACA,YACA,YACA,YACA,QACA,oBACA,kBACA,SACA,cACA,cACA,cACA,uBACA,YACA,QACA,MACA,aACA,wBACA,YACA,QACA,WACA,WACA,QACA,aACA,QACA,UACA,QACA,QACA,OACA,WACA,MACA,SACA,mBACA,cACA,cACA,oBACA,mBACA,kBACA,YACA,OACA,eACA,YACA,OACA,UACA,SACA,OACA,MACA,WACA,WACA,OACA,gBACA,OACA,UACA,QACA,aACA,UACA,eACA,UACA,QACA,SACA,UACA,OACA,OACA,UACA,iBACA,UACA,SACA,aACA,SACA,YACA,aACA,YACA,QACA,OACA,WACA,cACA,SACA,OACA,SACA,WACA,SACA,QACA,qBACA,YACA,WACA,SACA,kBACA,OACA,MACA,QACA,mBACA,SACA,UACA,QACA,UACA,iBACA,OACA,SACA,UACA,QACA,SACA,OACA,QACA,QACA,WACA,gBACA,OACA,IACA,MACA,UACA,UACF,6aCzJA,UAkBI,IAAA1oE,iBAAkB,MAAS,EAE3B68D,mBAAW,EAAK,EAIdn+B,EAAQiR,EAAO,EAAE,EAEf,MAAA8yB,EAAQrtB,EAAA,IAAAjF,EACZzR,CAAK,EAAC,SAAW,GACbgqC,GACAA,GAAS,OAAQn9C,GAAOA,EAAG,SAAQ4kB,EAACzR,CAAK,EAAC,KAAI,EAAG,YAAW,cAGzD6c,EAAKhwB,EAA8B,CACtCsxC,EAAQ,IACZ78D,EAAQurB,CAAE,eACCA,CAAE,EACf,KAGD+gB,EAAG15B,GA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ACTIVE","EACH_INDEX_REACTIVE","EACH_IS_CONTROLLED","EACH_IS_ANIMATED","EACH_ITEM_IMMUTABLE","PROPS_IS_IMMUTABLE","PROPS_IS_UPDATED","PROPS_IS_BINDABLE","PROPS_IS_LAZY_INITIAL","TRANSITION_IN","TRANSITION_OUT","TRANSITION_GLOBAL","TEMPLATE_FRAGMENT","TEMPLATE_USE_IMPORT_NODE","TEMPLATE_USE_SVG","TEMPLATE_USE_MATHML","HYDRATION_START","HYDRATION_START_ELSE","HYDRATION_START_FAILED","HYDRATION_END","HYDRATION_ERROR","UNINITIALIZED","FILENAME","HMR","NAMESPACE_HTML","NAMESPACE_SVG","NAMESPACE_MATHML","ATTACHMENT_KEY","DEV","is_array","index_of","includes","array_from","object_keys","define_property","get_descriptor","get_descriptors","object_prototype","array_prototype","get_prototype_of","is_extensible","has_own_property","is_function","thing","noop","is_promise","value","run","fn","run_all","arr","i","deferred","resolve","reject","promise","res","rej","fallback","lazy","to_array","n","array","element","exclude_from_object","obj","keys","result","key","symbol","DERIVED","EFFECT","RENDER_EFFECT","MANAGED_EFFECT","BLOCK_EFFECT","BRANCH_EFFECT","ROOT_EFFECT","BOUNDARY_EFFECT","CONNECTED","CLEAN","DIRTY","MAYBE_DIRTY","INERT","DESTROYED","REACTION_RAN","DESTROYING","EFFECT_TRANSPARENT","EAGER_EFFECT","HEAD_EFFECT","EFFECT_PRESERVED","USER_EFFECT","EFFECT_OFFSCREEN","WAS_MARKED","REACTION_IS_UPDATING","ASYNC","ERROR_VALUE","STATE_SYMBOL","LEGACY_PROPS","LOADING_ATTR_SYMBOL","PROXY_PATH_SYMBOL","HMR_ANCHOR","STALE_REACTION","IS_XHTML","ELEMENT_NODE","TEXT_NODE","COMMENT_NODE","DOCUMENT_FRAGMENT_NODE","experimental_async_required","name","invalid_default_snippet","invalid_snippet_arguments","lifecycle_outside_component","missing_context","snippet_without_render_tag","store_invalid_shape","svelte_element_invalid_this_value","async_derived_orphan","component_api_changed","method","component","component_api_invalid_new","each_key_duplicate","a","b","effect_in_teardown","rune","effect_in_unowned_derived","effect_orphan","effect_pending_outside_reaction","effect_update_depth_exceeded","fork_discarded","fork_timing","get_abort_signal_outside_reaction","hydration_failed","lifecycle_legacy_only","props_invalid_value","state_descriptors_fixed","state_prototype_fixed","state_unsafe_mutation","svelte_boundary_reset_onerror","assignment_value_stale","property","location","binding_property_non_reactive","binding","console_log_state","derived_inert","event_handler_invalid","handler","suggestion","hydratable_missing_but_expected","hydration_mismatch","ownership_invalid_binding","parent","prop","child","owner","ownership_invalid_mutation","select_multiple_invalid_value","state_proxy_equality_mismatch","operator","svelte_boundary_reset_noop","hydrating","set_hydrating","hydrate_node","set_hydrate_node","node","w.hydration_mismatch","hydrate_next","get_next_sibling","reset","hydrate_template","template","next","count","skip_nodes","remove","depth","data","read_hydration_instruction","equals","safe_not_equal","safe_equals","tracing_mode_flag","dynamic_void_element_content","tag","empty","snapshot","skip_warning","no_tojson","clone","cloned","path","paths","original","unwrapped","copy","tracing_expressions","log_entry","signal","entry","type","get_type","current_reaction","active_reaction","dirty","style","deps","dep","updated","trace","label","previously_tracing_expressions","start","time","prefix","untrack","effect_tracking","entries","traces","source","tag_proxy","get_error","error","stack","get_stack","limit","lines","new_lines","line","posixified","component_context","set_component_context","context","dev_stack","add_svelte_meta","callback","column","additional","dev_current_component_function","set_dev_current_component_function","createContext","hasContext","e.missing_context","getContext","setContext","get_or_init_context_map","getAllContexts","push","props","runes","active_effect","pop","effects","create_user_effect","is_runes","e.lifecycle_outside_component","get_parent_context","context_map","micro_tasks","run_micro_tasks","tasks","queue_micro_task","is_flushing_sync","flush_tasks","handle_error","effect","invoke_error_boundary","e","STATUS_MASK","set_signal_status","status","update_derived_status","derived","clear_marked","defer_effect","dirty_effects","maybe_dirty_effects","subscribe_to_store","store","invalidate","unsub","get","_","legacy_is_updating_store","is_store_binding","IS_UNMOUNTED","store_get","store_name","stores","mutable_source","is_synchronous_callback","v","set","get_store","store_unsub","store_set","update_with_flag","invalidate_store","setup_stores","cleanup","teardown","store_mutate","expression","new_value","update_store","store_value","d","update_pre_store","mark_store_binding","capture_store_binding","previous_is_store_binding","batches","current_batch","batch_values","last_scheduled_effect","is_processing","collected_effects","legacy_updates","flush_count","uid","Batch","#commit_callbacks","#discard_callbacks","#fork_commit_callbacks","#pending","#blocking_pending","#deferred","#roots","#new_effects","#dirty_effects","#maybe_dirty_effects","#skipped_branches","#unskipped_branches","#decrement_queued","#blockers","#is_deferred","#is_blocked","batch","skipped","tracked","#process","infinite_loop_guard","roots","render_effects","updates","root","#traverse","reset_all","#defer_effects","t","reset_branch","flush_queued_effects","next_batch","r","flags","is_branch","is_skippable_branch","skip","is_dirty","update_effect","is_derived","old_values","#commit","is_earlier","sources","batch_value","others","s","unskipped","marked","checked","mark_effects","current_unequal","c","depends_on","blocking","pending_count","blocking_pending_count","flushSync","was_flushing_sync","e.effect_update_depth_exceeded","eager_block_effects","length","unlink_effect","ordered_effects","ancestor","j","reaction","schedule_effect","mark_eager_effects","depends","eager_versions","eager_flush","eager","version","update","initial","eager_effect","previous_batch_values","fork","e.experimental_async_required","e.fork_timing","committed","settled","e.fork_discarded","increment_write_version","eager_effects","set_eager_effects","flush_eager_effects","createSubscriber","subscribers","stop","render_effect","increment","boundary","children","transform_error","Boundary","#anchor","#hydrate_open","#props","#children","#effect","#main_effect","#pending_effect","#failed_effect","#offscreen_fragment","#local_pending_count","#pending_count","#pending_count_update_queued","#effect_pending","#effect_pending_subscriber","anchor","block","comment","server_rendered_pending","serialized_error","#hydrate_failed_content","#hydrate_pending_content","#hydrate_resolved_content","#render","branch","failed","pending","fragment","create_text","#run","pause_effect","#resolve","move_effect","previous_effect","previous_reaction","previous_ctx","set_active_effect","set_active_reaction","#update_pending_count","internal_set","#handle_error","destroy_effect","onerror","did_reset","calling_on_error","w.svelte_boundary_reset_noop","e.svelte_boundary_reset_onerror","handle_error_result","transformed_error","e.effect_pending_outside_reaction","flatten","blockers","sync","async","restore","capture","blocker_promise","finish","values","unset_context","decrement_pending","increment_pending","async_derived","run_after_blockers","previous_component_context","previous_batch","activate_batch","save","track_reactivity_loss","previous_async_effect","reactivity_loss_tracker","set_reactivity_loss_tracker","for_await_track_reactivity_loss","iterable","iterator","normal_completion","done","prev","deactivate_batch","thunks","active","errored","aborted","blocker","wait","e.async_derived_orphan","should_suspend","deferreds","async_effect","fulfil","p","go","user_derived","push_reaction_value","derived_safe_equal","destroy_derived_effects","execute_derived","prev_active_effect","is_destroying_effect","w.derived_inert","update_reaction","update_derived","freeze_derived_effects","remove_reactions","destroy_effect_children","unfreeze_derived_effects","eager_effects_deferred","state","initial_value","immutable","trackable","mutate","should_proxy","untracking","current_sources","e.state_unsafe_mutation","proxy","updated_during_traversal","mark_reactions","untracked_writes","set_untracked_writes","update_pre","reactions","not_dirty","prototype","is_proxied_array","parent_version","update_version","with_parent","set_update_version","descriptor","e.state_descriptors_fixed","target","receiver","exists","has","other_s","ls","own_keys","e.state_prototype_fixed","get_proxied_value","is","strict_equals","equal","w.state_proxy_equality_mismatch","$window","$document","is_firefox","first_child_getter","next_sibling_getter","init_operations","element_prototype","node_prototype","text_prototype","get_first_child","is_text","text","merge_text_nodes","first_child","first","sibling","next_sibling","last_sibling","clear_text_content","should_defer_append","create_element","namespace","options","create_fragment","create_comment","set_attribute","autofocus","dom","body","remove_textarea_child","listening_to_form_reset","add_form_reset_listener","evt","listen","events","call_handler_immediately","without_reactive_context","listen_to_event_and_reset_event","event","on_reset","validate_effect","e.effect_orphan","e.effect_in_unowned_derived","e.effect_in_teardown","push_effect","parent_effect","parent_last","create_effect","user_effect","defer","user_pre_effect","effect_root","component_root","legacy_pre_effect","token","legacy_pre_effect_reset","template_effect","deferred_template_effect","managed","execute_effect_teardown","previously_destroying_effect","set_is_destroying_effect","remove_dom","controller","destroy_block_effect_children","removed","remove_effect_dom","transitions","transition","end","destroy","pause_children","remaining","check","local","transparent","resume_effect","resume_children","captured_signals","capture_signals","previous_captured_signals","invalidate_inner_signals","is_updating_effect","new_deps","skipped_deps","write_version","read_version","dependencies","dependency","schedule_possible_effect_self_invalidation","previous_deps","previous_skipped_deps","previous_untracked_writes","previous_sources","previous_untracking","previous_update_version","is_fork","remove_reaction","index","new_length","start_index","was_updating_effect","tick","destroyed","depends_on_old_values","should_connect","is_new","reconnect","safe_get","deep_read_state","deep_read","visited","proto","descriptors","hydratable","w.hydratable_missing_but_expected","event_symbol","all_registered_events","root_event_handles","replay_events","create_event","event_name","target_handler","handle_event_propagation","passive","delegated","delegate","last_propagated_event","handler_element","owner_document","current_target","path_idx","handled_at","at_idx","handler_idx","throw_error","other_errors","parent_element","apply","thunk","args","loc","has_side_effects","remove_parens","filename","phase","w.event_handler_invalid","policy","html","create_trusted_html","create_fragment_from_html","elem","TEMPLATE_TAG","SCRIPT_TAG","assign_nodes","from_html","content","is_fragment","use_import_node","has_start","from_namespace","ns","wrapped","from_svg","from_mathml","fragment_from_tree","structure","item","attributes","from_tree","with_script","run_scripts","scripts","script","attribute","frag","append","props_id","id","VOID_ELEMENT_NAMES","is_void","is_capture_event","DELEGATED_EVENTS","can_delegate_event","ATTRIBUTE_ALIASES","normalize_attribute","PASSIVE_EVENTS","is_passive_event","RAW_TEXT_ELEMENTS","is_raw_text_element","sanitize_location","should_intro","set_should_intro","set_text","str","mount","_mount","hydrate","was_hydrating","previous_hydrate_node","instance","e.hydration_failed","listeners","Component","intro","transformError","unmount","anchor_node","ctx","registered_events","event_handle","counts","mounted_components","validate_void_dynamic_element","tag_fn","w.dynamic_void_element_content","validate_dynamic_element_tag","e.svelte_element_invalid_this_value","validate_store","e.store_invalid_shape","prevent_snippet_stringification","e.snippet_without_render_tag","BranchManager","#batches","#onscreen","#offscreen","#outroing","#transition","onscreen","offscreen","k","on_destroy","#discard","snippet","get_snippet","branches","wrap_snippet","previous_component_function","createRawSnippet","params","getAbortSignal","e.get_abort_signal_outside_reaction","onMount","onDestroy","create_custom_event","detail","bubbles","cancelable","createEventDispatcher","active_component_context","callbacks","beforeUpdate","e.lifecycle_legacy_only","init_update_callbacks","afterUpdate","l","createAttachmentKey","compare","w.assignment_value_stale","assign","object","rhs","assign_async","all_styles","cleanup_styles","hash","styles","add_locations","locations","assign_locations","assign_location","hmr","current","wrapper","initial_anchor","ran","incoming","create_ownership_validator","is_bound_or_unset","w.ownership_invalid_mutation","child_component","w.ownership_invalid_binding","prop_name","is_entry_props","check_target","e.component_api_invalid_new","legacy_api","e.component_api_changed","inspect","get_value","inspector","show_stack","snap","expressions","validate_snippet_args","e.invalid_snippet_arguments","arg","PENDING","THEN","CATCH","await_block","get_input","pending_fn","then_fn","catch_fn","input","mismatch","resolved","if_block","elseif","marker","update_branch","has_branch","NAN","get_key","render_fn","css_props","get_styles","pause_effects","to_destroy","controlled_anchor","group","groups","destroy_effects","fast_path","parent_node","preserved_effects","offscreen_anchor","each","get_collection","fallback_fn","items","is_controlled","each_array","collection","first_run","commit","reconcile","move","discard","is_else","create_item","e.each_key_duplicate","skip_to_branch","is_animated","seen","to_animate","matched","stashed","link","destroy_length","dest","next_node","svg","mathml","last","slot","$$props","slot_props","slot_fn","is_interop","sanitize_slots","sanitized","get_component","hydration_start_node","server_had_component","client_has_component","now","raf","run_tasks","task","loop","fulfill","dispatch_event","css_property_to_camelcase","parts","word","css_to_keyframe","css","keyframe","part","formatted_property","linear","animation_effect_override","set_animation_effect_override","animation","get_fn","get_params","nodes","from","to","original_styles","animate","position","width","height","transform","is_intro","is_outro","is_both","is_global","direction","current_options","inert","overflow","outro","get_options","counterpart","t2","on_finish","o","delay","easing","keyframes","get_t","t1","delta","duration","needs_overflow_hidden","get_tag","is_svg","get_namespace","next_tag","child_anchor","head","head_anchor","append_styles","action","payload","inited","attach","ATTR_REGEX","escape_html","is_attr","pattern","escaped","ch","f","clsx","replacements","attr","is_boolean","normalized","assignment","_clsx","whitespace","to_class","directives","classname","len","important","separator","to_css_name","to_style","new_style","normal_styles","important_styles","in_str","in_apo","in_comment","reserved_names","name_index","set_class","is_html","prev_classes","next_classes","next_class_name","is_present","update_styles","priority","set_style","prev_styles","next_styles","next_style_attr","select_option","select","mounting","w.select_multiple_invalid_value","option","get_option_value","option_value","init_select","observer","bind_select_value","is_reset","query","selected_option","CLASS","STYLE","IS_CUSTOM_ELEMENT","IS_HTML","LINK_TAG","INPUT_TAG","OPTION_TAG","SELECT_TAG","PROGRESS_TAG","remove_input_defaults","already_removed","remove_defaults","set_value","get_attributes","set_checked","set_selected","selected","set_default_checked","existing_value","set_default_value","get_setters","set_xlink_attribute","set_custom_element_data","setters_cache","set_attributes","css_hash","should_remove_defaults","is_custom_element","preserve_attribute_case","is_hydrating_custom_element","is_option_element","setters","prev_value","opts","event_handle_key","is_delegated","handle","is_default","use_default","previous","attribute_effect","is_select","cache_key","element_proto","supported","is_supported","selectedcontent","update_element","customizable_select","rich_fn","bind_active_element","bind_value","is_numberlike_input","to_number","bind_group","inputs","group_index","is_checkbox","binding_group","get_binding_group_value","hydration_input","bind_checked","__value","bind_files","time_ranges_to_array","ranges","bind_current_time","media","raf_id","next_value","bind_buffered","range","bind_seekable","bind_played","bind_seeking","bind_ended","bind_ready_state","bind_playback_rate","bind_paused","paused","bind_volume","bind_muted","bind_online","bind_prop","desc","ResizeObserverSingleton","#listeners","#observer","#options","listener","#getObserver","resize_observer_content_box","resize_observer_border_box","resize_observer_device_pixel_content_box","bind_resize_observer","bind_element_size","is_bound_this","bound_value","element_or_component","bind_this","get_parts","component_effect","old_parts","original_teardown","bind_content_editable","non_null_value","bind_property","bind_focused","bind_window_scroll","is_scrolling_x","scrolling","timeout","clear","latest_value","bind_window_size","trusted","self","stopPropagation","once","stopImmediatePropagation","preventDefault","init","changed","observe_all","fns","reactive_import","bubble_event","add_legacy_event_listener","event_callback","update_legacy_props","$$new_props","update_prop","update_pre_prop","rest_props_handler","rest_props","exclude","legacy_rest_props_handler","legacy_rest_props","spread_props_handler","spread_props","bindable","fallback_value","fallback_dirty","get_fallback","setter","is_store_sub","e.props_invalid_value","getter","legacy_parent","mutation","overridden","validate_binding","get_object","get_property","warned","w.binding_property_non_reactive","createClassComponent","Svelte4Component","#events","#instance","add_source","cb","SvelteElement","$$componentCtor","$$slots","shadow_root_init","create_slot","existing_slots","get_custom_elements_slots","get_custom_element_value","attribute_value","_oldValue","newValue","attribute_name","props_definition","create_custom_element","slots","exports","extend","Class","log_if_contains_state","objects","has_state","transformed","w.console_log_state","MemoryBackend","#map","shardId","LocalStorageBackend","#prefix","raw","out","PERSISTENT_ZONES","PERMISSION_STATE_MANAGE","backends","flushScheduled","scheduleFlush","zone","createStateZones","schema","defaults","stored","$.user_effect","__setBackend","backend","peekZone","clearZone","PUBLIC_VERSION","FOCUSABLE_SELECTOR","createFocusTrap","container","previouslyFocused","getFocusables","onKeydown","focusables","box","handleFrameClick","ev","div","div_1","Content_1","$$anchor","$.spread_props","$$value","$.delegated","registerLayerRoot","layer","el","unregisterLayerRoot","getLayerRoot","registeredApps","activeApp","$.proxy","breadcrumbApp","getBreadcrumbAppId","registerApp","app","listRegisteredApps","getActiveApp","getRegisteredApp","dismissables","appNavEntries","lifecycleHandlers","setLifecycleHandlers","handlers","pushNavEntry","idx","registerDismissable","dismiss","clearAppNavEntries","dispatchBack","dispatchForward","escapeInstalled","backdrop","BACKDROP_OPACITY","syncBackdrop","topHost","onDocumentKeydown","ensureEscapeListener","removeEscapeListenerIfIdle","removeEntry","openModal","Content","host","dismissReg","originalClose","frame","ModalFrame","closeAll","modalManager","top","$.state","left","rect","margin","vw","vh","flipped","$.set","$.get","anchorRect","onDocumentPointerDown","installDismissListeners","removeDismissListeners","showPopup","PopupFrame","closeCurrent","popupManager","span","span_1","$$args","ensureContainer","notify","message","level","ToastItem","toastManager","DEFAULT_SLOT_MIN","computeMinSize","CASCADE_STEP","CASCADE_BASE","cascadePosition","existing","bounds","floatIdCounter","generateFloatId","isEmptyContent","findEnclosingOverlayHost","fallbackFloats","boundFloats","getTreeBounds","bindFloatStore","floats","getBounds","unbindFloatStore","activeStore","parentHosts","getFloatParentHost","floatSlotCounter","mintFloatSlotId","viewId","DEFAULT_SIZE","maxSize","openFloat","slotId","tab","computedMin","size","closeFloat","floatId","listFloats","focusFloat","floatManager","boundBlob","bindPresetBlob","blob","unbindPresetBlob","requireBlob","listPresets","activePreset","switchPreset","presetManager","points","emit","pointId","register","map","disposed","m","list","listPoints","onChange","TEXT_EXTENSIONS","inferKind","builtIns","registerBuiltInRenderer","pickRenderer","contributed","reference","isDualMode","$.derived","leftBranch","rightBranch","lineDiff","al","bl","max","right","diff","diffCount","$.first_child","div_2","header","pre","code","div_3","header_1","pre_1","code_1","details","summary","pre_2","code_2","$.index","root_2","$.set_text","text_5","classes","classes_1","text_2","text_4","div_4","root_3","div_5","root_4","text_6","div_6","button","root_5","classes_2","text_7","pre_3","root_6","code_3","$$render","consequent_1","consequent","alternate","formatSize","relTime","at","ul","li","root_1","$.sibling","$.template_effect","text_1","$0","$1","OVERSIZED_TEXT_LIMIT_BYTES","isOversized","sizeBytes","textDiffRenderer","TextDiffRenderer","metaOnlyRenderer","MetaOnlyRenderer","registered","ensureBuiltInRenderersRegistered","h3","button_1","button_2","selectedOrigin","renderer","rendererContainer","currentUnmount","rendererProps","origin","itemStates","it","aside","consequent_2","span_2","consequent_3","section","node_1","root_8","span_3","$.set_checked","consequent_4","footer","button_3","button_4","button_5","defaultMostRecentBy","pickMostRecent","cmp","err","startsInPrompt","selections","pick","currentIndex","finalize","choices","skippedIds","cancel","overwriteMostRecent","resolveIndividually","itemId","nextSkipped","toggleSkip","navigate","nextIndex","PromptView","DetailView","CONFLICT_RENDERER_POINT","ConflictPermissionError","ConflictSessionOrphanedError","getContributedRenderers","listContributions","resolvePrimitive","settle","title","mostRecentBy","requirePrompt","ConflictModal","ownShardHandle","h","crossShardHandle","extractExtension","resolveDocuments","callerShardId","statuses","extension","outcome","resolvedList","failedList","choice","after","conflictsApi","COLOR_PICKER_POINT","nativeFallback","pickColor","colorApi","__setBindingsZone","z","loadUserBindings","appId","saveUserBinding","actionId","shortcut","forApp","ACTIONS_POINT_ID","liveIds","registerAction","ownerShardId","dispose","contributionsRegister","listActions","contributionsList","onActionsChange","contributionsOnChange","resolveLabel","MOD_ORDER","MOD_ALIASES","PURE_MODIFIER_KEYS","titleCaseNamedKey","canonicalizeShortcut","rawParts","modifiers","lower","resolveMod","platform","eventToShortcut","mods","detectPlatform","effectiveShortcut","overrides","effectiveShortcutWithSource","scopeToTier","scope","normalizeScope","scopeBadge","innermostActiveScope","scopes","buckets","tier","TIER_ORDER","bucket","isScopeActive","scopeEquals","scopeToString","parseScopeString","rest","buildTierIndex","isTextInput","ce","dispatchKeydown","env","actionById","getSelection","makeSelectionApi","sel","clearSelectionForShard","clearSelectionUnconditional","views","viewRegistrationListeners","__addViewRegistrationListener","registerView","factory","getView","unregisterView","verbs","registerVerb","verb","getVerb","unregisterVerb","listVerbs","findTabBySlotId","walk","hit","locateSlotIn","tree","containsSlot","removeTabBySlotId","located","tabsNode","tabIndex","insertTabIntoTabs","clamped","moveTabWithinTabs","fromIndex","postRemovalToIndex","makeSplitWithNewTab","side","newGroup","snapshotNode","splitNodeAtPath","nodeAtPath","isPathFixedByParent","replacement","rootAsRecord","parentPath","indexInParent","cur","cleanupTree","cleanupPass","recursed","survivor","pool","pendingDestroy","onViewRegistered","dirtyState","activeLayout","closableState","onResize","createHost","meta","cancelled","acquireSlotHost","releaseSlotHost","fromWrapper","getSlotHandle","override","handleOverrides","isSlotDirty","isSlotClosable","isLayoutNode","x","isLayoutTree","wrapNodeAsTree","canonicalizePreset","variants","normalizeInitialLayout","collectSlotRefs","collectTreeSlotRefs","HOME_LAYOUT","HOME_TREE","appEntry","activeRoot","adaptLegacyBlob","currentTree","preset","attachApp","canonical","defaultBlob","adapted","acquireAppSlotHolds","refs","resetActivePresetToDefault","targetName","freshTree","detachApp","switchToHome","switchToApp","activeTree","presetName","getActiveRoot","layoutStore","activeAppId","activeAppRequiredShards","autostartShards","mountedViewIds","focusedViewId","userBindings","activeChangeListeners","notifyActiveChange","onActiveChange","__notifyActiveChange","setActiveApp","requiredShards","syncMountedViewIdsFromLayout","ids","setFocusedViewId","setUserBindings","bindings","getLiveDispatcherState","addAutostartShard","flatItems","cursor","nextEnabled","dir","q","onItemClick","$.each","sIdx","globalIdx","$.set_attribute","$.event","sections","ActionPanel","evalFlag","toMenuItem","matchesAnchor","buildContextMenuModel","byTier","winning","buildContextMenuSubmenu","parentId","scoreMatch","L","Q","score","runLen","prevMatchIdx","prefixBonus","runBonus","rankPaletteEntries","candidates","recency","ranked","recencyIdx","ra","prefill","buildPaletteCandidates","filterParent","attached","viewIdOfEl","resolveAnchor","scopeHost","parsed","runAction","chainedDispatch","onFocusIn","onFocusOut","_ev","isNativeOptOut","openContextSubmenu","sub","subItems","cid","onContextMenu","model","shell","ContextMenu","attachGlobalListeners","openContextMenu","RECENCY_CAP","recordUse","openPalette","CommandPalette","listActiveFromEntries","shellActions","listenersOpenContextMenu","listenersOpenPalette","offState","onActiveChangeState","offRegistry","compositeKey","tenantId","keyPrefix","IDB_NAME","IDB_STORE","IDB_VERSION","IndexedDBDocumentBackend","#dbPromise","#db","req","db","#tx","mode","oldPath","newPath","oldKey","newKey","tx","getOld","getNew","renamed","shards","slash","HttpDocumentBackend","#baseUrl","#apiKey","baseUrl","apiKey","url","headers","#authHeaders","DocumentChangeEmitter","change","documentChanges","DEFAULT_DEBOUNCE_MS","createDocumentHandle","controllers","unsubscribers","matchesExtensions","ext","emitChange","all","existed","ctrl","AutosaveControllerImpl","flushes","#handle","#path","#debounceMs","#timer","#dirty","#disposed","debounceMs","#scheduleFlush","#clearTimer","DEFAULT_SCOPE","scopeId","getActiveScopeId","getTenantId","getDocumentBackend","__setActiveScope","__setDocumentBackend","PERMISSION_SYNC_PEER","PERMISSION_SYNC_POLICY","currentUser","currentSession","guest","serverUrl","authConfig","initFromBoot","config","login","username","password","displayName","logout","setLocalOwner","isLocalOwner","isAdmin","isAuthenticated","isGuest","getUser","getAuthHeader","__setEnvServerUrl","fetchEnvState","putEnvState","auth","serverInstallPackage","manifest","clientBundle","serverBundle","form","serverUninstallPackage","fetchServerPackages","listZoneEntries","peekZoneEntry","clearZoneEntry","clearAllZoneEntries","createZoneManager","PERMISSION_DOCUMENTS_BROWSE","PERMISSION_DOCUMENTS_READ","PERMISSION_DOCUMENTS_WRITE","createBrowseCapability","capability","PERMISSION_KEYS_MINT","ScopeEscalationError","ConsentDeniedError","registerConsentListener","requestConsent","requestId","resolveConsent","approved","handlersByShard","recentByShard","DEDUP_TTL_MS","markRecent","keyId","isRecent","subscribe","star","startServerSideStream","es","msg","createShardKeysApi","shardPermissions","assertScopesSubset","ticketRes","ticket","mintRes","registeredShards","activeShards","erroredShards","registerShard","shard","deactivateShard","activateShard","envState","contributions","contributionsListPoints","off","prefixed","fwRegisterVerb","patch","$.snapshot","checkIsAdmin","shellOpenContextMenu","shellOpenPalette","view","merged","fwUnregisterVerb","getShardContext","listStandaloneViews","sessionState","setActiveProjectId","previousActive","lastAppState","readLastApp","writeLastApp","clearLastApp","appContexts","resolveLaunchScope","getOrCreateAppContext","launchApp","unloadApp","shardCtx","unregisterApp","returnToHome","inspectActiveLayout","spliceIntoActiveLayout","findFirstTabsNode","focusTab","focusTabWhere","focusTabInFloats","focusView","pred","floatEntry","collapseChild","splitPath","childIndex","setCollapsed","expandChild","split","closeTab","closeFloatTab","closable","tabs","popoutView","dockFloat","ok","dockIntoActiveLayout","findFirstSlotPath","slotPath","locateSlot","RegistryValidationError","validateRegistryIndex","validatePackageEntry","requireString","requireOneOf","authorPath","author","versions","validatePackageVersion","hasBundleUrl","hasIntegrity","hasServerBundleUrl","requires","validateRequiredDependency","field","SUPPORTED_ALGORITHMS","parseSri","integrity","dashIndex","algorithm","algorithmToWebCrypto","alg","bufferToBase64","buffer","bytes","binary","verifyIntegrity","expectedHash","webCryptoAlg","digest","actualHash","fetchRegistries","urls","results","response","fetchBundle","sourceRegistry","fetchServerBundle","buildPackageMeta","VERSION","STORAGE_KEY","appliedKeys","setTokenOverrides","newKeys","clearTokenOverrides","getTokenOverrides","hydrateTokenOverrides","iconsUrl","ICON_SPRITE_KEY","provideIcons","spriteUrl","getIconSprite","variant","disabled","contextSprite","isDirectUrl","iconHref","coreSpriteUrl","autoPending","iconOnly","handleClick","svg_1","use","open","toggle","$.set_class","invalid","required","showError","helperText","label_1","node_2","span_4","span_5","rows","resize","textarea","clamp","min","applyStep","base","step","bump","holdTimer","holdInterval","bumping","startHold","elapsed","stopHold","node_3","$.set_value","activeOptions","nextValue","prevValue","firstValue","lastValue","$.prop","onKey","opt","toggleSingle","candidate","toggleMultiple","multiple","isActive","onClick","$.snippet","valueToPercent","showValue","orientation","pct","styles_1","output","styles_2","$.set_style","constrainPair","which","lo","hi","lowPct","highPct","setLow","setHigh","input_1","showValues","bind_get","Slider","trigger","extractValue","files","buttonLabel","onPick","display","SEARCH_THRESHOLD","shouldShowSearch","filterOptions","matchTypeAhead","resolveValueLabel","toggleMulti","showSearch","initialActiveIdx","activeIdx","listEl","searchEl","typeAheadBuffer","typeAheadTimer","filtered","scrollActiveIntoView","isSelected","onListKey","placeholder","nativeRef","isOpen","displayLabel","onPopupClose","popupHandle","Listbox","origClose","onTriggerKey","onNativeChange","filterItems","loading","emptyText","searchThreshold","totalCount","selectedCount","toggleId","p_1","p_2","root_7","text_3","consequent_5","p_3","FRAMEWORK_APP_IDS","handleChange","PickerList","usersAdminState","inflight","refreshAdminUsers","u","capabilities","FRAMEWORK_SHARD_IDS","sh3Img","P5_CDN","p5Promise","loadP5","CHARS","ASCII_W","ASCII_H","CELL_W","CELL_H","DISPLAY_H","NATIVE_W","NATIVE_H","SCALE","p5inst","buildSketch","accentColor","gfx","src","ready","y","P5","h1","jsonFetch","projectsApi","qs","cancelBtn","busy","wipeData","handleConfirm","handleCancel","project","isEdit","me","description","members","userId","appAllowlist","saving","refreshProjects","DeleteProjectDialog","h2","label_2","UserPicker","label_3","AppPicker","projectsState","PROJECTS_MANAGE_VIEW","pendingTarget","consumePendingTarget","openProjectManage","projectsShard","_mountCtx","ProjectManage","manageUnregisters","currentIds","live","visible","activeId","elevated","selectProject","editProject","ICON_IDS","zoneState","__bindZone","__unbindZone","isEmpty","getAppearance","setAppearance","__resetForTests","manifestIcon","icon","color","pickerOpen","hasOverride","effectiveLabel","effectiveIcon","trimmed","IconPicker","ColorSwatch","readSelection","runCustomize","_ctx","ref","AppAppearanceModal","appearanceShard","customize","homeSelection","openAppContextMenu","filter","apps","activeProject","matches","needle","inAllowlist","userApps","adminApps","totalVisible","ShellTitle","ProjectsSection","appearance","section_1","use_1","loadError","confirmingId","refresh","revoke","formatDate","iso","subscribeBus","row","alternate_1","confirmLabel","cancelLabel","confirmTone","RESERVED","createShimUrl","globalKey","mod","names","safe","reserved","g","api","svelte","svelteInternalClient","shimUrls","BARE_IMPORT_RE","rewriteBareImports","match","_quote","specifier","shim","loadBundleModule","rewritten","isShard","isApp","DB_NAME","DB_VERSION","BUNDLES_STORE","META_STORE","openDb","request","objectStore","savePackage","bundle","loadBundle","loadMeta","listInstalled","removePackage","registerLoadedBundle","loaded","PERMISSION_DESCRIPTIONS","describePermission","extractBundlePermissions","perms","installPackage","record","hotLoaded","uninstallPackage","listInstalledPackages","loadInstalledPackages","packages","pkg","contract","permissions","added","fragment_3","ul_1","fragment_5","li_1","root_10","div_7","ul_2","fragment_6","li_2","root_12","div_8","div_9","text_8","text_9","alternate_2","displayPackageType","displayPackageTypeLabel","packageMatchesTypeFilter","search","typeFilter","installingIds","updatingIds","installError","newRegistryUrl","installModal","updateModal","storeContext","handleAddRegistry","handleRemoveRegistry","isInstalled","hasContractMismatch","hasUpdate","installedVersion","missingShards","installed","known","handleUpdate","confirmUpdate","cancelUpdate","handleInstall","confirmInstall","ctxModal","serverResult","cancelInstall","handleRefresh","option_1","option_2","installing","updatable","updating","missing","displayType","img","div_10","div_11","div_12","root_9","text_10","div_13","node_5","root_11","div_14","span_6","root_13","consequent_8","consequent_6","consequent_7","div_15","root_14","consequent_9","consequent_10","alternate_3","consequent_11","PermissionConfirmModal","consequent_12","consequent_13","findInCatalog","findInstalled","installVerb","uninstallVerb","updateVerb","fromVersion","confirmReject","finalVersion","appinfoVerb","catalogEntry","isNewerVersion","available","av","bv","pickVersion","requested","found","diffPermissions","oldPerms","newPerms","oldSet","newSet","storeShard","recomputeUpdatable","refreshCatalog","refreshInstalled","serverPkgs","addRegistry","registries","removeRegistry","updatePackage","confirmPermissionChange","installedRecord","picked","localMeta","oldBundle","oldRecord","rollbackErr","installerUninstallPackage","browseFactory","_context","StoreView","openPermissionConfirmModal","toVersion","confirm","strong","computeAppActionDisabled","computeAppActionLabelSuffix","findApp","isBuiltin","gateFor","runCheckUpdate","checking","AppUpdateAvailableModal","runUninstall","UninstallAppDialog","registerAppActions","infoLabel","updateLabel","uninstallLabel","isDisabledForCurrent","disposers","sh3coreShard","zones","_dispatchCtx","__vitePreload","ConfirmDialog","ShellHome","keysFactory","KeysAndPeers","launcherUnregisters","DEFAULT_CAP","nextId","mkId","Scrollback","cap","full","ANSI_RE","C_1","TextEntry","PromptEntry","StatusEntry","RichEntry","draft","historyIndex","savedDraft","submit","navHistoryUp","navHistoryDown","onKeyDown","BACKOFFS","SessionClient","#connected","#cwd","hello","queued","VerbRegistry","space","TenantFsClient","#get","route","ShellModeRegistry","#modes","role","DEV_MODE","USER_MODE","registerBuiltinModes","reg","readLastMode","writeLastMode","modeId","resolveInitialMode","persisted","makeDispatch","dispatch","resolution","firstToken","computeRelocate","fs","slotProps","Slot","Slot_1","ToolbarSlotRegistry","#slots","modes","scrollback","resolver","modeRegistry","setMode","session","locked","focusLocked","targetShard","toolbarRegistry","ModeSlot","FocusLockSlot","TargetShardSlot","getActiveViewId","getFocusedShardId","colon","focused","autoRelocate","isFocusLocked","handleServerMessage","Toolbar","ScrollbackView","InputLine","table","tbody","tr","td","td_1","makeHelpVerb","HelpTable","clearVerb","ol","historyVerb","HistoryList","appsVerb","AppsTable","appVerb","AppCard","td_2","shardsVerb","ShardsTable","td_3","viewsVerb","standalones","ViewsTable","openVerb","popoutVerb","dockVerb","closeVerb","zonesVerb","ZonesTable","zoneVerb","zoneName","ZoneTree","joinRel","cwd","normalizeRel","pwdVerb","rel","cdVerb","whoamiVerb","$$item","$$array","envVerb","EnvTable","lsVerb","catVerb","resolvePlatform","TauriStoreBackend","workspace","user","wipeUserData","LazyStore","resetVerb","registerV1Verbs","collectTabEntries","makeShellApi","standalone","locateSlotInActiveLayout","_shardId","_zoneName","shellShard","wsUrl","Terminal","storeApp","users","showCreate","newUsername","newDisplayName","newPassword","newRole","createError","editingId","editDisplayName","editRole","editPassword","fetchUsers","createUser","startEdit","saveEdit","deleteUser","input_2","form_1","input_3","input_4","select_1","option_3","settings","fetchSettings","SNAP_POINTS","restarting","restartError","cacheMaxAge","loadedMaxAge","savingCache","cacheError","humanized","humanize","sec","fetchVersion","age","saveCache","restart","newLabel","justCreated","fetchKeys","createKey","created","revokeKey","adminShard","usersFactory","UsersView","authFactory","AuthSettingsView","systemFactory","SystemView","ApiKeysView","adminApp","FLAG_KEY","OLD_PREFIX","NEW_PREFIX","OLD_THEME_KEY","NEW_THEME_KEY","runShellRenameMigration","storage","theme","installWebEmitter","registerShardInternal","createWorkspaceZoneAdapter","bootstrap","migrateLegacyWorkspaceKeys","exShards","frameworkShards","frameworkApps","lastId","MIN_PX","COLLAPSED_PX","modeOf","isCollapsed","isFixed","isHandleFrozen","canCollapse","flexFor","drag","beginDrag","handleIndex","containerPx","totalFr","pxUsed","moveDrag","deltaPx","modeA","modeB","frPerPx","minFr","deltaFr","maxDelta","minDelta","endDrag","classes_3","d_1","classes_4","computeIndicatorRect","insertIndex","tabEls","stripEl","stripRect","els","leftViewport","handleClose","hoverInsertIndex","onTabPointerDown","onStripPointerMove","rects","onStripPointerLeave","$.bind_this","_label","hasFactory","currentSlotId","wrapperEl","ro","em","dragState","clickSuppressedUntil","suppressNextClick","DRAG_THRESHOLD_PX","pendingStartX","pendingStartY","beginTabDrag","sourceRoot","tabElement","installGlobalListeners","onPointerMove","onPointerUp","onPointerCancel","removeGlobalListeners","dx","dy","_e","rootNode","autoCloseEmptyFloat","targetRoot","srcIdx","setDropTarget","clearDropTarget","zoneEl","hoveredSide","parentFixed","quadrantFor","cx","cy","nx","ny","onMove","onLeave","rootRef","makeController","pointerX","pointerY","tabRects","mid","asSplit","asTabs","asSlot","tabClosable","tabDirty","handleTabClose","mountEmptyRenderer","onEmptyTabsDrop","onEmptyTabsLeave","splitPane","$.noop","Self","ResizableSplitter","tabBody","SlotContainer","SlotDropZone","node_6","TabbedPanel","$$node","$$action_arg","node_8","node_9","registry","listenerAttached","ensureListener","teardownListenerIfEmpty","registerDismissableFrame","unregisterDismissableFrame","dragging","dragOffset","frameEl","onHeaderPointerDown","onHeaderPointerMove","onHeaderPointerUp","onFrameClick","onClose","LayoutRenderer","FloatFrame","showSignIn","handleLogin","approve","deny","dl","dd","dd_1","dd_2","fragment_1","dd_3","fragment_2","breadcrumbId","projectId","activeLabel","breadcrumbLabel","projectLabel","reopenApp","exitProject","reenterProjectHome","DEFAULT_MENU_CONTAINERS","resolveMenuContainers","declared","indexed","ao","bo","resolveMenuItems","containerId","resolveSubmenuItems","buttonEl","makeSections","order","dispatchLeaf","openSubmenu","subCmp","openPopup","iconPosition","declaredMenus","containers","containerItems","MenuButton","authenticated","onHome","overlayLayers","overlayRoots","BrandSlot","MenuBar","GuestBanner","node_4","main","FloatLayer","DragPreview","ConsentDialog","node_7","handleRegister","switchMode","createShell","sUrl","bootConfig","showSignInWall","bootstrapConfig","Shell","SignInWall","discoveredPackages"],"ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,100,101],"sources":["../../../../node_modules/svelte/src/constants.js","../../../../node_modules/esm-env/false.js","../../../../node_modules/svelte/src/internal/shared/utils.js","../../../../node_modules/svelte/src/internal/client/constants.js","../../../../node_modules/svelte/src/internal/shared/errors.js","../../../../node_modules/svelte/src/internal/client/errors.js","../../../../node_modules/svelte/src/internal/client/warnings.js","../../../../node_modules/svelte/src/internal/client/dom/hydration.js","../../../../node_modules/svelte/src/internal/client/reactivity/equality.js","../../../../node_modules/svelte/src/internal/flags/index.js","../../../../node_modules/svelte/src/internal/shared/warnings.js","../../../../node_modules/svelte/src/internal/shared/clone.js","../../../../node_modules/svelte/src/internal/client/dev/tracing.js","../../../../node_modules/svelte/src/internal/shared/dev.js","../../../../node_modules/svelte/src/internal/client/context.js","../../../../node_modules/svelte/src/internal/client/dom/task.js","../../../../node_modules/svelte/src/internal/client/error-handling.js","../../../../node_modules/svelte/src/internal/client/reactivity/status.js","../../../../node_modules/svelte/src/internal/client/reactivity/utils.js","../../../../node_modules/svelte/src/store/utils.js","../../../../node_modules/svelte/src/store/shared/index.js","../../../../node_modules/svelte/src/internal/client/reactivity/store.js","../../../../node_modules/svelte/src/internal/client/reactivity/batch.js","../../../../node_modules/svelte/src/reactivity/create-subscriber.js","../../../../node_modules/svelte/src/internal/client/dom/blocks/boundary.js","../../../../node_modules/svelte/src/internal/client/reactivity/async.js","../../../../node_modules/svelte/src/internal/client/reactivity/deriveds.js","../../../../node_modules/svelte/src/internal/client/reactivity/sources.js","../../../../node_modules/svelte/src/internal/client/proxy.js","../../../../node_modules/svelte/src/internal/client/dev/equality.js","../../../../node_modules/svelte/src/internal/client/dom/operations.js","../../../../node_modules/svelte/src/internal/client/dom/elements/misc.js","../../../../node_modules/svelte/src/internal/client/dom/elements/bindings/shared.js","../../../../node_modules/svelte/src/internal/client/reactivity/effects.js","../../../../node_modules/svelte/src/internal/client/legacy.js","../../../../node_modules/svelte/src/internal/client/runtime.js","../../../../node_modules/svelte/src/internal/client/hydratable.js","../../../../node_modules/svelte/src/internal/client/dom/elements/events.js","../../../../node_modules/svelte/src/internal/client/dom/reconciler.js","../../../../node_modules/svelte/src/internal/client/dom/template.js","../../../../node_modules/svelte/src/utils.js","../../../../node_modules/svelte/src/internal/client/render.js","../../../../node_modules/svelte/src/internal/shared/validate.js","../../../../node_modules/svelte/src/internal/client/dom/blocks/branches.js","../../../../node_modules/svelte/src/internal/client/dom/blocks/snippet.js","../../../../node_modules/svelte/src/index-client.js","../../../../node_modules/svelte/src/attachments/index.js","../../../../node_modules/svelte/src/internal/client/dev/assign.js","../../../../node_modules/svelte/src/internal/client/dev/css.js","../../../../node_modules/svelte/src/internal/client/dev/elements.js","../../../../node_modules/svelte/src/internal/client/dev/hmr.js","../../../../node_modules/svelte/src/internal/client/dev/ownership.js","../../../../node_modules/svelte/src/internal/client/dev/legacy.js","../../../../node_modules/svelte/src/internal/client/dev/inspect.js","../../../../node_modules/svelte/src/internal/client/dom/blocks/async.js","../../../../node_modules/svelte/src/internal/client/dev/validation.js","../../../../node_modules/svelte/src/internal/client/dom/blocks/await.js","../../../../node_modules/svelte/src/internal/client/dom/blocks/if.js","../../../../node_modules/svelte/src/internal/client/dom/blocks/key.js","../../../../node_modules/svelte/src/internal/client/dom/blocks/css-props.js","../../../../node_modules/svelte/src/internal/client/dom/blocks/each.js","../../../../node_modules/svelte/src/internal/client/dom/blocks/html.js","../../../../node_modules/svelte/src/internal/client/dom/blocks/slot.js","../../../../node_modules/svelte/src/internal/client/dom/blocks/svelte-component.js","../../../../node_modules/svelte/src/internal/client/timing.js","../../../../node_modules/svelte/src/internal/client/loop.js","../../../../node_modules/svelte/src/internal/client/dom/elements/transitions.js","../../../../node_modules/svelte/src/internal/client/dom/blocks/svelte-element.js","../../../../node_modules/svelte/src/internal/client/dom/blocks/svelte-head.js","../../../../node_modules/svelte/src/internal/client/dom/css.js","../../../../node_modules/svelte/src/internal/client/dom/elements/actions.js","../../../../node_modules/svelte/src/internal/client/dom/elements/attachments.js","../../../../node_modules/svelte/src/escaping.js","../../../../node_modules/clsx/dist/clsx.mjs","../../../../node_modules/svelte/src/internal/shared/attributes.js","../../../../node_modules/svelte/src/internal/client/dom/elements/class.js","../../../../node_modules/svelte/src/internal/client/dom/elements/style.js","../../../../node_modules/svelte/src/internal/client/dom/elements/bindings/select.js","../../../../node_modules/svelte/src/internal/client/dom/elements/attributes.js","../../../../node_modules/svelte/src/internal/client/dom/elements/customizable-select.js","../../../../node_modules/svelte/src/internal/client/dom/elements/bindings/document.js","../../../../node_modules/svelte/src/internal/client/dom/elements/bindings/input.js","../../../../node_modules/svelte/src/internal/client/dom/elements/bindings/media.js","../../../../node_modules/svelte/src/internal/client/dom/elements/bindings/navigator.js","../../../../node_modules/svelte/src/internal/client/dom/elements/bindings/props.js","../../../../node_modules/svelte/src/internal/client/dom/elements/bindings/size.js","../../../../node_modules/svelte/src/internal/client/dom/elements/bindings/this.js","../../../../node_modules/svelte/src/internal/client/dom/elements/bindings/universal.js","../../../../node_modules/svelte/src/internal/client/dom/elements/bindings/window.js","../../../../node_modules/svelte/src/internal/client/dom/legacy/event-modifiers.js","../../../../node_modules/svelte/src/internal/client/dom/legacy/lifecycle.js","../../../../node_modules/svelte/src/internal/client/dom/legacy/misc.js","../../../../node_modules/svelte/src/internal/client/reactivity/props.js","../../../../node_modules/svelte/src/internal/client/validate.js","../../../../node_modules/svelte/src/legacy/legacy-client.js","../../../../node_modules/svelte/src/internal/client/dom/elements/custom-element.js","../../../../node_modules/svelte/src/internal/client/dev/console-log.js","../../../sh3-core/src/state/backends.ts","../../../sh3-core/src/state/types.ts","../../../sh3-core/src/state/zones.svelte.ts","../../../../node_modules/svelte/src/version.js","../../../../node_modules/svelte/src/internal/disclose-version.js","../../../sh3-core/src/overlays/focusTrap.ts","../../../sh3-core/src/overlays/ModalFrame.svelte","../../../sh3-core/src/overlays/roots.ts","../../../sh3-core/src/apps/registry.svelte.ts","../../../sh3-core/src/navigation/back-stack.ts","../../../sh3-core/src/overlays/modal.ts","../../../sh3-core/src/overlays/PopupFrame.svelte","../../../sh3-core/src/overlays/popup.ts","../../../sh3-core/src/overlays/ToastItem.svelte","../../../sh3-core/src/overlays/toast.ts","../../../sh3-core/src/layout/floats.ts","../../../sh3-core/src/overlays/parentHost.ts","../../../sh3-core/src/overlays/float.ts","../../../sh3-core/src/overlays/presets.ts","../../../sh3-core/src/contributions/registry.ts","../../../sh3-core/src/conflicts/renderer-registry.ts","../../../sh3-core/src/conflicts/renderers/TextDiffRenderer.svelte","../../../sh3-core/src/conflicts/renderers/MetaOnlyRenderer.svelte","../../../sh3-core/src/conflicts/renderers/index.ts","../../../sh3-core/src/conflicts/PromptView.svelte","../../../sh3-core/src/conflicts/DetailView.svelte","../../../sh3-core/src/conflicts/most-recent.ts","../../../sh3-core/src/conflicts/ConflictModal.svelte","../../../sh3-core/src/conflicts/api.ts","../../../sh3-core/src/conflicts/resolve-primitive.ts","../../../sh3-core/src/conflicts/adapter-documents.ts","../../../sh3-core/src/conflicts/shell-api.ts","../../../sh3-core/src/color/api.ts","../../../sh3-core/src/color/primitive.ts","../../../sh3-core/src/color/shell-api.ts","../../../sh3-core/src/actions/bindings-store.ts","../../../sh3-core/src/actions/registry.ts","../../../sh3-core/src/actions/types.ts","../../../sh3-core/src/actions/shortcuts.ts","../../../sh3-core/src/actions/bindings.ts","../../../sh3-core/src/actions/scope-helpers.ts","../../../sh3-core/src/actions/dispatcher.svelte.ts","../../../sh3-core/src/actions/selection.svelte.ts","../../../sh3-core/src/shards/registry.ts","../../../sh3-core/src/layout/ops.ts","../../../sh3-core/src/layout/slotHostPool.svelte.ts","../../../sh3-core/src/layout/presets.ts","../../../sh3-core/src/layout/tree-walk.ts","../../../sh3-core/src/layout/store.svelte.ts","../../../sh3-core/src/actions/state.svelte.ts","../../../sh3-core/src/actions/ActionPanel.svelte","../../../sh3-core/src/actions/ContextMenu.svelte","../../../sh3-core/src/actions/contextMenuModel.ts","../../../sh3-core/src/actions/palette-scorer.ts","../../../sh3-core/src/actions/CommandPalette.svelte","../../../sh3-core/src/actions/paletteModel.ts","../../../sh3-core/src/actions/listeners.ts","../../../sh3-core/src/actions/listActive.ts","../../../sh3-core/src/shellRuntime.svelte.ts","../../../sh3-core/src/documents/backends.ts","../../../sh3-core/src/documents/http-backend.ts","../../../sh3-core/src/documents/notifications.ts","../../../sh3-core/src/documents/handle.ts","../../../sh3-core/src/documents/config.ts","../../../sh3-core/src/documents/sync-types.ts","../../../sh3-core/src/auth/auth.svelte.ts","../../../sh3-core/src/env/client.ts","../../../sh3-core/src/state/manage.ts","../../../sh3-core/src/documents/types.ts","../../../sh3-core/src/documents/browse.ts","../../../sh3-core/src/keys/types.ts","../../../sh3-core/src/keys/consent.svelte.ts","../../../sh3-core/src/keys/revocation-bus.svelte.ts","../../../sh3-core/src/keys/client.ts","../../../sh3-core/src/shards/activate.svelte.ts","../../../sh3-core/src/projects/session-state.svelte.ts","../../../sh3-core/src/apps/lifecycle.ts","../../../sh3-core/src/layout/inspection.ts","../../../sh3-core/src/registry/schema.ts","../../../sh3-core/src/registry/integrity.ts","../../../sh3-core/src/registry/client.ts","../../../sh3-core/src/version.ts","../../../sh3-core/src/theme.ts","../../../sh3-core/src/assets/icons.svg","../../../sh3-core/src/primitives/icon-context.ts","../../../sh3-core/src/primitives/Button.svelte","../../../sh3-core/src/primitives/Collapsible.svelte","../../../sh3-core/src/primitives/widgets/Field.svelte","../../../sh3-core/src/primitives/widgets/Textarea.svelte","../../../sh3-core/src/primitives/widgets/NumberInput.ts","../../../sh3-core/src/primitives/widgets/NumberInput.svelte","../../../sh3-core/src/primitives/widgets/Segmented.ts","../../../sh3-core/src/primitives/widgets/Segmented.svelte","../../../sh3-core/src/primitives/widgets/IconToggleGroup.ts","../../../sh3-core/src/primitives/widgets/IconToggleGroup.svelte","../../../sh3-core/src/primitives/widgets/Slider.ts","../../../sh3-core/src/primitives/widgets/Slider.svelte","../../../sh3-core/src/primitives/widgets/RangeSlider.ts","../../../sh3-core/src/primitives/widgets/RangeSlider.svelte","../../../sh3-core/src/primitives/widgets/SliderGroup.svelte","../../../sh3-core/src/primitives/widgets/ColorSwatch.svelte","../../../sh3-core/src/primitives/widgets/FilePicker.ts","../../../sh3-core/src/primitives/widgets/FilePicker.svelte","../../../sh3-core/src/primitives/widgets/Select.ts","../../../sh3-core/src/primitives/widgets/_select-listbox.svelte","../../../sh3-core/src/primitives/widgets/Select.svelte","../../../sh3-core/src/primitives/widgets/PickerList.ts","../../../sh3-core/src/primitives/widgets/PickerList.svelte","../../../sh3-core/src/primitives/widgets/AppPicker.svelte","../../../sh3-core/src/auth/admin-users.svelte.ts","../../../sh3-core/src/primitives/widgets/UserPicker.svelte","../../../sh3-core/src/api.ts","../../../sh3-core/src/assets/SH3.png","../../../sh3-core/src/sh3core-shard/ShellTitle.svelte","../../../sh3-core/src/projects-shard/projectsApi.ts","../../../sh3-core/src/projects-shard/DeleteProjectDialog.svelte","../../../sh3-core/src/projects-shard/ProjectManage.svelte","../../../sh3-core/src/projects-shard/projectsShard.svelte.ts","../../../sh3-core/src/projects-shard/ProjectsSection.svelte","../../../sh3-core/src/assets/iconIds.generated.ts","../../../sh3-core/src/primitives/widgets/IconPicker.svelte","../../../sh3-core/src/app-appearance/appearanceState.svelte.ts","../../../sh3-core/src/app-appearance/AppAppearanceModal.svelte","../../../sh3-core/src/app-appearance/appearanceShard.svelte.ts","../../../sh3-core/src/sh3core-shard/ShellHome.svelte","../../../sh3-core/src/shell/views/KeysAndPeers.svelte","../../../sh3-core/src/overlays/ConfirmDialog.svelte","../../../sh3-core/src/registry/loader.ts","../../../sh3-core/src/registry/storage.ts","../../../sh3-core/src/registry/register.ts","../../../sh3-core/src/registry/permission-descriptions.ts","../../../sh3-core/src/registry/installer.ts","../../../sh3-core/src/contract.ts","../../../sh3-core/src/app/store/PermissionConfirmModal.svelte","../../../sh3-core/src/app/store/storeTypes.ts","../../../sh3-core/src/app/store/StoreView.svelte","../../../sh3-core/src/app/store/verbs.ts","../../../sh3-core/src/app/store/storeShard.svelte.ts","../../../sh3-core/src/app/store/permissionConfirm.ts","../../../sh3-core/src/app/store/AppUpdateAvailableModal.svelte","../../../sh3-core/src/app/store/UninstallAppDialog.svelte","../../../sh3-core/src/sh3core-shard/appActions.ts","../../../sh3-core/src/sh3core-shard/sh3coreShard.svelte.ts","../../../sh3-core/src/shell-shard/manifest.ts","../../../sh3-core/src/shell-shard/scrollback.svelte.ts","../../../sh3-core/src/shell-shard/entries/TextEntry.svelte","../../../sh3-core/src/shell-shard/entries/PromptEntry.svelte","../../../sh3-core/src/shell-shard/entries/StatusEntry.svelte","../../../sh3-core/src/shell-shard/entries/RichEntry.svelte","../../../sh3-core/src/shell-shard/ScrollbackView.svelte","../../../sh3-core/src/shell-shard/InputLine.svelte","../../../sh3-core/src/shell-shard/session-client.svelte.ts","../../../sh3-core/src/shell-shard/registry.ts","../../../sh3-core/src/shell-shard/tenant-fs-client.ts","../../../sh3-core/src/shell-shard/modes/registry.ts","../../../sh3-core/src/shell-shard/modes/builtin.ts","../../../sh3-core/src/shell-shard/modes/prefs.ts","../../../sh3-core/src/shell-shard/dispatch.ts","../../../sh3-core/src/shell-shard/auto-relocate.ts","../../../sh3-core/src/shell-shard/toolbar/Toolbar.svelte","../../../sh3-core/src/shell-shard/toolbar/slots.ts","../../../sh3-core/src/shell-shard/toolbar/slots/ModeSlot.svelte","../../../sh3-core/src/shell-shard/toolbar/slots/FocusLockSlot.svelte","../../../sh3-core/src/shell-shard/toolbar/slots/TargetShardSlot.svelte","../../../sh3-core/src/shell-shard/Terminal.svelte","../../../sh3-core/src/shell-shard/rich/HelpTable.svelte","../../../sh3-core/src/shell-shard/verbs/help.ts","../../../sh3-core/src/shell-shard/verbs/clear.ts","../../../sh3-core/src/shell-shard/rich/HistoryList.svelte","../../../sh3-core/src/shell-shard/verbs/history.ts","../../../sh3-core/src/shell-shard/rich/AppsTable.svelte","../../../sh3-core/src/shell-shard/rich/AppCard.svelte","../../../sh3-core/src/shell-shard/verbs/apps.ts","../../../sh3-core/src/shell-shard/rich/ShardsTable.svelte","../../../sh3-core/src/shell-shard/verbs/shards.ts","../../../sh3-core/src/shell-shard/rich/ViewsTable.svelte","../../../sh3-core/src/shell-shard/verbs/views.ts","../../../sh3-core/src/shell-shard/rich/ZonesTable.svelte","../../../sh3-core/src/shell-shard/rich/ZoneTree.svelte","../../../sh3-core/src/shell-shard/verbs/zones.ts","../../../sh3-core/src/shell-shard/verbs/session.ts","../../../sh3-core/src/shell-shard/rich/EnvTable.svelte","../../../sh3-core/src/shell-shard/verbs/env.ts","../../../sh3-core/src/shell-shard/verbs/ls.ts","../../../sh3-core/src/shell-shard/verbs/cat.ts","../../../sh3-core/src/platform/index.ts","../../../sh3-core/src/shell-shard/verbs/reset.ts","../../../sh3-core/src/shell-shard/verbs/index.ts","../../../sh3-core/src/shell-shard/shellShard.svelte.ts","../../../sh3-core/src/app/store/storeApp.ts","../../../sh3-core/src/app/admin/UsersView.svelte","../../../sh3-core/src/app/admin/AuthSettingsView.svelte","../../../sh3-core/src/app/admin/SystemView.svelte","../../../sh3-core/src/app/admin/ApiKeysView.svelte","../../../sh3-core/src/app/admin/adminShard.svelte.ts","../../../sh3-core/src/app/admin/adminApp.ts","../../../sh3-core/src/migrations/shell-rename.ts","../../../sh3-core/src/navigation/platform-web.ts","../../../sh3-core/src/host.ts","../../../sh3-core/src/primitives/ResizableSplitter.svelte","../../../sh3-core/src/primitives/TabbedPanel.svelte","../../../sh3-core/src/layout/SlotContainer.svelte","../../../sh3-core/src/layout/drag.svelte.ts","../../../sh3-core/src/layout/SlotDropZone.svelte","../../../sh3-core/src/layout/LayoutRenderer.svelte","../../../sh3-core/src/layout/DragPreview.svelte","../../../sh3-core/src/overlays/floatDismiss.ts","../../../sh3-core/src/overlays/FloatFrame.svelte","../../../sh3-core/src/overlays/FloatLayer.svelte","../../../sh3-core/src/auth/GuestBanner.svelte","../../../sh3-core/src/keys/ConsentDialog.svelte","../../../sh3-core/src/BrandSlot.svelte","../../../sh3-core/src/actions/defaultMenuContainers.ts","../../../sh3-core/src/actions/menuBarModel.ts","../../../sh3-core/src/actions/MenuButton.svelte","../../../sh3-core/src/actions/MenuBar.svelte","../../../sh3-core/src/Shell.svelte","../../../sh3-core/src/auth/SignInWall.svelte","../../../sh3-core/src/createShell.ts","../../frontend/main.ts"],"sourcesContent":["export const EACH_ITEM_REACTIVE = 1;\nexport const EACH_INDEX_REACTIVE = 1 << 1;\n/** See EachBlock interface metadata.is_controlled for an explanation what this is */\nexport const EACH_IS_CONTROLLED = 1 << 2;\nexport const EACH_IS_ANIMATED = 1 << 3;\nexport const EACH_ITEM_IMMUTABLE = 1 << 4;\n\nexport const PROPS_IS_IMMUTABLE = 1;\nexport const PROPS_IS_RUNES = 1 << 1;\nexport const PROPS_IS_UPDATED = 1 << 2;\nexport const PROPS_IS_BINDABLE = 1 << 3;\nexport const PROPS_IS_LAZY_INITIAL = 1 << 4;\n\nexport const TRANSITION_IN = 1;\nexport const TRANSITION_OUT = 1 << 1;\nexport const TRANSITION_GLOBAL = 1 << 2;\n\nexport const TEMPLATE_FRAGMENT = 1;\nexport const TEMPLATE_USE_IMPORT_NODE = 1 << 1;\nexport const TEMPLATE_USE_SVG = 1 << 2;\nexport const TEMPLATE_USE_MATHML = 1 << 3;\n\nexport const HYDRATION_START = '[';\n/** used to indicate that an `{:else}...` block was rendered */\nexport const HYDRATION_START_ELSE = '[!';\n/** used to indicate that a boundary's `failed` snippet was rendered on the server */\nexport const HYDRATION_START_FAILED = '[?';\nexport const HYDRATION_END = ']';\nexport const HYDRATION_ERROR = {};\n\nexport const ELEMENT_IS_NAMESPACED = 1;\nexport const ELEMENT_PRESERVE_ATTRIBUTE_CASE = 1 << 1;\nexport const ELEMENT_IS_INPUT = 1 << 2;\n\nexport const UNINITIALIZED = Symbol();\n\n// Dev-time component properties\nexport const FILENAME = Symbol('filename');\nexport const HMR = Symbol('hmr');\n\nexport const NAMESPACE_HTML = 'http://www.w3.org/1999/xhtml';\nexport const NAMESPACE_SVG = 'http://www.w3.org/2000/svg';\nexport const NAMESPACE_MATHML = 'http://www.w3.org/1998/Math/MathML';\n\n// we use a list of ignorable runtime warnings because not every runtime warning\n// can be ignored and we want to keep the validation for svelte-ignore in place\nexport const IGNORABLE_RUNTIME_WARNINGS = /** @type {const} */ ([\n\t'await_waterfall',\n\t'await_reactivity_loss',\n\t'state_snapshot_uncloneable',\n\t'binding_property_non_reactive',\n\t'hydration_attribute_changed',\n\t'hydration_html_changed',\n\t'ownership_invalid_binding',\n\t'ownership_invalid_mutation'\n]);\n\n/**\n * Whitespace inside one of these elements will not result in\n * a whitespace node being created in any circumstances. (This\n * list is almost certainly very incomplete)\n * TODO this is currently unused\n */\nexport const ELEMENTS_WITHOUT_TEXT = ['audio', 'datalist', 'dl', 'optgroup', 'select', 'video'];\n\nexport const ATTACHMENT_KEY = '@attach';\n","export default false;\n","// Store the references to globals in case someone tries to monkey patch these, causing the below\n// to de-opt (this occurs often when using popular extensions).\nexport var is_array = Array.isArray;\nexport var index_of = Array.prototype.indexOf;\nexport var includes = Array.prototype.includes;\nexport var array_from = Array.from;\nexport var object_keys = Object.keys;\nexport var define_property = Object.defineProperty;\nexport var get_descriptor = Object.getOwnPropertyDescriptor;\nexport var get_descriptors = Object.getOwnPropertyDescriptors;\nexport var object_prototype = Object.prototype;\nexport var array_prototype = Array.prototype;\nexport var get_prototype_of = Object.getPrototypeOf;\nexport var is_extensible = Object.isExtensible;\nexport var has_own_property = Object.prototype.hasOwnProperty;\n\n/**\n * @param {any} thing\n * @returns {thing is Function}\n */\nexport function is_function(thing) {\n\treturn typeof thing === 'function';\n}\n\nexport const noop = () => {};\n\n// Adapted from https://github.com/then/is-promise/blob/master/index.js\n// Distributed under MIT License https://github.com/then/is-promise/blob/master/LICENSE\n\n/**\n * @template [T=any]\n * @param {any} value\n * @returns {value is PromiseLike<T>}\n */\nexport function is_promise(value) {\n\treturn typeof value?.then === 'function';\n}\n\n/** @param {Function} fn */\nexport function run(fn) {\n\treturn fn();\n}\n\n/** @param {Array<() => void>} arr */\nexport function run_all(arr) {\n\tfor (var i = 0; i < arr.length; i++) {\n\t\tarr[i]();\n\t}\n}\n\n/**\n * TODO replace with Promise.withResolvers once supported widely enough\n * @template [T=void]\n */\nexport function deferred() {\n\t/** @type {(value: T) => void} */\n\tvar resolve;\n\n\t/** @type {(reason: any) => void} */\n\tvar reject;\n\n\t/** @type {Promise<T>} */\n\tvar promise = new Promise((res, rej) => {\n\t\tresolve = res;\n\t\treject = rej;\n\t});\n\n\t// @ts-expect-error\n\treturn { promise, resolve, reject };\n}\n\n/**\n * @template V\n * @param {V} value\n * @param {V | (() => V)} fallback\n * @param {boolean} [lazy]\n * @returns {V}\n */\nexport function fallback(value, fallback, lazy = false) {\n\treturn value === undefined\n\t\t? lazy\n\t\t\t? /** @type {() => V} */ (fallback)()\n\t\t\t: /** @type {V} */ (fallback)\n\t\t: value;\n}\n\n/**\n * When encountering a situation like `let [a, b, c] = $derived(blah())`,\n * we need to stash an intermediate value that `a`, `b`, and `c` derive\n * from, in case it's an iterable\n * @template T\n * @param {ArrayLike<T> | Iterable<T>} value\n * @param {number} [n]\n * @returns {Array<T>}\n */\nexport function to_array(value, n) {\n\t// return arrays unchanged\n\tif (Array.isArray(value)) {\n\t\treturn value;\n\t}\n\n\t// if value is not iterable, or `n` is unspecified (indicates a rest\n\t// element, which means we're not concerned about unbounded iterables)\n\t// convert to an array with `Array.from`\n\tif (n === undefined || !(Symbol.iterator in value)) {\n\t\treturn Array.from(value);\n\t}\n\n\t// otherwise, populate an array with `n` values\n\n\t/** @type {T[]} */\n\tconst array = [];\n\n\tfor (const element of value) {\n\t\tarray.push(element);\n\t\tif (array.length === n) break;\n\t}\n\n\treturn array;\n}\n\n/**\n * @param {Record<string | symbol, unknown>} obj\n * @param {Array<string | symbol>} keys\n * @returns {Record<string | symbol, unknown>}\n */\nexport function exclude_from_object(obj, keys) {\n\t/** @type {Record<string | symbol, unknown>} */\n\tvar result = {};\n\n\tfor (var key in obj) {\n\t\tif (!keys.includes(key)) {\n\t\t\tresult[key] = obj[key];\n\t\t}\n\t}\n\n\tfor (var symbol of Object.getOwnPropertySymbols(obj)) {\n\t\tif (Object.propertyIsEnumerable.call(obj, symbol) && !keys.includes(symbol)) {\n\t\t\tresult[symbol] = obj[symbol];\n\t\t}\n\t}\n\n\treturn result;\n}\n","// General flags\nexport const DERIVED = 1 << 1;\nexport const EFFECT = 1 << 2;\nexport const RENDER_EFFECT = 1 << 3;\n/**\n * An effect that does not destroy its child effects when it reruns.\n * Runs as part of render effects, i.e. not eagerly as part of tree traversal or effect flushing.\n */\nexport const MANAGED_EFFECT = 1 << 24;\n/**\n * An effect that does not destroy its child effects when it reruns (like MANAGED_EFFECT).\n * Runs eagerly as part of tree traversal or effect flushing.\n */\nexport const BLOCK_EFFECT = 1 << 4;\nexport const BRANCH_EFFECT = 1 << 5;\nexport const ROOT_EFFECT = 1 << 6;\nexport const BOUNDARY_EFFECT = 1 << 7;\n/**\n * Indicates that a reaction is connected to an effect root — either it is an effect,\n * or it is a derived that is depended on by at least one effect. If a derived has\n * no dependents, we can disconnect it from the graph, allowing it to either be\n * GC'd or reconnected later if an effect comes to depend on it again\n */\nexport const CONNECTED = 1 << 9;\nexport const CLEAN = 1 << 10;\nexport const DIRTY = 1 << 11;\nexport const MAYBE_DIRTY = 1 << 12;\nexport const INERT = 1 << 13;\nexport const DESTROYED = 1 << 14;\n/** Set once a reaction has run for the first time */\nexport const REACTION_RAN = 1 << 15;\n/** Effect is in the process of getting destroyed. Can be observed in child teardown functions */\nexport const DESTROYING = 1 << 25;\n\n// Flags exclusive to effects\n/**\n * 'Transparent' effects do not create a transition boundary.\n * This is on a block effect 99% of the time but may also be on a branch effect if its parent block effect was pruned\n */\nexport const EFFECT_TRANSPARENT = 1 << 16;\nexport const EAGER_EFFECT = 1 << 17;\nexport const HEAD_EFFECT = 1 << 18;\nexport const EFFECT_PRESERVED = 1 << 19;\nexport const USER_EFFECT = 1 << 20;\nexport const EFFECT_OFFSCREEN = 1 << 25;\n\n// Flags exclusive to deriveds\n/**\n * Tells that we marked this derived and its reactions as visited during the \"mark as (maybe) dirty\"-phase.\n * Will be lifted during execution of the derived and during checking its dirty state (both are necessary\n * because a derived might be checked but not executed).\n */\nexport const WAS_MARKED = 1 << 16;\n\n// Flags used for async\nexport const REACTION_IS_UPDATING = 1 << 21;\nexport const ASYNC = 1 << 22;\n\nexport const ERROR_VALUE = 1 << 23;\n\nexport const STATE_SYMBOL = Symbol('$state');\nexport const LEGACY_PROPS = Symbol('legacy props');\nexport const LOADING_ATTR_SYMBOL = Symbol('');\nexport const PROXY_PATH_SYMBOL = Symbol('proxy path');\n/** An anchor might change, via this symbol on the original anchor we can tell HMR about the updated anchor */\nexport const HMR_ANCHOR = Symbol('hmr anchor');\n\n/** allow users to ignore aborted signal errors if `reason.name === 'StaleReactionError` */\nexport const STALE_REACTION = new (class StaleReactionError extends Error {\n\tname = 'StaleReactionError';\n\tmessage = 'The reaction that called `getAbortSignal()` was re-run or destroyed';\n})();\n\nexport const IS_XHTML =\n\t// We gotta write it like this because after downleveling the pure comment may end up in the wrong location\n\t!!globalThis.document?.contentType &&\n\t/* @__PURE__ */ globalThis.document.contentType.includes('xml');\nexport const ELEMENT_NODE = 1;\nexport const TEXT_NODE = 3;\nexport const COMMENT_NODE = 8;\nexport const DOCUMENT_FRAGMENT_NODE = 11;\n","/* This file is generated by scripts/process-messages/index.js. Do not edit! */\n\nimport { DEV } from 'esm-env';\n\n/**\n * Cannot use `%name%(...)` unless the `experimental.async` compiler option is `true`\n * @param {string} name\n * @returns {never}\n */\nexport function experimental_async_required(name) {\n\tif (DEV) {\n\t\tconst error = new Error(`experimental_async_required\\nCannot use \\`${name}(...)\\` unless the \\`experimental.async\\` compiler option is \\`true\\`\\nhttps://svelte.dev/e/experimental_async_required`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/experimental_async_required`);\n\t}\n}\n\n/**\n * Cannot use `{@render children(...)}` if the parent component uses `let:` directives. Consider using a named snippet instead\n * @returns {never}\n */\nexport function invalid_default_snippet() {\n\tif (DEV) {\n\t\tconst error = new Error(`invalid_default_snippet\\nCannot use \\`{@render children(...)}\\` if the parent component uses \\`let:\\` directives. Consider using a named snippet instead\\nhttps://svelte.dev/e/invalid_default_snippet`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/invalid_default_snippet`);\n\t}\n}\n\n/**\n * A snippet function was passed invalid arguments. Snippets should only be instantiated via `{@render ...}`\n * @returns {never}\n */\nexport function invalid_snippet_arguments() {\n\tif (DEV) {\n\t\tconst error = new Error(`invalid_snippet_arguments\\nA snippet function was passed invalid arguments. Snippets should only be instantiated via \\`{@render ...}\\`\\nhttps://svelte.dev/e/invalid_snippet_arguments`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/invalid_snippet_arguments`);\n\t}\n}\n\n/**\n * An invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app — please open an issue at https://github.com/sveltejs/svelte, citing the following message: \"%message%\"\n * @param {string} message\n * @returns {never}\n */\nexport function invariant_violation(message) {\n\tif (DEV) {\n\t\tconst error = new Error(`invariant_violation\\nAn invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app — please open an issue at https://github.com/sveltejs/svelte, citing the following message: \"${message}\"\\nhttps://svelte.dev/e/invariant_violation`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/invariant_violation`);\n\t}\n}\n\n/**\n * `%name%(...)` can only be used during component initialisation\n * @param {string} name\n * @returns {never}\n */\nexport function lifecycle_outside_component(name) {\n\tif (DEV) {\n\t\tconst error = new Error(`lifecycle_outside_component\\n\\`${name}(...)\\` can only be used during component initialisation\\nhttps://svelte.dev/e/lifecycle_outside_component`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/lifecycle_outside_component`);\n\t}\n}\n\n/**\n * Context was not set in a parent component\n * @returns {never}\n */\nexport function missing_context() {\n\tif (DEV) {\n\t\tconst error = new Error(`missing_context\\nContext was not set in a parent component\\nhttps://svelte.dev/e/missing_context`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/missing_context`);\n\t}\n}\n\n/**\n * Attempted to render a snippet without a `{@render}` block. This would cause the snippet code to be stringified instead of its content being rendered to the DOM. To fix this, change `{snippet}` to `{@render snippet()}`.\n * @returns {never}\n */\nexport function snippet_without_render_tag() {\n\tif (DEV) {\n\t\tconst error = new Error(`snippet_without_render_tag\\nAttempted to render a snippet without a \\`{@render}\\` block. This would cause the snippet code to be stringified instead of its content being rendered to the DOM. To fix this, change \\`{snippet}\\` to \\`{@render snippet()}\\`.\\nhttps://svelte.dev/e/snippet_without_render_tag`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/snippet_without_render_tag`);\n\t}\n}\n\n/**\n * `%name%` is not a store with a `subscribe` method\n * @param {string} name\n * @returns {never}\n */\nexport function store_invalid_shape(name) {\n\tif (DEV) {\n\t\tconst error = new Error(`store_invalid_shape\\n\\`${name}\\` is not a store with a \\`subscribe\\` method\\nhttps://svelte.dev/e/store_invalid_shape`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/store_invalid_shape`);\n\t}\n}\n\n/**\n * The `this` prop on `<svelte:element>` must be a string, if defined\n * @returns {never}\n */\nexport function svelte_element_invalid_this_value() {\n\tif (DEV) {\n\t\tconst error = new Error(`svelte_element_invalid_this_value\\nThe \\`this\\` prop on \\`<svelte:element>\\` must be a string, if defined\\nhttps://svelte.dev/e/svelte_element_invalid_this_value`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/svelte_element_invalid_this_value`);\n\t}\n}","/* This file is generated by scripts/process-messages/index.js. Do not edit! */\n\nimport { DEV } from 'esm-env';\n\nexport * from '../shared/errors.js';\n\n/**\n * Cannot create a `$derived(...)` with an `await` expression outside of an effect tree\n * @returns {never}\n */\nexport function async_derived_orphan() {\n\tif (DEV) {\n\t\tconst error = new Error(`async_derived_orphan\\nCannot create a \\`$derived(...)\\` with an \\`await\\` expression outside of an effect tree\\nhttps://svelte.dev/e/async_derived_orphan`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/async_derived_orphan`);\n\t}\n}\n\n/**\n * Using `bind:value` together with a checkbox input is not allowed. Use `bind:checked` instead\n * @returns {never}\n */\nexport function bind_invalid_checkbox_value() {\n\tif (DEV) {\n\t\tconst error = new Error(`bind_invalid_checkbox_value\\nUsing \\`bind:value\\` together with a checkbox input is not allowed. Use \\`bind:checked\\` instead\\nhttps://svelte.dev/e/bind_invalid_checkbox_value`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/bind_invalid_checkbox_value`);\n\t}\n}\n\n/**\n * Component %component% has an export named `%key%` that a consumer component is trying to access using `bind:%key%`, which is disallowed. Instead, use `bind:this` (e.g. `<%name% bind:this={component} />`) and then access the property on the bound component instance (e.g. `component.%key%`)\n * @param {string} component\n * @param {string} key\n * @param {string} name\n * @returns {never}\n */\nexport function bind_invalid_export(component, key, name) {\n\tif (DEV) {\n\t\tconst error = new Error(`bind_invalid_export\\nComponent ${component} has an export named \\`${key}\\` that a consumer component is trying to access using \\`bind:${key}\\`, which is disallowed. Instead, use \\`bind:this\\` (e.g. \\`<${name} bind:this={component} />\\`) and then access the property on the bound component instance (e.g. \\`component.${key}\\`)\\nhttps://svelte.dev/e/bind_invalid_export`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/bind_invalid_export`);\n\t}\n}\n\n/**\n * A component is attempting to bind to a non-bindable property `%key%` belonging to %component% (i.e. `<%name% bind:%key%={...}>`). To mark a property as bindable: `let { %key% = $bindable() } = $props()`\n * @param {string} key\n * @param {string} component\n * @param {string} name\n * @returns {never}\n */\nexport function bind_not_bindable(key, component, name) {\n\tif (DEV) {\n\t\tconst error = new Error(`bind_not_bindable\\nA component is attempting to bind to a non-bindable property \\`${key}\\` belonging to ${component} (i.e. \\`<${name} bind:${key}={...}>\\`). To mark a property as bindable: \\`let { ${key} = $bindable() } = $props()\\`\\nhttps://svelte.dev/e/bind_not_bindable`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/bind_not_bindable`);\n\t}\n}\n\n/**\n * Calling `%method%` on a component instance (of %component%) is no longer valid in Svelte 5\n * @param {string} method\n * @param {string} component\n * @returns {never}\n */\nexport function component_api_changed(method, component) {\n\tif (DEV) {\n\t\tconst error = new Error(`component_api_changed\\nCalling \\`${method}\\` on a component instance (of ${component}) is no longer valid in Svelte 5\\nhttps://svelte.dev/e/component_api_changed`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/component_api_changed`);\n\t}\n}\n\n/**\n * Attempted to instantiate %component% with `new %name%`, which is no longer valid in Svelte 5. If this component is not under your control, set the `compatibility.componentApi` compiler option to `4` to keep it working.\n * @param {string} component\n * @param {string} name\n * @returns {never}\n */\nexport function component_api_invalid_new(component, name) {\n\tif (DEV) {\n\t\tconst error = new Error(`component_api_invalid_new\\nAttempted to instantiate ${component} with \\`new ${name}\\`, which is no longer valid in Svelte 5. If this component is not under your control, set the \\`compatibility.componentApi\\` compiler option to \\`4\\` to keep it working.\\nhttps://svelte.dev/e/component_api_invalid_new`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/component_api_invalid_new`);\n\t}\n}\n\n/**\n * A derived value cannot reference itself recursively\n * @returns {never}\n */\nexport function derived_references_self() {\n\tif (DEV) {\n\t\tconst error = new Error(`derived_references_self\\nA derived value cannot reference itself recursively\\nhttps://svelte.dev/e/derived_references_self`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/derived_references_self`);\n\t}\n}\n\n/**\n * Keyed each block has duplicate key `%value%` at indexes %a% and %b%\n * @param {string} a\n * @param {string} b\n * @param {string | undefined | null} [value]\n * @returns {never}\n */\nexport function each_key_duplicate(a, b, value) {\n\tif (DEV) {\n\t\tconst error = new Error(`each_key_duplicate\\n${value\n\t\t\t? `Keyed each block has duplicate key \\`${value}\\` at indexes ${a} and ${b}`\n\t\t\t: `Keyed each block has duplicate key at indexes ${a} and ${b}`}\\nhttps://svelte.dev/e/each_key_duplicate`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/each_key_duplicate`);\n\t}\n}\n\n/**\n * Keyed each block has key that is not idempotent — the key for item at index %index% was `%a%` but is now `%b%`. Keys must be the same each time for a given item\n * @param {string} index\n * @param {string} a\n * @param {string} b\n * @returns {never}\n */\nexport function each_key_volatile(index, a, b) {\n\tif (DEV) {\n\t\tconst error = new Error(`each_key_volatile\\nKeyed each block has key that is not idempotent — the key for item at index ${index} was \\`${a}\\` but is now \\`${b}\\`. Keys must be the same each time for a given item\\nhttps://svelte.dev/e/each_key_volatile`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/each_key_volatile`);\n\t}\n}\n\n/**\n * `%rune%` cannot be used inside an effect cleanup function\n * @param {string} rune\n * @returns {never}\n */\nexport function effect_in_teardown(rune) {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_in_teardown\\n\\`${rune}\\` cannot be used inside an effect cleanup function\\nhttps://svelte.dev/e/effect_in_teardown`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_in_teardown`);\n\t}\n}\n\n/**\n * Effect cannot be created inside a `$derived` value that was not itself created inside an effect\n * @returns {never}\n */\nexport function effect_in_unowned_derived() {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_in_unowned_derived\\nEffect cannot be created inside a \\`$derived\\` value that was not itself created inside an effect\\nhttps://svelte.dev/e/effect_in_unowned_derived`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_in_unowned_derived`);\n\t}\n}\n\n/**\n * `%rune%` can only be used inside an effect (e.g. during component initialisation)\n * @param {string} rune\n * @returns {never}\n */\nexport function effect_orphan(rune) {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_orphan\\n\\`${rune}\\` can only be used inside an effect (e.g. during component initialisation)\\nhttps://svelte.dev/e/effect_orphan`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_orphan`);\n\t}\n}\n\n/**\n * `$effect.pending()` can only be called inside an effect or derived\n * @returns {never}\n */\nexport function effect_pending_outside_reaction() {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_pending_outside_reaction\\n\\`$effect.pending()\\` can only be called inside an effect or derived\\nhttps://svelte.dev/e/effect_pending_outside_reaction`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_pending_outside_reaction`);\n\t}\n}\n\n/**\n * Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state\n * @returns {never}\n */\nexport function effect_update_depth_exceeded() {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_update_depth_exceeded\\nMaximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state\\nhttps://svelte.dev/e/effect_update_depth_exceeded`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_update_depth_exceeded`);\n\t}\n}\n\n/**\n * Cannot use `flushSync` inside an effect\n * @returns {never}\n */\nexport function flush_sync_in_effect() {\n\tif (DEV) {\n\t\tconst error = new Error(`flush_sync_in_effect\\nCannot use \\`flushSync\\` inside an effect\\nhttps://svelte.dev/e/flush_sync_in_effect`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/flush_sync_in_effect`);\n\t}\n}\n\n/**\n * Cannot commit a fork that was already discarded\n * @returns {never}\n */\nexport function fork_discarded() {\n\tif (DEV) {\n\t\tconst error = new Error(`fork_discarded\\nCannot commit a fork that was already discarded\\nhttps://svelte.dev/e/fork_discarded`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/fork_discarded`);\n\t}\n}\n\n/**\n * Cannot create a fork inside an effect or when state changes are pending\n * @returns {never}\n */\nexport function fork_timing() {\n\tif (DEV) {\n\t\tconst error = new Error(`fork_timing\\nCannot create a fork inside an effect or when state changes are pending\\nhttps://svelte.dev/e/fork_timing`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/fork_timing`);\n\t}\n}\n\n/**\n * `getAbortSignal()` can only be called inside an effect or derived\n * @returns {never}\n */\nexport function get_abort_signal_outside_reaction() {\n\tif (DEV) {\n\t\tconst error = new Error(`get_abort_signal_outside_reaction\\n\\`getAbortSignal()\\` can only be called inside an effect or derived\\nhttps://svelte.dev/e/get_abort_signal_outside_reaction`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/get_abort_signal_outside_reaction`);\n\t}\n}\n\n/**\n * Expected to find a hydratable with key `%key%` during hydration, but did not.\n * @param {string} key\n * @returns {never}\n */\nexport function hydratable_missing_but_required(key) {\n\tif (DEV) {\n\t\tconst error = new Error(`hydratable_missing_but_required\\nExpected to find a hydratable with key \\`${key}\\` during hydration, but did not.\\nhttps://svelte.dev/e/hydratable_missing_but_required`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/hydratable_missing_but_required`);\n\t}\n}\n\n/**\n * Failed to hydrate the application\n * @returns {never}\n */\nexport function hydration_failed() {\n\tif (DEV) {\n\t\tconst error = new Error(`hydration_failed\\nFailed to hydrate the application\\nhttps://svelte.dev/e/hydration_failed`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/hydration_failed`);\n\t}\n}\n\n/**\n * Could not `{@render}` snippet due to the expression being `null` or `undefined`. Consider using optional chaining `{@render snippet?.()}`\n * @returns {never}\n */\nexport function invalid_snippet() {\n\tif (DEV) {\n\t\tconst error = new Error(`invalid_snippet\\nCould not \\`{@render}\\` snippet due to the expression being \\`null\\` or \\`undefined\\`. Consider using optional chaining \\`{@render snippet?.()}\\`\\nhttps://svelte.dev/e/invalid_snippet`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/invalid_snippet`);\n\t}\n}\n\n/**\n * `%name%(...)` cannot be used in runes mode\n * @param {string} name\n * @returns {never}\n */\nexport function lifecycle_legacy_only(name) {\n\tif (DEV) {\n\t\tconst error = new Error(`lifecycle_legacy_only\\n\\`${name}(...)\\` cannot be used in runes mode\\nhttps://svelte.dev/e/lifecycle_legacy_only`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/lifecycle_legacy_only`);\n\t}\n}\n\n/**\n * Cannot do `bind:%key%={undefined}` when `%key%` has a fallback value\n * @param {string} key\n * @returns {never}\n */\nexport function props_invalid_value(key) {\n\tif (DEV) {\n\t\tconst error = new Error(`props_invalid_value\\nCannot do \\`bind:${key}={undefined}\\` when \\`${key}\\` has a fallback value\\nhttps://svelte.dev/e/props_invalid_value`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/props_invalid_value`);\n\t}\n}\n\n/**\n * Rest element properties of `$props()` such as `%property%` are readonly\n * @param {string} property\n * @returns {never}\n */\nexport function props_rest_readonly(property) {\n\tif (DEV) {\n\t\tconst error = new Error(`props_rest_readonly\\nRest element properties of \\`$props()\\` such as \\`${property}\\` are readonly\\nhttps://svelte.dev/e/props_rest_readonly`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/props_rest_readonly`);\n\t}\n}\n\n/**\n * The `%rune%` rune is only available inside `.svelte` and `.svelte.js/ts` files\n * @param {string} rune\n * @returns {never}\n */\nexport function rune_outside_svelte(rune) {\n\tif (DEV) {\n\t\tconst error = new Error(`rune_outside_svelte\\nThe \\`${rune}\\` rune is only available inside \\`.svelte\\` and \\`.svelte.js/ts\\` files\\nhttps://svelte.dev/e/rune_outside_svelte`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/rune_outside_svelte`);\n\t}\n}\n\n/**\n * `setContext` must be called when a component first initializes, not in a subsequent effect or after an `await` expression\n * @returns {never}\n */\nexport function set_context_after_init() {\n\tif (DEV) {\n\t\tconst error = new Error(`set_context_after_init\\n\\`setContext\\` must be called when a component first initializes, not in a subsequent effect or after an \\`await\\` expression\\nhttps://svelte.dev/e/set_context_after_init`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/set_context_after_init`);\n\t}\n}\n\n/**\n * Property descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`.\n * @returns {never}\n */\nexport function state_descriptors_fixed() {\n\tif (DEV) {\n\t\tconst error = new Error(`state_descriptors_fixed\\nProperty descriptors defined on \\`$state\\` objects must contain \\`value\\` and always be \\`enumerable\\`, \\`configurable\\` and \\`writable\\`.\\nhttps://svelte.dev/e/state_descriptors_fixed`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/state_descriptors_fixed`);\n\t}\n}\n\n/**\n * Cannot set prototype of `$state` object\n * @returns {never}\n */\nexport function state_prototype_fixed() {\n\tif (DEV) {\n\t\tconst error = new Error(`state_prototype_fixed\\nCannot set prototype of \\`$state\\` object\\nhttps://svelte.dev/e/state_prototype_fixed`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/state_prototype_fixed`);\n\t}\n}\n\n/**\n * Updating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state`\n * @returns {never}\n */\nexport function state_unsafe_mutation() {\n\tif (DEV) {\n\t\tconst error = new Error(`state_unsafe_mutation\\nUpdating state inside \\`$derived(...)\\`, \\`$inspect(...)\\` or a template expression is forbidden. If the value should not be reactive, declare it without \\`$state\\`\\nhttps://svelte.dev/e/state_unsafe_mutation`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/state_unsafe_mutation`);\n\t}\n}\n\n/**\n * A `<svelte:boundary>` `reset` function cannot be called while an error is still being handled\n * @returns {never}\n */\nexport function svelte_boundary_reset_onerror() {\n\tif (DEV) {\n\t\tconst error = new Error(`svelte_boundary_reset_onerror\\nA \\`<svelte:boundary>\\` \\`reset\\` function cannot be called while an error is still being handled\\nhttps://svelte.dev/e/svelte_boundary_reset_onerror`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`);\n\t}\n}","/* This file is generated by scripts/process-messages/index.js. Do not edit! */\n\nimport { DEV } from 'esm-env';\n\nvar bold = 'font-weight: bold';\nvar normal = 'font-weight: normal';\n\n/**\n * Assignment to `%property%` property (%location%) will evaluate to the right-hand side, not the value of `%property%` following the assignment. This may result in unexpected behaviour.\n * @param {string} property\n * @param {string} location\n */\nexport function assignment_value_stale(property, location) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] assignment_value_stale\\n%cAssignment to \\`${property}\\` property (${location}) will evaluate to the right-hand side, not the value of \\`${property}\\` following the assignment. This may result in unexpected behaviour.\\nhttps://svelte.dev/e/assignment_value_stale`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/assignment_value_stale`);\n\t}\n}\n\n/**\n * Detected reactivity loss when reading `%name%`. This happens when state is read in an async function after an earlier `await`\n * @param {string} name\n */\nexport function await_reactivity_loss(name) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] await_reactivity_loss\\n%cDetected reactivity loss when reading \\`${name}\\`. This happens when state is read in an async function after an earlier \\`await\\`\\nhttps://svelte.dev/e/await_reactivity_loss`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/await_reactivity_loss`);\n\t}\n}\n\n/**\n * An async derived, `%name%` (%location%) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app\n * @param {string} name\n * @param {string} location\n */\nexport function await_waterfall(name, location) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] await_waterfall\\n%cAn async derived, \\`${name}\\` (${location}) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app\\nhttps://svelte.dev/e/await_waterfall`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/await_waterfall`);\n\t}\n}\n\n/**\n * `%binding%` (%location%) is binding to a non-reactive property\n * @param {string} binding\n * @param {string | undefined | null} [location]\n */\nexport function binding_property_non_reactive(binding, location) {\n\tif (DEV) {\n\t\tconsole.warn(\n\t\t\t`%c[svelte] binding_property_non_reactive\\n%c${location\n\t\t\t\t? `\\`${binding}\\` (${location}) is binding to a non-reactive property`\n\t\t\t\t: `\\`${binding}\\` is binding to a non-reactive property`}\\nhttps://svelte.dev/e/binding_property_non_reactive`,\n\t\t\tbold,\n\t\t\tnormal\n\t\t);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/binding_property_non_reactive`);\n\t}\n}\n\n/**\n * Your `console.%method%` contained `$state` proxies. Consider using `$inspect(...)` or `$state.snapshot(...)` instead\n * @param {string} method\n */\nexport function console_log_state(method) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] console_log_state\\n%cYour \\`console.${method}\\` contained \\`$state\\` proxies. Consider using \\`$inspect(...)\\` or \\`$state.snapshot(...)\\` instead\\nhttps://svelte.dev/e/console_log_state`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/console_log_state`);\n\t}\n}\n\n/**\n * Reading a derived belonging to a now-destroyed effect may result in stale values\n */\nexport function derived_inert() {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] derived_inert\\n%cReading a derived belonging to a now-destroyed effect may result in stale values\\nhttps://svelte.dev/e/derived_inert`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/derived_inert`);\n\t}\n}\n\n/**\n * %handler% should be a function. Did you mean to %suggestion%?\n * @param {string} handler\n * @param {string} suggestion\n */\nexport function event_handler_invalid(handler, suggestion) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] event_handler_invalid\\n%c${handler} should be a function. Did you mean to ${suggestion}?\\nhttps://svelte.dev/e/event_handler_invalid`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/event_handler_invalid`);\n\t}\n}\n\n/**\n * Expected to find a hydratable with key `%key%` during hydration, but did not.\n * @param {string} key\n */\nexport function hydratable_missing_but_expected(key) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] hydratable_missing_but_expected\\n%cExpected to find a hydratable with key \\`${key}\\` during hydration, but did not.\\nhttps://svelte.dev/e/hydratable_missing_but_expected`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/hydratable_missing_but_expected`);\n\t}\n}\n\n/**\n * The `%attribute%` attribute on `%html%` changed its value between server and client renders. The client value, `%value%`, will be ignored in favour of the server value\n * @param {string} attribute\n * @param {string} html\n * @param {string} value\n */\nexport function hydration_attribute_changed(attribute, html, value) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] hydration_attribute_changed\\n%cThe \\`${attribute}\\` attribute on \\`${html}\\` changed its value between server and client renders. The client value, \\`${value}\\`, will be ignored in favour of the server value\\nhttps://svelte.dev/e/hydration_attribute_changed`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/hydration_attribute_changed`);\n\t}\n}\n\n/**\n * The value of an `{@html ...}` block %location% changed between server and client renders. The client value will be ignored in favour of the server value\n * @param {string | undefined | null} [location]\n */\nexport function hydration_html_changed(location) {\n\tif (DEV) {\n\t\tconsole.warn(\n\t\t\t`%c[svelte] hydration_html_changed\\n%c${location\n\t\t\t\t? `The value of an \\`{@html ...}\\` block ${location} changed between server and client renders. The client value will be ignored in favour of the server value`\n\t\t\t\t: 'The value of an `{@html ...}` block changed between server and client renders. The client value will be ignored in favour of the server value'}\\nhttps://svelte.dev/e/hydration_html_changed`,\n\t\t\tbold,\n\t\t\tnormal\n\t\t);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/hydration_html_changed`);\n\t}\n}\n\n/**\n * Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near %location%\n * @param {string | undefined | null} [location]\n */\nexport function hydration_mismatch(location) {\n\tif (DEV) {\n\t\tconsole.warn(\n\t\t\t`%c[svelte] hydration_mismatch\\n%c${location\n\t\t\t\t? `Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${location}`\n\t\t\t\t: 'Hydration failed because the initial UI does not match what was rendered on the server'}\\nhttps://svelte.dev/e/hydration_mismatch`,\n\t\t\tbold,\n\t\t\tnormal\n\t\t);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/hydration_mismatch`);\n\t}\n}\n\n/**\n * The `render` function passed to `createRawSnippet` should return HTML for a single element\n */\nexport function invalid_raw_snippet_render() {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] invalid_raw_snippet_render\\n%cThe \\`render\\` function passed to \\`createRawSnippet\\` should return HTML for a single element\\nhttps://svelte.dev/e/invalid_raw_snippet_render`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/invalid_raw_snippet_render`);\n\t}\n}\n\n/**\n * Detected a migrated `$:` reactive block in `%filename%` that both accesses and updates the same reactive value. This may cause recursive updates when converted to an `$effect`.\n * @param {string} filename\n */\nexport function legacy_recursive_reactive_block(filename) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] legacy_recursive_reactive_block\\n%cDetected a migrated \\`$:\\` reactive block in \\`${filename}\\` that both accesses and updates the same reactive value. This may cause recursive updates when converted to an \\`$effect\\`.\\nhttps://svelte.dev/e/legacy_recursive_reactive_block`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/legacy_recursive_reactive_block`);\n\t}\n}\n\n/**\n * Tried to unmount a component that was not mounted\n */\nexport function lifecycle_double_unmount() {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] lifecycle_double_unmount\\n%cTried to unmount a component that was not mounted\\nhttps://svelte.dev/e/lifecycle_double_unmount`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/lifecycle_double_unmount`);\n\t}\n}\n\n/**\n * %parent% passed property `%prop%` to %child% with `bind:`, but its parent component %owner% did not declare `%prop%` as a binding. Consider creating a binding between %owner% and %parent% (e.g. `bind:%prop%={...}` instead of `%prop%={...}`)\n * @param {string} parent\n * @param {string} prop\n * @param {string} child\n * @param {string} owner\n */\nexport function ownership_invalid_binding(parent, prop, child, owner) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] ownership_invalid_binding\\n%c${parent} passed property \\`${prop}\\` to ${child} with \\`bind:\\`, but its parent component ${owner} did not declare \\`${prop}\\` as a binding. Consider creating a binding between ${owner} and ${parent} (e.g. \\`bind:${prop}={...}\\` instead of \\`${prop}={...}\\`)\\nhttps://svelte.dev/e/ownership_invalid_binding`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/ownership_invalid_binding`);\n\t}\n}\n\n/**\n * Mutating unbound props (`%name%`, at %location%) is strongly discouraged. Consider using `bind:%prop%={...}` in %parent% (or using a callback) instead\n * @param {string} name\n * @param {string} location\n * @param {string} prop\n * @param {string} parent\n */\nexport function ownership_invalid_mutation(name, location, prop, parent) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] ownership_invalid_mutation\\n%cMutating unbound props (\\`${name}\\`, at ${location}) is strongly discouraged. Consider using \\`bind:${prop}={...}\\` in ${parent} (or using a callback) instead\\nhttps://svelte.dev/e/ownership_invalid_mutation`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/ownership_invalid_mutation`);\n\t}\n}\n\n/**\n * The `value` property of a `<select multiple>` element should be an array, but it received a non-array value. The selection will be kept as is.\n */\nexport function select_multiple_invalid_value() {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] select_multiple_invalid_value\\n%cThe \\`value\\` property of a \\`<select multiple>\\` element should be an array, but it received a non-array value. The selection will be kept as is.\\nhttps://svelte.dev/e/select_multiple_invalid_value`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/select_multiple_invalid_value`);\n\t}\n}\n\n/**\n * Reactive `$state(...)` proxies and the values they proxy have different identities. Because of this, comparisons with `%operator%` will produce unexpected results\n * @param {string} operator\n */\nexport function state_proxy_equality_mismatch(operator) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] state_proxy_equality_mismatch\\n%cReactive \\`$state(...)\\` proxies and the values they proxy have different identities. Because of this, comparisons with \\`${operator}\\` will produce unexpected results\\nhttps://svelte.dev/e/state_proxy_equality_mismatch`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/state_proxy_equality_mismatch`);\n\t}\n}\n\n/**\n * Tried to unmount a state proxy, rather than a component\n */\nexport function state_proxy_unmount() {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] state_proxy_unmount\\n%cTried to unmount a state proxy, rather than a component\\nhttps://svelte.dev/e/state_proxy_unmount`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/state_proxy_unmount`);\n\t}\n}\n\n/**\n * A `<svelte:boundary>` `reset` function only resets the boundary the first time it is called\n */\nexport function svelte_boundary_reset_noop() {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] svelte_boundary_reset_noop\\n%cA \\`<svelte:boundary>\\` \\`reset\\` function only resets the boundary the first time it is called\\nhttps://svelte.dev/e/svelte_boundary_reset_noop`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/svelte_boundary_reset_noop`);\n\t}\n}\n\n/**\n * The `slide` transition does not work correctly for elements with `display: %value%`\n * @param {string} value\n */\nexport function transition_slide_display(value) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] transition_slide_display\\n%cThe \\`slide\\` transition does not work correctly for elements with \\`display: ${value}\\`\\nhttps://svelte.dev/e/transition_slide_display`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/transition_slide_display`);\n\t}\n}","/** @import { TemplateNode } from '#client' */\n\nimport { COMMENT_NODE } from '#client/constants';\nimport {\n\tHYDRATION_END,\n\tHYDRATION_ERROR,\n\tHYDRATION_START,\n\tHYDRATION_START_ELSE\n} from '../../../constants.js';\nimport * as w from '../warnings.js';\nimport { get_next_sibling } from './operations.js';\n\n/**\n * Use this variable to guard everything related to hydration code so it can be treeshaken out\n * if the user doesn't use the `hydrate` method and these code paths are therefore not needed.\n */\nexport let hydrating = false;\n\n/** @param {boolean} value */\nexport function set_hydrating(value) {\n\thydrating = value;\n}\n\n/**\n * The node that is currently being hydrated. This starts out as the first node inside the opening\n * <!--[--> comment, and updates each time a component calls `$.child(...)` or `$.sibling(...)`.\n * When entering a block (e.g. `{#if ...}`), `hydrate_node` is the block opening comment; by the\n * time we leave the block it is the closing comment, which serves as the block's anchor.\n * @type {TemplateNode}\n */\nexport let hydrate_node;\n\n/** @param {TemplateNode | null} node */\nexport function set_hydrate_node(node) {\n\tif (node === null) {\n\t\tw.hydration_mismatch();\n\t\tthrow HYDRATION_ERROR;\n\t}\n\n\treturn (hydrate_node = node);\n}\n\nexport function hydrate_next() {\n\treturn set_hydrate_node(get_next_sibling(hydrate_node));\n}\n\n/** @param {TemplateNode} node */\nexport function reset(node) {\n\tif (!hydrating) return;\n\n\t// If the node has remaining siblings, something has gone wrong\n\tif (get_next_sibling(hydrate_node) !== null) {\n\t\tw.hydration_mismatch();\n\t\tthrow HYDRATION_ERROR;\n\t}\n\n\thydrate_node = node;\n}\n\n/**\n * @param {HTMLTemplateElement} template\n */\nexport function hydrate_template(template) {\n\tif (hydrating) {\n\t\t// @ts-expect-error TemplateNode doesn't include DocumentFragment, but it's actually fine\n\t\thydrate_node = template.content;\n\t}\n}\n\nexport function next(count = 1) {\n\tif (hydrating) {\n\t\tvar i = count;\n\t\tvar node = hydrate_node;\n\n\t\twhile (i--) {\n\t\t\tnode = /** @type {TemplateNode} */ (get_next_sibling(node));\n\t\t}\n\n\t\thydrate_node = node;\n\t}\n}\n\n/**\n * Skips or removes (depending on {@link remove}) all nodes starting at `hydrate_node` up until the next hydration end comment\n * @param {boolean} remove\n */\nexport function skip_nodes(remove = true) {\n\tvar depth = 0;\n\tvar node = hydrate_node;\n\n\twhile (true) {\n\t\tif (node.nodeType === COMMENT_NODE) {\n\t\t\tvar data = /** @type {Comment} */ (node).data;\n\n\t\t\tif (data === HYDRATION_END) {\n\t\t\t\tif (depth === 0) return node;\n\t\t\t\tdepth -= 1;\n\t\t\t} else if (\n\t\t\t\tdata === HYDRATION_START ||\n\t\t\t\tdata === HYDRATION_START_ELSE ||\n\t\t\t\t// \"[1\", \"[2\", etc. for if blocks\n\t\t\t\t(data[0] === '[' && !isNaN(Number(data.slice(1))))\n\t\t\t) {\n\t\t\t\tdepth += 1;\n\t\t\t}\n\t\t}\n\n\t\tvar next = /** @type {TemplateNode} */ (get_next_sibling(node));\n\t\tif (remove) node.remove();\n\t\tnode = next;\n\t}\n}\n\n/**\n *\n * @param {TemplateNode} node\n */\nexport function read_hydration_instruction(node) {\n\tif (!node || node.nodeType !== COMMENT_NODE) {\n\t\tw.hydration_mismatch();\n\t\tthrow HYDRATION_ERROR;\n\t}\n\n\treturn /** @type {Comment} */ (node).data;\n}\n","/** @import { Equals } from '#client' */\n\n/** @type {Equals} */\nexport function equals(value) {\n\treturn value === this.v;\n}\n\n/**\n * @param {unknown} a\n * @param {unknown} b\n * @returns {boolean}\n */\nexport function safe_not_equal(a, b) {\n\treturn a != a\n\t\t? b == b\n\t\t: a !== b || (a !== null && typeof a === 'object') || typeof a === 'function';\n}\n\n/**\n * @param {unknown} a\n * @param {unknown} b\n * @returns {boolean}\n */\nexport function not_equal(a, b) {\n\treturn a !== b;\n}\n\n/** @type {Equals} */\nexport function safe_equals(value) {\n\treturn !safe_not_equal(value, this.v);\n}\n","/** True if experimental.async=true */\nexport let async_mode_flag = false;\n/** True if we're not certain that we only have Svelte 5 code in the compilation */\nexport let legacy_mode_flag = false;\n/** True if $inspect.trace is used */\nexport let tracing_mode_flag = false;\n\nexport function enable_async_mode_flag() {\n\tasync_mode_flag = true;\n}\n\n/** ONLY USE THIS DURING TESTING */\nexport function disable_async_mode_flag() {\n\tasync_mode_flag = false;\n}\n\nexport function enable_legacy_mode_flag() {\n\tlegacy_mode_flag = true;\n}\n\nexport function enable_tracing_mode_flag() {\n\ttracing_mode_flag = true;\n}\n","/* This file is generated by scripts/process-messages/index.js. Do not edit! */\n\nimport { DEV } from 'esm-env';\n\nvar bold = 'font-weight: bold';\nvar normal = 'font-weight: normal';\n\n/**\n * `<svelte:element this=\"%tag%\">` is a void element — it cannot have content\n * @param {string} tag\n */\nexport function dynamic_void_element_content(tag) {\n\tif (DEV) {\n\t\tconsole.warn(`%c[svelte] dynamic_void_element_content\\n%c\\`<svelte:element this=\"${tag}\">\\` is a void element — it cannot have content\\nhttps://svelte.dev/e/dynamic_void_element_content`, bold, normal);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/dynamic_void_element_content`);\n\t}\n}\n\n/**\n * The following properties cannot be cloned with `$state.snapshot` — the return value contains the originals:\n * \n * %properties%\n * @param {string | undefined | null} [properties]\n */\nexport function state_snapshot_uncloneable(properties) {\n\tif (DEV) {\n\t\tconsole.warn(\n\t\t\t`%c[svelte] state_snapshot_uncloneable\\n%c${properties\n\t\t\t\t? `The following properties cannot be cloned with \\`$state.snapshot\\` — the return value contains the originals:\n\n${properties}`\n\t\t\t\t: 'Value cannot be cloned with `$state.snapshot` — the original value was returned'}\\nhttps://svelte.dev/e/state_snapshot_uncloneable`,\n\t\t\tbold,\n\t\t\tnormal\n\t\t);\n\t} else {\n\t\tconsole.warn(`https://svelte.dev/e/state_snapshot_uncloneable`);\n\t}\n}","/** @import { Snapshot } from './types' */\nimport { DEV } from 'esm-env';\nimport * as w from './warnings.js';\nimport { get_prototype_of, is_array, object_prototype } from './utils.js';\n\n/**\n * In dev, we keep track of which properties could not be cloned. In prod\n * we don't bother, but we keep a dummy array around so that the\n * signature stays the same\n * @type {string[]}\n */\nconst empty = [];\n\n/**\n * @template T\n * @param {T} value\n * @param {boolean} [skip_warning]\n * @param {boolean} [no_tojson]\n * @returns {Snapshot<T>}\n */\nexport function snapshot(value, skip_warning = false, no_tojson = false) {\n\tif (DEV && !skip_warning) {\n\t\t/** @type {string[]} */\n\t\tconst paths = [];\n\n\t\tconst copy = clone(value, new Map(), '', paths, null, no_tojson);\n\t\tif (paths.length === 1 && paths[0] === '') {\n\t\t\t// value could not be cloned\n\t\t\tw.state_snapshot_uncloneable();\n\t\t} else if (paths.length > 0) {\n\t\t\t// some properties could not be cloned\n\t\t\tconst slice = paths.length > 10 ? paths.slice(0, 7) : paths.slice(0, 10);\n\t\t\tconst excess = paths.length - slice.length;\n\n\t\t\tlet uncloned = slice.map((path) => `- <value>${path}`).join('\\n');\n\t\t\tif (excess > 0) uncloned += `\\n- ...and ${excess} more`;\n\n\t\t\tw.state_snapshot_uncloneable(uncloned);\n\t\t}\n\n\t\treturn copy;\n\t}\n\n\treturn clone(value, new Map(), '', empty, null, no_tojson);\n}\n\n/**\n * @template T\n * @param {T} value\n * @param {Map<T, Snapshot<T>>} cloned\n * @param {string} path\n * @param {string[]} paths\n * @param {null | T} [original] The original value, if `value` was produced from a `toJSON` call\n * @param {boolean} [no_tojson]\n * @returns {Snapshot<T>}\n */\nfunction clone(value, cloned, path, paths, original = null, no_tojson = false) {\n\tif (typeof value === 'object' && value !== null) {\n\t\tvar unwrapped = cloned.get(value);\n\t\tif (unwrapped !== undefined) return unwrapped;\n\n\t\tif (value instanceof Map) return /** @type {Snapshot<T>} */ (new Map(value));\n\t\tif (value instanceof Set) return /** @type {Snapshot<T>} */ (new Set(value));\n\n\t\tif (is_array(value)) {\n\t\t\tvar copy = /** @type {Snapshot<any>} */ (Array(value.length));\n\t\t\tcloned.set(value, copy);\n\n\t\t\tif (original !== null) {\n\t\t\t\tcloned.set(original, copy);\n\t\t\t}\n\n\t\t\tfor (var i = 0; i < value.length; i += 1) {\n\t\t\t\tvar element = value[i];\n\t\t\t\tif (i in value) {\n\t\t\t\t\tcopy[i] = clone(element, cloned, DEV ? `${path}[${i}]` : path, paths, null, no_tojson);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn copy;\n\t\t}\n\n\t\tif (get_prototype_of(value) === object_prototype) {\n\t\t\t/** @type {Snapshot<any>} */\n\t\t\tcopy = {};\n\t\t\tcloned.set(value, copy);\n\n\t\t\tif (original !== null) {\n\t\t\t\tcloned.set(original, copy);\n\t\t\t}\n\n\t\t\tfor (var key of Object.keys(value)) {\n\t\t\t\tcopy[key] = clone(\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tvalue[key],\n\t\t\t\t\tcloned,\n\t\t\t\t\tDEV ? `${path}.${key}` : path,\n\t\t\t\t\tpaths,\n\t\t\t\t\tnull,\n\t\t\t\t\tno_tojson\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn copy;\n\t\t}\n\n\t\tif (value instanceof Date) {\n\t\t\treturn /** @type {Snapshot<T>} */ (structuredClone(value));\n\t\t}\n\n\t\tif (typeof (/** @type {T & { toJSON?: any } } */ (value).toJSON) === 'function' && !no_tojson) {\n\t\t\treturn clone(\n\t\t\t\t/** @type {T & { toJSON(): any } } */ (value).toJSON(),\n\t\t\t\tcloned,\n\t\t\t\tDEV ? `${path}.toJSON()` : path,\n\t\t\t\tpaths,\n\t\t\t\t// Associate the instance with the toJSON clone\n\t\t\t\tvalue\n\t\t\t);\n\t\t}\n\t}\n\n\tif (value instanceof EventTarget) {\n\t\t// can't be cloned\n\t\treturn /** @type {Snapshot<T>} */ (value);\n\t}\n\n\ttry {\n\t\treturn /** @type {Snapshot<T>} */ (structuredClone(value));\n\t} catch (e) {\n\t\tif (DEV) {\n\t\t\tpaths.push(path);\n\t\t}\n\n\t\treturn /** @type {Snapshot<T>} */ (value);\n\t}\n}\n","/** @import { Derived, Reaction, Value } from '#client' */\nimport { UNINITIALIZED } from '../../../constants.js';\nimport { snapshot } from '../../shared/clone.js';\nimport { DERIVED, ASYNC, PROXY_PATH_SYMBOL, STATE_SYMBOL } from '#client/constants';\nimport { effect_tracking } from '../reactivity/effects.js';\nimport { active_reaction, untrack } from '../runtime.js';\n\n/**\n * @typedef {{\n * traces: Error[];\n * }} TraceEntry\n */\n\n/** @type {{ reaction: Reaction | null, entries: Map<Value, TraceEntry> } | null} */\nexport let tracing_expressions = null;\n\n/**\n * @param {Value} signal\n * @param {TraceEntry} [entry]\n */\nfunction log_entry(signal, entry) {\n\tconst value = signal.v;\n\n\tif (value === UNINITIALIZED) {\n\t\treturn;\n\t}\n\n\tconst type = get_type(signal);\n\tconst current_reaction = /** @type {Reaction} */ (active_reaction);\n\tconst dirty = signal.wv > current_reaction.wv || current_reaction.wv === 0;\n\tconst style = dirty\n\t\t? 'color: CornflowerBlue; font-weight: bold'\n\t\t: 'color: grey; font-weight: normal';\n\n\t// eslint-disable-next-line no-console\n\tconsole.groupCollapsed(\n\t\tsignal.label ? `%c${type}%c ${signal.label}` : `%c${type}%c`,\n\t\tstyle,\n\t\tdirty ? 'font-weight: normal' : style,\n\t\ttypeof value === 'object' && value !== null && STATE_SYMBOL in value\n\t\t\t? snapshot(value, true)\n\t\t\t: value\n\t);\n\n\tif (type === '$derived') {\n\t\tconst deps = new Set(/** @type {Derived} */ (signal).deps);\n\t\tfor (const dep of deps) {\n\t\t\tlog_entry(dep);\n\t\t}\n\t}\n\n\tif (signal.created) {\n\t\t// eslint-disable-next-line no-console\n\t\tconsole.log(signal.created);\n\t}\n\n\tif (dirty && signal.updated) {\n\t\tfor (const updated of signal.updated.values()) {\n\t\t\tif (updated.error) {\n\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\tconsole.log(updated.error);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (entry) {\n\t\tfor (var trace of entry.traces) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.log(trace);\n\t\t}\n\t}\n\n\t// eslint-disable-next-line no-console\n\tconsole.groupEnd();\n}\n\n/**\n * @param {Value} signal\n * @returns {'$state' | '$derived' | 'store'}\n */\nfunction get_type(signal) {\n\tif ((signal.f & (DERIVED | ASYNC)) !== 0) return '$derived';\n\treturn signal.label?.startsWith('$') ? 'store' : '$state';\n}\n\n/**\n * @template T\n * @param {() => string} label\n * @param {() => T} fn\n */\nexport function trace(label, fn) {\n\tvar previously_tracing_expressions = tracing_expressions;\n\n\ttry {\n\t\ttracing_expressions = { entries: new Map(), reaction: active_reaction };\n\n\t\tvar start = performance.now();\n\t\tvar value = fn();\n\t\tvar time = (performance.now() - start).toFixed(2);\n\n\t\tvar prefix = untrack(label);\n\n\t\tif (!effect_tracking()) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.log(`${prefix} %cran outside of an effect (${time}ms)`, 'color: grey');\n\t\t} else if (tracing_expressions.entries.size === 0) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.log(`${prefix} %cno reactive dependencies (${time}ms)`, 'color: grey');\n\t\t} else {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.group(`${prefix} %c(${time}ms)`, 'color: grey');\n\n\t\t\tvar entries = tracing_expressions.entries;\n\n\t\t\tuntrack(() => {\n\t\t\t\tfor (const [signal, traces] of entries) {\n\t\t\t\t\tlog_entry(signal, traces);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\ttracing_expressions = null;\n\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.groupEnd();\n\t\t}\n\n\t\treturn value;\n\t} finally {\n\t\ttracing_expressions = previously_tracing_expressions;\n\t}\n}\n\n/**\n * @param {Value} source\n * @param {string} label\n */\nexport function tag(source, label) {\n\tsource.label = label;\n\ttag_proxy(source.v, label);\n\n\treturn source;\n}\n\n/**\n * @param {unknown} value\n * @param {string} label\n */\nexport function tag_proxy(value, label) {\n\t// @ts-expect-error\n\tvalue?.[PROXY_PATH_SYMBOL]?.(label);\n\treturn value;\n}\n\n/**\n * @param {unknown} value\n */\nexport function label(value) {\n\tif (typeof value === 'symbol') return `Symbol(${value.description})`;\n\tif (typeof value === 'function') return '<function>';\n\tif (typeof value === 'object' && value) return '<object>';\n\treturn String(value);\n}\n","import { DEV } from 'esm-env';\nimport { define_property } from './utils.js';\nimport * as e from './errors.js';\n\n/**\n * @param {string} label\n * @returns {Error & { stack: string } | null}\n */\nexport function get_error(label) {\n\tconst error = new Error();\n\tconst stack = get_stack();\n\n\tif (stack.length === 0) {\n\t\treturn null;\n\t}\n\n\tstack.unshift('\\n');\n\n\tdefine_property(error, 'stack', {\n\t\tvalue: stack.join('\\n')\n\t});\n\n\tdefine_property(error, 'name', {\n\t\tvalue: label\n\t});\n\n\treturn /** @type {Error & { stack: string }} */ (error);\n}\n\n/**\n * @returns {string[]}\n */\nexport function get_stack() {\n\t// @ts-ignore - doesn't exist everywhere\n\tconst limit = Error.stackTraceLimit;\n\t// @ts-ignore - doesn't exist everywhere\n\tError.stackTraceLimit = Infinity;\n\tconst stack = new Error().stack;\n\t// @ts-ignore - doesn't exist everywhere\n\tError.stackTraceLimit = limit;\n\n\tif (!stack) return [];\n\n\tconst lines = stack.split('\\n');\n\tconst new_lines = [];\n\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst line = lines[i];\n\t\tconst posixified = line.replaceAll('\\\\', '/');\n\n\t\tif (line.trim() === 'Error') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (line.includes('validate_each_keys')) {\n\t\t\treturn [];\n\t\t}\n\n\t\tif (posixified.includes('svelte/src/internal') || posixified.includes('node_modules/.vite')) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tnew_lines.push(line);\n\t}\n\n\treturn new_lines;\n}\n\n/**\n * @param {boolean} condition\n * @param {string} message\n */\nexport function invariant(condition, message) {\n\tif (!DEV) {\n\t\tthrow new Error('invariant(...) was not guarded by if (DEV)');\n\t}\n\n\tif (!condition) e.invariant_violation(message);\n}\n","/** @import { ComponentContext, DevStackEntry, Effect } from '#client' */\nimport { DEV } from 'esm-env';\nimport * as e from './errors.js';\nimport { active_effect, active_reaction } from './runtime.js';\nimport { create_user_effect } from './reactivity/effects.js';\nimport { async_mode_flag, legacy_mode_flag } from '../flags/index.js';\nimport { FILENAME } from '../../constants.js';\nimport { BRANCH_EFFECT } from './constants.js';\n\n/** @type {ComponentContext | null} */\nexport let component_context = null;\n\n/** @param {ComponentContext | null} context */\nexport function set_component_context(context) {\n\tcomponent_context = context;\n}\n\n/** @type {DevStackEntry | null} */\nexport let dev_stack = null;\n\n/** @param {DevStackEntry | null} stack */\nexport function set_dev_stack(stack) {\n\tdev_stack = stack;\n}\n\n/**\n * Execute a callback with a new dev stack entry\n * @param {() => any} callback - Function to execute\n * @param {DevStackEntry['type']} type - Type of block/component\n * @param {any} component - Component function\n * @param {number} line - Line number\n * @param {number} column - Column number\n * @param {Record<string, any>} [additional] - Any additional properties to add to the dev stack entry\n * @returns {any}\n */\nexport function add_svelte_meta(callback, type, component, line, column, additional) {\n\tconst parent = dev_stack;\n\n\tdev_stack = {\n\t\ttype,\n\t\tfile: component[FILENAME],\n\t\tline,\n\t\tcolumn,\n\t\tparent,\n\t\t...additional\n\t};\n\n\ttry {\n\t\treturn callback();\n\t} finally {\n\t\tdev_stack = parent;\n\t}\n}\n\n/**\n * The current component function. Different from current component context:\n * ```html\n * <!-- App.svelte -->\n * <Foo>\n * <Bar /> <!-- context == Foo.svelte, function == App.svelte -->\n * </Foo>\n * ```\n * @type {ComponentContext['function']}\n */\nexport let dev_current_component_function = null;\n\n/** @param {ComponentContext['function']} fn */\nexport function set_dev_current_component_function(fn) {\n\tdev_current_component_function = fn;\n}\n\n/**\n * Returns a `[get, set]` pair of functions for working with context in a type-safe way.\n *\n * `get` will throw an error if no parent component called `set`.\n *\n * @template T\n * @returns {[() => T, (context: T) => T]}\n * @since 5.40.0\n */\nexport function createContext() {\n\tconst key = {};\n\n\treturn [\n\t\t() => {\n\t\t\tif (!hasContext(key)) {\n\t\t\t\te.missing_context();\n\t\t\t}\n\n\t\t\treturn getContext(key);\n\t\t},\n\t\t(context) => setContext(key, context)\n\t];\n}\n\n/**\n * Retrieves the context that belongs to the closest parent component with the specified `key`.\n * Must be called during component initialisation.\n *\n * [`createContext`](https://svelte.dev/docs/svelte/svelte#createContext) is a type-safe alternative.\n *\n * @template T\n * @param {any} key\n * @returns {T}\n */\nexport function getContext(key) {\n\tconst context_map = get_or_init_context_map('getContext');\n\tconst result = /** @type {T} */ (context_map.get(key));\n\treturn result;\n}\n\n/**\n * Associates an arbitrary `context` object with the current component and the specified `key`\n * and returns that object. The context is then available to children of the component\n * (including slotted content) with `getContext`.\n *\n * Like lifecycle functions, this must be called during component initialisation.\n *\n * [`createContext`](https://svelte.dev/docs/svelte/svelte#createContext) is a type-safe alternative.\n *\n * @template T\n * @param {any} key\n * @param {T} context\n * @returns {T}\n */\nexport function setContext(key, context) {\n\tconst context_map = get_or_init_context_map('setContext');\n\n\tif (async_mode_flag) {\n\t\tvar flags = /** @type {Effect} */ (active_effect).f;\n\t\tvar valid =\n\t\t\t!active_reaction &&\n\t\t\t(flags & BRANCH_EFFECT) !== 0 &&\n\t\t\t// pop() runs synchronously, so this indicates we're setting context after an await\n\t\t\t!(/** @type {ComponentContext} */ (component_context).i);\n\n\t\tif (!valid) {\n\t\t\te.set_context_after_init();\n\t\t}\n\t}\n\n\tcontext_map.set(key, context);\n\treturn context;\n}\n\n/**\n * Checks whether a given `key` has been set in the context of a parent component.\n * Must be called during component initialisation.\n *\n * @param {any} key\n * @returns {boolean}\n */\nexport function hasContext(key) {\n\tconst context_map = get_or_init_context_map('hasContext');\n\treturn context_map.has(key);\n}\n\n/**\n * Retrieves the whole context map that belongs to the closest parent component.\n * Must be called during component initialisation. Useful, for example, if you\n * programmatically create a component and want to pass the existing context to it.\n *\n * @template {Map<any, any>} [T=Map<any, any>]\n * @returns {T}\n */\nexport function getAllContexts() {\n\tconst context_map = get_or_init_context_map('getAllContexts');\n\treturn /** @type {T} */ (context_map);\n}\n\n/**\n * @param {Record<string, unknown>} props\n * @param {any} runes\n * @param {Function} [fn]\n * @returns {void}\n */\nexport function push(props, runes = false, fn) {\n\tcomponent_context = {\n\t\tp: component_context,\n\t\ti: false,\n\t\tc: null,\n\t\te: null,\n\t\ts: props,\n\t\tx: null,\n\t\tr: /** @type {Effect} */ (active_effect),\n\t\tl: legacy_mode_flag && !runes ? { s: null, u: null, $: [] } : null\n\t};\n\n\tif (DEV) {\n\t\t// component function\n\t\tcomponent_context.function = fn;\n\t\tdev_current_component_function = fn;\n\t}\n}\n\n/**\n * @template {Record<string, any>} T\n * @param {T} [component]\n * @returns {T}\n */\nexport function pop(component) {\n\tvar context = /** @type {ComponentContext} */ (component_context);\n\tvar effects = context.e;\n\n\tif (effects !== null) {\n\t\tcontext.e = null;\n\n\t\tfor (var fn of effects) {\n\t\t\tcreate_user_effect(fn);\n\t\t}\n\t}\n\n\tif (component !== undefined) {\n\t\tcontext.x = component;\n\t}\n\n\tcontext.i = true;\n\n\tcomponent_context = context.p;\n\n\tif (DEV) {\n\t\tdev_current_component_function = component_context?.function ?? null;\n\t}\n\n\treturn component ?? /** @type {T} */ ({});\n}\n\n/** @returns {boolean} */\nexport function is_runes() {\n\treturn !legacy_mode_flag || (component_context !== null && component_context.l === null);\n}\n\n/**\n * @param {string} name\n * @returns {Map<unknown, unknown>}\n */\nfunction get_or_init_context_map(name) {\n\tif (component_context === null) {\n\t\te.lifecycle_outside_component(name);\n\t}\n\n\treturn (component_context.c ??= new Map(get_parent_context(component_context) || undefined));\n}\n\n/**\n * @param {ComponentContext} component_context\n * @returns {Map<unknown, unknown> | null}\n */\nfunction get_parent_context(component_context) {\n\tlet parent = component_context.p;\n\twhile (parent !== null) {\n\t\tconst context_map = parent.c;\n\t\tif (context_map !== null) {\n\t\t\treturn context_map;\n\t\t}\n\t\tparent = parent.p;\n\t}\n\treturn null;\n}\n","import { run_all } from '../../shared/utils.js';\nimport { is_flushing_sync } from '../reactivity/batch.js';\n\n/** @type {Array<() => void>} */\nlet micro_tasks = [];\n\nfunction run_micro_tasks() {\n\tvar tasks = micro_tasks;\n\tmicro_tasks = [];\n\trun_all(tasks);\n}\n\n/**\n * @param {() => void} fn\n */\nexport function queue_micro_task(fn) {\n\tif (micro_tasks.length === 0 && !is_flushing_sync) {\n\t\tvar tasks = micro_tasks;\n\t\tqueueMicrotask(() => {\n\t\t\t// If this is false, a flushSync happened in the meantime. Do _not_ run new scheduled microtasks in that case\n\t\t\t// as the ordering of microtasks would be broken at that point - consider this case:\n\t\t\t// - queue_micro_task schedules microtask A to flush task X\n\t\t\t// - synchronously after, flushSync runs, processing task X\n\t\t\t// - synchronously after, some other microtask B is scheduled, but not through queue_micro_task but for example a Promise.resolve() in user code\n\t\t\t// - synchronously after, queue_micro_task schedules microtask C to flush task Y\n\t\t\t// - one tick later, microtask A now resolves, flushing task Y before microtask B, which is incorrect\n\t\t\t// This if check prevents that race condition (that realistically will only happen in tests)\n\t\t\tif (tasks === micro_tasks) run_micro_tasks();\n\t\t});\n\t}\n\n\tmicro_tasks.push(fn);\n}\n\n/**\n * Synchronously run any queued tasks.\n */\nexport function flush_tasks() {\n\twhile (micro_tasks.length > 0) {\n\t\trun_micro_tasks();\n\t}\n}\n","/** @import { Derived, Effect } from '#client' */\n/** @import { Boundary } from './dom/blocks/boundary.js' */\nimport { DEV } from 'esm-env';\nimport { FILENAME } from '../../constants.js';\nimport { is_firefox } from './dom/operations.js';\nimport { ERROR_VALUE, BOUNDARY_EFFECT, REACTION_RAN, EFFECT } from './constants.js';\nimport { define_property, get_descriptor } from '../shared/utils.js';\nimport { active_effect, active_reaction } from './runtime.js';\n\nconst adjustments = new WeakMap();\n\n/**\n * @param {unknown} error\n */\nexport function handle_error(error) {\n\tvar effect = active_effect;\n\n\t// for unowned deriveds, don't throw until we read the value\n\tif (effect === null) {\n\t\t/** @type {Derived} */ (active_reaction).f |= ERROR_VALUE;\n\t\treturn error;\n\t}\n\n\tif (DEV && error instanceof Error && !adjustments.has(error)) {\n\t\tadjustments.set(error, get_adjustments(error, effect));\n\t}\n\n\t// if the error occurred while creating this subtree, we let it\n\t// bubble up until it hits a boundary that can handle it, unless\n\t// it's an $effect in which case it doesn't run immediately\n\tif ((effect.f & REACTION_RAN) === 0 && (effect.f & EFFECT) === 0) {\n\t\tif (DEV && !effect.parent && error instanceof Error) {\n\t\t\tapply_adjustments(error);\n\t\t}\n\n\t\tthrow error;\n\t}\n\n\t// otherwise we bubble up the effect tree ourselves\n\tinvoke_error_boundary(error, effect);\n}\n\n/**\n * @param {unknown} error\n * @param {Effect | null} effect\n */\nexport function invoke_error_boundary(error, effect) {\n\twhile (effect !== null) {\n\t\tif ((effect.f & BOUNDARY_EFFECT) !== 0) {\n\t\t\tif ((effect.f & REACTION_RAN) === 0) {\n\t\t\t\t// we are still creating the boundary effect\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t/** @type {Boundary} */ (effect.b).error(error);\n\t\t\t\treturn;\n\t\t\t} catch (e) {\n\t\t\t\terror = e;\n\t\t\t}\n\t\t}\n\n\t\teffect = effect.parent;\n\t}\n\n\tif (DEV && error instanceof Error) {\n\t\tapply_adjustments(error);\n\t}\n\n\tthrow error;\n}\n\n/**\n * Add useful information to the error message/stack in development\n * @param {Error} error\n * @param {Effect} effect\n */\nfunction get_adjustments(error, effect) {\n\tconst message_descriptor = get_descriptor(error, 'message');\n\n\t// if the message was already changed and it's not configurable we can't change it\n\t// or it will throw a different error swallowing the original error\n\tif (message_descriptor && !message_descriptor.configurable) return;\n\n\tvar indent = is_firefox ? ' ' : '\\t';\n\tvar component_stack = `\\n${indent}in ${effect.fn?.name || '<unknown>'}`;\n\tvar context = effect.ctx;\n\n\twhile (context !== null) {\n\t\tcomponent_stack += `\\n${indent}in ${context.function?.[FILENAME].split('/').pop()}`;\n\t\tcontext = context.p;\n\t}\n\n\treturn {\n\t\tmessage: error.message + `\\n${component_stack}\\n`,\n\t\tstack: error.stack\n\t\t\t?.split('\\n')\n\t\t\t.filter((line) => !line.includes('svelte/src/internal'))\n\t\t\t.join('\\n')\n\t};\n}\n\n/**\n * @param {Error} error\n */\nfunction apply_adjustments(error) {\n\tconst adjusted = adjustments.get(error);\n\n\tif (adjusted) {\n\t\tdefine_property(error, 'message', {\n\t\t\tvalue: adjusted.message\n\t\t});\n\n\t\tdefine_property(error, 'stack', {\n\t\t\tvalue: adjusted.stack\n\t\t});\n\t}\n}\n","/** @import { Derived, Signal } from '#client' */\nimport { CLEAN, CONNECTED, DIRTY, MAYBE_DIRTY } from '#client/constants';\n\nconst STATUS_MASK = ~(DIRTY | MAYBE_DIRTY | CLEAN);\n\n/**\n * @param {Signal} signal\n * @param {number} status\n */\nexport function set_signal_status(signal, status) {\n\tsignal.f = (signal.f & STATUS_MASK) | status;\n}\n\n/**\n * Set a derived's status to CLEAN or MAYBE_DIRTY based on its connection state.\n * @param {Derived} derived\n */\nexport function update_derived_status(derived) {\n\t// Only mark as MAYBE_DIRTY if disconnected and has dependencies.\n\tif ((derived.f & CONNECTED) !== 0 || derived.deps === null) {\n\t\tset_signal_status(derived, CLEAN);\n\t} else {\n\t\tset_signal_status(derived, MAYBE_DIRTY);\n\t}\n}\n","/** @import { Derived, Effect, Value } from '#client' */\nimport { CLEAN, DERIVED, DIRTY, MAYBE_DIRTY, WAS_MARKED } from '#client/constants';\nimport { set_signal_status } from './status.js';\n\n/**\n * @param {Value[] | null} deps\n */\nfunction clear_marked(deps) {\n\tif (deps === null) return;\n\n\tfor (const dep of deps) {\n\t\tif ((dep.f & DERIVED) === 0 || (dep.f & WAS_MARKED) === 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tdep.f ^= WAS_MARKED;\n\n\t\tclear_marked(/** @type {Derived} */ (dep).deps);\n\t}\n}\n\n/**\n * @param {Effect} effect\n * @param {Set<Effect>} dirty_effects\n * @param {Set<Effect>} maybe_dirty_effects\n */\nexport function defer_effect(effect, dirty_effects, maybe_dirty_effects) {\n\tif ((effect.f & DIRTY) !== 0) {\n\t\tdirty_effects.add(effect);\n\t} else if ((effect.f & MAYBE_DIRTY) !== 0) {\n\t\tmaybe_dirty_effects.add(effect);\n\t}\n\n\t// Since we're not executing these effects now, we need to clear any WAS_MARKED flags\n\t// so that other batches can correctly reach these effects during their own traversal\n\tclear_marked(effect.deps);\n\n\t// mark as clean so they get scheduled if they depend on pending async state\n\tset_signal_status(effect, CLEAN);\n}\n","/** @import { Readable } from './public' */\nimport { untrack } from '../internal/client/runtime.js';\nimport { noop } from '../internal/shared/utils.js';\n\n/**\n * @template T\n * @param {Readable<T> | null | undefined} store\n * @param {(value: T) => void} run\n * @param {(value: T) => void} [invalidate]\n * @returns {() => void}\n */\nexport function subscribe_to_store(store, run, invalidate) {\n\tif (store == null) {\n\t\t// @ts-expect-error\n\t\trun(undefined);\n\n\t\t// @ts-expect-error\n\t\tif (invalidate) invalidate(undefined);\n\n\t\treturn noop;\n\t}\n\n\t// Svelte store takes a private second argument\n\t// StartStopNotifier could mutate state, and we want to silence the corresponding validation error\n\tconst unsub = untrack(() =>\n\t\tstore.subscribe(\n\t\t\trun,\n\t\t\t// @ts-expect-error\n\t\t\tinvalidate\n\t\t)\n\t);\n\n\t// Also support RxJS\n\t// @ts-expect-error TODO fix this in the types?\n\treturn unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;\n}\n","/** @import { Readable, StartStopNotifier, Subscriber, Unsubscriber, Updater, Writable } from '../public.js' */\n/** @import { Stores, StoresValues, SubscribeInvalidateTuple } from '../private.js' */\nimport { noop, run_all } from '../../internal/shared/utils.js';\nimport { safe_not_equal } from '../../internal/client/reactivity/equality.js';\nimport { subscribe_to_store } from '../utils.js';\n\n/**\n * @type {Array<SubscribeInvalidateTuple<any> | any>}\n */\nconst subscriber_queue = [];\n\n/**\n * Creates a `Readable` store that allows reading by subscription.\n *\n * @template T\n * @param {T} [value] initial value\n * @param {StartStopNotifier<T>} [start]\n * @returns {Readable<T>}\n */\nexport function readable(value, start) {\n\treturn {\n\t\tsubscribe: writable(value, start).subscribe\n\t};\n}\n\n/**\n * Create a `Writable` store that allows both updating and reading by subscription.\n *\n * @template T\n * @param {T} [value] initial value\n * @param {StartStopNotifier<T>} [start]\n * @returns {Writable<T>}\n */\nexport function writable(value, start = noop) {\n\t/** @type {Unsubscriber | null} */\n\tlet stop = null;\n\n\t/** @type {Set<SubscribeInvalidateTuple<T>>} */\n\tconst subscribers = new Set();\n\n\t/**\n\t * @param {T} new_value\n\t * @returns {void}\n\t */\n\tfunction set(new_value) {\n\t\tif (safe_not_equal(value, new_value)) {\n\t\t\tvalue = new_value;\n\t\t\tif (stop) {\n\t\t\t\t// store is ready\n\t\t\t\tconst run_queue = !subscriber_queue.length;\n\t\t\t\tfor (const subscriber of subscribers) {\n\t\t\t\t\tsubscriber[1]();\n\t\t\t\t\tsubscriber_queue.push(subscriber, value);\n\t\t\t\t}\n\t\t\t\tif (run_queue) {\n\t\t\t\t\tfor (let i = 0; i < subscriber_queue.length; i += 2) {\n\t\t\t\t\t\tsubscriber_queue[i][0](subscriber_queue[i + 1]);\n\t\t\t\t\t}\n\t\t\t\t\tsubscriber_queue.length = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param {Updater<T>} fn\n\t * @returns {void}\n\t */\n\tfunction update(fn) {\n\t\tset(fn(/** @type {T} */ (value)));\n\t}\n\n\t/**\n\t * @param {Subscriber<T>} run\n\t * @param {() => void} [invalidate]\n\t * @returns {Unsubscriber}\n\t */\n\tfunction subscribe(run, invalidate = noop) {\n\t\t/** @type {SubscribeInvalidateTuple<T>} */\n\t\tconst subscriber = [run, invalidate];\n\t\tsubscribers.add(subscriber);\n\t\tif (subscribers.size === 1) {\n\t\t\tstop = start(set, update) || noop;\n\t\t}\n\t\trun(/** @type {T} */ (value));\n\t\treturn () => {\n\t\t\tsubscribers.delete(subscriber);\n\t\t\tif (subscribers.size === 0 && stop) {\n\t\t\t\tstop();\n\t\t\t\tstop = null;\n\t\t\t}\n\t\t};\n\t}\n\treturn { set, update, subscribe };\n}\n\n/**\n * Derived value store by synchronizing one or more readable stores and\n * applying an aggregation function over its input values.\n *\n * @template {Stores} S\n * @template T\n * @overload\n * @param {S} stores\n * @param {(values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void} fn\n * @param {T} [initial_value]\n * @returns {Readable<T>}\n */\n/**\n * Derived value store by synchronizing one or more readable stores and\n * applying an aggregation function over its input values.\n *\n * @template {Stores} S\n * @template T\n * @overload\n * @param {S} stores\n * @param {(values: StoresValues<S>) => T} fn\n * @param {T} [initial_value]\n * @returns {Readable<T>}\n */\n/**\n * @template {Stores} S\n * @template T\n * @param {S} stores\n * @param {Function} fn\n * @param {T} [initial_value]\n * @returns {Readable<T>}\n */\nexport function derived(stores, fn, initial_value) {\n\tconst single = !Array.isArray(stores);\n\t/** @type {Array<Readable<any>>} */\n\tconst stores_array = single ? [stores] : stores;\n\tif (!stores_array.every(Boolean)) {\n\t\tthrow new Error('derived() expects stores as input, got a falsy value');\n\t}\n\tconst auto = fn.length < 2;\n\treturn readable(initial_value, (set, update) => {\n\t\tlet started = false;\n\t\t/** @type {T[]} */\n\t\tconst values = [];\n\t\tlet pending = 0;\n\t\tlet cleanup = noop;\n\t\tconst sync = () => {\n\t\t\tif (pending) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcleanup();\n\t\t\tconst result = fn(single ? values[0] : values, set, update);\n\t\t\tif (auto) {\n\t\t\t\tset(result);\n\t\t\t} else {\n\t\t\t\tcleanup = typeof result === 'function' ? result : noop;\n\t\t\t}\n\t\t};\n\t\tconst unsubscribers = stores_array.map((store, i) =>\n\t\t\tsubscribe_to_store(\n\t\t\t\tstore,\n\t\t\t\t(value) => {\n\t\t\t\t\tvalues[i] = value;\n\t\t\t\t\tpending &= ~(1 << i);\n\t\t\t\t\tif (started) {\n\t\t\t\t\t\tsync();\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tpending |= 1 << i;\n\t\t\t\t}\n\t\t\t)\n\t\t);\n\t\tstarted = true;\n\t\tsync();\n\t\treturn function stop() {\n\t\t\trun_all(unsubscribers);\n\t\t\tcleanup();\n\t\t\t// We need to set this to false because callbacks can still happen despite having unsubscribed:\n\t\t\t// Callbacks might already be placed in the queue which doesn't know it should no longer\n\t\t\t// invoke this derived store.\n\t\t\tstarted = false;\n\t\t};\n\t});\n}\n\n/**\n * Takes a store and returns a new one derived from the old one that is readable.\n *\n * @template T\n * @param {Readable<T>} store - store to make readonly\n * @returns {Readable<T>}\n */\nexport function readonly(store) {\n\treturn {\n\t\t// @ts-expect-error TODO i suspect the bind is unnecessary\n\t\tsubscribe: store.subscribe.bind(store)\n\t};\n}\n\n/**\n * Get the current value from a store by subscribing and immediately unsubscribing.\n *\n * @template T\n * @param {Readable<T>} store\n * @returns {T}\n */\nexport function get(store) {\n\tlet value;\n\tsubscribe_to_store(store, (_) => (value = _))();\n\t// @ts-expect-error\n\treturn value;\n}\n","/** @import { StoreReferencesContainer } from '#client' */\n/** @import { Store } from '#shared' */\nimport { subscribe_to_store } from '../../../store/utils.js';\nimport { get as get_store } from '../../../store/shared/index.js';\nimport { define_property, noop } from '../../shared/utils.js';\nimport { get } from '../runtime.js';\nimport { teardown } from './effects.js';\nimport { mutable_source, set } from './sources.js';\nimport { DEV } from 'esm-env';\n\n/**\n * We set this to `true` when updating a store so that we correctly\n * schedule effects if the update takes place inside a `$:` effect\n */\nexport let legacy_is_updating_store = false;\n\n/**\n * Whether or not the prop currently being read is a store binding, as in\n * `<Child bind:x={$y} />`. If it is, we treat the prop as mutable even in\n * runes mode, and skip `binding_property_non_reactive` validation\n */\nlet is_store_binding = false;\n\nlet IS_UNMOUNTED = Symbol();\n\n/**\n * Gets the current value of a store. If the store isn't subscribed to yet, it will create a proxy\n * signal that will be updated when the store is. The store references container is needed to\n * track reassignments to stores and to track the correct component context.\n * @template V\n * @param {Store<V> | null | undefined} store\n * @param {string} store_name\n * @param {StoreReferencesContainer} stores\n * @returns {V}\n */\nexport function store_get(store, store_name, stores) {\n\tconst entry = (stores[store_name] ??= {\n\t\tstore: null,\n\t\tsource: mutable_source(undefined),\n\t\tunsubscribe: noop\n\t});\n\n\tif (DEV) {\n\t\tentry.source.label = store_name;\n\t}\n\n\t// if the component that setup this is already unmounted we don't want to register a subscription\n\tif (entry.store !== store && !(IS_UNMOUNTED in stores)) {\n\t\tentry.unsubscribe();\n\t\tentry.store = store ?? null;\n\n\t\tif (store == null) {\n\t\t\tentry.source.v = undefined; // see synchronous callback comment below\n\t\t\tentry.unsubscribe = noop;\n\t\t} else {\n\t\t\tvar is_synchronous_callback = true;\n\n\t\t\tentry.unsubscribe = subscribe_to_store(store, (v) => {\n\t\t\t\tif (is_synchronous_callback) {\n\t\t\t\t\t// If the first updates to the store value (possibly multiple of them) are synchronously\n\t\t\t\t\t// inside a derived, we will hit the `state_unsafe_mutation` error if we `set` the value\n\t\t\t\t\tentry.source.v = v;\n\t\t\t\t} else {\n\t\t\t\t\tset(entry.source, v);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tis_synchronous_callback = false;\n\t\t}\n\t}\n\n\t// if the component that setup this stores is already unmounted the source will be out of sync\n\t// so we just use the `get` for the stores, less performant but it avoids to create a memory leak\n\t// and it will keep the value consistent\n\tif (store && IS_UNMOUNTED in stores) {\n\t\treturn get_store(store);\n\t}\n\n\treturn get(entry.source);\n}\n\n/**\n * Unsubscribe from a store if it's not the same as the one in the store references container.\n * We need this in addition to `store_get` because someone could unsubscribe from a store but\n * then never subscribe to the new one (if any), causing the subscription to stay open wrongfully.\n * @param {Store<any> | null | undefined} store\n * @param {string} store_name\n * @param {StoreReferencesContainer} stores\n */\nexport function store_unsub(store, store_name, stores) {\n\t/** @type {StoreReferencesContainer[''] | undefined} */\n\tlet entry = stores[store_name];\n\n\tif (entry && entry.store !== store) {\n\t\t// Don't reset store yet, so that store_get above can resubscribe to new store if necessary\n\t\tentry.unsubscribe();\n\t\tentry.unsubscribe = noop;\n\t}\n\n\treturn store;\n}\n\n/**\n * Sets the new value of a store and returns that value.\n * @template V\n * @param {Store<V>} store\n * @param {V} value\n * @returns {V}\n */\nexport function store_set(store, value) {\n\tupdate_with_flag(store, value);\n\treturn value;\n}\n\n/**\n * @param {StoreReferencesContainer} stores\n * @param {string} store_name\n */\nexport function invalidate_store(stores, store_name) {\n\tvar entry = stores[store_name];\n\tif (entry.store !== null) {\n\t\tstore_set(entry.store, entry.source.v);\n\t}\n}\n\n/**\n * Unsubscribes from all auto-subscribed stores on destroy\n * @returns {[StoreReferencesContainer, ()=>void]}\n */\nexport function setup_stores() {\n\t/** @type {StoreReferencesContainer} */\n\tconst stores = {};\n\n\tfunction cleanup() {\n\t\tteardown(() => {\n\t\t\tfor (var store_name in stores) {\n\t\t\t\tconst ref = stores[store_name];\n\t\t\t\tref.unsubscribe();\n\t\t\t}\n\t\t\tdefine_property(stores, IS_UNMOUNTED, {\n\t\t\t\tenumerable: false,\n\t\t\t\tvalue: true\n\t\t\t});\n\t\t});\n\t}\n\n\treturn [stores, cleanup];\n}\n\n/**\n * @param {Store<V>} store\n * @param {V} value\n * @template V\n */\nfunction update_with_flag(store, value) {\n\tlegacy_is_updating_store = true;\n\n\ttry {\n\t\tstore.set(value);\n\t} finally {\n\t\tlegacy_is_updating_store = false;\n\t}\n}\n\n/**\n * Updates a store with a new value.\n * @param {Store<V>} store the store to update\n * @param {any} expression the expression that mutates the store\n * @param {V} new_value the new store value\n * @template V\n */\nexport function store_mutate(store, expression, new_value) {\n\tupdate_with_flag(store, new_value);\n\treturn expression;\n}\n\n/**\n * @param {Store<number>} store\n * @param {number} store_value\n * @param {1 | -1} [d]\n * @returns {number}\n */\nexport function update_store(store, store_value, d = 1) {\n\tupdate_with_flag(store, store_value + d);\n\treturn store_value;\n}\n\n/**\n * @param {Store<number>} store\n * @param {number} store_value\n * @param {1 | -1} [d]\n * @returns {number}\n */\nexport function update_pre_store(store, store_value, d = 1) {\n\tconst value = store_value + d;\n\tupdate_with_flag(store, value);\n\treturn value;\n}\n\n/**\n * Called inside prop getters to communicate that the prop is a store binding\n */\nexport function mark_store_binding() {\n\tis_store_binding = true;\n}\n\n/**\n * Returns a tuple that indicates whether `fn()` reads a prop that is a store binding.\n * Used to prevent `binding_property_non_reactive` validation false positives and\n * ensure that these props are treated as mutable even in runes mode\n * @template T\n * @param {() => T} fn\n * @returns {[T, boolean]}\n */\nexport function capture_store_binding(fn) {\n\tvar previous_is_store_binding = is_store_binding;\n\n\ttry {\n\t\tis_store_binding = false;\n\t\treturn [fn(), is_store_binding];\n\t} finally {\n\t\tis_store_binding = previous_is_store_binding;\n\t}\n}\n","/** @import { Fork } from 'svelte' */\n/** @import { Derived, Effect, Reaction, Source, Value } from '#client' */\nimport {\n\tBLOCK_EFFECT,\n\tBRANCH_EFFECT,\n\tCLEAN,\n\tDESTROYED,\n\tDIRTY,\n\tEFFECT,\n\tASYNC,\n\tINERT,\n\tRENDER_EFFECT,\n\tROOT_EFFECT,\n\tMAYBE_DIRTY,\n\tDERIVED,\n\tEAGER_EFFECT,\n\tERROR_VALUE,\n\tMANAGED_EFFECT,\n\tREACTION_RAN\n} from '#client/constants';\nimport { async_mode_flag } from '../../flags/index.js';\nimport { deferred, define_property, includes } from '../../shared/utils.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tget,\n\tincrement_write_version,\n\tis_dirty,\n\tupdate_effect\n} from '../runtime.js';\nimport * as e from '../errors.js';\nimport { flush_tasks, queue_micro_task } from '../dom/task.js';\nimport { DEV } from 'esm-env';\nimport { invoke_error_boundary } from '../error-handling.js';\nimport { flush_eager_effects, old_values, set_eager_effects, source, update } from './sources.js';\nimport { eager_effect, unlink_effect } from './effects.js';\nimport { defer_effect } from './utils.js';\nimport { UNINITIALIZED } from '../../../constants.js';\nimport { set_signal_status } from './status.js';\nimport { legacy_is_updating_store } from './store.js';\nimport { invariant } from '../../shared/dev.js';\nimport { log_effect_tree } from '../dev/debug.js';\n\n/** @type {Set<Batch>} */\nconst batches = new Set();\n\n/** @type {Batch | null} */\nexport let current_batch = null;\n\n/**\n * This is needed to avoid overwriting inputs\n * @type {Batch | null}\n */\nexport let previous_batch = null;\n\n/**\n * When time travelling (i.e. working in one batch, while other batches\n * still have ongoing work), we ignore the real values of affected\n * signals in favour of their values within the batch\n * @type {Map<Value, any> | null}\n */\nexport let batch_values = null;\n\n/** @type {Effect | null} */\nlet last_scheduled_effect = null;\n\nexport let is_flushing_sync = false;\nlet is_processing = false;\n\n/**\n * During traversal, this is an array. Newly created effects are (if not immediately\n * executed) pushed to this array, rather than going through the scheduling\n * rigamarole that would cause another turn of the flush loop.\n * @type {Effect[] | null}\n */\nexport let collected_effects = null;\n\n/**\n * An array of effects that are marked during traversal as a result of a `set`\n * (not `internal_set`) call. These will be added to the next batch and\n * trigger another `batch.process()`\n * @type {Effect[] | null}\n * @deprecated when we get rid of legacy mode and stores, we can get rid of this\n */\nexport let legacy_updates = null;\n\nvar flush_count = 0;\nvar source_stacks = DEV ? new Set() : null;\n\nlet uid = 1;\n\nexport class Batch {\n\tid = uid++;\n\n\t/**\n\t * The current values of any signals that are updated in this batch.\n\t * Tuple format: [value, is_derived] (note: is_derived is false for deriveds, too, if they were overridden via assignment)\n\t * They keys of this map are identical to `this.#previous`\n\t * @type {Map<Value, [any, boolean]>}\n\t */\n\tcurrent = new Map();\n\n\t/**\n\t * The values of any signals (sources and deriveds) that are updated in this batch _before_ those updates took place.\n\t * They keys of this map are identical to `this.#current`\n\t * @type {Map<Value, any>}\n\t */\n\tprevious = new Map();\n\n\t/**\n\t * When the batch is committed (and the DOM is updated), we need to remove old branches\n\t * and append new ones by calling the functions added inside (if/each/key/etc) blocks\n\t * @type {Set<(batch: Batch) => void>}\n\t */\n\t#commit_callbacks = new Set();\n\n\t/**\n\t * If a fork is discarded, we need to destroy any effects that are no longer needed\n\t * @type {Set<(batch: Batch) => void>}\n\t */\n\t#discard_callbacks = new Set();\n\n\t/**\n\t * Callbacks that should run only when a fork is committed.\n\t * @type {Set<(batch: Batch) => void>}\n\t */\n\t#fork_commit_callbacks = new Set();\n\n\t/**\n\t * Async effects that are currently in flight\n\t * @type {Map<Effect, number>}\n\t */\n\t#pending = new Map();\n\n\t/**\n\t * Async effects that are currently in flight, _not_ inside a pending boundary\n\t * @type {Map<Effect, number>}\n\t */\n\t#blocking_pending = new Map();\n\n\t/**\n\t * A deferred that resolves when the batch is committed, used with `settled()`\n\t * TODO replace with Promise.withResolvers once supported widely enough\n\t * @type {{ promise: Promise<void>, resolve: (value?: any) => void, reject: (reason: unknown) => void } | null}\n\t */\n\t#deferred = null;\n\n\t/**\n\t * The root effects that need to be flushed\n\t * @type {Effect[]}\n\t */\n\t#roots = [];\n\n\t/**\n\t * Effects created while this batch was active.\n\t * @type {Effect[]}\n\t */\n\t#new_effects = [];\n\n\t/**\n\t * Deferred effects (which run after async work has completed) that are DIRTY\n\t * @type {Set<Effect>}\n\t */\n\t#dirty_effects = new Set();\n\n\t/**\n\t * Deferred effects that are MAYBE_DIRTY\n\t * @type {Set<Effect>}\n\t */\n\t#maybe_dirty_effects = new Set();\n\n\t/**\n\t * A map of branches that still exist, but will be destroyed when this batch\n\t * is committed — we skip over these during `process`.\n\t * The value contains child effects that were dirty/maybe_dirty before being reset,\n\t * so they can be rescheduled if the branch survives.\n\t * @type {Map<Effect, { d: Effect[], m: Effect[] }>}\n\t */\n\t#skipped_branches = new Map();\n\n\t/**\n\t * Inverse of #skipped_branches which we need to tell prior batches to unskip them when committing\n\t * @type {Set<Effect>}\n\t */\n\t#unskipped_branches = new Set();\n\n\tis_fork = false;\n\n\t#decrement_queued = false;\n\n\t/** @type {Set<Batch>} */\n\t#blockers = new Set();\n\n\t#is_deferred() {\n\t\treturn this.is_fork || this.#blocking_pending.size > 0;\n\t}\n\n\t#is_blocked() {\n\t\tfor (const batch of this.#blockers) {\n\t\t\tfor (const effect of batch.#blocking_pending.keys()) {\n\t\t\t\tvar skipped = false;\n\t\t\t\tvar e = effect;\n\n\t\t\t\twhile (e.parent !== null) {\n\t\t\t\t\tif (this.#skipped_branches.has(e)) {\n\t\t\t\t\t\tskipped = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\te = e.parent;\n\t\t\t\t}\n\n\t\t\t\tif (!skipped) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Add an effect to the #skipped_branches map and reset its children\n\t * @param {Effect} effect\n\t */\n\tskip_effect(effect) {\n\t\tif (!this.#skipped_branches.has(effect)) {\n\t\t\tthis.#skipped_branches.set(effect, { d: [], m: [] });\n\t\t}\n\t\tthis.#unskipped_branches.delete(effect);\n\t}\n\n\t/**\n\t * Remove an effect from the #skipped_branches map and reschedule\n\t * any tracked dirty/maybe_dirty child effects\n\t * @param {Effect} effect\n\t * @param {(e: Effect) => void} callback\n\t */\n\tunskip_effect(effect, callback = (e) => this.schedule(e)) {\n\t\tvar tracked = this.#skipped_branches.get(effect);\n\t\tif (tracked) {\n\t\t\tthis.#skipped_branches.delete(effect);\n\n\t\t\tfor (var e of tracked.d) {\n\t\t\t\tset_signal_status(e, DIRTY);\n\t\t\t\tcallback(e);\n\t\t\t}\n\n\t\t\tfor (e of tracked.m) {\n\t\t\t\tset_signal_status(e, MAYBE_DIRTY);\n\t\t\t\tcallback(e);\n\t\t\t}\n\t\t}\n\t\tthis.#unskipped_branches.add(effect);\n\t}\n\n\t#process() {\n\t\tif (flush_count++ > 1000) {\n\t\t\tbatches.delete(this);\n\t\t\tinfinite_loop_guard();\n\t\t}\n\n\t\t// we only reschedule previously-deferred effects if we expect\n\t\t// to be able to run them after processing the batch\n\t\tif (!this.#is_deferred()) {\n\t\t\tfor (const e of this.#dirty_effects) {\n\t\t\t\tthis.#maybe_dirty_effects.delete(e);\n\t\t\t\tset_signal_status(e, DIRTY);\n\t\t\t\tthis.schedule(e);\n\t\t\t}\n\n\t\t\tfor (const e of this.#maybe_dirty_effects) {\n\t\t\t\tset_signal_status(e, MAYBE_DIRTY);\n\t\t\t\tthis.schedule(e);\n\t\t\t}\n\t\t}\n\n\t\tconst roots = this.#roots;\n\t\tthis.#roots = [];\n\n\t\tthis.apply();\n\n\t\t/** @type {Effect[]} */\n\t\tvar effects = (collected_effects = []);\n\n\t\t/** @type {Effect[]} */\n\t\tvar render_effects = [];\n\n\t\t/**\n\t\t * @type {Effect[]}\n\t\t * @deprecated when we get rid of legacy mode and stores, we can get rid of this\n\t\t */\n\t\tvar updates = (legacy_updates = []);\n\n\t\tfor (const root of roots) {\n\t\t\ttry {\n\t\t\t\tthis.#traverse(root, effects, render_effects);\n\t\t\t} catch (e) {\n\t\t\t\treset_all(root);\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\n\t\t// any writes should take effect in a subsequent batch\n\t\tcurrent_batch = null;\n\n\t\tif (updates.length > 0) {\n\t\t\tvar batch = Batch.ensure();\n\t\t\tfor (const e of updates) {\n\t\t\t\tbatch.schedule(e);\n\t\t\t}\n\t\t}\n\n\t\tcollected_effects = null;\n\t\tlegacy_updates = null;\n\n\t\tif (this.#is_deferred() || this.#is_blocked()) {\n\t\t\tthis.#defer_effects(render_effects);\n\t\t\tthis.#defer_effects(effects);\n\n\t\t\tfor (const [e, t] of this.#skipped_branches) {\n\t\t\t\treset_branch(e, t);\n\t\t\t}\n\t\t} else {\n\t\t\tif (this.#pending.size === 0) {\n\t\t\t\tbatches.delete(this);\n\t\t\t}\n\n\t\t\t// clear effects. Those that are still needed will be rescheduled through unskipping the skipped branches.\n\t\t\tthis.#dirty_effects.clear();\n\t\t\tthis.#maybe_dirty_effects.clear();\n\n\t\t\t// append/remove branches\n\t\t\tfor (const fn of this.#commit_callbacks) fn(this);\n\t\t\tthis.#commit_callbacks.clear();\n\n\t\t\tprevious_batch = this;\n\t\t\tflush_queued_effects(render_effects);\n\t\t\tflush_queued_effects(effects);\n\t\t\tprevious_batch = null;\n\n\t\t\tthis.#deferred?.resolve();\n\t\t}\n\n\t\tvar next_batch = /** @type {Batch | null} */ (/** @type {unknown} */ (current_batch));\n\n\t\t// Edge case: During traversal new branches might create effects that run immediately and set state,\n\t\t// causing an effect and therefore a root to be scheduled again. We need to traverse the current batch\n\t\t// once more in that case - most of the time this will just clean up dirty branches.\n\t\tif (this.#roots.length > 0) {\n\t\t\tconst batch = (next_batch ??= this);\n\t\t\tbatch.#roots.push(...this.#roots.filter((r) => !batch.#roots.includes(r)));\n\t\t}\n\n\t\tif (next_batch !== null) {\n\t\t\tbatches.add(next_batch);\n\n\t\t\tif (DEV) {\n\t\t\t\tfor (const source of this.current.keys()) {\n\t\t\t\t\t/** @type {Set<Source>} */ (source_stacks).add(source);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnext_batch.#process();\n\t\t}\n\n\t\t// In sync mode flushSync can cause #commit to wrongfully think that there needs to be a rebase, so we only do it in async mode\n\t\t// TODO fix the underlying cause, otherwise this will likely regress when non-async mode is removed\n\t\tif (async_mode_flag && !batches.has(this)) {\n\t\t\tthis.#commit();\n\t\t}\n\t}\n\n\t/**\n\t * Traverse the effect tree, executing effects or stashing\n\t * them for later execution as appropriate\n\t * @param {Effect} root\n\t * @param {Effect[]} effects\n\t * @param {Effect[]} render_effects\n\t */\n\t#traverse(root, effects, render_effects) {\n\t\troot.f ^= CLEAN;\n\n\t\tvar effect = root.first;\n\n\t\twhile (effect !== null) {\n\t\t\tvar flags = effect.f;\n\t\t\tvar is_branch = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0;\n\t\t\tvar is_skippable_branch = is_branch && (flags & CLEAN) !== 0;\n\n\t\t\tvar skip = is_skippable_branch || (flags & INERT) !== 0 || this.#skipped_branches.has(effect);\n\n\t\t\tif (!skip && effect.fn !== null) {\n\t\t\t\tif (is_branch) {\n\t\t\t\t\teffect.f ^= CLEAN;\n\t\t\t\t} else if ((flags & EFFECT) !== 0) {\n\t\t\t\t\teffects.push(effect);\n\t\t\t\t} else if (async_mode_flag && (flags & (RENDER_EFFECT | MANAGED_EFFECT)) !== 0) {\n\t\t\t\t\trender_effects.push(effect);\n\t\t\t\t} else if (is_dirty(effect)) {\n\t\t\t\t\tif ((flags & BLOCK_EFFECT) !== 0) this.#maybe_dirty_effects.add(effect);\n\t\t\t\t\tupdate_effect(effect);\n\t\t\t\t}\n\n\t\t\t\tvar child = effect.first;\n\n\t\t\t\tif (child !== null) {\n\t\t\t\t\teffect = child;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\twhile (effect !== null) {\n\t\t\t\tvar next = effect.next;\n\n\t\t\t\tif (next !== null) {\n\t\t\t\t\teffect = next;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\teffect = effect.parent;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param {Effect[]} effects\n\t */\n\t#defer_effects(effects) {\n\t\tfor (var i = 0; i < effects.length; i += 1) {\n\t\t\tdefer_effect(effects[i], this.#dirty_effects, this.#maybe_dirty_effects);\n\t\t}\n\t}\n\n\t/**\n\t * Associate a change to a given source with the current\n\t * batch, noting its previous and current values\n\t * @param {Value} source\n\t * @param {any} value\n\t * @param {boolean} [is_derived]\n\t */\n\tcapture(source, value, is_derived = false) {\n\t\tif (source.v !== UNINITIALIZED && !this.previous.has(source)) {\n\t\t\tthis.previous.set(source, source.v);\n\t\t}\n\n\t\t// Don't save errors in `batch_values`, or they won't be thrown in `runtime.js#get`\n\t\tif ((source.f & ERROR_VALUE) === 0) {\n\t\t\tthis.current.set(source, [value, is_derived]);\n\t\t\tbatch_values?.set(source, value);\n\t\t}\n\n\t\tif (!this.is_fork) {\n\t\t\tsource.v = value;\n\t\t}\n\t}\n\n\tactivate() {\n\t\tcurrent_batch = this;\n\t}\n\n\tdeactivate() {\n\t\tcurrent_batch = null;\n\t\tbatch_values = null;\n\t}\n\n\tflush() {\n\t\tvar source_stacks = DEV ? new Set() : null;\n\n\t\ttry {\n\t\t\tis_processing = true;\n\t\t\tcurrent_batch = this;\n\n\t\t\tthis.#process();\n\t\t} finally {\n\t\t\tflush_count = 0;\n\t\t\tlast_scheduled_effect = null;\n\t\t\tcollected_effects = null;\n\t\t\tlegacy_updates = null;\n\t\t\tis_processing = false;\n\n\t\t\tcurrent_batch = null;\n\t\t\tbatch_values = null;\n\n\t\t\told_values.clear();\n\n\t\t\tif (DEV) {\n\t\t\t\tfor (const source of /** @type {Set<Source>} */ (source_stacks)) {\n\t\t\t\t\tsource.updated = null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdiscard() {\n\t\tfor (const fn of this.#discard_callbacks) fn(this);\n\t\tthis.#discard_callbacks.clear();\n\t\tthis.#fork_commit_callbacks.clear();\n\n\t\tbatches.delete(this);\n\t}\n\n\t/**\n\t * @param {Effect} effect\n\t */\n\tregister_created_effect(effect) {\n\t\tthis.#new_effects.push(effect);\n\t}\n\n\t#commit() {\n\t\t// If there are other pending batches, they now need to be 'rebased' —\n\t\t// in other words, we re-run block/async effects with the newly\n\t\t// committed state, unless the batch in question has a more\n\t\t// recent value for a given source\n\t\tfor (const batch of batches) {\n\t\t\tvar is_earlier = batch.id < this.id;\n\n\t\t\t/** @type {Source[]} */\n\t\t\tvar sources = [];\n\n\t\t\tfor (const [source, [value, is_derived]] of this.current) {\n\t\t\t\tif (batch.current.has(source)) {\n\t\t\t\t\tvar batch_value = /** @type {[any, boolean]} */ (batch.current.get(source))[0]; // faster than destructuring\n\n\t\t\t\t\tif (is_earlier && value !== batch_value) {\n\t\t\t\t\t\t// bring the value up to date\n\t\t\t\t\t\tbatch.current.set(source, [value, is_derived]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// same value or later batch has more recent value,\n\t\t\t\t\t\t// no need to re-run these effects\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsources.push(source);\n\t\t\t}\n\n\t\t\t// Re-run async/block effects that depend on distinct values changed in both batches\n\t\t\tvar others = [...batch.current.keys()].filter((s) => !this.current.has(s));\n\n\t\t\tif (others.length === 0) {\n\t\t\t\tif (is_earlier) {\n\t\t\t\t\t// this batch is now obsolete and can be discarded\n\t\t\t\t\tbatch.discard();\n\t\t\t\t}\n\t\t\t} else if (sources.length > 0) {\n\t\t\t\tif (DEV) {\n\t\t\t\t\tinvariant(batch.#roots.length === 0, 'Batch has scheduled roots');\n\t\t\t\t}\n\n\t\t\t\t// A batch was unskipped in a later batch -> tell prior batches to unskip it, too\n\t\t\t\tif (is_earlier) {\n\t\t\t\t\tfor (const unskipped of this.#unskipped_branches) {\n\t\t\t\t\t\tbatch.unskip_effect(unskipped, (e) => {\n\t\t\t\t\t\t\tif ((e.f & (BLOCK_EFFECT | ASYNC)) !== 0) {\n\t\t\t\t\t\t\t\tbatch.schedule(e);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbatch.#defer_effects([e]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbatch.activate();\n\n\t\t\t\t/** @type {Set<Value>} */\n\t\t\t\tvar marked = new Set();\n\n\t\t\t\t/** @type {Map<Reaction, boolean>} */\n\t\t\t\tvar checked = new Map();\n\n\t\t\t\tfor (var source of sources) {\n\t\t\t\t\tmark_effects(source, others, marked, checked);\n\t\t\t\t}\n\n\t\t\t\tchecked = new Map();\n\t\t\t\tvar current_unequal = [...batch.current.keys()].filter((c) =>\n\t\t\t\t\tthis.current.has(c) ? /** @type {[any, boolean]} */ (this.current.get(c))[0] !== c : true\n\t\t\t\t);\n\n\t\t\t\tfor (const effect of this.#new_effects) {\n\t\t\t\t\tif (\n\t\t\t\t\t\t(effect.f & (DESTROYED | INERT | EAGER_EFFECT)) === 0 &&\n\t\t\t\t\t\tdepends_on(effect, current_unequal, checked)\n\t\t\t\t\t) {\n\t\t\t\t\t\tif ((effect.f & (ASYNC | BLOCK_EFFECT)) !== 0) {\n\t\t\t\t\t\t\tset_signal_status(effect, DIRTY);\n\t\t\t\t\t\t\tbatch.schedule(effect);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tbatch.#dirty_effects.add(effect);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Only apply and traverse when we know we triggered async work with marking the effects\n\t\t\t\tif (batch.#roots.length > 0) {\n\t\t\t\t\tbatch.apply();\n\n\t\t\t\t\tfor (var root of batch.#roots) {\n\t\t\t\t\t\tbatch.#traverse(root, [], []);\n\t\t\t\t\t}\n\n\t\t\t\t\tbatch.#roots = [];\n\t\t\t\t}\n\n\t\t\t\tbatch.deactivate();\n\t\t\t}\n\t\t}\n\n\t\tfor (const batch of batches) {\n\t\t\tif (batch.#blockers.has(this)) {\n\t\t\t\tbatch.#blockers.delete(this);\n\n\t\t\t\tif (batch.#blockers.size === 0 && !batch.#is_deferred()) {\n\t\t\t\t\tbatch.activate();\n\t\t\t\t\tbatch.#process();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param {boolean} blocking\n\t * @param {Effect} effect\n\t */\n\tincrement(blocking, effect) {\n\t\tlet pending_count = this.#pending.get(effect) ?? 0;\n\t\tthis.#pending.set(effect, pending_count + 1);\n\n\t\tif (blocking) {\n\t\t\tlet blocking_pending_count = this.#blocking_pending.get(effect) ?? 0;\n\t\t\tthis.#blocking_pending.set(effect, blocking_pending_count + 1);\n\t\t}\n\t}\n\n\t/**\n\t * @param {boolean} blocking\n\t * @param {Effect} effect\n\t * @param {boolean} skip - whether to skip updates (because this is triggered by a stale reaction)\n\t */\n\tdecrement(blocking, effect, skip) {\n\t\tlet pending_count = this.#pending.get(effect) ?? 0;\n\n\t\tif (pending_count === 1) {\n\t\t\tthis.#pending.delete(effect);\n\t\t} else {\n\t\t\tthis.#pending.set(effect, pending_count - 1);\n\t\t}\n\n\t\tif (blocking) {\n\t\t\tlet blocking_pending_count = this.#blocking_pending.get(effect) ?? 0;\n\n\t\t\tif (blocking_pending_count === 1) {\n\t\t\t\tthis.#blocking_pending.delete(effect);\n\t\t\t} else {\n\t\t\t\tthis.#blocking_pending.set(effect, blocking_pending_count - 1);\n\t\t\t}\n\t\t}\n\n\t\tif (this.#decrement_queued || skip) return;\n\t\tthis.#decrement_queued = true;\n\n\t\tqueue_micro_task(() => {\n\t\t\tthis.#decrement_queued = false;\n\t\t\tthis.flush();\n\t\t});\n\t}\n\n\t/**\n\t * @param {Set<Effect>} dirty_effects\n\t * @param {Set<Effect>} maybe_dirty_effects\n\t */\n\ttransfer_effects(dirty_effects, maybe_dirty_effects) {\n\t\tfor (const e of dirty_effects) {\n\t\t\tthis.#dirty_effects.add(e);\n\t\t}\n\n\t\tfor (const e of maybe_dirty_effects) {\n\t\t\tthis.#maybe_dirty_effects.add(e);\n\t\t}\n\n\t\tdirty_effects.clear();\n\t\tmaybe_dirty_effects.clear();\n\t}\n\n\t/** @param {(batch: Batch) => void} fn */\n\toncommit(fn) {\n\t\tthis.#commit_callbacks.add(fn);\n\t}\n\n\t/** @param {(batch: Batch) => void} fn */\n\tondiscard(fn) {\n\t\tthis.#discard_callbacks.add(fn);\n\t}\n\n\t/** @param {(batch: Batch) => void} fn */\n\ton_fork_commit(fn) {\n\t\tthis.#fork_commit_callbacks.add(fn);\n\t}\n\n\trun_fork_commit_callbacks() {\n\t\tfor (const fn of this.#fork_commit_callbacks) fn(this);\n\t\tthis.#fork_commit_callbacks.clear();\n\t}\n\n\tsettled() {\n\t\treturn (this.#deferred ??= deferred()).promise;\n\t}\n\n\tstatic ensure() {\n\t\tif (current_batch === null) {\n\t\t\tconst batch = (current_batch = new Batch());\n\n\t\t\tif (!is_processing) {\n\t\t\t\tbatches.add(current_batch);\n\n\t\t\t\tif (!is_flushing_sync) {\n\t\t\t\t\tqueue_micro_task(() => {\n\t\t\t\t\t\tif (current_batch !== batch) {\n\t\t\t\t\t\t\t// a flushSync happened in the meantime\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tbatch.flush();\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn current_batch;\n\t}\n\n\tapply() {\n\t\tif (!async_mode_flag || (!this.is_fork && batches.size === 1)) {\n\t\t\tbatch_values = null;\n\t\t\treturn;\n\t\t}\n\n\t\t// if there are multiple batches, we are 'time travelling' —\n\t\t// we need to override values with the ones in this batch...\n\t\tbatch_values = new Map();\n\t\tfor (const [source, [value]] of this.current) {\n\t\t\tbatch_values.set(source, value);\n\t\t}\n\n\t\t// ...and undo changes belonging to other batches unless they block this one\n\t\tfor (const batch of batches) {\n\t\t\tif (batch === this || batch.is_fork) continue;\n\n\t\t\t// A batch is blocked on an earlier batch if it overlaps with the earlier batch's changes but is not a superset\n\t\t\tvar intersects = false;\n\t\t\tvar differs = false;\n\n\t\t\tif (batch.id < this.id) {\n\t\t\t\tfor (const [source, [, is_derived]] of batch.current) {\n\t\t\t\t\t// Derived values don't partake in the blocking mechanism, because a derived could\n\t\t\t\t\t// be triggered in one batch already but not the other one yet, causing a false-positive\n\t\t\t\t\tif (is_derived) continue;\n\n\t\t\t\t\tintersects ||= this.current.has(source);\n\t\t\t\t\tdiffers ||= !this.current.has(source);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (intersects && differs) {\n\t\t\t\tthis.#blockers.add(batch);\n\t\t\t} else {\n\t\t\t\tfor (const [source, previous] of batch.previous) {\n\t\t\t\t\tif (!batch_values.has(source)) {\n\t\t\t\t\t\tbatch_values.set(source, previous);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t *\n\t * @param {Effect} effect\n\t */\n\tschedule(effect) {\n\t\tlast_scheduled_effect = effect;\n\n\t\t// defer render effects inside a pending boundary\n\t\t// TODO the `REACTION_RAN` check is only necessary because of legacy `$:` effects AFAICT — we can remove later\n\t\tif (\n\t\t\teffect.b?.is_pending &&\n\t\t\t(effect.f & (EFFECT | RENDER_EFFECT | MANAGED_EFFECT)) !== 0 &&\n\t\t\t(effect.f & REACTION_RAN) === 0\n\t\t) {\n\t\t\teffect.b.defer_effect(effect);\n\t\t\treturn;\n\t\t}\n\n\t\tvar e = effect;\n\n\t\twhile (e.parent !== null) {\n\t\t\te = e.parent;\n\t\t\tvar flags = e.f;\n\n\t\t\t// if the effect is being scheduled because a parent (each/await/etc) block\n\t\t\t// updated an internal source, or because a branch is being unskipped,\n\t\t\t// bail out or we'll cause a second flush\n\t\t\tif (collected_effects !== null && e === active_effect) {\n\t\t\t\tif (async_mode_flag) return;\n\n\t\t\t\t// in sync mode, render effects run during traversal. in an extreme edge case\n\t\t\t\t// — namely that we're setting a value inside a derived read during traversal —\n\t\t\t\t// they can be made dirty after they have already been visited, in which\n\t\t\t\t// case we shouldn't bail out. we also shouldn't bail out if we're\n\t\t\t\t// updating a store inside a `$:`, since this might invalidate\n\t\t\t\t// effects that were already visited\n\t\t\t\tif (\n\t\t\t\t\t(active_reaction === null || (active_reaction.f & DERIVED) === 0) &&\n\t\t\t\t\t!legacy_is_updating_store\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ((flags & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) {\n\t\t\t\tif ((flags & CLEAN) === 0) {\n\t\t\t\t\t// branch is already dirty, bail\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\te.f ^= CLEAN;\n\t\t\t}\n\t\t}\n\n\t\tthis.#roots.push(e);\n\t}\n}\n\n// TODO Svelte@6 think about removing the callback argument.\n/**\n * Synchronously flush any pending updates.\n * Returns void if no callback is provided, otherwise returns the result of calling the callback.\n * @template [T=void]\n * @param {(() => T) | undefined} [fn]\n * @returns {T}\n */\nexport function flushSync(fn) {\n\tvar was_flushing_sync = is_flushing_sync;\n\tis_flushing_sync = true;\n\n\ttry {\n\t\tvar result;\n\n\t\tif (fn) {\n\t\t\tif (current_batch !== null && !current_batch.is_fork) {\n\t\t\t\tcurrent_batch.flush();\n\t\t\t}\n\n\t\t\tresult = fn();\n\t\t}\n\n\t\twhile (true) {\n\t\t\tflush_tasks();\n\n\t\t\tif (current_batch === null) {\n\t\t\t\treturn /** @type {T} */ (result);\n\t\t\t}\n\n\t\t\tcurrent_batch.flush();\n\t\t}\n\t} finally {\n\t\tis_flushing_sync = was_flushing_sync;\n\t}\n}\n\nfunction infinite_loop_guard() {\n\tif (DEV) {\n\t\tvar updates = new Map();\n\n\t\tfor (const source of /** @type {Batch} */ (current_batch).current.keys()) {\n\t\t\tfor (const [stack, update] of source.updated ?? []) {\n\t\t\t\tvar entry = updates.get(stack);\n\n\t\t\t\tif (!entry) {\n\t\t\t\t\tentry = { error: update.error, count: 0 };\n\t\t\t\t\tupdates.set(stack, entry);\n\t\t\t\t}\n\n\t\t\t\tentry.count += update.count;\n\t\t\t}\n\t\t}\n\n\t\tfor (const update of updates.values()) {\n\t\t\tif (update.error) {\n\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\tconsole.error(update.error);\n\t\t\t}\n\t\t}\n\t}\n\n\ttry {\n\t\te.effect_update_depth_exceeded();\n\t} catch (error) {\n\t\tif (DEV) {\n\t\t\t// stack contains no useful information, replace it\n\t\t\tdefine_property(error, 'stack', { value: '' });\n\t\t}\n\n\t\t// Best effort: invoke the boundary nearest the most recent\n\t\t// effect and hope that it's relevant to the infinite loop\n\t\tinvoke_error_boundary(error, last_scheduled_effect);\n\t}\n}\n\n/** @type {Set<Effect> | null} */\nexport let eager_block_effects = null;\n\n/**\n * @param {Array<Effect>} effects\n * @returns {void}\n */\nfunction flush_queued_effects(effects) {\n\tvar length = effects.length;\n\tif (length === 0) return;\n\n\tvar i = 0;\n\n\twhile (i < length) {\n\t\tvar effect = effects[i++];\n\n\t\tif ((effect.f & (DESTROYED | INERT)) === 0 && is_dirty(effect)) {\n\t\t\teager_block_effects = new Set();\n\n\t\t\tupdate_effect(effect);\n\n\t\t\t// Effects with no dependencies or teardown do not get added to the effect tree.\n\t\t\t// Deferred effects (e.g. `$effect(...)`) _are_ added to the tree because we\n\t\t\t// don't know if we need to keep them until they are executed. Doing the check\n\t\t\t// here (rather than in `update_effect`) allows us to skip the work for\n\t\t\t// immediate effects.\n\t\t\tif (\n\t\t\t\teffect.deps === null &&\n\t\t\t\teffect.first === null &&\n\t\t\t\teffect.nodes === null &&\n\t\t\t\teffect.teardown === null &&\n\t\t\t\teffect.ac === null\n\t\t\t) {\n\t\t\t\t// remove this effect from the graph\n\t\t\t\tunlink_effect(effect);\n\t\t\t}\n\n\t\t\t// If update_effect() has a flushSync() in it, we may have flushed another flush_queued_effects(),\n\t\t\t// which already handled this logic and did set eager_block_effects to null.\n\t\t\tif (eager_block_effects?.size > 0) {\n\t\t\t\told_values.clear();\n\n\t\t\t\tfor (const e of eager_block_effects) {\n\t\t\t\t\t// Skip eager effects that have already been unmounted\n\t\t\t\t\tif ((e.f & (DESTROYED | INERT)) !== 0) continue;\n\n\t\t\t\t\t// Run effects in order from ancestor to descendant, else we could run into nullpointers\n\t\t\t\t\t/** @type {Effect[]} */\n\t\t\t\t\tconst ordered_effects = [e];\n\t\t\t\t\tlet ancestor = e.parent;\n\t\t\t\t\twhile (ancestor !== null) {\n\t\t\t\t\t\tif (eager_block_effects.has(ancestor)) {\n\t\t\t\t\t\t\teager_block_effects.delete(ancestor);\n\t\t\t\t\t\t\tordered_effects.push(ancestor);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tancestor = ancestor.parent;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (let j = ordered_effects.length - 1; j >= 0; j--) {\n\t\t\t\t\t\tconst e = ordered_effects[j];\n\t\t\t\t\t\t// Skip eager effects that have already been unmounted\n\t\t\t\t\t\tif ((e.f & (DESTROYED | INERT)) !== 0) continue;\n\t\t\t\t\t\tupdate_effect(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\teager_block_effects.clear();\n\t\t\t}\n\t\t}\n\t}\n\n\teager_block_effects = null;\n}\n\n/**\n * This is similar to `mark_reactions`, but it only marks async/block effects\n * depending on `value` and at least one of the other `sources`, so that\n * these effects can re-run after another batch has been committed\n * @param {Value} value\n * @param {Source[]} sources\n * @param {Set<Value>} marked\n * @param {Map<Reaction, boolean>} checked\n */\nfunction mark_effects(value, sources, marked, checked) {\n\tif (marked.has(value)) return;\n\tmarked.add(value);\n\n\tif (value.reactions !== null) {\n\t\tfor (const reaction of value.reactions) {\n\t\t\tconst flags = reaction.f;\n\n\t\t\tif ((flags & DERIVED) !== 0) {\n\t\t\t\tmark_effects(/** @type {Derived} */ (reaction), sources, marked, checked);\n\t\t\t} else if (\n\t\t\t\t(flags & (ASYNC | BLOCK_EFFECT)) !== 0 &&\n\t\t\t\t(flags & DIRTY) === 0 &&\n\t\t\t\tdepends_on(reaction, sources, checked)\n\t\t\t) {\n\t\t\t\tset_signal_status(reaction, DIRTY);\n\t\t\t\tschedule_effect(/** @type {Effect} */ (reaction));\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * When committing a fork, we need to trigger eager effects so that\n * any `$state.eager(...)` expressions update immediately. This\n * function allows us to discover them\n * @param {Value} value\n * @param {Set<Effect>} effects\n */\nfunction mark_eager_effects(value, effects) {\n\tif (value.reactions === null) return;\n\n\tfor (const reaction of value.reactions) {\n\t\tconst flags = reaction.f;\n\n\t\tif ((flags & DERIVED) !== 0) {\n\t\t\tmark_eager_effects(/** @type {Derived} */ (reaction), effects);\n\t\t} else if ((flags & EAGER_EFFECT) !== 0) {\n\t\t\tset_signal_status(reaction, DIRTY);\n\t\t\teffects.add(/** @type {Effect} */ (reaction));\n\t\t}\n\t}\n}\n\n/**\n * @param {Reaction} reaction\n * @param {Source[]} sources\n * @param {Map<Reaction, boolean>} checked\n */\nfunction depends_on(reaction, sources, checked) {\n\tconst depends = checked.get(reaction);\n\tif (depends !== undefined) return depends;\n\n\tif (reaction.deps !== null) {\n\t\tfor (const dep of reaction.deps) {\n\t\t\tif (includes.call(sources, dep)) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tif ((dep.f & DERIVED) !== 0 && depends_on(/** @type {Derived} */ (dep), sources, checked)) {\n\t\t\t\tchecked.set(/** @type {Derived} */ (dep), true);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\tchecked.set(reaction, false);\n\n\treturn false;\n}\n\n/**\n * @param {Effect} effect\n * @returns {void}\n */\nexport function schedule_effect(effect) {\n\t/** @type {Batch} */ (current_batch).schedule(effect);\n}\n\n/** @type {Source<number>[]} */\nlet eager_versions = [];\n\nfunction eager_flush() {\n\tflushSync(() => {\n\t\tconst eager = eager_versions;\n\t\teager_versions = [];\n\t\tfor (const version of eager) {\n\t\t\tupdate(version);\n\t\t}\n\t});\n}\n\n/**\n * Implementation of `$state.eager(fn())`\n * @template T\n * @param {() => T} fn\n * @returns {T}\n */\nexport function eager(fn) {\n\tvar version = source(0);\n\tvar initial = true;\n\tvar value = /** @type {T} */ (undefined);\n\n\tget(version);\n\n\teager_effect(() => {\n\t\tif (initial) {\n\t\t\t// the first time this runs, we create an eager effect\n\t\t\t// that will run eagerly whenever the expression changes\n\t\t\tvar previous_batch_values = batch_values;\n\n\t\t\ttry {\n\t\t\t\tbatch_values = null;\n\t\t\t\tvalue = fn();\n\t\t\t} finally {\n\t\t\t\tbatch_values = previous_batch_values;\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\t// the second time this effect runs, it's to schedule a\n\t\t// `version` update. since this will recreate the effect,\n\t\t// we don't need to evaluate the expression here\n\t\tif (eager_versions.length === 0) {\n\t\t\tqueue_micro_task(eager_flush);\n\t\t}\n\n\t\teager_versions.push(version);\n\t});\n\n\tinitial = false;\n\n\treturn value;\n}\n\n/**\n * Mark all the effects inside a skipped branch CLEAN, so that\n * they can be correctly rescheduled later. Tracks dirty and maybe_dirty\n * effects so they can be rescheduled if the branch survives.\n * @param {Effect} effect\n * @param {{ d: Effect[], m: Effect[] }} tracked\n */\nfunction reset_branch(effect, tracked) {\n\t// clean branch = nothing dirty inside, no need to traverse further\n\tif ((effect.f & BRANCH_EFFECT) !== 0 && (effect.f & CLEAN) !== 0) {\n\t\treturn;\n\t}\n\n\tif ((effect.f & DIRTY) !== 0) {\n\t\ttracked.d.push(effect);\n\t} else if ((effect.f & MAYBE_DIRTY) !== 0) {\n\t\ttracked.m.push(effect);\n\t}\n\n\tset_signal_status(effect, CLEAN);\n\n\tvar e = effect.first;\n\twhile (e !== null) {\n\t\treset_branch(e, tracked);\n\t\te = e.next;\n\t}\n}\n\n/**\n * Mark an entire effect tree clean following an error\n * @param {Effect} effect\n */\nfunction reset_all(effect) {\n\tset_signal_status(effect, CLEAN);\n\n\tvar e = effect.first;\n\twhile (e !== null) {\n\t\treset_all(e);\n\t\te = e.next;\n\t}\n}\n\n/**\n * Creates a 'fork', in which state changes are evaluated but not applied to the DOM.\n * This is useful for speculatively loading data (for example) when you suspect that\n * the user is about to take some action.\n *\n * Frameworks like SvelteKit can use this to preload data when the user touches or\n * hovers over a link, making any subsequent navigation feel instantaneous.\n *\n * The `fn` parameter is a synchronous function that modifies some state. The\n * state changes will be reverted after the fork is initialised, then reapplied\n * if and when the fork is eventually committed.\n *\n * When it becomes clear that a fork will _not_ be committed (e.g. because the\n * user navigated elsewhere), it must be discarded to avoid leaking memory.\n *\n * @param {() => void} fn\n * @returns {Fork}\n * @since 5.42\n */\nexport function fork(fn) {\n\tif (!async_mode_flag) {\n\t\te.experimental_async_required('fork');\n\t}\n\n\tif (current_batch !== null) {\n\t\te.fork_timing();\n\t}\n\n\tvar batch = Batch.ensure();\n\tbatch.is_fork = true;\n\tbatch_values = new Map();\n\n\tvar committed = false;\n\tvar settled = batch.settled();\n\n\tflushSync(fn);\n\n\treturn {\n\t\tcommit: async () => {\n\t\t\tif (committed) {\n\t\t\t\tawait settled;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!batches.has(batch)) {\n\t\t\t\te.fork_discarded();\n\t\t\t}\n\n\t\t\tcommitted = true;\n\n\t\t\tbatch.is_fork = false;\n\n\t\t\t// apply changes and update write versions so deriveds see the change\n\t\t\tfor (var [source, [value]] of batch.current) {\n\t\t\t\tsource.v = value;\n\t\t\t\tsource.wv = increment_write_version();\n\t\t\t}\n\n\t\t\tbatch.activate();\n\t\t\tbatch.run_fork_commit_callbacks();\n\t\t\tbatch.deactivate();\n\n\t\t\t// trigger any `$state.eager(...)` expressions with the new state.\n\t\t\t// eager effects don't get scheduled like other effects, so we\n\t\t\t// can't just encounter them during traversal, we need to\n\t\t\t// proactively flush them\n\t\t\t// TODO maybe there's a better implementation?\n\t\t\tflushSync(() => {\n\t\t\t\t/** @type {Set<Effect>} */\n\t\t\t\tvar eager_effects = new Set();\n\n\t\t\t\tfor (var source of batch.current.keys()) {\n\t\t\t\t\tmark_eager_effects(source, eager_effects);\n\t\t\t\t}\n\n\t\t\t\tset_eager_effects(eager_effects);\n\t\t\t\tflush_eager_effects();\n\t\t\t});\n\n\t\t\tbatch.flush();\n\t\t\tawait settled;\n\t\t},\n\t\tdiscard: () => {\n\t\t\t// cause any MAYBE_DIRTY deriveds to update\n\t\t\t// if they depend on things thath changed\n\t\t\t// inside the discarded fork\n\t\t\tfor (var source of batch.current.keys()) {\n\t\t\t\tsource.wv = increment_write_version();\n\t\t\t}\n\n\t\t\tif (!committed && batches.has(batch)) {\n\t\t\t\tbatch.discard();\n\t\t\t}\n\t\t}\n\t};\n}\n\n/**\n * Forcibly remove all current batches, to prevent cross-talk between tests\n */\nexport function clear() {\n\tbatches.clear();\n}\n","import { get, tick, untrack } from '../internal/client/runtime.js';\nimport { effect_tracking, render_effect } from '../internal/client/reactivity/effects.js';\nimport { source, increment } from '../internal/client/reactivity/sources.js';\nimport { tag } from '../internal/client/dev/tracing.js';\nimport { DEV } from 'esm-env';\nimport { queue_micro_task } from '../internal/client/dom/task.js';\n\n/**\n * Returns a `subscribe` function that integrates external event-based systems with Svelte's reactivity.\n * It's particularly useful for integrating with web APIs like `MediaQuery`, `IntersectionObserver`, or `WebSocket`.\n *\n * If `subscribe` is called inside an effect (including indirectly, for example inside a getter),\n * the `start` callback will be called with an `update` function. Whenever `update` is called, the effect re-runs.\n *\n * If `start` returns a cleanup function, it will be called when the effect is destroyed.\n *\n * If `subscribe` is called in multiple effects, `start` will only be called once as long as the effects\n * are active, and the returned teardown function will only be called when all effects are destroyed.\n *\n * It's best understood with an example. Here's an implementation of [`MediaQuery`](https://svelte.dev/docs/svelte/svelte-reactivity#MediaQuery):\n *\n * ```js\n * import { createSubscriber } from 'svelte/reactivity';\n * import { on } from 'svelte/events';\n *\n * export class MediaQuery {\n * \t#query;\n * \t#subscribe;\n *\n * \tconstructor(query) {\n * \t\tthis.#query = window.matchMedia(`(${query})`);\n *\n * \t\tthis.#subscribe = createSubscriber((update) => {\n * \t\t\t// when the `change` event occurs, re-run any effects that read `this.current`\n * \t\t\tconst off = on(this.#query, 'change', update);\n *\n * \t\t\t// stop listening when all the effects are destroyed\n * \t\t\treturn () => off();\n * \t\t});\n * \t}\n *\n * \tget current() {\n * \t\t// This makes the getter reactive, if read in an effect\n * \t\tthis.#subscribe();\n *\n * \t\t// Return the current state of the query, whether or not we're in an effect\n * \t\treturn this.#query.matches;\n * \t}\n * }\n * ```\n * @param {(update: () => void) => (() => void) | void} start\n * @since 5.7.0\n */\nexport function createSubscriber(start) {\n\tlet subscribers = 0;\n\tlet version = source(0);\n\t/** @type {(() => void) | void} */\n\tlet stop;\n\n\tif (DEV) {\n\t\ttag(version, 'createSubscriber version');\n\t}\n\n\treturn () => {\n\t\tif (effect_tracking()) {\n\t\t\tget(version);\n\n\t\t\trender_effect(() => {\n\t\t\t\tif (subscribers === 0) {\n\t\t\t\t\tstop = untrack(() => start(() => increment(version)));\n\t\t\t\t}\n\n\t\t\t\tsubscribers += 1;\n\n\t\t\t\treturn () => {\n\t\t\t\t\tqueue_micro_task(() => {\n\t\t\t\t\t\t// Only count down after a microtask, else we would reach 0 before our own render effect reruns,\n\t\t\t\t\t\t// but reach 1 again when the tick callback of the prior teardown runs. That would mean we\n\t\t\t\t\t\t// re-subcribe unnecessarily and create a memory leak because the old subscription is never cleaned up.\n\t\t\t\t\t\tsubscribers -= 1;\n\n\t\t\t\t\t\tif (subscribers === 0) {\n\t\t\t\t\t\t\tstop?.();\n\t\t\t\t\t\t\tstop = undefined;\n\t\t\t\t\t\t\t// Increment the version to ensure any dependent deriveds are marked dirty when the subscription is picked up again later.\n\t\t\t\t\t\t\t// If we didn't do this then the comparison of write versions would determine that the derived has a later version than\n\t\t\t\t\t\t\t// the subscriber, and it would not be re-run.\n\t\t\t\t\t\t\tincrement(version);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t});\n\t\t}\n\t};\n}\n","/** @import { Effect, Source, TemplateNode, } from '#client' */\nimport {\n\tBOUNDARY_EFFECT,\n\tDIRTY,\n\tEFFECT_PRESERVED,\n\tEFFECT_TRANSPARENT,\n\tMAYBE_DIRTY\n} from '#client/constants';\nimport { HYDRATION_START_ELSE, HYDRATION_START_FAILED } from '../../../../constants.js';\nimport { component_context, set_component_context } from '../../context.js';\nimport { handle_error, invoke_error_boundary } from '../../error-handling.js';\nimport {\n\tblock,\n\tbranch,\n\tdestroy_effect,\n\tmove_effect,\n\tpause_effect\n} from '../../reactivity/effects.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tget,\n\tset_active_effect,\n\tset_active_reaction\n} from '../../runtime.js';\nimport {\n\thydrate_next,\n\thydrate_node,\n\thydrating,\n\tnext,\n\tskip_nodes,\n\tset_hydrate_node\n} from '../hydration.js';\nimport { queue_micro_task } from '../task.js';\nimport * as e from '../../errors.js';\nimport * as w from '../../warnings.js';\nimport { DEV } from 'esm-env';\nimport { Batch, current_batch, previous_batch, schedule_effect } from '../../reactivity/batch.js';\nimport { internal_set, source } from '../../reactivity/sources.js';\nimport { tag } from '../../dev/tracing.js';\nimport { createSubscriber } from '../../../../reactivity/create-subscriber.js';\nimport { create_text } from '../operations.js';\nimport { defer_effect } from '../../reactivity/utils.js';\nimport { set_signal_status } from '../../reactivity/status.js';\n\n/**\n * @typedef {{\n * \t onerror?: (error: unknown, reset: () => void) => void;\n * failed?: (anchor: Node, error: () => unknown, reset: () => () => void) => void;\n * pending?: (anchor: Node) => void;\n * }} BoundaryProps\n */\n\nvar flags = EFFECT_TRANSPARENT | EFFECT_PRESERVED;\n\n/**\n * @param {TemplateNode} node\n * @param {BoundaryProps} props\n * @param {((anchor: Node) => void)} children\n * @param {((error: unknown) => unknown) | undefined} [transform_error]\n * @returns {void}\n */\nexport function boundary(node, props, children, transform_error) {\n\tnew Boundary(node, props, children, transform_error);\n}\n\nexport class Boundary {\n\t/** @type {Boundary | null} */\n\tparent;\n\n\tis_pending = false;\n\n\t/**\n\t * API-level transformError transform function. Transforms errors before they reach the `failed` snippet.\n\t * Inherited from parent boundary, or defaults to identity.\n\t * @type {(error: unknown) => unknown}\n\t */\n\ttransform_error;\n\n\t/** @type {TemplateNode} */\n\t#anchor;\n\n\t/** @type {TemplateNode | null} */\n\t#hydrate_open = hydrating ? hydrate_node : null;\n\n\t/** @type {BoundaryProps} */\n\t#props;\n\n\t/** @type {((anchor: Node) => void)} */\n\t#children;\n\n\t/** @type {Effect} */\n\t#effect;\n\n\t/** @type {Effect | null} */\n\t#main_effect = null;\n\n\t/** @type {Effect | null} */\n\t#pending_effect = null;\n\n\t/** @type {Effect | null} */\n\t#failed_effect = null;\n\n\t/** @type {DocumentFragment | null} */\n\t#offscreen_fragment = null;\n\n\t#local_pending_count = 0;\n\t#pending_count = 0;\n\t#pending_count_update_queued = false;\n\n\t/** @type {Set<Effect>} */\n\t#dirty_effects = new Set();\n\n\t/** @type {Set<Effect>} */\n\t#maybe_dirty_effects = new Set();\n\n\t/**\n\t * A source containing the number of pending async deriveds/expressions.\n\t * Only created if `$effect.pending()` is used inside the boundary,\n\t * otherwise updating the source results in needless `Batch.ensure()`\n\t * calls followed by no-op flushes\n\t * @type {Source<number> | null}\n\t */\n\t#effect_pending = null;\n\n\t#effect_pending_subscriber = createSubscriber(() => {\n\t\tthis.#effect_pending = source(this.#local_pending_count);\n\n\t\tif (DEV) {\n\t\t\ttag(this.#effect_pending, '$effect.pending()');\n\t\t}\n\n\t\treturn () => {\n\t\t\tthis.#effect_pending = null;\n\t\t};\n\t});\n\n\t/**\n\t * @param {TemplateNode} node\n\t * @param {BoundaryProps} props\n\t * @param {((anchor: Node) => void)} children\n\t * @param {((error: unknown) => unknown) | undefined} [transform_error]\n\t */\n\tconstructor(node, props, children, transform_error) {\n\t\tthis.#anchor = node;\n\t\tthis.#props = props;\n\n\t\tthis.#children = (anchor) => {\n\t\t\tvar effect = /** @type {Effect} */ (active_effect);\n\n\t\t\teffect.b = this;\n\t\t\teffect.f |= BOUNDARY_EFFECT;\n\n\t\t\tchildren(anchor);\n\t\t};\n\n\t\tthis.parent = /** @type {Effect} */ (active_effect).b;\n\n\t\t// Inherit transform_error from parent boundary, or use the provided one, or default to identity\n\t\tthis.transform_error = transform_error ?? this.parent?.transform_error ?? ((e) => e);\n\n\t\tthis.#effect = block(() => {\n\t\t\tif (hydrating) {\n\t\t\t\tconst comment = /** @type {Comment} */ (this.#hydrate_open);\n\t\t\t\thydrate_next();\n\n\t\t\t\tconst server_rendered_pending = comment.data === HYDRATION_START_ELSE;\n\t\t\t\tconst server_rendered_failed = comment.data.startsWith(HYDRATION_START_FAILED);\n\n\t\t\t\tif (server_rendered_failed) {\n\t\t\t\t\t// Server rendered the failed snippet - hydrate it.\n\t\t\t\t\t// The serialized error is embedded in the comment: <!--[?<json>-->\n\t\t\t\t\tconst serialized_error = JSON.parse(comment.data.slice(HYDRATION_START_FAILED.length));\n\t\t\t\t\tthis.#hydrate_failed_content(serialized_error);\n\t\t\t\t} else if (server_rendered_pending) {\n\t\t\t\t\tthis.#hydrate_pending_content();\n\t\t\t\t} else {\n\t\t\t\t\tthis.#hydrate_resolved_content();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.#render();\n\t\t\t}\n\t\t}, flags);\n\n\t\tif (hydrating) {\n\t\t\tthis.#anchor = hydrate_node;\n\t\t}\n\t}\n\n\t#hydrate_resolved_content() {\n\t\ttry {\n\t\t\tthis.#main_effect = branch(() => this.#children(this.#anchor));\n\t\t} catch (error) {\n\t\t\tthis.error(error);\n\t\t}\n\t}\n\n\t/**\n\t * @param {unknown} error The deserialized error from the server's hydration comment\n\t */\n\t#hydrate_failed_content(error) {\n\t\tconst failed = this.#props.failed;\n\t\tif (!failed) return;\n\n\t\tthis.#failed_effect = branch(() => {\n\t\t\tfailed(\n\t\t\t\tthis.#anchor,\n\t\t\t\t() => error,\n\t\t\t\t() => () => {}\n\t\t\t);\n\t\t});\n\t}\n\n\t#hydrate_pending_content() {\n\t\tconst pending = this.#props.pending;\n\t\tif (!pending) return;\n\n\t\tthis.is_pending = true;\n\t\tthis.#pending_effect = branch(() => pending(this.#anchor));\n\n\t\tqueue_micro_task(() => {\n\t\t\tvar fragment = (this.#offscreen_fragment = document.createDocumentFragment());\n\t\t\tvar anchor = create_text();\n\n\t\t\tfragment.append(anchor);\n\n\t\t\tthis.#main_effect = this.#run(() => {\n\t\t\t\treturn branch(() => this.#children(anchor));\n\t\t\t});\n\n\t\t\tif (this.#pending_count === 0) {\n\t\t\t\tthis.#anchor.before(fragment);\n\t\t\t\tthis.#offscreen_fragment = null;\n\n\t\t\t\tpause_effect(/** @type {Effect} */ (this.#pending_effect), () => {\n\t\t\t\t\tthis.#pending_effect = null;\n\t\t\t\t});\n\n\t\t\t\tthis.#resolve(/** @type {Batch} */ (current_batch));\n\t\t\t}\n\t\t});\n\t}\n\n\t#render() {\n\t\ttry {\n\t\t\tthis.is_pending = this.has_pending_snippet();\n\t\t\tthis.#pending_count = 0;\n\t\t\tthis.#local_pending_count = 0;\n\n\t\t\tthis.#main_effect = branch(() => {\n\t\t\t\tthis.#children(this.#anchor);\n\t\t\t});\n\n\t\t\tif (this.#pending_count > 0) {\n\t\t\t\tvar fragment = (this.#offscreen_fragment = document.createDocumentFragment());\n\t\t\t\tmove_effect(this.#main_effect, fragment);\n\n\t\t\t\tconst pending = /** @type {(anchor: Node) => void} */ (this.#props.pending);\n\t\t\t\tthis.#pending_effect = branch(() => pending(this.#anchor));\n\t\t\t} else {\n\t\t\t\tthis.#resolve(/** @type {Batch} */ (current_batch));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.error(error);\n\t\t}\n\t}\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\t#resolve(batch) {\n\t\tthis.is_pending = false;\n\n\t\t// any effects that were previously deferred should be transferred\n\t\t// to the batch, which will flush in the next microtask\n\t\tbatch.transfer_effects(this.#dirty_effects, this.#maybe_dirty_effects);\n\t}\n\n\t/**\n\t * Defer an effect inside a pending boundary until the boundary resolves\n\t * @param {Effect} effect\n\t */\n\tdefer_effect(effect) {\n\t\tdefer_effect(effect, this.#dirty_effects, this.#maybe_dirty_effects);\n\t}\n\n\t/**\n\t * Returns `false` if the effect exists inside a boundary whose pending snippet is shown\n\t * @returns {boolean}\n\t */\n\tis_rendered() {\n\t\treturn !this.is_pending && (!this.parent || this.parent.is_rendered());\n\t}\n\n\thas_pending_snippet() {\n\t\treturn !!this.#props.pending;\n\t}\n\n\t/**\n\t * @template T\n\t * @param {() => T} fn\n\t */\n\t#run(fn) {\n\t\tvar previous_effect = active_effect;\n\t\tvar previous_reaction = active_reaction;\n\t\tvar previous_ctx = component_context;\n\n\t\tset_active_effect(this.#effect);\n\t\tset_active_reaction(this.#effect);\n\t\tset_component_context(this.#effect.ctx);\n\n\t\ttry {\n\t\t\tBatch.ensure();\n\t\t\treturn fn();\n\t\t} catch (e) {\n\t\t\thandle_error(e);\n\t\t\treturn null;\n\t\t} finally {\n\t\t\tset_active_effect(previous_effect);\n\t\t\tset_active_reaction(previous_reaction);\n\t\t\tset_component_context(previous_ctx);\n\t\t}\n\t}\n\n\t/**\n\t * Updates the pending count associated with the currently visible pending snippet,\n\t * if any, such that we can replace the snippet with content once work is done\n\t * @param {1 | -1} d\n\t * @param {Batch} batch\n\t */\n\t#update_pending_count(d, batch) {\n\t\tif (!this.has_pending_snippet()) {\n\t\t\tif (this.parent) {\n\t\t\t\tthis.parent.#update_pending_count(d, batch);\n\t\t\t}\n\n\t\t\t// if there's no parent, we're in a scope with no pending snippet\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#pending_count += d;\n\n\t\tif (this.#pending_count === 0) {\n\t\t\tthis.#resolve(batch);\n\n\t\t\tif (this.#pending_effect) {\n\t\t\t\tpause_effect(this.#pending_effect, () => {\n\t\t\t\t\tthis.#pending_effect = null;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (this.#offscreen_fragment) {\n\t\t\t\tthis.#anchor.before(this.#offscreen_fragment);\n\t\t\t\tthis.#offscreen_fragment = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Update the source that powers `$effect.pending()` inside this boundary,\n\t * and controls when the current `pending` snippet (if any) is removed.\n\t * Do not call from inside the class\n\t * @param {1 | -1} d\n\t * @param {Batch} batch\n\t */\n\tupdate_pending_count(d, batch) {\n\t\tthis.#update_pending_count(d, batch);\n\n\t\tthis.#local_pending_count += d;\n\n\t\tif (!this.#effect_pending || this.#pending_count_update_queued) return;\n\t\tthis.#pending_count_update_queued = true;\n\n\t\tqueue_micro_task(() => {\n\t\t\tthis.#pending_count_update_queued = false;\n\t\t\tif (this.#effect_pending) {\n\t\t\t\tinternal_set(this.#effect_pending, this.#local_pending_count);\n\t\t\t}\n\t\t});\n\t}\n\n\tget_effect_pending() {\n\t\tthis.#effect_pending_subscriber();\n\t\treturn get(/** @type {Source<number>} */ (this.#effect_pending));\n\t}\n\n\t/** @param {unknown} error */\n\terror(error) {\n\t\t// If we have nothing to capture the error, or if we hit an error while\n\t\t// rendering the fallback, re-throw for another boundary to handle\n\t\tif (!this.#props.onerror && !this.#props.failed) {\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (current_batch?.is_fork) {\n\t\t\tif (this.#main_effect) current_batch.skip_effect(this.#main_effect);\n\t\t\tif (this.#pending_effect) current_batch.skip_effect(this.#pending_effect);\n\t\t\tif (this.#failed_effect) current_batch.skip_effect(this.#failed_effect);\n\n\t\t\tcurrent_batch.on_fork_commit(() => {\n\t\t\t\tthis.#handle_error(error);\n\t\t\t});\n\t\t} else {\n\t\t\tthis.#handle_error(error);\n\t\t}\n\t}\n\n\t/**\n\t * @param {unknown} error\n\t */\n\t#handle_error(error) {\n\t\tif (this.#main_effect) {\n\t\t\tdestroy_effect(this.#main_effect);\n\t\t\tthis.#main_effect = null;\n\t\t}\n\n\t\tif (this.#pending_effect) {\n\t\t\tdestroy_effect(this.#pending_effect);\n\t\t\tthis.#pending_effect = null;\n\t\t}\n\n\t\tif (this.#failed_effect) {\n\t\t\tdestroy_effect(this.#failed_effect);\n\t\t\tthis.#failed_effect = null;\n\t\t}\n\n\t\tif (hydrating) {\n\t\t\tset_hydrate_node(/** @type {TemplateNode} */ (this.#hydrate_open));\n\t\t\tnext();\n\t\t\tset_hydrate_node(skip_nodes());\n\t\t}\n\n\t\tvar onerror = this.#props.onerror;\n\t\tlet failed = this.#props.failed;\n\t\tvar did_reset = false;\n\t\tvar calling_on_error = false;\n\n\t\tconst reset = () => {\n\t\t\tif (did_reset) {\n\t\t\t\tw.svelte_boundary_reset_noop();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tdid_reset = true;\n\n\t\t\tif (calling_on_error) {\n\t\t\t\te.svelte_boundary_reset_onerror();\n\t\t\t}\n\n\t\t\tif (this.#failed_effect !== null) {\n\t\t\t\tpause_effect(this.#failed_effect, () => {\n\t\t\t\t\tthis.#failed_effect = null;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthis.#run(() => {\n\t\t\t\tthis.#render();\n\t\t\t});\n\t\t};\n\n\t\t/** @param {unknown} transformed_error */\n\t\tconst handle_error_result = (transformed_error) => {\n\t\t\ttry {\n\t\t\t\tcalling_on_error = true;\n\t\t\t\tonerror?.(transformed_error, reset);\n\t\t\t\tcalling_on_error = false;\n\t\t\t} catch (error) {\n\t\t\t\tinvoke_error_boundary(error, this.#effect && this.#effect.parent);\n\t\t\t}\n\n\t\t\tif (failed) {\n\t\t\t\tthis.#failed_effect = this.#run(() => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn branch(() => {\n\t\t\t\t\t\t\t// errors in `failed` snippets cause the boundary to error again\n\t\t\t\t\t\t\t// TODO Svelte 6: revisit this decision, most likely better to go to parent boundary instead\n\t\t\t\t\t\t\tvar effect = /** @type {Effect} */ (active_effect);\n\n\t\t\t\t\t\t\teffect.b = this;\n\t\t\t\t\t\t\teffect.f |= BOUNDARY_EFFECT;\n\n\t\t\t\t\t\t\tfailed(\n\t\t\t\t\t\t\t\tthis.#anchor,\n\t\t\t\t\t\t\t\t() => transformed_error,\n\t\t\t\t\t\t\t\t() => reset\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tinvoke_error_boundary(error, /** @type {Effect} */ (this.#effect.parent));\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\tqueue_micro_task(() => {\n\t\t\t// Run the error through the API-level transformError transform (e.g. SvelteKit's handleError)\n\t\t\t/** @type {unknown} */\n\t\t\tvar result;\n\t\t\ttry {\n\t\t\t\tresult = this.transform_error(error);\n\t\t\t} catch (e) {\n\t\t\t\tinvoke_error_boundary(e, this.#effect && this.#effect.parent);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tresult !== null &&\n\t\t\t\ttypeof result === 'object' &&\n\t\t\t\ttypeof (/** @type {any} */ (result).then) === 'function'\n\t\t\t) {\n\t\t\t\t// transformError returned a Promise — wait for it\n\t\t\t\t/** @type {any} */ (result).then(\n\t\t\t\t\thandle_error_result,\n\t\t\t\t\t/** @param {unknown} e */\n\t\t\t\t\t(e) => invoke_error_boundary(e, this.#effect && this.#effect.parent)\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// Synchronous result — handle immediately\n\t\t\t\thandle_error_result(result);\n\t\t\t}\n\t\t});\n\t}\n}\n\nexport function pending() {\n\tif (active_effect === null) {\n\t\te.effect_pending_outside_reaction();\n\t}\n\n\tvar boundary = active_effect.b;\n\n\tif (boundary === null) {\n\t\treturn 0; // TODO eventually we will need this to be global\n\t}\n\n\treturn boundary.get_effect_pending();\n}\n","/** @import { Blocker, Effect, Value } from '#client' */\nimport { DESTROYED, STALE_REACTION } from '#client/constants';\nimport { DEV } from 'esm-env';\nimport {\n\tcomponent_context,\n\tdev_stack,\n\tis_runes,\n\tset_component_context,\n\tset_dev_stack\n} from '../context.js';\nimport { Boundary } from '../dom/blocks/boundary.js';\nimport { invoke_error_boundary } from '../error-handling.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tset_active_effect,\n\tset_active_reaction\n} from '../runtime.js';\nimport { Batch, current_batch } from './batch.js';\nimport {\n\tasync_derived,\n\treactivity_loss_tracker,\n\tderived,\n\tderived_safe_equal,\n\tset_reactivity_loss_tracker\n} from './deriveds.js';\nimport { aborted } from './effects.js';\n\n/**\n * @param {Blocker[]} blockers\n * @param {Array<() => any>} sync\n * @param {Array<() => Promise<any>>} async\n * @param {(values: Value[]) => any} fn\n */\nexport function flatten(blockers, sync, async, fn) {\n\tconst d = is_runes() ? derived : derived_safe_equal;\n\n\t// Filter out already-settled blockers - no need to wait for them\n\tvar pending = blockers.filter((b) => !b.settled);\n\n\tif (async.length === 0 && pending.length === 0) {\n\t\tfn(sync.map(d));\n\t\treturn;\n\t}\n\n\tvar parent = /** @type {Effect} */ (active_effect);\n\n\tvar restore = capture();\n\tvar blocker_promise =\n\t\tpending.length === 1\n\t\t\t? pending[0].promise\n\t\t\t: pending.length > 1\n\t\t\t\t? Promise.all(pending.map((b) => b.promise))\n\t\t\t\t: null;\n\n\t/** @param {Value[]} values */\n\tfunction finish(values) {\n\t\trestore();\n\n\t\ttry {\n\t\t\tfn(values);\n\t\t} catch (error) {\n\t\t\tif ((parent.f & DESTROYED) === 0) {\n\t\t\t\tinvoke_error_boundary(error, parent);\n\t\t\t}\n\t\t}\n\n\t\tunset_context();\n\t}\n\n\t// Fast path: blockers but no async expressions\n\tif (async.length === 0) {\n\t\t/** @type {Promise<any>} */ (blocker_promise).then(() => finish(sync.map(d)));\n\t\treturn;\n\t}\n\n\tvar decrement_pending = increment_pending();\n\n\t// Full path: has async expressions\n\tfunction run() {\n\t\tPromise.all(async.map((expression) => async_derived(expression)))\n\t\t\t.then((result) => finish([...sync.map(d), ...result]))\n\t\t\t.catch((error) => invoke_error_boundary(error, parent))\n\t\t\t.finally(() => decrement_pending());\n\t}\n\n\tif (blocker_promise) {\n\t\tblocker_promise.then(() => {\n\t\t\trestore();\n\t\t\trun();\n\t\t\tunset_context();\n\t\t});\n\t} else {\n\t\trun();\n\t}\n}\n\n/**\n * @param {Blocker[]} blockers\n * @param {(values: Value[]) => any} fn\n */\nexport function run_after_blockers(blockers, fn) {\n\tflatten(blockers, [], [], fn);\n}\n\n/**\n * Captures the current effect context so that we can restore it after\n * some asynchronous work has happened (so that e.g. `await a + b`\n * causes `b` to be registered as a dependency).\n */\nexport function capture() {\n\tvar previous_effect = /** @type {Effect} */ (active_effect);\n\tvar previous_reaction = active_reaction;\n\tvar previous_component_context = component_context;\n\tvar previous_batch = /** @type {Batch} */ (current_batch);\n\n\tif (DEV) {\n\t\tvar previous_dev_stack = dev_stack;\n\t}\n\n\treturn function restore(activate_batch = true) {\n\t\tset_active_effect(previous_effect);\n\t\tset_active_reaction(previous_reaction);\n\t\tset_component_context(previous_component_context);\n\n\t\tif (activate_batch && (previous_effect.f & DESTROYED) === 0) {\n\t\t\t// TODO we only need optional chaining here because `{#await ...}` blocks\n\t\t\t// are anomalous. Once we retire them we can get rid of it\n\t\t\tprevious_batch?.activate();\n\t\t\tprevious_batch?.apply();\n\t\t}\n\n\t\tif (DEV) {\n\t\t\tset_reactivity_loss_tracker(null);\n\t\t\tset_dev_stack(previous_dev_stack);\n\t\t}\n\t};\n}\n\n/**\n * Wraps an `await` expression in such a way that the effect context that was\n * active before the expression evaluated can be reapplied afterwards —\n * `await a + b` becomes `(await $.save(a))() + b`\n * @template T\n * @param {Promise<T>} promise\n * @returns {Promise<() => T>}\n */\nexport async function save(promise) {\n\tvar restore = capture();\n\tvar value = await promise;\n\n\treturn () => {\n\t\trestore();\n\t\treturn value;\n\t};\n}\n\n/**\n * Reset `current_async_effect` after the `promise` resolves, so\n * that we can emit `await_reactivity_loss` warnings\n * @template T\n * @param {Promise<T>} promise\n * @returns {Promise<() => T>}\n */\nexport async function track_reactivity_loss(promise) {\n\tvar previous_async_effect = reactivity_loss_tracker;\n\t// Ensure that unrelated reads after an async operation is kicked off don't cause false positives\n\tqueueMicrotask(() => {\n\t\tif (reactivity_loss_tracker === previous_async_effect) {\n\t\t\tset_reactivity_loss_tracker(null);\n\t\t}\n\t});\n\n\tvar value = await promise;\n\n\treturn () => {\n\t\tset_reactivity_loss_tracker(previous_async_effect);\n\t\t// While this can result in false negatives it also guards against the more important\n\t\t// false positives that would occur if this is the last in a chain of async operations,\n\t\t// and the reactivity_loss_tracker would then stay around until the next async operation happens.\n\t\tqueueMicrotask(() => {\n\t\t\tif (reactivity_loss_tracker === previous_async_effect) {\n\t\t\t\tset_reactivity_loss_tracker(null);\n\t\t\t}\n\t\t});\n\n\t\treturn value;\n\t};\n}\n\n/**\n * Used in `for await` loops in DEV, so\n * that we can emit `await_reactivity_loss` warnings\n * after each `async_iterator` result resolves and\n * after the `async_iterator` return resolves (if it runs)\n * @template T\n * @template TReturn\n * @param {Iterable<T> | AsyncIterable<T>} iterable\n * @returns {AsyncGenerator<T, TReturn | undefined>}\n */\nexport async function* for_await_track_reactivity_loss(iterable) {\n\t// This is based on the algorithms described in ECMA-262:\n\t// ForIn/OfBodyEvaluation\n\t// https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset\n\t// AsyncIteratorClose\n\t// https://tc39.es/ecma262/multipage/abstract-operations.html#sec-asynciteratorclose\n\n\t/** @type {AsyncIterator<T, TReturn>} */\n\t// @ts-ignore\n\tconst iterator = iterable[Symbol.asyncIterator]?.() ?? iterable[Symbol.iterator]?.();\n\n\tif (iterator === undefined) {\n\t\tthrow new TypeError('value is not async iterable');\n\t}\n\n\t/** Whether the completion of the iterator was \"normal\", meaning it wasn't ended via `break` or a similar method */\n\tlet normal_completion = false;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = (await track_reactivity_loss(iterator.next()))();\n\t\t\tif (done) {\n\t\t\t\tnormal_completion = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tvar prev = reactivity_loss_tracker;\n\t\t\tyield value;\n\t\t\tset_reactivity_loss_tracker(prev);\n\t\t}\n\t} finally {\n\t\t// If the iterator had an abrupt completion and `return` is defined on the iterator, call it and return the value\n\t\tif (!normal_completion && iterator.return !== undefined) {\n\t\t\t// eslint-disable-next-line no-unsafe-finally\n\t\t\treturn /** @type {TReturn} */ ((await track_reactivity_loss(iterator.return()))().value);\n\t\t}\n\t}\n}\n\nexport function unset_context(deactivate_batch = true) {\n\tset_active_effect(null);\n\tset_active_reaction(null);\n\tset_component_context(null);\n\tif (deactivate_batch) current_batch?.deactivate();\n\n\tif (DEV) {\n\t\tset_reactivity_loss_tracker(null);\n\t\tset_dev_stack(null);\n\t}\n}\n\n/**\n * @param {Array<() => void | Promise<void>>} thunks\n */\nexport function run(thunks) {\n\tconst restore = capture();\n\n\tconst decrement_pending = increment_pending();\n\n\tvar active = /** @type {Effect} */ (active_effect);\n\n\t/** @type {null | { error: any }} */\n\tvar errored = null;\n\n\t/** @param {any} error */\n\tconst handle_error = (error) => {\n\t\terrored = { error }; // wrap in object in case a promise rejects with a falsy value\n\n\t\tif (!aborted(active)) {\n\t\t\tinvoke_error_boundary(error, active);\n\t\t}\n\t};\n\n\tvar promise = Promise.resolve(thunks[0]()).catch(handle_error);\n\n\t/** @type {Blocker} */\n\tvar blocker = { promise, settled: false };\n\tvar blockers = [blocker];\n\n\tpromise.finally(() => {\n\t\tblocker.settled = true;\n\t\tunset_context();\n\t});\n\n\tfor (const fn of thunks.slice(1)) {\n\t\tpromise = promise\n\t\t\t.then(() => {\n\t\t\t\trestore();\n\n\t\t\t\tif (errored) {\n\t\t\t\t\tthrow errored.error;\n\t\t\t\t}\n\n\t\t\t\tif (aborted(active)) {\n\t\t\t\t\tthrow STALE_REACTION;\n\t\t\t\t}\n\n\t\t\t\treturn fn();\n\t\t\t})\n\t\t\t.catch(handle_error);\n\n\t\tconst blocker = { promise, settled: false };\n\t\tblockers.push(blocker);\n\n\t\tpromise.finally(() => {\n\t\t\tblocker.settled = true;\n\t\t\tunset_context();\n\t\t});\n\t}\n\n\tpromise\n\t\t// wait one more tick, so that template effects are\n\t\t// guaranteed to run before `$effect(...)`\n\t\t.then(() => Promise.resolve())\n\t\t.finally(() => decrement_pending());\n\n\treturn blockers;\n}\n\n/**\n * @param {Blocker[]} blockers\n */\nexport function wait(blockers) {\n\treturn Promise.all(blockers.map((b) => b.promise));\n}\n\n/**\n * @returns {(skip?: boolean) => void}\n */\nexport function increment_pending() {\n\tvar effect = /** @type {Effect} */ (active_effect);\n\tvar boundary = /** @type {Boundary} */ (effect.b);\n\tvar batch = /** @type {Batch} */ (current_batch);\n\tvar blocking = boundary.is_rendered();\n\n\tboundary.update_pending_count(1, batch);\n\tbatch.increment(blocking, effect);\n\n\treturn (skip = false) => {\n\t\tboundary.update_pending_count(-1, batch);\n\t\tbatch.decrement(blocking, effect, skip);\n\t};\n}\n","/** @import { Derived, Effect, Reaction, Source, Value } from '#client' */\n/** @import { Batch } from './batch.js'; */\n/** @import { Boundary } from '../dom/blocks/boundary.js'; */\nimport { DEV } from 'esm-env';\nimport {\n\tERROR_VALUE,\n\tDERIVED,\n\tDIRTY,\n\tEFFECT_PRESERVED,\n\tSTALE_REACTION,\n\tASYNC,\n\tWAS_MARKED,\n\tDESTROYED,\n\tCLEAN,\n\tREACTION_RAN,\n\tINERT\n} from '#client/constants';\nimport {\n\tactive_reaction,\n\tactive_effect,\n\tupdate_reaction,\n\tincrement_write_version,\n\tset_active_effect,\n\tpush_reaction_value,\n\tis_destroying_effect,\n\tupdate_effect,\n\tremove_reactions,\n\tskipped_deps,\n\tnew_deps\n} from '../runtime.js';\nimport { equals, safe_equals } from './equality.js';\nimport * as e from '../errors.js';\nimport * as w from '../warnings.js';\nimport {\n\tasync_effect,\n\tdestroy_effect,\n\tdestroy_effect_children,\n\teffect_tracking,\n\tteardown\n} from './effects.js';\nimport { eager_effects, internal_set, set_eager_effects, source } from './sources.js';\nimport { get_error } from '../../shared/dev.js';\nimport { async_mode_flag, tracing_mode_flag } from '../../flags/index.js';\nimport { component_context } from '../context.js';\nimport { UNINITIALIZED } from '../../../constants.js';\nimport { batch_values, current_batch } from './batch.js';\nimport { increment_pending, unset_context } from './async.js';\nimport { deferred, includes, noop } from '../../shared/utils.js';\nimport { set_signal_status, update_derived_status } from './status.js';\n\n/**\n * This allows us to track 'reactivity loss' that occurs when signals\n * are read after a non-context-restoring `await`. Dev-only\n * @type {{ effect: Effect, effect_deps: Set<Value>, warned: boolean } | null}\n */\nexport let reactivity_loss_tracker = null;\n\n/** @param {{ effect: Effect, effect_deps: Set<Value>, warned: boolean } | null} v */\nexport function set_reactivity_loss_tracker(v) {\n\treactivity_loss_tracker = v;\n}\n\nexport const recent_async_deriveds = new Set();\n\n/**\n * @template V\n * @param {() => V} fn\n * @returns {Derived<V>}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function derived(fn) {\n\tvar flags = DERIVED | DIRTY;\n\n\tif (active_effect !== null) {\n\t\t// Since deriveds are evaluated lazily, any effects created inside them are\n\t\t// created too late to ensure that the parent effect is added to the tree\n\t\tactive_effect.f |= EFFECT_PRESERVED;\n\t}\n\n\t/** @type {Derived<V>} */\n\tconst signal = {\n\t\tctx: component_context,\n\t\tdeps: null,\n\t\teffects: null,\n\t\tequals,\n\t\tf: flags,\n\t\tfn,\n\t\treactions: null,\n\t\trv: 0,\n\t\tv: /** @type {V} */ (UNINITIALIZED),\n\t\twv: 0,\n\t\tparent: active_effect,\n\t\tac: null\n\t};\n\n\tif (DEV && tracing_mode_flag) {\n\t\tsignal.created = get_error('created at');\n\t}\n\n\treturn signal;\n}\n\n/**\n * @template V\n * @param {() => V | Promise<V>} fn\n * @param {string} [label]\n * @param {string} [location] If provided, print a warning if the value is not read immediately after update\n * @returns {Promise<Source<V>>}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function async_derived(fn, label, location) {\n\tlet parent = /** @type {Effect | null} */ (active_effect);\n\n\tif (parent === null) {\n\t\te.async_derived_orphan();\n\t}\n\n\tvar promise = /** @type {Promise<V>} */ (/** @type {unknown} */ (undefined));\n\tvar signal = source(/** @type {V} */ (UNINITIALIZED));\n\n\tif (DEV) signal.label = label;\n\n\t// only suspend in async deriveds created on initialisation\n\tvar should_suspend = !active_reaction;\n\n\t/** @type {Map<Batch, ReturnType<typeof deferred<V>>>} */\n\tvar deferreds = new Map();\n\n\tasync_effect(() => {\n\t\tvar effect = /** @type {Effect} */ (active_effect);\n\n\t\tif (DEV) {\n\t\t\treactivity_loss_tracker = { effect, effect_deps: new Set(), warned: false };\n\t\t}\n\n\t\t/** @type {ReturnType<typeof deferred<V>>} */\n\t\tvar d = deferred();\n\t\tpromise = d.promise;\n\n\t\ttry {\n\t\t\t// If this code is changed at some point, make sure to still access the then property\n\t\t\t// of fn() to read any signals it might access, so that we track them as dependencies.\n\t\t\t// We call `unset_context` to undo any `save` calls that happen inside `fn()`\n\t\t\tPromise.resolve(fn()).then(d.resolve, d.reject).finally(unset_context);\n\t\t} catch (error) {\n\t\t\td.reject(error);\n\t\t\tunset_context();\n\t\t}\n\n\t\tif (DEV) {\n\t\t\tif (reactivity_loss_tracker) {\n\t\t\t\t// Reused deps from previous run (indices 0 to skipped_deps-1)\n\t\t\t\t// We deliberately only track direct dependencies of the async expression to encourage\n\t\t\t\t// dependencies being directly visible at the point of the expression\n\t\t\t\tif (effect.deps !== null) {\n\t\t\t\t\tfor (let i = 0; i < skipped_deps; i += 1) {\n\t\t\t\t\t\treactivity_loss_tracker.effect_deps.add(effect.deps[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// New deps discovered this run\n\t\t\t\tif (new_deps !== null) {\n\t\t\t\t\tfor (let i = 0; i < new_deps.length; i += 1) {\n\t\t\t\t\t\treactivity_loss_tracker.effect_deps.add(new_deps[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treactivity_loss_tracker = null;\n\t\t}\n\n\t\tvar batch = /** @type {Batch} */ (current_batch);\n\n\t\tif (should_suspend) {\n\t\t\t// we only increment the batch's pending state for updates, not creation, otherwise\n\t\t\t// we will decrement to zero before the work that depends on this promise (e.g. a\n\t\t\t// template effect) has initialized, causing the batch to resolve prematurely\n\t\t\tif ((effect.f & REACTION_RAN) !== 0) {\n\t\t\t\tvar decrement_pending = increment_pending();\n\t\t\t}\n\n\t\t\tif (/** @type {Boundary} */ (parent.b).is_rendered()) {\n\t\t\t\tdeferreds.get(batch)?.reject(STALE_REACTION);\n\t\t\t\tdeferreds.delete(batch); // delete to ensure correct order in Map iteration below\n\t\t\t} else {\n\t\t\t\t// While the boundary is still showing pending, a new run supersedes all older in-flight runs\n\t\t\t\t// for this async expression. Cancel eagerly so resolution cannot commit stale values.\n\t\t\t\tfor (const d of deferreds.values()) {\n\t\t\t\t\td.reject(STALE_REACTION);\n\t\t\t\t}\n\t\t\t\tdeferreds.clear();\n\t\t\t}\n\n\t\t\tdeferreds.set(batch, d);\n\t\t}\n\n\t\t/**\n\t\t * @param {any} value\n\t\t * @param {unknown} error\n\t\t */\n\t\tconst handler = (value, error = undefined) => {\n\t\t\tif (DEV) {\n\t\t\t\treactivity_loss_tracker = null;\n\t\t\t}\n\n\t\t\tif (decrement_pending) {\n\t\t\t\t// don't trigger an update if we're only here because\n\t\t\t\t// the promise was superseded before it could resolve\n\t\t\t\tvar skip = error === STALE_REACTION;\n\t\t\t\tdecrement_pending(skip);\n\t\t\t}\n\n\t\t\tif (error === STALE_REACTION || (effect.f & DESTROYED) !== 0) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tbatch.activate();\n\n\t\t\tif (error) {\n\t\t\t\tsignal.f |= ERROR_VALUE;\n\n\t\t\t\t// @ts-expect-error the error is the wrong type, but we don't care\n\t\t\t\tinternal_set(signal, error);\n\t\t\t} else {\n\t\t\t\tif ((signal.f & ERROR_VALUE) !== 0) {\n\t\t\t\t\tsignal.f ^= ERROR_VALUE;\n\t\t\t\t}\n\n\t\t\t\tinternal_set(signal, value);\n\n\t\t\t\t// All prior async derived runs are now stale\n\t\t\t\tfor (const [b, d] of deferreds) {\n\t\t\t\t\tdeferreds.delete(b);\n\t\t\t\t\tif (b === batch) break;\n\t\t\t\t\td.reject(STALE_REACTION);\n\t\t\t\t}\n\n\t\t\t\tif (DEV && location !== undefined) {\n\t\t\t\t\trecent_async_deriveds.add(signal);\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tif (recent_async_deriveds.has(signal)) {\n\t\t\t\t\t\t\tw.await_waterfall(/** @type {string} */ (signal.label), location);\n\t\t\t\t\t\t\trecent_async_deriveds.delete(signal);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbatch.deactivate();\n\t\t};\n\n\t\td.promise.then(handler, (e) => handler(null, e || 'unknown'));\n\t});\n\n\tteardown(() => {\n\t\tfor (const d of deferreds.values()) {\n\t\t\td.reject(STALE_REACTION);\n\t\t}\n\t});\n\n\tif (DEV) {\n\t\t// add a flag that lets this be printed as a derived\n\t\t// when using `$inspect.trace()`\n\t\tsignal.f |= ASYNC;\n\t}\n\n\treturn new Promise((fulfil) => {\n\t\t/** @param {Promise<V>} p */\n\t\tfunction next(p) {\n\t\t\tfunction go() {\n\t\t\t\tif (p === promise) {\n\t\t\t\t\tfulfil(signal);\n\t\t\t\t} else {\n\t\t\t\t\t// if the effect re-runs before the initial promise\n\t\t\t\t\t// resolves, delay resolution until we have a value\n\t\t\t\t\tnext(promise);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tp.then(go, go);\n\t\t}\n\n\t\tnext(promise);\n\t});\n}\n\n/**\n * @template V\n * @param {() => V} fn\n * @returns {Derived<V>}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function user_derived(fn) {\n\tconst d = derived(fn);\n\n\tif (!async_mode_flag) push_reaction_value(d);\n\n\treturn d;\n}\n\n/**\n * @template V\n * @param {() => V} fn\n * @returns {Derived<V>}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function derived_safe_equal(fn) {\n\tconst signal = derived(fn);\n\tsignal.equals = safe_equals;\n\treturn signal;\n}\n\n/**\n * @param {Derived} derived\n * @returns {void}\n */\nexport function destroy_derived_effects(derived) {\n\tvar effects = derived.effects;\n\n\tif (effects !== null) {\n\t\tderived.effects = null;\n\n\t\tfor (var i = 0; i < effects.length; i += 1) {\n\t\t\tdestroy_effect(/** @type {Effect} */ (effects[i]));\n\t\t}\n\t}\n}\n\n/**\n * The currently updating deriveds, used to detect infinite recursion\n * in dev mode and provide a nicer error than 'too much recursion'\n * @type {Derived[]}\n */\nlet stack = [];\n\n/**\n * @template T\n * @param {Derived} derived\n * @returns {T}\n */\nexport function execute_derived(derived) {\n\tvar value;\n\tvar prev_active_effect = active_effect;\n\tvar parent = derived.parent;\n\n\tif (!is_destroying_effect && parent !== null && (parent.f & (DESTROYED | INERT)) !== 0) {\n\t\tw.derived_inert();\n\n\t\treturn derived.v;\n\t}\n\n\tset_active_effect(parent);\n\n\tif (DEV) {\n\t\tlet prev_eager_effects = eager_effects;\n\t\tset_eager_effects(new Set());\n\t\ttry {\n\t\t\tif (includes.call(stack, derived)) {\n\t\t\t\te.derived_references_self();\n\t\t\t}\n\n\t\t\tstack.push(derived);\n\n\t\t\tderived.f &= ~WAS_MARKED;\n\t\t\tdestroy_derived_effects(derived);\n\t\t\tvalue = update_reaction(derived);\n\t\t} finally {\n\t\t\tset_active_effect(prev_active_effect);\n\t\t\tset_eager_effects(prev_eager_effects);\n\t\t\tstack.pop();\n\t\t}\n\t} else {\n\t\ttry {\n\t\t\tderived.f &= ~WAS_MARKED;\n\t\t\tdestroy_derived_effects(derived);\n\t\t\tvalue = update_reaction(derived);\n\t\t} finally {\n\t\t\tset_active_effect(prev_active_effect);\n\t\t}\n\t}\n\n\treturn value;\n}\n\n/**\n * @param {Derived} derived\n * @returns {void}\n */\nexport function update_derived(derived) {\n\tvar value = execute_derived(derived);\n\n\tif (!derived.equals(value)) {\n\t\tderived.wv = increment_write_version();\n\n\t\t// in a fork, we don't update the underlying value, just `batch_values`.\n\t\t// the underlying value will be updated when the fork is committed.\n\t\t// otherwise, the next time we get here after a 'real world' state\n\t\t// change, `derived.equals` may incorrectly return `true`\n\t\tif (!current_batch?.is_fork || derived.deps === null) {\n\t\t\tif (current_batch !== null) {\n\t\t\t\tcurrent_batch.capture(derived, value, true);\n\t\t\t} else {\n\t\t\t\tderived.v = value;\n\t\t\t}\n\n\t\t\t// deriveds without dependencies should never be recomputed\n\t\t\tif (derived.deps === null) {\n\t\t\t\tset_signal_status(derived, CLEAN);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t// don't mark derived clean if we're reading it inside a\n\t// cleanup function, or it will cache a stale value\n\tif (is_destroying_effect) {\n\t\treturn;\n\t}\n\n\t// During time traveling we don't want to reset the status so that\n\t// traversal of the graph in the other batches still happens\n\tif (batch_values !== null) {\n\t\t// only cache the value if we're in a tracking context, otherwise we won't\n\t\t// clear the cache in `mark_reactions` when dependencies are updated\n\t\tif (effect_tracking() || current_batch?.is_fork) {\n\t\t\tbatch_values.set(derived, value);\n\t\t}\n\t} else {\n\t\tupdate_derived_status(derived);\n\t}\n}\n\n/**\n * @param {Derived} derived\n */\nexport function freeze_derived_effects(derived) {\n\tif (derived.effects === null) return;\n\n\tfor (const e of derived.effects) {\n\t\t// if the effect has a teardown function or abort signal, call it\n\t\tif (e.teardown || e.ac) {\n\t\t\te.teardown?.();\n\t\t\te.ac?.abort(STALE_REACTION);\n\n\t\t\t// make it a noop so it doesn't get called again if the derived\n\t\t\t// is unfrozen. we don't set it to `null`, because the existence\n\t\t\t// of a teardown function is what determines whether the\n\t\t\t// effect runs again during unfreezing\n\t\t\te.teardown = noop;\n\t\t\te.ac = null;\n\n\t\t\tremove_reactions(e, 0);\n\t\t\tdestroy_effect_children(e);\n\t\t}\n\t}\n}\n\n/**\n * @param {Derived} derived\n */\nexport function unfreeze_derived_effects(derived) {\n\tif (derived.effects === null) return;\n\n\tfor (const e of derived.effects) {\n\t\t// if the effect was previously frozen — indicated by the presence\n\t\t// of a teardown function — unfreeze it\n\t\tif (e.teardown) {\n\t\t\tupdate_effect(e);\n\t\t}\n\t}\n}\n","/** @import { Derived, Effect, Source, Value } from '#client' */\nimport { DEV } from 'esm-env';\nimport {\n\tactive_reaction,\n\tactive_effect,\n\tuntracked_writes,\n\tget,\n\tset_untracked_writes,\n\tuntrack,\n\tincrement_write_version,\n\tupdate_effect,\n\tcurrent_sources,\n\tis_dirty,\n\tuntracking,\n\tis_destroying_effect,\n\tpush_reaction_value\n} from '../runtime.js';\nimport { equals, safe_equals } from './equality.js';\nimport {\n\tCLEAN,\n\tDERIVED,\n\tDIRTY,\n\tBRANCH_EFFECT,\n\tEAGER_EFFECT,\n\tMAYBE_DIRTY,\n\tBLOCK_EFFECT,\n\tROOT_EFFECT,\n\tASYNC,\n\tWAS_MARKED,\n\tCONNECTED\n} from '#client/constants';\nimport * as e from '../errors.js';\nimport { legacy_mode_flag, tracing_mode_flag } from '../../flags/index.js';\nimport { includes } from '../../shared/utils.js';\nimport { tag_proxy } from '../dev/tracing.js';\nimport { get_error } from '../../shared/dev.js';\nimport { component_context, is_runes } from '../context.js';\nimport {\n\tBatch,\n\tbatch_values,\n\teager_block_effects,\n\tschedule_effect,\n\tlegacy_updates\n} from './batch.js';\nimport { proxy } from '../proxy.js';\nimport { execute_derived } from './deriveds.js';\nimport { set_signal_status, update_derived_status } from './status.js';\n\n/** @type {Set<any>} */\nexport let eager_effects = new Set();\n\n/** @type {Map<Source, any>} */\nexport const old_values = new Map();\n\n/**\n * @param {Set<any>} v\n */\nexport function set_eager_effects(v) {\n\teager_effects = v;\n}\n\nlet eager_effects_deferred = false;\n\nexport function set_eager_effects_deferred() {\n\teager_effects_deferred = true;\n}\n\n/**\n * @template V\n * @param {V} v\n * @param {Error | null} [stack]\n * @returns {Source<V>}\n */\n// TODO rename this to `state` throughout the codebase\nexport function source(v, stack) {\n\t/** @type {Value} */\n\tvar signal = {\n\t\tf: 0, // TODO ideally we could skip this altogether, but it causes type errors\n\t\tv,\n\t\treactions: null,\n\t\tequals,\n\t\trv: 0,\n\t\twv: 0\n\t};\n\n\tif (DEV && tracing_mode_flag) {\n\t\tsignal.created = stack ?? get_error('created at');\n\t\tsignal.updated = null;\n\t\tsignal.set_during_effect = false;\n\t\tsignal.trace = null;\n\t}\n\n\treturn signal;\n}\n\n/**\n * @template V\n * @param {V} v\n * @param {Error | null} [stack]\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function state(v, stack) {\n\tconst s = source(v, stack);\n\n\tpush_reaction_value(s);\n\n\treturn s;\n}\n\n/**\n * @template V\n * @param {V} initial_value\n * @param {boolean} [immutable]\n * @returns {Source<V>}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function mutable_source(initial_value, immutable = false, trackable = true) {\n\tconst s = source(initial_value);\n\tif (!immutable) {\n\t\ts.equals = safe_equals;\n\t}\n\n\t// bind the signal to the component context, in case we need to\n\t// track updates to trigger beforeUpdate/afterUpdate callbacks\n\tif (legacy_mode_flag && trackable && component_context !== null && component_context.l !== null) {\n\t\t(component_context.l.s ??= []).push(s);\n\t}\n\n\treturn s;\n}\n\n/**\n * @template V\n * @param {Value<V>} source\n * @param {V} value\n */\nexport function mutate(source, value) {\n\tset(\n\t\tsource,\n\t\tuntrack(() => get(source))\n\t);\n\treturn value;\n}\n\n/**\n * @template V\n * @param {Source<V>} source\n * @param {V} value\n * @param {boolean} [should_proxy]\n * @returns {V}\n */\nexport function set(source, value, should_proxy = false) {\n\tif (\n\t\tactive_reaction !== null &&\n\t\t// since we are untracking the function inside `$inspect.with` we need to add this check\n\t\t// to ensure we error if state is set inside an inspect effect\n\t\t(!untracking || (active_reaction.f & EAGER_EFFECT) !== 0) &&\n\t\tis_runes() &&\n\t\t(active_reaction.f & (DERIVED | BLOCK_EFFECT | ASYNC | EAGER_EFFECT)) !== 0 &&\n\t\t(current_sources === null || !includes.call(current_sources, source))\n\t) {\n\t\te.state_unsafe_mutation();\n\t}\n\n\tlet new_value = should_proxy ? proxy(value) : value;\n\n\tif (DEV) {\n\t\ttag_proxy(new_value, /** @type {string} */ (source.label));\n\t}\n\n\treturn internal_set(source, new_value, legacy_updates);\n}\n\n/**\n * @template V\n * @param {Source<V>} source\n * @param {V} value\n * @param {Effect[] | null} [updated_during_traversal]\n * @returns {V}\n */\nexport function internal_set(source, value, updated_during_traversal = null) {\n\tif (!source.equals(value)) {\n\t\told_values.set(source, is_destroying_effect ? value : source.v);\n\n\t\tvar batch = Batch.ensure();\n\t\tbatch.capture(source, value);\n\n\t\tif (DEV) {\n\t\t\tif (tracing_mode_flag || active_effect !== null) {\n\t\t\t\tsource.updated ??= new Map();\n\n\t\t\t\t// For performance reasons, when not using $inspect.trace, we only start collecting stack traces\n\t\t\t\t// after the same source has been updated more than 5 times in the same flush cycle.\n\t\t\t\tconst count = (source.updated.get('')?.count ?? 0) + 1;\n\t\t\t\tsource.updated.set('', { error: /** @type {any} */ (null), count });\n\n\t\t\t\tif (tracing_mode_flag || count > 5) {\n\t\t\t\t\tconst error = get_error('updated at');\n\n\t\t\t\t\tif (error !== null) {\n\t\t\t\t\t\tlet entry = source.updated.get(error.stack);\n\n\t\t\t\t\t\tif (!entry) {\n\t\t\t\t\t\t\tentry = { error, count: 0 };\n\t\t\t\t\t\t\tsource.updated.set(error.stack, entry);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tentry.count++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (active_effect !== null) {\n\t\t\t\tsource.set_during_effect = true;\n\t\t\t}\n\t\t}\n\n\t\tif ((source.f & DERIVED) !== 0) {\n\t\t\tconst derived = /** @type {Derived} */ (source);\n\n\t\t\t// if we are assigning to a dirty derived we set it to clean/maybe dirty but we also eagerly execute it to track the dependencies\n\t\t\tif ((source.f & DIRTY) !== 0) {\n\t\t\t\texecute_derived(derived);\n\t\t\t}\n\n\t\t\t// During time traveling we don't want to reset the status so that\n\t\t\t// traversal of the graph in the other batches still happens\n\t\t\tif (batch_values === null) {\n\t\t\t\tupdate_derived_status(derived);\n\t\t\t}\n\t\t}\n\n\t\tsource.wv = increment_write_version();\n\n\t\t// For debugging, in case you want to know which reactions are being scheduled:\n\t\t// log_reactions(source);\n\t\tmark_reactions(source, DIRTY, updated_during_traversal);\n\n\t\t// It's possible that the current reaction might not have up-to-date dependencies\n\t\t// whilst it's actively running. So in the case of ensuring it registers the reaction\n\t\t// properly for itself, we need to ensure the current effect actually gets\n\t\t// scheduled. i.e: `$effect(() => x++)`\n\t\tif (\n\t\t\tis_runes() &&\n\t\t\tactive_effect !== null &&\n\t\t\t(active_effect.f & CLEAN) !== 0 &&\n\t\t\t(active_effect.f & (BRANCH_EFFECT | ROOT_EFFECT)) === 0\n\t\t) {\n\t\t\tif (untracked_writes === null) {\n\t\t\t\tset_untracked_writes([source]);\n\t\t\t} else {\n\t\t\t\tuntracked_writes.push(source);\n\t\t\t}\n\t\t}\n\n\t\tif (!batch.is_fork && eager_effects.size > 0 && !eager_effects_deferred) {\n\t\t\tflush_eager_effects();\n\t\t}\n\t}\n\n\treturn value;\n}\n\nexport function flush_eager_effects() {\n\teager_effects_deferred = false;\n\n\tfor (const effect of eager_effects) {\n\t\t// Mark clean inspect-effects as maybe dirty and then check their dirtiness\n\t\t// instead of just updating the effects - this way we avoid overfiring.\n\t\tif ((effect.f & CLEAN) !== 0) {\n\t\t\tset_signal_status(effect, MAYBE_DIRTY);\n\t\t}\n\n\t\tif (is_dirty(effect)) {\n\t\t\tupdate_effect(effect);\n\t\t}\n\t}\n\n\teager_effects.clear();\n}\n\n/**\n * @template {number | bigint} T\n * @param {Source<T>} source\n * @param {1 | -1} [d]\n * @returns {T}\n */\nexport function update(source, d = 1) {\n\tvar value = get(source);\n\tvar result = d === 1 ? value++ : value--;\n\n\tset(source, value);\n\n\t// @ts-expect-error\n\treturn result;\n}\n\n/**\n * @template {number | bigint} T\n * @param {Source<T>} source\n * @param {1 | -1} [d]\n * @returns {T}\n */\nexport function update_pre(source, d = 1) {\n\tvar value = get(source);\n\n\t// @ts-expect-error\n\t// eslint-disable-next-line no-useless-assignment -- `++`/`--` used for return value, not side effect on `value`\n\treturn set(source, d === 1 ? ++value : --value);\n}\n\n/**\n * Silently (without using `get`) increment a source\n * @param {Source<number>} source\n */\nexport function increment(source) {\n\tset(source, source.v + 1);\n}\n\n/**\n * @param {Value} signal\n * @param {number} status should be DIRTY or MAYBE_DIRTY\n * @param {Effect[] | null} updated_during_traversal\n * @returns {void}\n */\nfunction mark_reactions(signal, status, updated_during_traversal) {\n\tvar reactions = signal.reactions;\n\tif (reactions === null) return;\n\n\tvar runes = is_runes();\n\tvar length = reactions.length;\n\n\tfor (var i = 0; i < length; i++) {\n\t\tvar reaction = reactions[i];\n\t\tvar flags = reaction.f;\n\n\t\t// In legacy mode, skip the current effect to prevent infinite loops\n\t\tif (!runes && reaction === active_effect) continue;\n\n\t\t// Inspect effects need to run immediately, so that the stack trace makes sense\n\t\tif (DEV && (flags & EAGER_EFFECT) !== 0) {\n\t\t\teager_effects.add(reaction);\n\t\t\tcontinue;\n\t\t}\n\n\t\tvar not_dirty = (flags & DIRTY) === 0;\n\n\t\t// don't set a DIRTY reaction to MAYBE_DIRTY\n\t\tif (not_dirty) {\n\t\t\tset_signal_status(reaction, status);\n\t\t}\n\n\t\tif ((flags & DERIVED) !== 0) {\n\t\t\tvar derived = /** @type {Derived} */ (reaction);\n\n\t\t\tbatch_values?.delete(derived);\n\n\t\t\tif ((flags & WAS_MARKED) === 0) {\n\t\t\t\t// Only connected deriveds can be reliably unmarked right away\n\t\t\t\tif (flags & CONNECTED) {\n\t\t\t\t\treaction.f |= WAS_MARKED;\n\t\t\t\t}\n\n\t\t\t\tmark_reactions(derived, MAYBE_DIRTY, updated_during_traversal);\n\t\t\t}\n\t\t} else if (not_dirty) {\n\t\t\tvar effect = /** @type {Effect} */ (reaction);\n\n\t\t\tif ((flags & BLOCK_EFFECT) !== 0 && eager_block_effects !== null) {\n\t\t\t\teager_block_effects.add(effect);\n\t\t\t}\n\n\t\t\tif (updated_during_traversal !== null) {\n\t\t\t\tupdated_during_traversal.push(effect);\n\t\t\t} else {\n\t\t\t\tschedule_effect(effect);\n\t\t\t}\n\t\t}\n\t}\n}\n","/** @import { Source } from '#client' */\nimport { DEV } from 'esm-env';\nimport {\n\tget,\n\tactive_effect,\n\tupdate_version,\n\tactive_reaction,\n\tset_update_version,\n\tset_active_reaction\n} from './runtime.js';\nimport {\n\tarray_prototype,\n\tget_descriptor,\n\tget_prototype_of,\n\tis_array,\n\tobject_prototype\n} from '../shared/utils.js';\nimport {\n\tstate as source,\n\tset,\n\tincrement,\n\tflush_eager_effects,\n\tset_eager_effects_deferred\n} from './reactivity/sources.js';\nimport { PROXY_PATH_SYMBOL, STATE_SYMBOL } from '#client/constants';\nimport { UNINITIALIZED } from '../../constants.js';\nimport * as e from './errors.js';\nimport { tag } from './dev/tracing.js';\nimport { get_error } from '../shared/dev.js';\nimport { tracing_mode_flag } from '../flags/index.js';\n\n// TODO move all regexes into shared module?\nconst regex_is_valid_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;\n\n/**\n * @template T\n * @param {T} value\n * @returns {T}\n */\nexport function proxy(value) {\n\t// if non-proxyable, or is already a proxy, return `value`\n\tif (typeof value !== 'object' || value === null || STATE_SYMBOL in value) {\n\t\treturn value;\n\t}\n\n\tconst prototype = get_prototype_of(value);\n\n\tif (prototype !== object_prototype && prototype !== array_prototype) {\n\t\treturn value;\n\t}\n\n\t/** @type {Map<any, Source<any>>} */\n\tvar sources = new Map();\n\tvar is_proxied_array = is_array(value);\n\tvar version = source(0);\n\n\tvar stack = DEV && tracing_mode_flag ? get_error('created at') : null;\n\tvar parent_version = update_version;\n\n\t/**\n\t * Executes the proxy in the context of the reaction it was originally created in, if any\n\t * @template T\n\t * @param {() => T} fn\n\t */\n\tvar with_parent = (fn) => {\n\t\tif (update_version === parent_version) {\n\t\t\treturn fn();\n\t\t}\n\n\t\t// child source is being created after the initial proxy —\n\t\t// prevent it from being associated with the current reaction\n\t\tvar reaction = active_reaction;\n\t\tvar version = update_version;\n\n\t\tset_active_reaction(null);\n\t\tset_update_version(parent_version);\n\n\t\tvar result = fn();\n\n\t\tset_active_reaction(reaction);\n\t\tset_update_version(version);\n\n\t\treturn result;\n\t};\n\n\tif (is_proxied_array) {\n\t\t// We need to create the length source eagerly to ensure that\n\t\t// mutations to the array are properly synced with our proxy\n\t\tsources.set('length', source(/** @type {any[]} */ (value).length, stack));\n\t\tif (DEV) {\n\t\t\tvalue = /** @type {any} */ (inspectable_array(/** @type {any[]} */ (value)));\n\t\t}\n\t}\n\n\t/** Used in dev for $inspect.trace() */\n\tvar path = '';\n\tlet updating = false;\n\t/** @param {string} new_path */\n\tfunction update_path(new_path) {\n\t\tif (updating) return;\n\t\tupdating = true;\n\t\tpath = new_path;\n\n\t\ttag(version, `${path} version`);\n\n\t\t// rename all child sources and child proxies\n\t\tfor (const [prop, source] of sources) {\n\t\t\ttag(source, get_label(path, prop));\n\t\t}\n\t\tupdating = false;\n\t}\n\n\treturn new Proxy(/** @type {any} */ (value), {\n\t\tdefineProperty(_, prop, descriptor) {\n\t\t\tif (\n\t\t\t\t!('value' in descriptor) ||\n\t\t\t\tdescriptor.configurable === false ||\n\t\t\t\tdescriptor.enumerable === false ||\n\t\t\t\tdescriptor.writable === false\n\t\t\t) {\n\t\t\t\t// we disallow non-basic descriptors, because unless they are applied to the\n\t\t\t\t// target object — which we avoid, so that state can be forked — we will run\n\t\t\t\t// afoul of the various invariants\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/getOwnPropertyDescriptor#invariants\n\t\t\t\te.state_descriptors_fixed();\n\t\t\t}\n\t\t\tvar s = sources.get(prop);\n\t\t\tif (s === undefined) {\n\t\t\t\twith_parent(() => {\n\t\t\t\t\tvar s = source(descriptor.value, stack);\n\t\t\t\t\tsources.set(prop, s);\n\t\t\t\t\tif (DEV && typeof prop === 'string') {\n\t\t\t\t\t\ttag(s, get_label(path, prop));\n\t\t\t\t\t}\n\t\t\t\t\treturn s;\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tset(s, descriptor.value, true);\n\t\t\t}\n\n\t\t\treturn true;\n\t\t},\n\n\t\tdeleteProperty(target, prop) {\n\t\t\tvar s = sources.get(prop);\n\n\t\t\tif (s === undefined) {\n\t\t\t\tif (prop in target) {\n\t\t\t\t\tconst s = with_parent(() => source(UNINITIALIZED, stack));\n\t\t\t\t\tsources.set(prop, s);\n\t\t\t\t\tincrement(version);\n\n\t\t\t\t\tif (DEV) {\n\t\t\t\t\t\ttag(s, get_label(path, prop));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tset(s, UNINITIALIZED);\n\t\t\t\tincrement(version);\n\t\t\t}\n\n\t\t\treturn true;\n\t\t},\n\n\t\tget(target, prop, receiver) {\n\t\t\tif (prop === STATE_SYMBOL) {\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\tif (DEV && prop === PROXY_PATH_SYMBOL) {\n\t\t\t\treturn update_path;\n\t\t\t}\n\n\t\t\tvar s = sources.get(prop);\n\t\t\tvar exists = prop in target;\n\n\t\t\t// create a source, but only if it's an own property and not a prototype property\n\t\t\tif (s === undefined && (!exists || get_descriptor(target, prop)?.writable)) {\n\t\t\t\ts = with_parent(() => {\n\t\t\t\t\tvar p = proxy(exists ? target[prop] : UNINITIALIZED);\n\t\t\t\t\tvar s = source(p, stack);\n\n\t\t\t\t\tif (DEV) {\n\t\t\t\t\t\ttag(s, get_label(path, prop));\n\t\t\t\t\t}\n\n\t\t\t\t\treturn s;\n\t\t\t\t});\n\n\t\t\t\tsources.set(prop, s);\n\t\t\t}\n\n\t\t\tif (s !== undefined) {\n\t\t\t\tvar v = get(s);\n\t\t\t\treturn v === UNINITIALIZED ? undefined : v;\n\t\t\t}\n\n\t\t\treturn Reflect.get(target, prop, receiver);\n\t\t},\n\n\t\tgetOwnPropertyDescriptor(target, prop) {\n\t\t\tvar descriptor = Reflect.getOwnPropertyDescriptor(target, prop);\n\n\t\t\tif (descriptor && 'value' in descriptor) {\n\t\t\t\tvar s = sources.get(prop);\n\t\t\t\tif (s) descriptor.value = get(s);\n\t\t\t} else if (descriptor === undefined) {\n\t\t\t\tvar source = sources.get(prop);\n\t\t\t\tvar value = source?.v;\n\n\t\t\t\tif (source !== undefined && value !== UNINITIALIZED) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t\twritable: true\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn descriptor;\n\t\t},\n\n\t\thas(target, prop) {\n\t\t\tif (prop === STATE_SYMBOL) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tvar s = sources.get(prop);\n\t\t\tvar has = (s !== undefined && s.v !== UNINITIALIZED) || Reflect.has(target, prop);\n\n\t\t\tif (\n\t\t\t\ts !== undefined ||\n\t\t\t\t(active_effect !== null && (!has || get_descriptor(target, prop)?.writable))\n\t\t\t) {\n\t\t\t\tif (s === undefined) {\n\t\t\t\t\ts = with_parent(() => {\n\t\t\t\t\t\tvar p = has ? proxy(target[prop]) : UNINITIALIZED;\n\t\t\t\t\t\tvar s = source(p, stack);\n\n\t\t\t\t\t\tif (DEV) {\n\t\t\t\t\t\t\ttag(s, get_label(path, prop));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn s;\n\t\t\t\t\t});\n\n\t\t\t\t\tsources.set(prop, s);\n\t\t\t\t}\n\n\t\t\t\tvar value = get(s);\n\t\t\t\tif (value === UNINITIALIZED) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn has;\n\t\t},\n\n\t\tset(target, prop, value, receiver) {\n\t\t\tvar s = sources.get(prop);\n\t\t\tvar has = prop in target;\n\n\t\t\t// variable.length = value -> clear all signals with index >= value\n\t\t\tif (is_proxied_array && prop === 'length') {\n\t\t\t\tfor (var i = value; i < /** @type {Source<number>} */ (s).v; i += 1) {\n\t\t\t\t\tvar other_s = sources.get(i + '');\n\t\t\t\t\tif (other_s !== undefined) {\n\t\t\t\t\t\tset(other_s, UNINITIALIZED);\n\t\t\t\t\t} else if (i in target) {\n\t\t\t\t\t\t// If the item exists in the original, we need to create an uninitialized source,\n\t\t\t\t\t\t// else a later read of the property would result in a source being created with\n\t\t\t\t\t\t// the value of the original item at that index.\n\t\t\t\t\t\tother_s = with_parent(() => source(UNINITIALIZED, stack));\n\t\t\t\t\t\tsources.set(i + '', other_s);\n\n\t\t\t\t\t\tif (DEV) {\n\t\t\t\t\t\t\ttag(other_s, get_label(path, i));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If we haven't yet created a source for this property, we need to ensure\n\t\t\t// we do so otherwise if we read it later, then the write won't be tracked and\n\t\t\t// the heuristics of effects will be different vs if we had read the proxied\n\t\t\t// object property before writing to that property.\n\t\t\tif (s === undefined) {\n\t\t\t\tif (!has || get_descriptor(target, prop)?.writable) {\n\t\t\t\t\ts = with_parent(() => source(undefined, stack));\n\n\t\t\t\t\tif (DEV) {\n\t\t\t\t\t\ttag(s, get_label(path, prop));\n\t\t\t\t\t}\n\t\t\t\t\tset(s, proxy(value));\n\n\t\t\t\t\tsources.set(prop, s);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thas = s.v !== UNINITIALIZED;\n\n\t\t\t\tvar p = with_parent(() => proxy(value));\n\t\t\t\tset(s, p);\n\t\t\t}\n\n\t\t\tvar descriptor = Reflect.getOwnPropertyDescriptor(target, prop);\n\n\t\t\t// Set the new value before updating any signals so that any listeners get the new value\n\t\t\tif (descriptor?.set) {\n\t\t\t\tdescriptor.set.call(receiver, value);\n\t\t\t}\n\n\t\t\tif (!has) {\n\t\t\t\t// If we have mutated an array directly, we might need to\n\t\t\t\t// signal that length has also changed. Do it before updating metadata\n\t\t\t\t// to ensure that iterating over the array as a result of a metadata update\n\t\t\t\t// will not cause the length to be out of sync.\n\t\t\t\tif (is_proxied_array && typeof prop === 'string') {\n\t\t\t\t\tvar ls = /** @type {Source<number>} */ (sources.get('length'));\n\t\t\t\t\tvar n = Number(prop);\n\n\t\t\t\t\tif (Number.isInteger(n) && n >= ls.v) {\n\t\t\t\t\t\tset(ls, n + 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tincrement(version);\n\t\t\t}\n\n\t\t\treturn true;\n\t\t},\n\n\t\townKeys(target) {\n\t\t\tget(version);\n\n\t\t\tvar own_keys = Reflect.ownKeys(target).filter((key) => {\n\t\t\t\tvar source = sources.get(key);\n\t\t\t\treturn source === undefined || source.v !== UNINITIALIZED;\n\t\t\t});\n\n\t\t\tfor (var [key, source] of sources) {\n\t\t\t\tif (source.v !== UNINITIALIZED && !(key in target)) {\n\t\t\t\t\town_keys.push(key);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn own_keys;\n\t\t},\n\n\t\tsetPrototypeOf() {\n\t\t\te.state_prototype_fixed();\n\t\t}\n\t});\n}\n\n/**\n * @param {string} path\n * @param {string | symbol} prop\n */\nfunction get_label(path, prop) {\n\tif (typeof prop === 'symbol') return `${path}[Symbol(${prop.description ?? ''})]`;\n\tif (regex_is_valid_identifier.test(prop)) return `${path}.${prop}`;\n\treturn /^\\d+$/.test(prop) ? `${path}[${prop}]` : `${path}['${prop}']`;\n}\n\n/**\n * @param {any} value\n */\nexport function get_proxied_value(value) {\n\ttry {\n\t\tif (value !== null && typeof value === 'object' && STATE_SYMBOL in value) {\n\t\t\treturn value[STATE_SYMBOL];\n\t\t}\n\t} catch {\n\t\t// the above if check can throw an error if the value in question\n\t\t// is the contentWindow of an iframe on another domain, in which\n\t\t// case we want to just return the value (because it's definitely\n\t\t// not a proxied value) so we don't break any JavaScript interacting\n\t\t// with that iframe (such as various payment companies client side\n\t\t// JavaScript libraries interacting with their iframes on the same\n\t\t// domain)\n\t}\n\n\treturn value;\n}\n\n/**\n * @param {any} a\n * @param {any} b\n */\nexport function is(a, b) {\n\treturn Object.is(get_proxied_value(a), get_proxied_value(b));\n}\n\nconst ARRAY_MUTATING_METHODS = new Set([\n\t'copyWithin',\n\t'fill',\n\t'pop',\n\t'push',\n\t'reverse',\n\t'shift',\n\t'sort',\n\t'splice',\n\t'unshift'\n]);\n\n/**\n * Wrap array mutating methods so $inspect is triggered only once and\n * to prevent logging an array in intermediate state (e.g. with an empty slot)\n * @param {any[]} array\n */\nfunction inspectable_array(array) {\n\treturn new Proxy(array, {\n\t\tget(target, prop, receiver) {\n\t\t\tvar value = Reflect.get(target, prop, receiver);\n\t\t\tif (!ARRAY_MUTATING_METHODS.has(/** @type {string} */ (prop))) {\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * @this {any[]}\n\t\t\t * @param {any[]} args\n\t\t\t */\n\t\t\treturn function (...args) {\n\t\t\t\tset_eager_effects_deferred();\n\t\t\t\tvar result = value.apply(this, args);\n\t\t\t\tflush_eager_effects();\n\t\t\t\treturn result;\n\t\t\t};\n\t\t}\n\t});\n}\n","import * as w from '../warnings.js';\nimport { get_proxied_value } from '../proxy.js';\n\nexport function init_array_prototype_warnings() {\n\tconst array_prototype = Array.prototype;\n\t// The REPL ends up here over and over, and this prevents it from adding more and more patches\n\t// of the same kind to the prototype, which would slow down everything over time.\n\t// @ts-expect-error\n\tconst cleanup = Array.__svelte_cleanup;\n\tif (cleanup) {\n\t\tcleanup();\n\t}\n\n\tconst { indexOf, lastIndexOf, includes } = array_prototype;\n\n\tarray_prototype.indexOf = function (item, from_index) {\n\t\tconst index = indexOf.call(this, item, from_index);\n\n\t\tif (index === -1) {\n\t\t\tfor (let i = from_index ?? 0; i < this.length; i += 1) {\n\t\t\t\tif (get_proxied_value(this[i]) === item) {\n\t\t\t\t\tw.state_proxy_equality_mismatch('array.indexOf(...)');\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn index;\n\t};\n\n\tarray_prototype.lastIndexOf = function (item, from_index) {\n\t\t// we need to specify this.length - 1 because it's probably using something like\n\t\t// `arguments` inside so passing undefined is different from not passing anything\n\t\tconst index = lastIndexOf.call(this, item, from_index ?? this.length - 1);\n\n\t\tif (index === -1) {\n\t\t\tfor (let i = 0; i <= (from_index ?? this.length - 1); i += 1) {\n\t\t\t\tif (get_proxied_value(this[i]) === item) {\n\t\t\t\t\tw.state_proxy_equality_mismatch('array.lastIndexOf(...)');\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn index;\n\t};\n\n\tarray_prototype.includes = function (item, from_index) {\n\t\tconst has = includes.call(this, item, from_index);\n\n\t\tif (!has) {\n\t\t\tfor (let i = 0; i < this.length; i += 1) {\n\t\t\t\tif (get_proxied_value(this[i]) === item) {\n\t\t\t\t\tw.state_proxy_equality_mismatch('array.includes(...)');\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn has;\n\t};\n\n\t// @ts-expect-error\n\tArray.__svelte_cleanup = () => {\n\t\tarray_prototype.indexOf = indexOf;\n\t\tarray_prototype.lastIndexOf = lastIndexOf;\n\t\tarray_prototype.includes = includes;\n\t};\n}\n\n/**\n * @param {any} a\n * @param {any} b\n * @param {boolean} equal\n * @returns {boolean}\n */\nexport function strict_equals(a, b, equal = true) {\n\t// try-catch needed because this tries to read properties of `a` and `b`,\n\t// which could be disallowed for example in a secure context\n\ttry {\n\t\tif ((a === b) !== (get_proxied_value(a) === get_proxied_value(b))) {\n\t\t\tw.state_proxy_equality_mismatch(equal ? '===' : '!==');\n\t\t}\n\t} catch {}\n\n\treturn (a === b) === equal;\n}\n\n/**\n * @param {any} a\n * @param {any} b\n * @param {boolean} equal\n * @returns {boolean}\n */\nexport function equals(a, b, equal = true) {\n\tif ((a == b) !== (get_proxied_value(a) == get_proxied_value(b))) {\n\t\tw.state_proxy_equality_mismatch(equal ? '==' : '!=');\n\t}\n\n\treturn (a == b) === equal;\n}\n","/** @import { Effect, TemplateNode } from '#client' */\nimport { hydrate_node, hydrating, set_hydrate_node } from './hydration.js';\nimport { DEV } from 'esm-env';\nimport { init_array_prototype_warnings } from '../dev/equality.js';\nimport { get_descriptor, is_extensible } from '../../shared/utils.js';\nimport { active_effect } from '../runtime.js';\nimport { async_mode_flag } from '../../flags/index.js';\nimport { TEXT_NODE, REACTION_RAN } from '#client/constants';\nimport { eager_block_effects } from '../reactivity/batch.js';\nimport { NAMESPACE_HTML } from '../../../constants.js';\n\n// export these for reference in the compiled code, making global name deduplication unnecessary\n/** @type {Window} */\nexport var $window;\n\n/** @type {Document} */\nexport var $document;\n\n/** @type {boolean} */\nexport var is_firefox;\n\n/** @type {() => Node | null} */\nvar first_child_getter;\n/** @type {() => Node | null} */\nvar next_sibling_getter;\n\n/**\n * Initialize these lazily to avoid issues when using the runtime in a server context\n * where these globals are not available while avoiding a separate server entry point\n */\nexport function init_operations() {\n\tif ($window !== undefined) {\n\t\treturn;\n\t}\n\n\t$window = window;\n\t$document = document;\n\tis_firefox = /Firefox/.test(navigator.userAgent);\n\n\tvar element_prototype = Element.prototype;\n\tvar node_prototype = Node.prototype;\n\tvar text_prototype = Text.prototype;\n\n\t// @ts-ignore\n\tfirst_child_getter = get_descriptor(node_prototype, 'firstChild').get;\n\t// @ts-ignore\n\tnext_sibling_getter = get_descriptor(node_prototype, 'nextSibling').get;\n\n\tif (is_extensible(element_prototype)) {\n\t\t// the following assignments improve perf of lookups on DOM nodes\n\t\t// @ts-expect-error\n\t\telement_prototype.__click = undefined;\n\t\t// @ts-expect-error\n\t\telement_prototype.__className = undefined;\n\t\t// @ts-expect-error\n\t\telement_prototype.__attributes = null;\n\t\t// @ts-expect-error\n\t\telement_prototype.__style = undefined;\n\t\t// @ts-expect-error\n\t\telement_prototype.__e = undefined;\n\t}\n\n\tif (is_extensible(text_prototype)) {\n\t\t// @ts-expect-error\n\t\ttext_prototype.__t = undefined;\n\t}\n\n\tif (DEV) {\n\t\t// @ts-expect-error\n\t\telement_prototype.__svelte_meta = null;\n\n\t\tinit_array_prototype_warnings();\n\t}\n}\n\n/**\n * @param {string} value\n * @returns {Text}\n */\nexport function create_text(value = '') {\n\treturn document.createTextNode(value);\n}\n\n/**\n * @template {Node} N\n * @param {N} node\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function get_first_child(node) {\n\treturn /** @type {TemplateNode | null} */ (first_child_getter.call(node));\n}\n\n/**\n * @template {Node} N\n * @param {N} node\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function get_next_sibling(node) {\n\treturn /** @type {TemplateNode | null} */ (next_sibling_getter.call(node));\n}\n\n/**\n * Don't mark this as side-effect-free, hydration needs to walk all nodes\n * @template {Node} N\n * @param {N} node\n * @param {boolean} is_text\n * @returns {TemplateNode | null}\n */\nexport function child(node, is_text) {\n\tif (!hydrating) {\n\t\treturn get_first_child(node);\n\t}\n\n\tvar child = get_first_child(hydrate_node);\n\n\t// Child can be null if we have an element with a single child, like `<p>{text}</p>`, where `text` is empty\n\tif (child === null) {\n\t\tchild = hydrate_node.appendChild(create_text());\n\t} else if (is_text && child.nodeType !== TEXT_NODE) {\n\t\tvar text = create_text();\n\t\tchild?.before(text);\n\t\tset_hydrate_node(text);\n\t\treturn text;\n\t}\n\n\tif (is_text) {\n\t\tmerge_text_nodes(/** @type {Text} */ (child));\n\t}\n\n\tset_hydrate_node(child);\n\treturn child;\n}\n\n/**\n * Don't mark this as side-effect-free, hydration needs to walk all nodes\n * @param {TemplateNode} node\n * @param {boolean} [is_text]\n * @returns {TemplateNode | null}\n */\nexport function first_child(node, is_text = false) {\n\tif (!hydrating) {\n\t\tvar first = get_first_child(node);\n\n\t\t// TODO prevent user comments with the empty string when preserveComments is true\n\t\tif (first instanceof Comment && first.data === '') return get_next_sibling(first);\n\n\t\treturn first;\n\t}\n\n\tif (is_text) {\n\t\t// if an {expression} is empty during SSR, there might be no\n\t\t// text node to hydrate — we must therefore create one\n\t\tif (hydrate_node?.nodeType !== TEXT_NODE) {\n\t\t\tvar text = create_text();\n\n\t\t\thydrate_node?.before(text);\n\t\t\tset_hydrate_node(text);\n\t\t\treturn text;\n\t\t}\n\n\t\tmerge_text_nodes(/** @type {Text} */ (hydrate_node));\n\t}\n\n\treturn hydrate_node;\n}\n\n/**\n * Don't mark this as side-effect-free, hydration needs to walk all nodes\n * @param {TemplateNode} node\n * @param {number} count\n * @param {boolean} is_text\n * @returns {TemplateNode | null}\n */\nexport function sibling(node, count = 1, is_text = false) {\n\tlet next_sibling = hydrating ? hydrate_node : node;\n\tvar last_sibling;\n\n\twhile (count--) {\n\t\tlast_sibling = next_sibling;\n\t\tnext_sibling = /** @type {TemplateNode} */ (get_next_sibling(next_sibling));\n\t}\n\n\tif (!hydrating) {\n\t\treturn next_sibling;\n\t}\n\n\tif (is_text) {\n\t\t// if a sibling {expression} is empty during SSR, there might be no\n\t\t// text node to hydrate — we must therefore create one\n\t\tif (next_sibling?.nodeType !== TEXT_NODE) {\n\t\t\tvar text = create_text();\n\t\t\t// If the next sibling is `null` and we're handling text then it's because\n\t\t\t// the SSR content was empty for the text, so we need to generate a new text\n\t\t\t// node and insert it after the last sibling\n\t\t\tif (next_sibling === null) {\n\t\t\t\tlast_sibling?.after(text);\n\t\t\t} else {\n\t\t\t\tnext_sibling.before(text);\n\t\t\t}\n\t\t\tset_hydrate_node(text);\n\t\t\treturn text;\n\t\t}\n\n\t\tmerge_text_nodes(/** @type {Text} */ (next_sibling));\n\t}\n\n\tset_hydrate_node(next_sibling);\n\treturn next_sibling;\n}\n\n/**\n * @template {Node} N\n * @param {N} node\n * @returns {void}\n */\nexport function clear_text_content(node) {\n\tnode.textContent = '';\n}\n\n/**\n * Returns `true` if we're updating the current block, for example `condition` in\n * an `{#if condition}` block just changed. In this case, the branch should be\n * appended (or removed) at the same time as other updates within the\n * current `<svelte:boundary>`\n */\nexport function should_defer_append() {\n\tif (!async_mode_flag) return false;\n\tif (eager_block_effects !== null) return false;\n\n\tvar flags = /** @type {Effect} */ (active_effect).f;\n\treturn (flags & REACTION_RAN) !== 0;\n}\n\n/**\n * @template {keyof HTMLElementTagNameMap | string} T\n * @param {T} tag\n * @param {string} [namespace]\n * @param {string} [is]\n * @returns {T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : Element}\n */\nexport function create_element(tag, namespace, is) {\n\tlet options = is ? { is } : undefined;\n\treturn /** @type {T extends keyof HTMLElementTagNameMap ? HTMLElementTagNameMap[T] : Element} */ (\n\t\tdocument.createElementNS(namespace ?? NAMESPACE_HTML, tag, options)\n\t);\n}\n\nexport function create_fragment() {\n\treturn document.createDocumentFragment();\n}\n\n/**\n * @param {string} data\n * @returns\n */\nexport function create_comment(data = '') {\n\treturn document.createComment(data);\n}\n\n/**\n * @param {Element} element\n * @param {string} key\n * @param {string} value\n * @returns\n */\nexport function set_attribute(element, key, value = '') {\n\tif (key.startsWith('xlink:')) {\n\t\telement.setAttributeNS('http://www.w3.org/1999/xlink', key, value);\n\t\treturn;\n\t}\n\treturn element.setAttribute(key, value);\n}\n\n/**\n * Browsers split text nodes larger than 65536 bytes when parsing.\n * For hydration to succeed, we need to stitch them back together\n * @param {Text} text\n */\nexport function merge_text_nodes(text) {\n\tif (/** @type {string} */ (text.nodeValue).length < 65536) {\n\t\treturn;\n\t}\n\n\tlet next = text.nextSibling;\n\n\twhile (next !== null && next.nodeType === TEXT_NODE) {\n\t\tnext.remove();\n\n\t\t/** @type {string} */ (text.nodeValue) += /** @type {string} */ (next.nodeValue);\n\n\t\tnext = text.nextSibling;\n\t}\n}\n","import { hydrating } from '../hydration.js';\nimport { clear_text_content, get_first_child } from '../operations.js';\nimport { queue_micro_task } from '../task.js';\n\n/**\n * @param {HTMLElement} dom\n * @param {boolean} value\n * @returns {void}\n */\nexport function autofocus(dom, value) {\n\tif (value) {\n\t\tconst body = document.body;\n\t\tdom.autofocus = true;\n\n\t\tqueue_micro_task(() => {\n\t\t\tif (document.activeElement === body) {\n\t\t\t\tdom.focus();\n\t\t\t}\n\t\t});\n\t}\n}\n\n/**\n * The child of a textarea actually corresponds to the defaultValue property, so we need\n * to remove it upon hydration to avoid a bug when someone resets the form value.\n * @param {HTMLTextAreaElement} dom\n * @returns {void}\n */\nexport function remove_textarea_child(dom) {\n\tif (hydrating && get_first_child(dom) !== null) {\n\t\tclear_text_content(dom);\n\t}\n}\n\nlet listening_to_form_reset = false;\n\nexport function add_form_reset_listener() {\n\tif (!listening_to_form_reset) {\n\t\tlistening_to_form_reset = true;\n\t\tdocument.addEventListener(\n\t\t\t'reset',\n\t\t\t(evt) => {\n\t\t\t\t// Needs to happen one tick later or else the dom properties of the form\n\t\t\t\t// elements have not updated to their reset values yet\n\t\t\t\tPromise.resolve().then(() => {\n\t\t\t\t\tif (!evt.defaultPrevented) {\n\t\t\t\t\t\tfor (const e of /**@type {HTMLFormElement} */ (evt.target).elements) {\n\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\te.__on_r?.();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t\t// In the capture phase to guarantee we get noticed of it (no possibility of stopPropagation)\n\t\t\t{ capture: true }\n\t\t);\n\t}\n}\n","import { teardown } from '../../../reactivity/effects.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tset_active_effect,\n\tset_active_reaction\n} from '../../../runtime.js';\nimport { add_form_reset_listener } from '../misc.js';\n\n/**\n * Fires the handler once immediately (unless corresponding arg is set to `false`),\n * then listens to the given events until the render effect context is destroyed\n * @param {EventTarget} target\n * @param {Array<string>} events\n * @param {(event?: Event) => void} handler\n * @param {any} call_handler_immediately\n */\nexport function listen(target, events, handler, call_handler_immediately = true) {\n\tif (call_handler_immediately) {\n\t\thandler();\n\t}\n\n\tfor (var name of events) {\n\t\ttarget.addEventListener(name, handler);\n\t}\n\n\tteardown(() => {\n\t\tfor (var name of events) {\n\t\t\ttarget.removeEventListener(name, handler);\n\t\t}\n\t});\n}\n\n/**\n * @template T\n * @param {() => T} fn\n */\nexport function without_reactive_context(fn) {\n\tvar previous_reaction = active_reaction;\n\tvar previous_effect = active_effect;\n\tset_active_reaction(null);\n\tset_active_effect(null);\n\ttry {\n\t\treturn fn();\n\t} finally {\n\t\tset_active_reaction(previous_reaction);\n\t\tset_active_effect(previous_effect);\n\t}\n}\n\n/**\n * Listen to the given event, and then instantiate a global form reset listener if not already done,\n * to notify all bindings when the form is reset\n * @param {HTMLElement} element\n * @param {string} event\n * @param {(is_reset?: true) => void} handler\n * @param {(is_reset?: true) => void} [on_reset]\n */\nexport function listen_to_event_and_reset_event(element, event, handler, on_reset = handler) {\n\telement.addEventListener(event, () => without_reactive_context(handler));\n\t// @ts-expect-error\n\tconst prev = element.__on_r;\n\tif (prev) {\n\t\t// special case for checkbox that can have multiple binds (group & checked)\n\t\t// @ts-expect-error\n\t\telement.__on_r = () => {\n\t\t\tprev();\n\t\t\ton_reset(true);\n\t\t};\n\t} else {\n\t\t// @ts-expect-error\n\t\telement.__on_r = () => on_reset(true);\n\t}\n\n\tadd_form_reset_listener();\n}\n","/** @import { Blocker, ComponentContext, ComponentContextLegacy, Derived, Effect, TemplateNode, TransitionManager } from '#client' */\nimport {\n\tis_dirty,\n\tactive_effect,\n\tactive_reaction,\n\tupdate_effect,\n\tget,\n\tis_destroying_effect,\n\tremove_reactions,\n\tset_active_reaction,\n\tset_is_destroying_effect,\n\tuntrack,\n\tuntracking,\n\tset_active_effect\n} from '../runtime.js';\nimport {\n\tDIRTY,\n\tBRANCH_EFFECT,\n\tRENDER_EFFECT,\n\tEFFECT,\n\tDESTROYED,\n\tINERT,\n\tREACTION_RAN,\n\tBLOCK_EFFECT,\n\tROOT_EFFECT,\n\tEFFECT_TRANSPARENT,\n\tDERIVED,\n\tCLEAN,\n\tEAGER_EFFECT,\n\tHEAD_EFFECT,\n\tMAYBE_DIRTY,\n\tEFFECT_PRESERVED,\n\tSTALE_REACTION,\n\tUSER_EFFECT,\n\tASYNC,\n\tCONNECTED,\n\tMANAGED_EFFECT,\n\tDESTROYING\n} from '#client/constants';\nimport * as e from '../errors.js';\nimport { DEV } from 'esm-env';\nimport { define_property } from '../../shared/utils.js';\nimport { get_next_sibling } from '../dom/operations.js';\nimport { component_context, dev_current_component_function, dev_stack } from '../context.js';\nimport { Batch, collected_effects, current_batch } from './batch.js';\nimport { flatten, increment_pending } from './async.js';\nimport { without_reactive_context } from '../dom/elements/bindings/shared.js';\nimport { set_signal_status } from './status.js';\n\n/**\n * @param {'$effect' | '$effect.pre' | '$inspect'} rune\n */\nexport function validate_effect(rune) {\n\tif (active_effect === null) {\n\t\tif (active_reaction === null) {\n\t\t\te.effect_orphan(rune);\n\t\t}\n\n\t\te.effect_in_unowned_derived();\n\t}\n\n\tif (is_destroying_effect) {\n\t\te.effect_in_teardown(rune);\n\t}\n}\n\n/**\n * @param {Effect} effect\n * @param {Effect} parent_effect\n */\nfunction push_effect(effect, parent_effect) {\n\tvar parent_last = parent_effect.last;\n\tif (parent_last === null) {\n\t\tparent_effect.last = parent_effect.first = effect;\n\t} else {\n\t\tparent_last.next = effect;\n\t\teffect.prev = parent_last;\n\t\tparent_effect.last = effect;\n\t}\n}\n\n/**\n * @param {number} type\n * @param {null | (() => void | (() => void))} fn\n * @returns {Effect}\n */\nfunction create_effect(type, fn) {\n\tvar parent = active_effect;\n\n\tif (DEV) {\n\t\t// Ensure the parent is never an inspect effect\n\t\twhile (parent !== null && (parent.f & EAGER_EFFECT) !== 0) {\n\t\t\tparent = parent.parent;\n\t\t}\n\t}\n\n\tif (parent !== null && (parent.f & INERT) !== 0) {\n\t\ttype |= INERT;\n\t}\n\n\t/** @type {Effect} */\n\tvar effect = {\n\t\tctx: component_context,\n\t\tdeps: null,\n\t\tnodes: null,\n\t\tf: type | DIRTY | CONNECTED,\n\t\tfirst: null,\n\t\tfn,\n\t\tlast: null,\n\t\tnext: null,\n\t\tparent,\n\t\tb: parent && parent.b,\n\t\tprev: null,\n\t\tteardown: null,\n\t\twv: 0,\n\t\tac: null\n\t};\n\n\tif (DEV) {\n\t\teffect.component_function = dev_current_component_function;\n\t}\n\n\tcurrent_batch?.register_created_effect(effect);\n\n\t/** @type {Effect | null} */\n\tvar e = effect;\n\n\tif ((type & EFFECT) !== 0) {\n\t\tif (collected_effects !== null) {\n\t\t\t// created during traversal — collect and run afterwards\n\t\t\tcollected_effects.push(effect);\n\t\t} else {\n\t\t\t// schedule for later\n\t\t\tBatch.ensure().schedule(effect);\n\t\t}\n\t} else if (fn !== null) {\n\t\ttry {\n\t\t\tupdate_effect(effect);\n\t\t} catch (e) {\n\t\t\tdestroy_effect(effect);\n\t\t\tthrow e;\n\t\t}\n\n\t\t// if an effect doesn't need to be kept in the tree (because it\n\t\t// won't re-run, has no DOM, and has no teardown etc)\n\t\t// then we skip it and go to its child (if any)\n\t\tif (\n\t\t\te.deps === null &&\n\t\t\te.teardown === null &&\n\t\t\te.nodes === null &&\n\t\t\te.first === e.last && // either `null`, or a singular child\n\t\t\t(e.f & EFFECT_PRESERVED) === 0\n\t\t) {\n\t\t\te = e.first;\n\t\t\tif ((type & BLOCK_EFFECT) !== 0 && (type & EFFECT_TRANSPARENT) !== 0 && e !== null) {\n\t\t\t\te.f |= EFFECT_TRANSPARENT;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (e !== null) {\n\t\te.parent = parent;\n\n\t\tif (parent !== null) {\n\t\t\tpush_effect(e, parent);\n\t\t}\n\n\t\t// if we're in a derived, add the effect there too\n\t\tif (\n\t\t\tactive_reaction !== null &&\n\t\t\t(active_reaction.f & DERIVED) !== 0 &&\n\t\t\t(type & ROOT_EFFECT) === 0\n\t\t) {\n\t\t\tvar derived = /** @type {Derived} */ (active_reaction);\n\t\t\t(derived.effects ??= []).push(e);\n\t\t}\n\t}\n\n\treturn effect;\n}\n\n/**\n * Internal representation of `$effect.tracking()`\n * @returns {boolean}\n */\nexport function effect_tracking() {\n\treturn active_reaction !== null && !untracking;\n}\n\n/**\n * @param {() => void} fn\n */\nexport function teardown(fn) {\n\tconst effect = create_effect(RENDER_EFFECT, null);\n\tset_signal_status(effect, CLEAN);\n\teffect.teardown = fn;\n\treturn effect;\n}\n\n/**\n * Internal representation of `$effect(...)`\n * @param {() => void | (() => void)} fn\n */\nexport function user_effect(fn) {\n\tvalidate_effect('$effect');\n\n\tif (DEV) {\n\t\tdefine_property(fn, 'name', {\n\t\t\tvalue: '$effect'\n\t\t});\n\t}\n\n\t// Non-nested `$effect(...)` in a component should be deferred\n\t// until the component is mounted\n\tvar flags = /** @type {Effect} */ (active_effect).f;\n\tvar defer = !active_reaction && (flags & BRANCH_EFFECT) !== 0 && (flags & REACTION_RAN) === 0;\n\n\tif (defer) {\n\t\t// Top-level `$effect(...)` in an unmounted component — defer until mount\n\t\tvar context = /** @type {ComponentContext} */ (component_context);\n\t\t(context.e ??= []).push(fn);\n\t} else {\n\t\t// Everything else — create immediately\n\t\treturn create_user_effect(fn);\n\t}\n}\n\n/**\n * @param {() => void | (() => void)} fn\n */\nexport function create_user_effect(fn) {\n\treturn create_effect(EFFECT | USER_EFFECT, fn);\n}\n\n/**\n * Internal representation of `$effect.pre(...)`\n * @param {() => void | (() => void)} fn\n * @returns {Effect}\n */\nexport function user_pre_effect(fn) {\n\tvalidate_effect('$effect.pre');\n\tif (DEV) {\n\t\tdefine_property(fn, 'name', {\n\t\t\tvalue: '$effect.pre'\n\t\t});\n\t}\n\treturn create_effect(RENDER_EFFECT | USER_EFFECT, fn);\n}\n\n/** @param {() => void | (() => void)} fn */\nexport function eager_effect(fn) {\n\treturn create_effect(EAGER_EFFECT, fn);\n}\n\n/**\n * Internal representation of `$effect.root(...)`\n * @param {() => void | (() => void)} fn\n * @returns {() => void}\n */\nexport function effect_root(fn) {\n\tBatch.ensure();\n\tconst effect = create_effect(ROOT_EFFECT | EFFECT_PRESERVED, fn);\n\n\treturn () => {\n\t\tdestroy_effect(effect);\n\t};\n}\n\n/**\n * An effect root whose children can transition out\n * @param {() => void} fn\n * @returns {(options?: { outro?: boolean }) => Promise<void>}\n */\nexport function component_root(fn) {\n\tBatch.ensure();\n\tconst effect = create_effect(ROOT_EFFECT | EFFECT_PRESERVED, fn);\n\n\treturn (options = {}) => {\n\t\treturn new Promise((fulfil) => {\n\t\t\tif (options.outro) {\n\t\t\t\tpause_effect(effect, () => {\n\t\t\t\t\tdestroy_effect(effect);\n\t\t\t\t\tfulfil(undefined);\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tdestroy_effect(effect);\n\t\t\t\tfulfil(undefined);\n\t\t\t}\n\t\t});\n\t};\n}\n\n/**\n * @param {() => void | (() => void)} fn\n * @returns {Effect}\n */\nexport function effect(fn) {\n\treturn create_effect(EFFECT, fn);\n}\n\n/**\n * Internal representation of `$: ..`\n * @param {() => any} deps\n * @param {() => void | (() => void)} fn\n */\nexport function legacy_pre_effect(deps, fn) {\n\tvar context = /** @type {ComponentContextLegacy} */ (component_context);\n\n\t/** @type {{ effect: null | Effect, ran: boolean, deps: () => any }} */\n\tvar token = { effect: null, ran: false, deps };\n\n\tcontext.l.$.push(token);\n\n\ttoken.effect = render_effect(() => {\n\t\tdeps();\n\n\t\t// If this legacy pre effect has already run before the end of the reset, then\n\t\t// bail out to emulate the same behavior.\n\t\tif (token.ran) return;\n\n\t\ttoken.ran = true;\n\n\t\tvar effect = /** @type {Effect} */ (active_effect);\n\n\t\t// here, we lie: by setting `active_effect` to be the parent branch, any writes\n\t\t// that happen inside `fn` will _not_ cause an unnecessary reschedule, because\n\t\t// the affected effects will be children of `active_effect`. this is safe\n\t\t// because these effects are known to run in the correct order\n\t\ttry {\n\t\t\tset_active_effect(effect.parent);\n\t\t\tuntrack(fn);\n\t\t} finally {\n\t\t\tset_active_effect(effect);\n\t\t}\n\t});\n}\n\nexport function legacy_pre_effect_reset() {\n\tvar context = /** @type {ComponentContextLegacy} */ (component_context);\n\n\trender_effect(() => {\n\t\t// Run dirty `$:` statements\n\t\tfor (var token of context.l.$) {\n\t\t\ttoken.deps();\n\n\t\t\tvar effect = token.effect;\n\n\t\t\t// If the effect is CLEAN, then make it MAYBE_DIRTY. This ensures we traverse through\n\t\t\t// the effects dependencies and correctly ensure each dependency is up-to-date.\n\t\t\tif ((effect.f & CLEAN) !== 0 && effect.deps !== null) {\n\t\t\t\tset_signal_status(effect, MAYBE_DIRTY);\n\t\t\t}\n\n\t\t\tif (is_dirty(effect)) {\n\t\t\t\tupdate_effect(effect);\n\t\t\t}\n\n\t\t\ttoken.ran = false;\n\t\t}\n\t});\n}\n\n/**\n * @param {() => void | (() => void)} fn\n * @returns {Effect}\n */\nexport function async_effect(fn) {\n\treturn create_effect(ASYNC | EFFECT_PRESERVED, fn);\n}\n\n/**\n * @param {() => void | (() => void)} fn\n * @returns {Effect}\n */\nexport function render_effect(fn, flags = 0) {\n\treturn create_effect(RENDER_EFFECT | flags, fn);\n}\n\n/**\n * @param {(...expressions: any) => void | (() => void)} fn\n * @param {Array<() => any>} sync\n * @param {Array<() => Promise<any>>} async\n * @param {Blocker[]} blockers\n */\nexport function template_effect(fn, sync = [], async = [], blockers = []) {\n\tflatten(blockers, sync, async, (values) => {\n\t\tcreate_effect(RENDER_EFFECT, () => fn(...values.map(get)));\n\t});\n}\n\n/**\n * Like `template_effect`, but with an effect which is deferred until the batch commits\n * @param {(...expressions: any) => void | (() => void)} fn\n * @param {Array<() => any>} sync\n * @param {Array<() => Promise<any>>} async\n * @param {Blocker[]} blockers\n */\nexport function deferred_template_effect(fn, sync = [], async = [], blockers = []) {\n\tif (async.length > 0 || blockers.length > 0) {\n\t\tvar decrement_pending = increment_pending();\n\t}\n\n\tflatten(blockers, sync, async, (values) => {\n\t\tcreate_effect(EFFECT, () => fn(...values.map(get)));\n\n\t\tif (decrement_pending) {\n\t\t\tdecrement_pending();\n\t\t}\n\t});\n}\n\n/**\n * @param {(() => void)} fn\n * @param {number} flags\n */\nexport function block(fn, flags = 0) {\n\tvar effect = create_effect(BLOCK_EFFECT | flags, fn);\n\tif (DEV) {\n\t\teffect.dev_stack = dev_stack;\n\t}\n\treturn effect;\n}\n\n/**\n * @param {(() => void)} fn\n * @param {number} flags\n */\nexport function managed(fn, flags = 0) {\n\tvar effect = create_effect(MANAGED_EFFECT | flags, fn);\n\tif (DEV) {\n\t\teffect.dev_stack = dev_stack;\n\t}\n\treturn effect;\n}\n\n/**\n * @param {(() => void)} fn\n */\nexport function branch(fn) {\n\treturn create_effect(BRANCH_EFFECT | EFFECT_PRESERVED, fn);\n}\n\n/**\n * @param {Effect} effect\n */\nexport function execute_effect_teardown(effect) {\n\tvar teardown = effect.teardown;\n\tif (teardown !== null) {\n\t\tconst previously_destroying_effect = is_destroying_effect;\n\t\tconst previous_reaction = active_reaction;\n\t\tset_is_destroying_effect(true);\n\t\tset_active_reaction(null);\n\t\ttry {\n\t\t\tteardown.call(null);\n\t\t} finally {\n\t\t\tset_is_destroying_effect(previously_destroying_effect);\n\t\t\tset_active_reaction(previous_reaction);\n\t\t}\n\t}\n}\n\n/**\n * @param {Effect} signal\n * @param {boolean} remove_dom\n * @returns {void}\n */\nexport function destroy_effect_children(signal, remove_dom = false) {\n\tvar effect = signal.first;\n\tsignal.first = signal.last = null;\n\n\twhile (effect !== null) {\n\t\tconst controller = effect.ac;\n\n\t\tif (controller !== null) {\n\t\t\twithout_reactive_context(() => {\n\t\t\t\tcontroller.abort(STALE_REACTION);\n\t\t\t});\n\t\t}\n\n\t\tvar next = effect.next;\n\n\t\tif ((effect.f & ROOT_EFFECT) !== 0) {\n\t\t\t// this is now an independent root\n\t\t\teffect.parent = null;\n\t\t} else {\n\t\t\tdestroy_effect(effect, remove_dom);\n\t\t}\n\n\t\teffect = next;\n\t}\n}\n\n/**\n * @param {Effect} signal\n * @returns {void}\n */\nexport function destroy_block_effect_children(signal) {\n\tvar effect = signal.first;\n\n\twhile (effect !== null) {\n\t\tvar next = effect.next;\n\t\tif ((effect.f & BRANCH_EFFECT) === 0) {\n\t\t\tdestroy_effect(effect);\n\t\t}\n\t\teffect = next;\n\t}\n}\n\n/**\n * @param {Effect} effect\n * @param {boolean} [remove_dom]\n * @returns {void}\n */\nexport function destroy_effect(effect, remove_dom = true) {\n\tvar removed = false;\n\n\tif (\n\t\t(remove_dom || (effect.f & HEAD_EFFECT) !== 0) &&\n\t\teffect.nodes !== null &&\n\t\teffect.nodes.end !== null\n\t) {\n\t\tremove_effect_dom(effect.nodes.start, /** @type {TemplateNode} */ (effect.nodes.end));\n\t\tremoved = true;\n\t}\n\n\tset_signal_status(effect, DESTROYING);\n\tdestroy_effect_children(effect, remove_dom && !removed);\n\tremove_reactions(effect, 0);\n\n\tvar transitions = effect.nodes && effect.nodes.t;\n\n\tif (transitions !== null) {\n\t\tfor (const transition of transitions) {\n\t\t\ttransition.stop();\n\t\t}\n\t}\n\n\texecute_effect_teardown(effect);\n\n\teffect.f ^= DESTROYING;\n\teffect.f |= DESTROYED;\n\n\tvar parent = effect.parent;\n\n\t// If the parent doesn't have any children, then skip this work altogether\n\tif (parent !== null && parent.first !== null) {\n\t\tunlink_effect(effect);\n\t}\n\n\tif (DEV) {\n\t\teffect.component_function = null;\n\t}\n\n\t// `first` and `child` are nulled out in destroy_effect_children\n\t// we don't null out `parent` so that error propagation can work correctly\n\teffect.next =\n\t\teffect.prev =\n\t\teffect.teardown =\n\t\teffect.ctx =\n\t\teffect.deps =\n\t\teffect.fn =\n\t\teffect.nodes =\n\t\teffect.ac =\n\t\teffect.b =\n\t\t\tnull;\n}\n\n/**\n *\n * @param {TemplateNode | null} node\n * @param {TemplateNode} end\n */\nexport function remove_effect_dom(node, end) {\n\twhile (node !== null) {\n\t\t/** @type {TemplateNode | null} */\n\t\tvar next = node === end ? null : get_next_sibling(node);\n\n\t\tnode.remove();\n\t\tnode = next;\n\t}\n}\n\n/**\n * Detach an effect from the effect tree, freeing up memory and\n * reducing the amount of work that happens on subsequent traversals\n * @param {Effect} effect\n */\nexport function unlink_effect(effect) {\n\tvar parent = effect.parent;\n\tvar prev = effect.prev;\n\tvar next = effect.next;\n\n\tif (prev !== null) prev.next = next;\n\tif (next !== null) next.prev = prev;\n\n\tif (parent !== null) {\n\t\tif (parent.first === effect) parent.first = next;\n\t\tif (parent.last === effect) parent.last = prev;\n\t}\n}\n\n/**\n * When a block effect is removed, we don't immediately destroy it or yank it\n * out of the DOM, because it might have transitions. Instead, we 'pause' it.\n * It stays around (in memory, and in the DOM) until outro transitions have\n * completed, and if the state change is reversed then we _resume_ it.\n * A paused effect does not update, and the DOM subtree becomes inert.\n * @param {Effect} effect\n * @param {() => void} [callback]\n * @param {boolean} [destroy]\n */\nexport function pause_effect(effect, callback, destroy = true) {\n\t/** @type {TransitionManager[]} */\n\tvar transitions = [];\n\n\tpause_children(effect, transitions, true);\n\n\tvar fn = () => {\n\t\tif (destroy) destroy_effect(effect);\n\t\tif (callback) callback();\n\t};\n\n\tvar remaining = transitions.length;\n\tif (remaining > 0) {\n\t\tvar check = () => --remaining || fn();\n\t\tfor (var transition of transitions) {\n\t\t\ttransition.out(check);\n\t\t}\n\t} else {\n\t\tfn();\n\t}\n}\n\n/**\n * @param {Effect} effect\n * @param {TransitionManager[]} transitions\n * @param {boolean} local\n */\nfunction pause_children(effect, transitions, local) {\n\tif ((effect.f & INERT) !== 0) return;\n\teffect.f ^= INERT;\n\n\tvar t = effect.nodes && effect.nodes.t;\n\n\tif (t !== null) {\n\t\tfor (const transition of t) {\n\t\t\tif (transition.is_global || local) {\n\t\t\t\ttransitions.push(transition);\n\t\t\t}\n\t\t}\n\t}\n\n\tvar child = effect.first;\n\n\twhile (child !== null) {\n\t\tvar sibling = child.next;\n\n\t\t// If this child is a root effect, then it will become an independent root when its parent\n\t\t// is destroyed, it should therefore not become inert nor partake in transitions.\n\t\tif ((child.f & ROOT_EFFECT) === 0) {\n\t\t\tvar transparent =\n\t\t\t\t(child.f & EFFECT_TRANSPARENT) !== 0 ||\n\t\t\t\t// If this is a branch effect without a block effect parent,\n\t\t\t\t// it means the parent block effect was pruned. In that case,\n\t\t\t\t// transparency information was transferred to the branch effect.\n\t\t\t\t((child.f & BRANCH_EFFECT) !== 0 && (effect.f & BLOCK_EFFECT) !== 0);\n\t\t\t// TODO we don't need to call pause_children recursively with a linked list in place\n\t\t\t// it's slightly more involved though as we have to account for `transparent` changing\n\t\t\t// through the tree.\n\t\t\tpause_children(child, transitions, transparent ? local : false);\n\t\t}\n\n\t\tchild = sibling;\n\t}\n}\n\n/**\n * The opposite of `pause_effect`. We call this if (for example)\n * `x` becomes falsy then truthy: `{#if x}...{/if}`\n * @param {Effect} effect\n */\nexport function resume_effect(effect) {\n\tresume_children(effect, true);\n}\n\n/**\n * @param {Effect} effect\n * @param {boolean} local\n */\nfunction resume_children(effect, local) {\n\tif ((effect.f & INERT) === 0) return;\n\teffect.f ^= INERT;\n\n\t// If a dependency of this effect changed while it was paused,\n\t// schedule the effect to update. we don't use `is_dirty`\n\t// here because we don't want to eagerly recompute a derived like\n\t// `{#if foo}{foo.bar()}{/if}` if `foo` is now `undefined\n\tif ((effect.f & CLEAN) === 0) {\n\t\tset_signal_status(effect, DIRTY);\n\t\tBatch.ensure().schedule(effect); // Assumption: This happens during the commit phase of the batch, causing another flush, but it's safe\n\t}\n\n\tvar child = effect.first;\n\n\twhile (child !== null) {\n\t\tvar sibling = child.next;\n\t\tvar transparent = (child.f & EFFECT_TRANSPARENT) !== 0 || (child.f & BRANCH_EFFECT) !== 0;\n\t\t// TODO we don't need to call resume_children recursively with a linked list in place\n\t\t// it's slightly more involved though as we have to account for `transparent` changing\n\t\t// through the tree.\n\t\tresume_children(child, transparent ? local : false);\n\t\tchild = sibling;\n\t}\n\n\tvar t = effect.nodes && effect.nodes.t;\n\n\tif (t !== null) {\n\t\tfor (const transition of t) {\n\t\t\tif (transition.is_global || local) {\n\t\t\t\ttransition.in();\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport function aborted(effect = /** @type {Effect} */ (active_effect)) {\n\treturn (effect.f & DESTROYED) !== 0;\n}\n\n/**\n * @param {Effect} effect\n * @param {DocumentFragment} fragment\n */\nexport function move_effect(effect, fragment) {\n\tif (!effect.nodes) return;\n\n\t/** @type {TemplateNode | null} */\n\tvar node = effect.nodes.start;\n\tvar end = effect.nodes.end;\n\n\twhile (node !== null) {\n\t\t/** @type {TemplateNode | null} */\n\t\tvar next = node === end ? null : get_next_sibling(node);\n\n\t\tfragment.append(node);\n\t\tnode = next;\n\t}\n}\n","/** @import { Value } from '#client' */\nimport { internal_set } from './reactivity/sources.js';\nimport { untrack } from './runtime.js';\n\n/**\n * @type {Set<Value> | null}\n * @deprecated\n */\nexport let captured_signals = null;\n\n/**\n * Capture an array of all the signals that are read when `fn` is called\n * @template T\n * @param {() => T} fn\n */\nfunction capture_signals(fn) {\n\tvar previous_captured_signals = captured_signals;\n\n\ttry {\n\t\tcaptured_signals = new Set();\n\n\t\tuntrack(fn);\n\n\t\tif (previous_captured_signals !== null) {\n\t\t\tfor (var signal of captured_signals) {\n\t\t\t\tprevious_captured_signals.add(signal);\n\t\t\t}\n\t\t}\n\n\t\treturn captured_signals;\n\t} finally {\n\t\tcaptured_signals = previous_captured_signals;\n\t}\n}\n\n/**\n * Invokes a function and captures all signals that are read during the invocation,\n * then invalidates them.\n * @param {() => any} fn\n * @deprecated\n */\nexport function invalidate_inner_signals(fn) {\n\tfor (var signal of capture_signals(fn)) {\n\t\tinternal_set(signal, signal.v);\n\t}\n}\n","/** @import { Derived, Effect, Reaction, Source, Value } from '#client' */\nimport { DEV } from 'esm-env';\nimport { get_descriptors, get_prototype_of, includes, index_of } from '../shared/utils.js';\nimport {\n\tdestroy_block_effect_children,\n\tdestroy_effect_children,\n\teffect_tracking,\n\texecute_effect_teardown\n} from './reactivity/effects.js';\nimport {\n\tDIRTY,\n\tMAYBE_DIRTY,\n\tCLEAN,\n\tDERIVED,\n\tDESTROYED,\n\tBRANCH_EFFECT,\n\tSTATE_SYMBOL,\n\tBLOCK_EFFECT,\n\tROOT_EFFECT,\n\tCONNECTED,\n\tREACTION_IS_UPDATING,\n\tSTALE_REACTION,\n\tERROR_VALUE,\n\tWAS_MARKED,\n\tMANAGED_EFFECT,\n\tREACTION_RAN\n} from './constants.js';\nimport { old_values } from './reactivity/sources.js';\nimport {\n\treactivity_loss_tracker,\n\texecute_derived,\n\tfreeze_derived_effects,\n\trecent_async_deriveds,\n\tunfreeze_derived_effects,\n\tupdate_derived\n} from './reactivity/deriveds.js';\nimport { async_mode_flag, tracing_mode_flag } from '../flags/index.js';\nimport { tracing_expressions } from './dev/tracing.js';\nimport { get_error } from '../shared/dev.js';\nimport {\n\tcomponent_context,\n\tdev_current_component_function,\n\tdev_stack,\n\tis_runes,\n\tset_component_context,\n\tset_dev_current_component_function,\n\tset_dev_stack\n} from './context.js';\nimport {\n\tBatch,\n\tbatch_values,\n\tcurrent_batch,\n\tflushSync,\n\tschedule_effect\n} from './reactivity/batch.js';\nimport { handle_error } from './error-handling.js';\nimport { UNINITIALIZED } from '../../constants.js';\nimport { captured_signals } from './legacy.js';\nimport { without_reactive_context } from './dom/elements/bindings/shared.js';\nimport { set_signal_status, update_derived_status } from './reactivity/status.js';\nimport * as w from './warnings.js';\n\nlet is_updating_effect = false;\n\nexport let is_destroying_effect = false;\n\n/** @param {boolean} value */\nexport function set_is_destroying_effect(value) {\n\tis_destroying_effect = value;\n}\n\n/** @type {null | Reaction} */\nexport let active_reaction = null;\n\nexport let untracking = false;\n\n/** @param {null | Reaction} reaction */\nexport function set_active_reaction(reaction) {\n\tactive_reaction = reaction;\n}\n\n/** @type {null | Effect} */\nexport let active_effect = null;\n\n/** @param {null | Effect} effect */\nexport function set_active_effect(effect) {\n\tactive_effect = effect;\n}\n\n/**\n * When sources are created within a reaction, reading and writing\n * them within that reaction should not cause a re-run\n * @type {null | Source[]}\n */\nexport let current_sources = null;\n\n/** @param {Value} value */\nexport function push_reaction_value(value) {\n\tif (active_reaction !== null && (!async_mode_flag || (active_reaction.f & DERIVED) !== 0)) {\n\t\tif (current_sources === null) {\n\t\t\tcurrent_sources = [value];\n\t\t} else {\n\t\t\tcurrent_sources.push(value);\n\t\t}\n\t}\n}\n\n/**\n * The dependencies of the reaction that is currently being executed. In many cases,\n * the dependencies are unchanged between runs, and so this will be `null` unless\n * and until a new dependency is accessed — we track this via `skipped_deps`\n * @type {null | Value[]}\n */\nexport let new_deps = null;\n\nexport let skipped_deps = 0;\n\n/**\n * Tracks writes that the effect it's executed in doesn't listen to yet,\n * so that the dependency can be added to the effect later on if it then reads it\n * @type {null | Source[]}\n */\nexport let untracked_writes = null;\n\n/** @param {null | Source[]} value */\nexport function set_untracked_writes(value) {\n\tuntracked_writes = value;\n}\n\n/**\n * @type {number} Used by sources and deriveds for handling updates.\n * Version starts from 1 so that unowned deriveds differentiate between a created effect and a run one for tracing\n **/\nexport let write_version = 1;\n\n/** @type {number} Used to version each read of a source of derived to avoid duplicating depedencies inside a reaction */\nlet read_version = 0;\n\nexport let update_version = read_version;\n\n/** @param {number} value */\nexport function set_update_version(value) {\n\tupdate_version = value;\n}\n\nexport function increment_write_version() {\n\treturn ++write_version;\n}\n\n/**\n * Determines whether a derived or effect is dirty.\n * If it is MAYBE_DIRTY, will set the status to CLEAN\n * @param {Reaction} reaction\n * @returns {boolean}\n */\nexport function is_dirty(reaction) {\n\tvar flags = reaction.f;\n\n\tif ((flags & DIRTY) !== 0) {\n\t\treturn true;\n\t}\n\n\tif (flags & DERIVED) {\n\t\treaction.f &= ~WAS_MARKED;\n\t}\n\n\tif ((flags & MAYBE_DIRTY) !== 0) {\n\t\tvar dependencies = /** @type {Value[]} */ (reaction.deps);\n\t\tvar length = dependencies.length;\n\n\t\tfor (var i = 0; i < length; i++) {\n\t\t\tvar dependency = dependencies[i];\n\n\t\t\tif (is_dirty(/** @type {Derived} */ (dependency))) {\n\t\t\t\tupdate_derived(/** @type {Derived} */ (dependency));\n\t\t\t}\n\n\t\t\tif (dependency.wv > reaction.wv) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\t(flags & CONNECTED) !== 0 &&\n\t\t\t// During time traveling we don't want to reset the status so that\n\t\t\t// traversal of the graph in the other batches still happens\n\t\t\tbatch_values === null\n\t\t) {\n\t\t\tset_signal_status(reaction, CLEAN);\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * @param {Value} signal\n * @param {Effect} effect\n * @param {boolean} [root]\n */\nfunction schedule_possible_effect_self_invalidation(signal, effect, root = true) {\n\tvar reactions = signal.reactions;\n\tif (reactions === null) return;\n\n\tif (!async_mode_flag && current_sources !== null && includes.call(current_sources, signal)) {\n\t\treturn;\n\t}\n\n\tfor (var i = 0; i < reactions.length; i++) {\n\t\tvar reaction = reactions[i];\n\n\t\tif ((reaction.f & DERIVED) !== 0) {\n\t\t\tschedule_possible_effect_self_invalidation(/** @type {Derived} */ (reaction), effect, false);\n\t\t} else if (effect === reaction) {\n\t\t\tif (root) {\n\t\t\t\tset_signal_status(reaction, DIRTY);\n\t\t\t} else if ((reaction.f & CLEAN) !== 0) {\n\t\t\t\tset_signal_status(reaction, MAYBE_DIRTY);\n\t\t\t}\n\t\t\tschedule_effect(/** @type {Effect} */ (reaction));\n\t\t}\n\t}\n}\n\n/** @param {Reaction} reaction */\nexport function update_reaction(reaction) {\n\tvar previous_deps = new_deps;\n\tvar previous_skipped_deps = skipped_deps;\n\tvar previous_untracked_writes = untracked_writes;\n\tvar previous_reaction = active_reaction;\n\tvar previous_sources = current_sources;\n\tvar previous_component_context = component_context;\n\tvar previous_untracking = untracking;\n\tvar previous_update_version = update_version;\n\n\tvar flags = reaction.f;\n\n\tnew_deps = /** @type {null | Value[]} */ (null);\n\tskipped_deps = 0;\n\tuntracked_writes = null;\n\tactive_reaction = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null;\n\n\tcurrent_sources = null;\n\tset_component_context(reaction.ctx);\n\tuntracking = false;\n\tupdate_version = ++read_version;\n\n\tif (reaction.ac !== null) {\n\t\twithout_reactive_context(() => {\n\t\t\t/** @type {AbortController} */ (reaction.ac).abort(STALE_REACTION);\n\t\t});\n\n\t\treaction.ac = null;\n\t}\n\n\ttry {\n\t\treaction.f |= REACTION_IS_UPDATING;\n\t\tvar fn = /** @type {Function} */ (reaction.fn);\n\t\tvar result = fn();\n\t\treaction.f |= REACTION_RAN;\n\t\tvar deps = reaction.deps;\n\n\t\t// Don't remove reactions during fork;\n\t\t// they must remain for when fork is discarded\n\t\tvar is_fork = current_batch?.is_fork;\n\n\t\tif (new_deps !== null) {\n\t\t\tvar i;\n\n\t\t\tif (!is_fork) {\n\t\t\t\tremove_reactions(reaction, skipped_deps);\n\t\t\t}\n\n\t\t\tif (deps !== null && skipped_deps > 0) {\n\t\t\t\tdeps.length = skipped_deps + new_deps.length;\n\t\t\t\tfor (i = 0; i < new_deps.length; i++) {\n\t\t\t\t\tdeps[skipped_deps + i] = new_deps[i];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treaction.deps = deps = new_deps;\n\t\t\t}\n\n\t\t\tif (effect_tracking() && (reaction.f & CONNECTED) !== 0) {\n\t\t\t\tfor (i = skipped_deps; i < deps.length; i++) {\n\t\t\t\t\t(deps[i].reactions ??= []).push(reaction);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (!is_fork && deps !== null && skipped_deps < deps.length) {\n\t\t\tremove_reactions(reaction, skipped_deps);\n\t\t\tdeps.length = skipped_deps;\n\t\t}\n\n\t\t// If we're inside an effect and we have untracked writes, then we need to\n\t\t// ensure that if any of those untracked writes result in re-invalidation\n\t\t// of the current effect, then that happens accordingly\n\t\tif (\n\t\t\tis_runes() &&\n\t\t\tuntracked_writes !== null &&\n\t\t\t!untracking &&\n\t\t\tdeps !== null &&\n\t\t\t(reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0\n\t\t) {\n\t\t\tfor (i = 0; i < /** @type {Source[]} */ (untracked_writes).length; i++) {\n\t\t\t\tschedule_possible_effect_self_invalidation(\n\t\t\t\t\tuntracked_writes[i],\n\t\t\t\t\t/** @type {Effect} */ (reaction)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// If we are returning to an previous reaction then\n\t\t// we need to increment the read version to ensure that\n\t\t// any dependencies in this reaction aren't marked with\n\t\t// the same version\n\t\tif (previous_reaction !== null && previous_reaction !== reaction) {\n\t\t\tread_version++;\n\n\t\t\t// update the `rv` of the previous reaction's deps — both existing and new —\n\t\t\t// so that they are not added again\n\t\t\tif (previous_reaction.deps !== null) {\n\t\t\t\tfor (let i = 0; i < previous_skipped_deps; i += 1) {\n\t\t\t\t\tprevious_reaction.deps[i].rv = read_version;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (previous_deps !== null) {\n\t\t\t\tfor (const dep of previous_deps) {\n\t\t\t\t\tdep.rv = read_version;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (untracked_writes !== null) {\n\t\t\t\tif (previous_untracked_writes === null) {\n\t\t\t\t\tprevious_untracked_writes = untracked_writes;\n\t\t\t\t} else {\n\t\t\t\t\tprevious_untracked_writes.push(.../** @type {Source[]} */ (untracked_writes));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif ((reaction.f & ERROR_VALUE) !== 0) {\n\t\t\treaction.f ^= ERROR_VALUE;\n\t\t}\n\n\t\treturn result;\n\t} catch (error) {\n\t\treturn handle_error(error);\n\t} finally {\n\t\treaction.f ^= REACTION_IS_UPDATING;\n\t\tnew_deps = previous_deps;\n\t\tskipped_deps = previous_skipped_deps;\n\t\tuntracked_writes = previous_untracked_writes;\n\t\tactive_reaction = previous_reaction;\n\t\tcurrent_sources = previous_sources;\n\t\tset_component_context(previous_component_context);\n\t\tuntracking = previous_untracking;\n\t\tupdate_version = previous_update_version;\n\t}\n}\n\n/**\n * @template V\n * @param {Reaction} signal\n * @param {Value<V>} dependency\n * @returns {void}\n */\nfunction remove_reaction(signal, dependency) {\n\tlet reactions = dependency.reactions;\n\tif (reactions !== null) {\n\t\tvar index = index_of.call(reactions, signal);\n\t\tif (index !== -1) {\n\t\t\tvar new_length = reactions.length - 1;\n\t\t\tif (new_length === 0) {\n\t\t\t\treactions = dependency.reactions = null;\n\t\t\t} else {\n\t\t\t\t// Swap with last element and then remove.\n\t\t\t\treactions[index] = reactions[new_length];\n\t\t\t\treactions.pop();\n\t\t\t}\n\t\t}\n\t}\n\n\t// If the derived has no reactions, then we can disconnect it from the graph,\n\t// allowing it to either reconnect in the future, or be GC'd by the VM.\n\tif (\n\t\treactions === null &&\n\t\t(dependency.f & DERIVED) !== 0 &&\n\t\t// Destroying a child effect while updating a parent effect can cause a dependency to appear\n\t\t// to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps`\n\t\t// allows us to skip the expensive work of disconnecting and immediately reconnecting it\n\t\t(new_deps === null || !includes.call(new_deps, dependency))\n\t) {\n\t\tvar derived = /** @type {Derived} */ (dependency);\n\n\t\t// If we are working with a derived that is owned by an effect, then mark it as being\n\t\t// disconnected and remove the mark flag, as it cannot be reliably removed otherwise\n\t\tif ((derived.f & CONNECTED) !== 0) {\n\t\t\tderived.f ^= CONNECTED;\n\t\t\tderived.f &= ~WAS_MARKED;\n\t\t}\n\n\t\t// In a fork it's possible that a derived is executed and gets reactions, then commits, but is\n\t\t// never re-executed. This is possible when the derived is only executed once in the context\n\t\t// of a new branch which happens before fork.commit() runs. In this case, the derived still has\n\t\t// UNINITIALIZED as its value, and then when it's loosing its reactions we need to ensure it stays\n\t\t// DIRTY so it is reexecuted once someone wants its value again.\n\t\tif (derived.v !== UNINITIALIZED) {\n\t\t\tupdate_derived_status(derived);\n\t\t}\n\n\t\t// freeze any effects inside this derived\n\t\tfreeze_derived_effects(derived);\n\n\t\t// Disconnect any reactions owned by this reaction\n\t\tremove_reactions(derived, 0);\n\t}\n}\n\n/**\n * @param {Reaction} signal\n * @param {number} start_index\n * @returns {void}\n */\nexport function remove_reactions(signal, start_index) {\n\tvar dependencies = signal.deps;\n\tif (dependencies === null) return;\n\n\tfor (var i = start_index; i < dependencies.length; i++) {\n\t\tremove_reaction(signal, dependencies[i]);\n\t}\n}\n\n/**\n * @param {Effect} effect\n * @returns {void}\n */\nexport function update_effect(effect) {\n\tvar flags = effect.f;\n\n\tif ((flags & DESTROYED) !== 0) {\n\t\treturn;\n\t}\n\n\tset_signal_status(effect, CLEAN);\n\n\tvar previous_effect = active_effect;\n\tvar was_updating_effect = is_updating_effect;\n\n\tactive_effect = effect;\n\tis_updating_effect = true;\n\n\tif (DEV) {\n\t\tvar previous_component_fn = dev_current_component_function;\n\t\tset_dev_current_component_function(effect.component_function);\n\t\tvar previous_stack = /** @type {any} */ (dev_stack);\n\t\t// only block effects have a dev stack, keep the current one otherwise\n\t\tset_dev_stack(effect.dev_stack ?? dev_stack);\n\t}\n\n\ttry {\n\t\tif ((flags & (BLOCK_EFFECT | MANAGED_EFFECT)) !== 0) {\n\t\t\tdestroy_block_effect_children(effect);\n\t\t} else {\n\t\t\tdestroy_effect_children(effect);\n\t\t}\n\n\t\texecute_effect_teardown(effect);\n\t\tvar teardown = update_reaction(effect);\n\t\teffect.teardown = typeof teardown === 'function' ? teardown : null;\n\t\teffect.wv = write_version;\n\n\t\t// In DEV, increment versions of any sources that were written to during the effect,\n\t\t// so that they are correctly marked as dirty when the effect re-runs\n\t\tif (DEV && tracing_mode_flag && (effect.f & DIRTY) !== 0 && effect.deps !== null) {\n\t\t\tfor (var dep of effect.deps) {\n\t\t\t\tif (dep.set_during_effect) {\n\t\t\t\t\tdep.wv = increment_write_version();\n\t\t\t\t\tdep.set_during_effect = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tis_updating_effect = was_updating_effect;\n\t\tactive_effect = previous_effect;\n\n\t\tif (DEV) {\n\t\t\tset_dev_current_component_function(previous_component_fn);\n\t\t\tset_dev_stack(previous_stack);\n\t\t}\n\t}\n}\n\n/**\n * Returns a promise that resolves once any pending state changes have been applied.\n * @returns {Promise<void>}\n */\nexport async function tick() {\n\tif (async_mode_flag) {\n\t\treturn new Promise((f) => {\n\t\t\t// Race them against each other - in almost all cases requestAnimationFrame will fire first,\n\t\t\t// but e.g. in case the window is not focused or a view transition happens, requestAnimationFrame\n\t\t\t// will be delayed and setTimeout helps us resolve fast enough in that case\n\t\t\trequestAnimationFrame(() => f());\n\t\t\tsetTimeout(() => f());\n\t\t});\n\t}\n\n\tawait Promise.resolve();\n\n\t// By calling flushSync we guarantee that any pending state changes are applied after one tick.\n\t// TODO look into whether we can make flushing subsequent updates synchronously in the future.\n\tflushSync();\n}\n\n/**\n * Returns a promise that resolves once any state changes, and asynchronous work resulting from them,\n * have resolved and the DOM has been updated\n * @returns {Promise<void>}\n * @since 5.36\n */\nexport function settled() {\n\treturn Batch.ensure().settled();\n}\n\n/**\n * @template V\n * @param {Value<V>} signal\n * @returns {V}\n */\nexport function get(signal) {\n\tvar flags = signal.f;\n\tvar is_derived = (flags & DERIVED) !== 0;\n\n\tcaptured_signals?.add(signal);\n\n\t// Register the dependency on the current reaction signal.\n\tif (active_reaction !== null && !untracking) {\n\t\t// if we're in a derived that is being read inside an _async_ derived,\n\t\t// it's possible that the effect was already destroyed. In this case,\n\t\t// we don't add the dependency, because that would create a memory leak\n\t\tvar destroyed = active_effect !== null && (active_effect.f & DESTROYED) !== 0;\n\n\t\tif (!destroyed && (current_sources === null || !includes.call(current_sources, signal))) {\n\t\t\tvar deps = active_reaction.deps;\n\n\t\t\tif ((active_reaction.f & REACTION_IS_UPDATING) !== 0) {\n\t\t\t\t// we're in the effect init/update cycle\n\t\t\t\tif (signal.rv < read_version) {\n\t\t\t\t\tsignal.rv = read_version;\n\n\t\t\t\t\t// If the signal is accessing the same dependencies in the same\n\t\t\t\t\t// order as it did last time, increment `skipped_deps`\n\t\t\t\t\t// rather than updating `new_deps`, which creates GC cost\n\t\t\t\t\tif (new_deps === null && deps !== null && deps[skipped_deps] === signal) {\n\t\t\t\t\t\tskipped_deps++;\n\t\t\t\t\t} else if (new_deps === null) {\n\t\t\t\t\t\tnew_deps = [signal];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnew_deps.push(signal);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// we're adding a dependency outside the init/update cycle\n\t\t\t\t// (i.e. after an `await`)\n\t\t\t\t(active_reaction.deps ??= []).push(signal);\n\n\t\t\t\tvar reactions = signal.reactions;\n\n\t\t\t\tif (reactions === null) {\n\t\t\t\t\tsignal.reactions = [active_reaction];\n\t\t\t\t} else if (!includes.call(reactions, active_reaction)) {\n\t\t\t\t\treactions.push(active_reaction);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (DEV) {\n\t\tif (\n\t\t\t!untracking &&\n\t\t\treactivity_loss_tracker &&\n\t\t\t!reactivity_loss_tracker.warned &&\n\t\t\t(reactivity_loss_tracker.effect.f & REACTION_IS_UPDATING) === 0 &&\n\t\t\t!reactivity_loss_tracker.effect_deps.has(signal)\n\t\t) {\n\t\t\treactivity_loss_tracker.warned = true;\n\n\t\t\tw.await_reactivity_loss(/** @type {string} */ (signal.label));\n\n\t\t\tvar trace = get_error('traced at');\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tif (trace) console.warn(trace);\n\t\t}\n\n\t\trecent_async_deriveds.delete(signal);\n\n\t\tif (\n\t\t\ttracing_mode_flag &&\n\t\t\t!untracking &&\n\t\t\ttracing_expressions !== null &&\n\t\t\tactive_reaction !== null &&\n\t\t\ttracing_expressions.reaction === active_reaction\n\t\t) {\n\t\t\t// Used when mapping state between special blocks like `each`\n\t\t\tif (signal.trace) {\n\t\t\t\tsignal.trace();\n\t\t\t} else {\n\t\t\t\ttrace = get_error('traced at');\n\n\t\t\t\tif (trace) {\n\t\t\t\t\tvar entry = tracing_expressions.entries.get(signal);\n\n\t\t\t\t\tif (entry === undefined) {\n\t\t\t\t\t\tentry = { traces: [] };\n\t\t\t\t\t\ttracing_expressions.entries.set(signal, entry);\n\t\t\t\t\t}\n\n\t\t\t\t\tvar last = entry.traces[entry.traces.length - 1];\n\n\t\t\t\t\t// traces can be duplicated, e.g. by `snapshot` invoking both\n\t\t\t\t\t// both `getOwnPropertyDescriptor` and `get` traps at once\n\t\t\t\t\tif (trace.stack !== last?.stack) {\n\t\t\t\t\t\tentry.traces.push(trace);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (is_destroying_effect && old_values.has(signal)) {\n\t\treturn old_values.get(signal);\n\t}\n\n\tif (is_derived) {\n\t\tvar derived = /** @type {Derived} */ (signal);\n\n\t\tif (is_destroying_effect) {\n\t\t\tvar value = derived.v;\n\n\t\t\t// if the derived is dirty and has reactions, or depends on the values that just changed, re-execute\n\t\t\t// (a derived can be maybe_dirty due to the effect destroy removing its last reaction)\n\t\t\tif (\n\t\t\t\t((derived.f & CLEAN) === 0 && derived.reactions !== null) ||\n\t\t\t\tdepends_on_old_values(derived)\n\t\t\t) {\n\t\t\t\tvalue = execute_derived(derived);\n\t\t\t}\n\n\t\t\told_values.set(derived, value);\n\n\t\t\treturn value;\n\t\t}\n\n\t\t// connect disconnected deriveds if we are reading them inside an effect,\n\t\t// or inside another derived that is already connected\n\t\tvar should_connect =\n\t\t\t(derived.f & CONNECTED) === 0 &&\n\t\t\t!untracking &&\n\t\t\tactive_reaction !== null &&\n\t\t\t(is_updating_effect || (active_reaction.f & CONNECTED) !== 0);\n\n\t\tvar is_new = (derived.f & REACTION_RAN) === 0;\n\n\t\tif (is_dirty(derived)) {\n\t\t\tif (should_connect) {\n\t\t\t\t// set the flag before `update_derived`, so that the derived\n\t\t\t\t// is added as a reaction to its dependencies\n\t\t\t\tderived.f |= CONNECTED;\n\t\t\t}\n\n\t\t\tupdate_derived(derived);\n\t\t}\n\n\t\tif (should_connect && !is_new) {\n\t\t\tunfreeze_derived_effects(derived);\n\t\t\treconnect(derived);\n\t\t}\n\t}\n\n\tif (batch_values?.has(signal)) {\n\t\treturn batch_values.get(signal);\n\t}\n\n\tif ((signal.f & ERROR_VALUE) !== 0) {\n\t\tthrow signal.v;\n\t}\n\n\treturn signal.v;\n}\n\n/**\n * (Re)connect a disconnected derived, so that it is notified\n * of changes in `mark_reactions`\n * @param {Derived} derived\n */\nfunction reconnect(derived) {\n\tderived.f |= CONNECTED;\n\n\tif (derived.deps === null) return;\n\n\tfor (const dep of derived.deps) {\n\t\t(dep.reactions ??= []).push(derived);\n\n\t\tif ((dep.f & DERIVED) !== 0 && (dep.f & CONNECTED) === 0) {\n\t\t\tunfreeze_derived_effects(/** @type {Derived} */ (dep));\n\t\t\treconnect(/** @type {Derived} */ (dep));\n\t\t}\n\t}\n}\n\n/** @param {Derived} derived */\nfunction depends_on_old_values(derived) {\n\tif (derived.v === UNINITIALIZED) return true; // we don't know, so assume the worst\n\tif (derived.deps === null) return false;\n\n\tfor (const dep of derived.deps) {\n\t\tif (old_values.has(dep)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif ((dep.f & DERIVED) !== 0 && depends_on_old_values(/** @type {Derived} */ (dep))) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * Like `get`, but checks for `undefined`. Used for `var` declarations because they can be accessed before being declared\n * @template V\n * @param {Value<V> | undefined} signal\n * @returns {V | undefined}\n */\nexport function safe_get(signal) {\n\treturn signal && get(signal);\n}\n\n/**\n * When used inside a [`$derived`](https://svelte.dev/docs/svelte/$derived) or [`$effect`](https://svelte.dev/docs/svelte/$effect),\n * any state read inside `fn` will not be treated as a dependency.\n *\n * ```ts\n * $effect(() => {\n * // this will run when `data` changes, but not when `time` changes\n * save(data, {\n * timestamp: untrack(() => time)\n * });\n * });\n * ```\n * @template T\n * @param {() => T} fn\n * @returns {T}\n */\nexport function untrack(fn) {\n\tvar previous_untracking = untracking;\n\ttry {\n\t\tuntracking = true;\n\t\treturn fn();\n\t} finally {\n\t\tuntracking = previous_untracking;\n\t}\n}\n\n/**\n * Possibly traverse an object and read all its properties so that they're all reactive in case this is `$state`.\n * Does only check first level of an object for performance reasons (heuristic should be good for 99% of all cases).\n * @param {any} value\n * @returns {void}\n */\nexport function deep_read_state(value) {\n\tif (typeof value !== 'object' || !value || value instanceof EventTarget) {\n\t\treturn;\n\t}\n\n\tif (STATE_SYMBOL in value) {\n\t\tdeep_read(value);\n\t} else if (!Array.isArray(value)) {\n\t\tfor (let key in value) {\n\t\t\tconst prop = value[key];\n\t\t\tif (typeof prop === 'object' && prop && STATE_SYMBOL in prop) {\n\t\t\t\tdeep_read(prop);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Deeply traverse an object and read all its properties\n * so that they're all reactive in case this is `$state`\n * @param {any} value\n * @param {Set<any>} visited\n * @returns {void}\n */\nexport function deep_read(value, visited = new Set()) {\n\tif (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t// We don't want to traverse DOM elements\n\t\t!(value instanceof EventTarget) &&\n\t\t!visited.has(value)\n\t) {\n\t\tvisited.add(value);\n\t\t// When working with a possible SvelteDate, this\n\t\t// will ensure we capture changes to it.\n\t\tif (value instanceof Date) {\n\t\t\tvalue.getTime();\n\t\t}\n\t\tfor (let key in value) {\n\t\t\ttry {\n\t\t\t\tdeep_read(value[key], visited);\n\t\t\t} catch (e) {\n\t\t\t\t// continue\n\t\t\t}\n\t\t}\n\t\tconst proto = get_prototype_of(value);\n\t\tif (\n\t\t\tproto !== Object.prototype &&\n\t\t\tproto !== Array.prototype &&\n\t\t\tproto !== Map.prototype &&\n\t\t\tproto !== Set.prototype &&\n\t\t\tproto !== Date.prototype\n\t\t) {\n\t\t\tconst descriptors = get_descriptors(proto);\n\t\t\tfor (let key in descriptors) {\n\t\t\t\tconst get = descriptors[key].get;\n\t\t\t\tif (get) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tget.call(value);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t// continue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n","import { async_mode_flag } from '../flags/index.js';\nimport { hydrating } from './dom/hydration.js';\nimport * as w from './warnings.js';\nimport * as e from './errors.js';\nimport { DEV } from 'esm-env';\n\n/**\n * @template T\n * @param {string} key\n * @param {() => T} fn\n * @returns {T}\n */\nexport function hydratable(key, fn) {\n\tif (!async_mode_flag) {\n\t\te.experimental_async_required('hydratable');\n\t}\n\n\tif (hydrating) {\n\t\tconst store = window.__svelte?.h;\n\n\t\tif (store?.has(key)) {\n\t\t\treturn /** @type {T} */ (store.get(key));\n\t\t}\n\n\t\tif (DEV) {\n\t\t\te.hydratable_missing_but_required(key);\n\t\t} else {\n\t\t\tw.hydratable_missing_but_expected(key);\n\t\t}\n\t}\n\n\treturn fn();\n}\n","import { teardown } from '../../reactivity/effects.js';\nimport { define_property } from '../../../shared/utils.js';\nimport { hydrating } from '../hydration.js';\nimport { queue_micro_task } from '../task.js';\nimport { FILENAME } from '../../../../constants.js';\nimport * as w from '../../warnings.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tset_active_effect,\n\tset_active_reaction\n} from '../../runtime.js';\nimport { without_reactive_context } from './bindings/shared.js';\n\n/**\n * Used on elements, as a map of event type -> event handler,\n * and on events themselves to track which element handled an event\n */\nexport const event_symbol = Symbol('events');\n\n/** @type {Set<string>} */\nexport const all_registered_events = new Set();\n\n/** @type {Set<(events: Array<string>) => void>} */\nexport const root_event_handles = new Set();\n\n/**\n * SSR adds onload and onerror attributes to catch those events before the hydration.\n * This function detects those cases, removes the attributes and replays the events.\n * @param {HTMLElement} dom\n */\nexport function replay_events(dom) {\n\tif (!hydrating) return;\n\n\tdom.removeAttribute('onload');\n\tdom.removeAttribute('onerror');\n\t// @ts-expect-error\n\tconst event = dom.__e;\n\tif (event !== undefined) {\n\t\t// @ts-expect-error\n\t\tdom.__e = undefined;\n\t\tqueueMicrotask(() => {\n\t\t\tif (dom.isConnected) {\n\t\t\t\tdom.dispatchEvent(event);\n\t\t\t}\n\t\t});\n\t}\n}\n\n/**\n * @param {string} event_name\n * @param {EventTarget} dom\n * @param {EventListener} [handler]\n * @param {AddEventListenerOptions} [options]\n */\nexport function create_event(event_name, dom, handler, options = {}) {\n\t/**\n\t * @this {EventTarget}\n\t */\n\tfunction target_handler(/** @type {Event} */ event) {\n\t\tif (!options.capture) {\n\t\t\t// Only call in the bubble phase, else delegated events would be called before the capturing events\n\t\t\thandle_event_propagation.call(dom, event);\n\t\t}\n\t\tif (!event.cancelBubble) {\n\t\t\treturn without_reactive_context(() => {\n\t\t\t\treturn handler?.call(this, event);\n\t\t\t});\n\t\t}\n\t}\n\n\t// Chrome has a bug where pointer events don't work when attached to a DOM element that has been cloned\n\t// with cloneNode() and the DOM element is disconnected from the document. To ensure the event works, we\n\t// defer the attachment till after it's been appended to the document. TODO: remove this once Chrome fixes\n\t// this bug. The same applies to wheel events and touch events.\n\tif (\n\t\tevent_name.startsWith('pointer') ||\n\t\tevent_name.startsWith('touch') ||\n\t\tevent_name === 'wheel'\n\t) {\n\t\tqueue_micro_task(() => {\n\t\t\tdom.addEventListener(event_name, target_handler, options);\n\t\t});\n\t} else {\n\t\tdom.addEventListener(event_name, target_handler, options);\n\t}\n\n\treturn target_handler;\n}\n\n/**\n * Attaches an event handler to an element and returns a function that removes the handler. Using this\n * rather than `addEventListener` will preserve the correct order relative to handlers added declaratively\n * (with attributes like `onclick`), which use event delegation for performance reasons\n *\n * @param {EventTarget} element\n * @param {string} type\n * @param {EventListener} handler\n * @param {AddEventListenerOptions} [options]\n */\nexport function on(element, type, handler, options = {}) {\n\tvar target_handler = create_event(type, element, handler, options);\n\n\treturn () => {\n\t\telement.removeEventListener(type, target_handler, options);\n\t};\n}\n\n/**\n * @param {string} event_name\n * @param {Element} dom\n * @param {EventListener} [handler]\n * @param {boolean} [capture]\n * @param {boolean} [passive]\n * @returns {void}\n */\nexport function event(event_name, dom, handler, capture, passive) {\n\tvar options = { capture, passive };\n\tvar target_handler = create_event(event_name, dom, handler, options);\n\n\tif (\n\t\tdom === document.body ||\n\t\t// @ts-ignore\n\t\tdom === window ||\n\t\t// @ts-ignore\n\t\tdom === document ||\n\t\t// Firefox has quirky behavior, it can happen that we still get \"canplay\" events when the element is already removed\n\t\tdom instanceof HTMLMediaElement\n\t) {\n\t\tteardown(() => {\n\t\t\tdom.removeEventListener(event_name, target_handler, options);\n\t\t});\n\t}\n}\n\n/**\n * @param {string} event_name\n * @param {Element} element\n * @param {EventListener} [handler]\n * @returns {void}\n */\nexport function delegated(event_name, element, handler) {\n\t// @ts-expect-error\n\t(element[event_symbol] ??= {})[event_name] = handler;\n}\n\n/**\n * @param {Array<string>} events\n * @returns {void}\n */\nexport function delegate(events) {\n\tfor (var i = 0; i < events.length; i++) {\n\t\tall_registered_events.add(events[i]);\n\t}\n\n\tfor (var fn of root_event_handles) {\n\t\tfn(events);\n\t}\n}\n\n// used to store the reference to the currently propagated event\n// to prevent garbage collection between microtasks in Firefox\n// If the event object is GCed too early, the expando __root property\n// set on the event object is lost, causing the event delegation\n// to process the event twice\nlet last_propagated_event = null;\n\n/**\n * @this {EventTarget}\n * @param {Event} event\n * @returns {void}\n */\nexport function handle_event_propagation(event) {\n\tvar handler_element = this;\n\tvar owner_document = /** @type {Node} */ (handler_element).ownerDocument;\n\tvar event_name = event.type;\n\tvar path = event.composedPath?.() || [];\n\tvar current_target = /** @type {null | Element} */ (path[0] || event.target);\n\n\tlast_propagated_event = event;\n\n\t// composedPath contains list of nodes the event has propagated through.\n\t// We check `event_symbol` to skip all nodes below it in case this is a\n\t// parent of the `event_symbol` node, which indicates that there's nested\n\t// mounted apps. In this case we don't want to trigger events multiple times.\n\tvar path_idx = 0;\n\n\t// the `last_propagated_event === event` check is redundant, but\n\t// without it the variable will be DCE'd and things will\n\t// fail mysteriously in Firefox\n\t// @ts-expect-error is added below\n\tvar handled_at = last_propagated_event === event && event[event_symbol];\n\n\tif (handled_at) {\n\t\tvar at_idx = path.indexOf(handled_at);\n\t\tif (\n\t\t\tat_idx !== -1 &&\n\t\t\t(handler_element === document || handler_element === /** @type {any} */ (window))\n\t\t) {\n\t\t\t// This is the fallback document listener or a window listener, but the event was already handled\n\t\t\t// -> ignore, but set handle_at to document/window so that we're resetting the event\n\t\t\t// chain in case someone manually dispatches the same event object again.\n\t\t\t// @ts-expect-error\n\t\t\tevent[event_symbol] = handler_element;\n\t\t\treturn;\n\t\t}\n\n\t\t// We're deliberately not skipping if the index is higher, because\n\t\t// someone could create an event programmatically and emit it multiple times,\n\t\t// in which case we want to handle the whole propagation chain properly each time.\n\t\t// (this will only be a false negative if the event is dispatched multiple times and\n\t\t// the fallback document listener isn't reached in between, but that's super rare)\n\t\tvar handler_idx = path.indexOf(handler_element);\n\t\tif (handler_idx === -1) {\n\t\t\t// handle_idx can theoretically be -1 (happened in some JSDOM testing scenarios with an event listener on the window object)\n\t\t\t// so guard against that, too, and assume that everything was handled at this point.\n\t\t\treturn;\n\t\t}\n\n\t\tif (at_idx <= handler_idx) {\n\t\t\tpath_idx = at_idx;\n\t\t}\n\t}\n\n\tcurrent_target = /** @type {Element} */ (path[path_idx] || event.target);\n\t// there can only be one delegated event per element, and we either already handled the current target,\n\t// or this is the very first target in the chain which has a non-delegated listener, in which case it's safe\n\t// to handle a possible delegated event on it later (through the root delegation listener for example).\n\tif (current_target === handler_element) return;\n\n\t// Proxy currentTarget to correct target\n\tdefine_property(event, 'currentTarget', {\n\t\tconfigurable: true,\n\t\tget() {\n\t\t\treturn current_target || owner_document;\n\t\t}\n\t});\n\n\t// This started because of Chromium issue https://chromestatus.com/feature/5128696823545856,\n\t// where removal or moving of of the DOM can cause sync `blur` events to fire, which can cause logic\n\t// to run inside the current `active_reaction`, which isn't what we want at all. However, on reflection,\n\t// it's probably best that all event handled by Svelte have this behaviour, as we don't really want\n\t// an event handler to run in the context of another reaction or effect.\n\tvar previous_reaction = active_reaction;\n\tvar previous_effect = active_effect;\n\tset_active_reaction(null);\n\tset_active_effect(null);\n\n\ttry {\n\t\t/**\n\t\t * @type {unknown}\n\t\t */\n\t\tvar throw_error;\n\t\t/**\n\t\t * @type {unknown[]}\n\t\t */\n\t\tvar other_errors = [];\n\n\t\twhile (current_target !== null) {\n\t\t\t/** @type {null | Element} */\n\t\t\tvar parent_element =\n\t\t\t\tcurrent_target.assignedSlot ||\n\t\t\t\tcurrent_target.parentNode ||\n\t\t\t\t/** @type {any} */ (current_target).host ||\n\t\t\t\tnull;\n\n\t\t\ttry {\n\t\t\t\t// @ts-expect-error\n\t\t\t\tvar delegated = current_target[event_symbol]?.[event_name];\n\n\t\t\t\tif (\n\t\t\t\t\tdelegated != null &&\n\t\t\t\t\t(!(/** @type {any} */ (current_target).disabled) ||\n\t\t\t\t\t\t// DOM could've been updated already by the time this is reached, so we check this as well\n\t\t\t\t\t\t// -> the target could not have been disabled because it emits the event in the first place\n\t\t\t\t\t\tevent.target === current_target)\n\t\t\t\t) {\n\t\t\t\t\tdelegated.call(current_target, event);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (throw_error) {\n\t\t\t\t\tother_errors.push(error);\n\t\t\t\t} else {\n\t\t\t\t\tthrow_error = error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (event.cancelBubble || parent_element === handler_element || parent_element === null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcurrent_target = parent_element;\n\t\t}\n\n\t\tif (throw_error) {\n\t\t\tfor (let error of other_errors) {\n\t\t\t\t// Throw the rest of the errors, one-by-one on a microtask\n\t\t\t\tqueueMicrotask(() => {\n\t\t\t\t\tthrow error;\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow throw_error;\n\t\t}\n\t} finally {\n\t\t// @ts-expect-error is used above\n\t\tevent[event_symbol] = handler_element;\n\t\t// @ts-ignore remove proxy on currentTarget\n\t\tdelete event.currentTarget;\n\t\tset_active_reaction(previous_reaction);\n\t\tset_active_effect(previous_effect);\n\t}\n}\n\n/**\n * In dev, warn if an event handler is not a function, as it means the\n * user probably called the handler or forgot to add a `() =>`\n * @param {() => (event: Event, ...args: any) => void} thunk\n * @param {EventTarget} element\n * @param {[Event, ...any]} args\n * @param {any} component\n * @param {[number, number]} [loc]\n * @param {boolean} [remove_parens]\n */\nexport function apply(\n\tthunk,\n\telement,\n\targs,\n\tcomponent,\n\tloc,\n\thas_side_effects = false,\n\tremove_parens = false\n) {\n\tlet handler;\n\tlet error;\n\n\ttry {\n\t\thandler = thunk();\n\t} catch (e) {\n\t\terror = e;\n\t}\n\n\tif (typeof handler !== 'function' && (has_side_effects || handler != null || error)) {\n\t\tconst filename = component?.[FILENAME];\n\t\tconst location = loc ? ` at ${filename}:${loc[0]}:${loc[1]}` : ` in ${filename}`;\n\t\tconst phase = args[0]?.eventPhase < Event.BUBBLING_PHASE ? 'capture' : '';\n\t\tconst event_name = args[0]?.type + phase;\n\t\tconst description = `\\`${event_name}\\` handler${location}`;\n\t\tconst suggestion = remove_parens ? 'remove the trailing `()`' : 'add a leading `() =>`';\n\n\t\tw.event_handler_invalid(description, suggestion);\n\n\t\tif (error) {\n\t\t\tthrow error;\n\t\t}\n\t}\n\thandler?.apply(element, args);\n}\n","import { create_element } from './operations.js';\n\nconst policy =\n\t// We gotta write it like this because after downleveling the pure comment may end up in the wrong location\n\tglobalThis?.window?.trustedTypes &&\n\t/* @__PURE__ */ globalThis.window.trustedTypes.createPolicy('svelte-trusted-html', {\n\t\t/** @param {string} html */\n\t\tcreateHTML: (html) => {\n\t\t\treturn html;\n\t\t}\n\t});\n\n/** @param {string} html */\nexport function create_trusted_html(html) {\n\treturn /** @type {string} */ (policy?.createHTML(html) ?? html);\n}\n\n/**\n * @param {string} html\n */\nexport function create_fragment_from_html(html) {\n\tvar elem = create_element('template');\n\telem.innerHTML = create_trusted_html(html.replaceAll('<!>', '<!---->')); // XHTML compliance\n\treturn elem.content;\n}\n","/** @import { Effect, EffectNodes, TemplateNode } from '#client' */\n/** @import { TemplateStructure } from './types' */\nimport { hydrate_next, hydrate_node, hydrating, set_hydrate_node } from './hydration.js';\nimport {\n\tcreate_text,\n\tget_first_child,\n\tget_next_sibling,\n\tis_firefox,\n\tcreate_element,\n\tcreate_fragment,\n\tcreate_comment,\n\tset_attribute,\n\tmerge_text_nodes\n} from './operations.js';\nimport { create_fragment_from_html } from './reconciler.js';\nimport { active_effect } from '../runtime.js';\nimport {\n\tNAMESPACE_MATHML,\n\tNAMESPACE_SVG,\n\tTEMPLATE_FRAGMENT,\n\tTEMPLATE_USE_IMPORT_NODE,\n\tTEMPLATE_USE_MATHML,\n\tTEMPLATE_USE_SVG\n} from '../../../constants.js';\nimport {\n\tCOMMENT_NODE,\n\tDOCUMENT_FRAGMENT_NODE,\n\tIS_XHTML,\n\tREACTION_RAN,\n\tTEXT_NODE\n} from '#client/constants';\n\nconst TEMPLATE_TAG = IS_XHTML ? 'template' : 'TEMPLATE';\nconst SCRIPT_TAG = IS_XHTML ? 'script' : 'SCRIPT';\n\n/**\n * @param {TemplateNode} start\n * @param {TemplateNode | null} end\n */\nexport function assign_nodes(start, end) {\n\tvar effect = /** @type {Effect} */ (active_effect);\n\tif (effect.nodes === null) {\n\t\teffect.nodes = { start, end, a: null, t: null };\n\t}\n}\n\n/**\n * @param {string} content\n * @param {number} flags\n * @returns {() => Node | Node[]}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function from_html(content, flags) {\n\tvar is_fragment = (flags & TEMPLATE_FRAGMENT) !== 0;\n\tvar use_import_node = (flags & TEMPLATE_USE_IMPORT_NODE) !== 0;\n\n\t/** @type {Node} */\n\tvar node;\n\n\t/**\n\t * Whether or not the first item is a text/element node. If not, we need to\n\t * create an additional comment node to act as `effect.nodes.start`\n\t */\n\tvar has_start = !content.startsWith('<!>');\n\n\treturn () => {\n\t\tif (hydrating) {\n\t\t\tassign_nodes(hydrate_node, null);\n\t\t\treturn hydrate_node;\n\t\t}\n\n\t\tif (node === undefined) {\n\t\t\tnode = create_fragment_from_html(has_start ? content : '<!>' + content);\n\t\t\tif (!is_fragment) node = /** @type {TemplateNode} */ (get_first_child(node));\n\t\t}\n\n\t\tvar clone = /** @type {TemplateNode} */ (\n\t\t\tuse_import_node || is_firefox ? document.importNode(node, true) : node.cloneNode(true)\n\t\t);\n\n\t\tif (is_fragment) {\n\t\t\tvar start = /** @type {TemplateNode} */ (get_first_child(clone));\n\t\t\tvar end = /** @type {TemplateNode} */ (clone.lastChild);\n\n\t\t\tassign_nodes(start, end);\n\t\t} else {\n\t\t\tassign_nodes(clone, clone);\n\t\t}\n\n\t\treturn clone;\n\t};\n}\n\n/**\n * @param {string} content\n * @param {number} flags\n * @param {'svg' | 'math'} ns\n * @returns {() => Node | Node[]}\n */\n/*#__NO_SIDE_EFFECTS__*/\nfunction from_namespace(content, flags, ns = 'svg') {\n\t/**\n\t * Whether or not the first item is a text/element node. If not, we need to\n\t * create an additional comment node to act as `effect.nodes.start`\n\t */\n\tvar has_start = !content.startsWith('<!>');\n\n\tvar is_fragment = (flags & TEMPLATE_FRAGMENT) !== 0;\n\tvar wrapped = `<${ns}>${has_start ? content : '<!>' + content}</${ns}>`;\n\n\t/** @type {Element | DocumentFragment} */\n\tvar node;\n\n\treturn () => {\n\t\tif (hydrating) {\n\t\t\tassign_nodes(hydrate_node, null);\n\t\t\treturn hydrate_node;\n\t\t}\n\n\t\tif (!node) {\n\t\t\tvar fragment = /** @type {DocumentFragment} */ (create_fragment_from_html(wrapped));\n\t\t\tvar root = /** @type {Element} */ (get_first_child(fragment));\n\n\t\t\tif (is_fragment) {\n\t\t\t\tnode = document.createDocumentFragment();\n\t\t\t\twhile (get_first_child(root)) {\n\t\t\t\t\tnode.appendChild(/** @type {TemplateNode} */ (get_first_child(root)));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnode = /** @type {Element} */ (get_first_child(root));\n\t\t\t}\n\t\t}\n\n\t\tvar clone = /** @type {TemplateNode} */ (node.cloneNode(true));\n\n\t\tif (is_fragment) {\n\t\t\tvar start = /** @type {TemplateNode} */ (get_first_child(clone));\n\t\t\tvar end = /** @type {TemplateNode} */ (clone.lastChild);\n\n\t\t\tassign_nodes(start, end);\n\t\t} else {\n\t\t\tassign_nodes(clone, clone);\n\t\t}\n\n\t\treturn clone;\n\t};\n}\n\n/**\n * @param {string} content\n * @param {number} flags\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function from_svg(content, flags) {\n\treturn from_namespace(content, flags, 'svg');\n}\n\n/**\n * @param {string} content\n * @param {number} flags\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function from_mathml(content, flags) {\n\treturn from_namespace(content, flags, 'math');\n}\n\n/**\n * @param {TemplateStructure[]} structure\n * @param {typeof NAMESPACE_SVG | typeof NAMESPACE_MATHML | undefined} [ns]\n */\nfunction fragment_from_tree(structure, ns) {\n\tvar fragment = create_fragment();\n\n\tfor (var item of structure) {\n\t\tif (typeof item === 'string') {\n\t\t\tfragment.append(create_text(item));\n\t\t\tcontinue;\n\t\t}\n\n\t\t// if `preserveComments === true`, comments are represented as `['// <data>']`\n\t\tif (item === undefined || item[0][0] === '/') {\n\t\t\tfragment.append(create_comment(item ? item[0].slice(3) : ''));\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst [name, attributes, ...children] = item;\n\n\t\tconst namespace = name === 'svg' ? NAMESPACE_SVG : name === 'math' ? NAMESPACE_MATHML : ns;\n\n\t\tvar element = create_element(name, namespace, attributes?.is);\n\n\t\tfor (var key in attributes) {\n\t\t\tset_attribute(element, key, attributes[key]);\n\t\t}\n\n\t\tif (children.length > 0) {\n\t\t\tvar target =\n\t\t\t\telement.nodeName === TEMPLATE_TAG\n\t\t\t\t\t? /** @type {HTMLTemplateElement} */ (element).content\n\t\t\t\t\t: element;\n\n\t\t\ttarget.append(\n\t\t\t\tfragment_from_tree(children, element.nodeName === 'foreignObject' ? undefined : namespace)\n\t\t\t);\n\t\t}\n\n\t\tfragment.append(element);\n\t}\n\n\treturn fragment;\n}\n\n/**\n * @param {TemplateStructure[]} structure\n * @param {number} flags\n * @returns {() => Node | Node[]}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function from_tree(structure, flags) {\n\tvar is_fragment = (flags & TEMPLATE_FRAGMENT) !== 0;\n\tvar use_import_node = (flags & TEMPLATE_USE_IMPORT_NODE) !== 0;\n\n\t/** @type {Node} */\n\tvar node;\n\n\treturn () => {\n\t\tif (hydrating) {\n\t\t\tassign_nodes(hydrate_node, null);\n\t\t\treturn hydrate_node;\n\t\t}\n\n\t\tif (node === undefined) {\n\t\t\tconst ns =\n\t\t\t\t(flags & TEMPLATE_USE_SVG) !== 0\n\t\t\t\t\t? NAMESPACE_SVG\n\t\t\t\t\t: (flags & TEMPLATE_USE_MATHML) !== 0\n\t\t\t\t\t\t? NAMESPACE_MATHML\n\t\t\t\t\t\t: undefined;\n\n\t\t\tnode = fragment_from_tree(structure, ns);\n\t\t\tif (!is_fragment) node = /** @type {TemplateNode} */ (get_first_child(node));\n\t\t}\n\n\t\tvar clone = /** @type {TemplateNode} */ (\n\t\t\tuse_import_node || is_firefox ? document.importNode(node, true) : node.cloneNode(true)\n\t\t);\n\n\t\tif (is_fragment) {\n\t\t\tvar start = /** @type {TemplateNode} */ (get_first_child(clone));\n\t\t\tvar end = /** @type {TemplateNode} */ (clone.lastChild);\n\n\t\t\tassign_nodes(start, end);\n\t\t} else {\n\t\t\tassign_nodes(clone, clone);\n\t\t}\n\n\t\treturn clone;\n\t};\n}\n\n/**\n * @param {() => Element | DocumentFragment} fn\n */\nexport function with_script(fn) {\n\treturn () => run_scripts(fn());\n}\n\n/**\n * Creating a document fragment from HTML that contains script tags will not execute\n * the scripts. We need to replace the script tags with new ones so that they are executed.\n * @param {Element | DocumentFragment} node\n * @returns {Node | Node[]}\n */\nfunction run_scripts(node) {\n\t// scripts were SSR'd, in which case they will run\n\tif (hydrating) return node;\n\n\tconst is_fragment = node.nodeType === DOCUMENT_FRAGMENT_NODE;\n\tconst scripts =\n\t\t/** @type {HTMLElement} */ (node).nodeName === SCRIPT_TAG\n\t\t\t? [/** @type {HTMLScriptElement} */ (node)]\n\t\t\t: node.querySelectorAll('script');\n\n\tconst effect = /** @type {Effect & { nodes: EffectNodes }} */ (active_effect);\n\n\tfor (const script of scripts) {\n\t\tconst clone = create_element('script');\n\t\tfor (var attribute of script.attributes) {\n\t\t\tclone.setAttribute(attribute.name, attribute.value);\n\t\t}\n\n\t\tclone.textContent = script.textContent;\n\n\t\t// The script has changed - if it's at the edges, the effect now points at dead nodes\n\t\tif (is_fragment ? node.firstChild === script : node === script) {\n\t\t\teffect.nodes.start = clone;\n\t\t}\n\t\tif (is_fragment ? node.lastChild === script : node === script) {\n\t\t\teffect.nodes.end = clone;\n\t\t}\n\n\t\tscript.replaceWith(clone);\n\t}\n\treturn node;\n}\n\n/**\n * Don't mark this as side-effect-free, hydration needs to walk all nodes\n * @param {any} value\n */\nexport function text(value = '') {\n\tif (!hydrating) {\n\t\tvar t = create_text(value + '');\n\t\tassign_nodes(t, t);\n\t\treturn t;\n\t}\n\n\tvar node = hydrate_node;\n\n\tif (node.nodeType !== TEXT_NODE) {\n\t\t// if an {expression} is empty during SSR, we need to insert an empty text node\n\t\tnode.before((node = create_text()));\n\t\tset_hydrate_node(node);\n\t} else {\n\t\tmerge_text_nodes(/** @type {Text} */ (node));\n\t}\n\n\tassign_nodes(node, node);\n\treturn node;\n}\n\n/**\n * @returns {TemplateNode | DocumentFragment}\n */\nexport function comment() {\n\t// we're not delegating to `template` here for performance reasons\n\tif (hydrating) {\n\t\tassign_nodes(hydrate_node, null);\n\t\treturn hydrate_node;\n\t}\n\n\tvar frag = document.createDocumentFragment();\n\tvar start = document.createComment('');\n\tvar anchor = create_text();\n\tfrag.append(start, anchor);\n\n\tassign_nodes(start, anchor);\n\n\treturn frag;\n}\n\n/**\n * Assign the created (or in hydration mode, traversed) dom elements to the current block\n * and insert the elements into the dom (in client mode).\n * @param {Text | Comment | Element} anchor\n * @param {DocumentFragment | Element} dom\n */\nexport function append(anchor, dom) {\n\tif (hydrating) {\n\t\tvar effect = /** @type {Effect & { nodes: EffectNodes }} */ (active_effect);\n\n\t\t// When hydrating and outer component and an inner component is async, i.e. blocked on a promise,\n\t\t// then by the time the inner resolves we have already advanced to the end of the hydrated nodes\n\t\t// of the parent component. Check for defined for that reason to avoid rewinding the parent's end marker.\n\t\tif ((effect.f & REACTION_RAN) === 0 || effect.nodes.end === null) {\n\t\t\teffect.nodes.end = hydrate_node;\n\t\t}\n\n\t\thydrate_next();\n\t\treturn;\n\t}\n\n\tif (anchor === null) {\n\t\t// edge case — void `<svelte:element>` with content\n\t\treturn;\n\t}\n\n\tanchor.before(/** @type {Node} */ (dom));\n}\n\n/**\n * Create (or hydrate) an unique UID for the component instance.\n */\nexport function props_id() {\n\tif (\n\t\thydrating &&\n\t\thydrate_node &&\n\t\thydrate_node.nodeType === COMMENT_NODE &&\n\t\thydrate_node.textContent?.startsWith(`$`)\n\t) {\n\t\tconst id = hydrate_node.textContent.substring(1);\n\t\thydrate_next();\n\t\treturn id;\n\t}\n\n\t// @ts-expect-error This way we ensure the id is unique even across Svelte runtimes\n\t(window.__svelte ??= {}).uid ??= 1;\n\n\t// @ts-expect-error\n\treturn `c${window.__svelte.uid++}`;\n}\n","const regex_return_characters = /\\r/g;\n\n/**\n * @param {string} str\n * @returns {string}\n */\nexport function hash(str) {\n\tstr = str.replace(regex_return_characters, '');\n\tlet hash = 5381;\n\tlet i = str.length;\n\n\twhile (i--) hash = ((hash << 5) - hash) ^ str.charCodeAt(i);\n\treturn (hash >>> 0).toString(36);\n}\n\nconst VOID_ELEMENT_NAMES = [\n\t'area',\n\t'base',\n\t'br',\n\t'col',\n\t'command',\n\t'embed',\n\t'hr',\n\t'img',\n\t'input',\n\t'keygen',\n\t'link',\n\t'meta',\n\t'param',\n\t'source',\n\t'track',\n\t'wbr'\n];\n\n/**\n * Returns `true` if `name` is of a void element\n * @param {string} name\n */\nexport function is_void(name) {\n\treturn VOID_ELEMENT_NAMES.includes(name) || name.toLowerCase() === '!doctype';\n}\n\nconst RESERVED_WORDS = [\n\t'arguments',\n\t'await',\n\t'break',\n\t'case',\n\t'catch',\n\t'class',\n\t'const',\n\t'continue',\n\t'debugger',\n\t'default',\n\t'delete',\n\t'do',\n\t'else',\n\t'enum',\n\t'eval',\n\t'export',\n\t'extends',\n\t'false',\n\t'finally',\n\t'for',\n\t'function',\n\t'if',\n\t'implements',\n\t'import',\n\t'in',\n\t'instanceof',\n\t'interface',\n\t'let',\n\t'new',\n\t'null',\n\t'package',\n\t'private',\n\t'protected',\n\t'public',\n\t'return',\n\t'static',\n\t'super',\n\t'switch',\n\t'this',\n\t'throw',\n\t'true',\n\t'try',\n\t'typeof',\n\t'var',\n\t'void',\n\t'while',\n\t'with',\n\t'yield'\n];\n\n/**\n * Returns `true` if `word` is a reserved JavaScript keyword\n * @param {string} word\n */\nexport function is_reserved(word) {\n\treturn RESERVED_WORDS.includes(word);\n}\n\n/**\n * @param {string} name\n */\nexport function is_capture_event(name) {\n\treturn name.endsWith('capture') && name !== 'gotpointercapture' && name !== 'lostpointercapture';\n}\n\n/** List of Element events that will be delegated */\nconst DELEGATED_EVENTS = [\n\t'beforeinput',\n\t'click',\n\t'change',\n\t'dblclick',\n\t'contextmenu',\n\t'focusin',\n\t'focusout',\n\t'input',\n\t'keydown',\n\t'keyup',\n\t'mousedown',\n\t'mousemove',\n\t'mouseout',\n\t'mouseover',\n\t'mouseup',\n\t'pointerdown',\n\t'pointermove',\n\t'pointerout',\n\t'pointerover',\n\t'pointerup',\n\t'touchend',\n\t'touchmove',\n\t'touchstart'\n];\n\n/**\n * Returns `true` if `event_name` is a delegated event\n * @param {string} event_name\n */\nexport function can_delegate_event(event_name) {\n\treturn DELEGATED_EVENTS.includes(event_name);\n}\n\n/**\n * Attributes that are boolean, i.e. they are present or not present.\n */\nconst DOM_BOOLEAN_ATTRIBUTES = [\n\t'allowfullscreen',\n\t'async',\n\t'autofocus',\n\t'autoplay',\n\t'checked',\n\t'controls',\n\t'default',\n\t'disabled',\n\t'formnovalidate',\n\t'indeterminate',\n\t'inert',\n\t'ismap',\n\t'loop',\n\t'multiple',\n\t'muted',\n\t'nomodule',\n\t'novalidate',\n\t'open',\n\t'playsinline',\n\t'readonly',\n\t'required',\n\t'reversed',\n\t'seamless',\n\t'selected',\n\t'webkitdirectory',\n\t'defer',\n\t'disablepictureinpicture',\n\t'disableremoteplayback'\n];\n\n/**\n * Returns `true` if `name` is a boolean attribute\n * @param {string} name\n */\nexport function is_boolean_attribute(name) {\n\treturn DOM_BOOLEAN_ATTRIBUTES.includes(name);\n}\n\n/**\n * @type {Record<string, string>}\n * List of attribute names that should be aliased to their property names\n * because they behave differently between setting them as an attribute and\n * setting them as a property.\n */\nconst ATTRIBUTE_ALIASES = {\n\t// no `class: 'className'` because we handle that separately\n\tformnovalidate: 'formNoValidate',\n\tismap: 'isMap',\n\tnomodule: 'noModule',\n\tplaysinline: 'playsInline',\n\treadonly: 'readOnly',\n\tdefaultvalue: 'defaultValue',\n\tdefaultchecked: 'defaultChecked',\n\tsrcobject: 'srcObject',\n\tnovalidate: 'noValidate',\n\tallowfullscreen: 'allowFullscreen',\n\tdisablepictureinpicture: 'disablePictureInPicture',\n\tdisableremoteplayback: 'disableRemotePlayback'\n};\n\n/**\n * @param {string} name\n */\nexport function normalize_attribute(name) {\n\tname = name.toLowerCase();\n\treturn ATTRIBUTE_ALIASES[name] ?? name;\n}\n\nconst DOM_PROPERTIES = [\n\t...DOM_BOOLEAN_ATTRIBUTES,\n\t'formNoValidate',\n\t'isMap',\n\t'noModule',\n\t'playsInline',\n\t'readOnly',\n\t'value',\n\t'volume',\n\t'defaultValue',\n\t'defaultChecked',\n\t'srcObject',\n\t'noValidate',\n\t'allowFullscreen',\n\t'disablePictureInPicture',\n\t'disableRemotePlayback'\n];\n\n/**\n * @param {string} name\n */\nexport function is_dom_property(name) {\n\treturn DOM_PROPERTIES.includes(name);\n}\n\nconst NON_STATIC_PROPERTIES = ['autofocus', 'muted', 'defaultValue', 'defaultChecked'];\n\n/**\n * Returns `true` if the given attribute cannot be set through the template\n * string, i.e. needs some kind of JavaScript handling to work.\n * @param {string} name\n */\nexport function cannot_be_set_statically(name) {\n\treturn NON_STATIC_PROPERTIES.includes(name);\n}\n\n/**\n * Subset of delegated events which should be passive by default.\n * These two are already passive via browser defaults on window, document and body.\n * But since\n * - we're delegating them\n * - they happen often\n * - they apply to mobile which is generally less performant\n * we're marking them as passive by default for other elements, too.\n */\nconst PASSIVE_EVENTS = ['touchstart', 'touchmove'];\n\n/**\n * Returns `true` if `name` is a passive event\n * @param {string} name\n */\nexport function is_passive_event(name) {\n\treturn PASSIVE_EVENTS.includes(name);\n}\n\nconst CONTENT_EDITABLE_BINDINGS = ['textContent', 'innerHTML', 'innerText'];\n\n/** @param {string} name */\nexport function is_content_editable_binding(name) {\n\treturn CONTENT_EDITABLE_BINDINGS.includes(name);\n}\n\nconst LOAD_ERROR_ELEMENTS = [\n\t'body',\n\t'embed',\n\t'iframe',\n\t'img',\n\t'link',\n\t'object',\n\t'script',\n\t'style',\n\t'track'\n];\n\n/**\n * Returns `true` if the element emits `load` and `error` events\n * @param {string} name\n */\nexport function is_load_error_element(name) {\n\treturn LOAD_ERROR_ELEMENTS.includes(name);\n}\n\nconst SVG_ELEMENTS = [\n\t'altGlyph',\n\t'altGlyphDef',\n\t'altGlyphItem',\n\t'animate',\n\t'animateColor',\n\t'animateMotion',\n\t'animateTransform',\n\t'circle',\n\t'clipPath',\n\t'color-profile',\n\t'cursor',\n\t'defs',\n\t'desc',\n\t'discard',\n\t'ellipse',\n\t'feBlend',\n\t'feColorMatrix',\n\t'feComponentTransfer',\n\t'feComposite',\n\t'feConvolveMatrix',\n\t'feDiffuseLighting',\n\t'feDisplacementMap',\n\t'feDistantLight',\n\t'feDropShadow',\n\t'feFlood',\n\t'feFuncA',\n\t'feFuncB',\n\t'feFuncG',\n\t'feFuncR',\n\t'feGaussianBlur',\n\t'feImage',\n\t'feMerge',\n\t'feMergeNode',\n\t'feMorphology',\n\t'feOffset',\n\t'fePointLight',\n\t'feSpecularLighting',\n\t'feSpotLight',\n\t'feTile',\n\t'feTurbulence',\n\t'filter',\n\t'font',\n\t'font-face',\n\t'font-face-format',\n\t'font-face-name',\n\t'font-face-src',\n\t'font-face-uri',\n\t'foreignObject',\n\t'g',\n\t'glyph',\n\t'glyphRef',\n\t'hatch',\n\t'hatchpath',\n\t'hkern',\n\t'image',\n\t'line',\n\t'linearGradient',\n\t'marker',\n\t'mask',\n\t'mesh',\n\t'meshgradient',\n\t'meshpatch',\n\t'meshrow',\n\t'metadata',\n\t'missing-glyph',\n\t'mpath',\n\t'path',\n\t'pattern',\n\t'polygon',\n\t'polyline',\n\t'radialGradient',\n\t'rect',\n\t'set',\n\t'solidcolor',\n\t'stop',\n\t'svg',\n\t'switch',\n\t'symbol',\n\t'text',\n\t'textPath',\n\t'tref',\n\t'tspan',\n\t'unknown',\n\t'use',\n\t'view',\n\t'vkern'\n];\n\n/** @param {string} name */\nexport function is_svg(name) {\n\treturn SVG_ELEMENTS.includes(name);\n}\n\nconst MATHML_ELEMENTS = [\n\t'annotation',\n\t'annotation-xml',\n\t'maction',\n\t'math',\n\t'merror',\n\t'mfrac',\n\t'mi',\n\t'mmultiscripts',\n\t'mn',\n\t'mo',\n\t'mover',\n\t'mpadded',\n\t'mphantom',\n\t'mprescripts',\n\t'mroot',\n\t'mrow',\n\t'ms',\n\t'mspace',\n\t'msqrt',\n\t'mstyle',\n\t'msub',\n\t'msubsup',\n\t'msup',\n\t'mtable',\n\t'mtd',\n\t'mtext',\n\t'mtr',\n\t'munder',\n\t'munderover',\n\t'semantics'\n];\n\n/** @param {string} name */\nexport function is_mathml(name) {\n\treturn MATHML_ELEMENTS.includes(name);\n}\n\nconst STATE_CREATION_RUNES = /** @type {const} */ ([\n\t'$state',\n\t'$state.raw',\n\t'$derived',\n\t'$derived.by'\n]);\n\nconst RUNES = /** @type {const} */ ([\n\t...STATE_CREATION_RUNES,\n\t'$state.eager',\n\t'$state.snapshot',\n\t'$props',\n\t'$props.id',\n\t'$bindable',\n\t'$effect',\n\t'$effect.pre',\n\t'$effect.tracking',\n\t'$effect.root',\n\t'$effect.pending',\n\t'$inspect',\n\t'$inspect().with',\n\t'$inspect.trace',\n\t'$host'\n]);\n\n/** @typedef {typeof RUNES[number]} RuneName */\n\n/**\n * @param {string} name\n * @returns {name is RuneName}\n */\nexport function is_rune(name) {\n\treturn RUNES.includes(/** @type {RuneName} */ (name));\n}\n\n/** @typedef {typeof STATE_CREATION_RUNES[number]} StateCreationRuneName */\n\n/**\n * @param {string} name\n * @returns {name is StateCreationRuneName}\n */\nexport function is_state_creation_rune(name) {\n\treturn STATE_CREATION_RUNES.includes(/** @type {StateCreationRuneName} */ (name));\n}\n\n/** List of elements that require raw contents and should not have SSR comments put in them */\nconst RAW_TEXT_ELEMENTS = /** @type {const} */ (['textarea', 'script', 'style', 'title']);\n\n/** @param {string} name */\nexport function is_raw_text_element(name) {\n\treturn RAW_TEXT_ELEMENTS.includes(/** @type {typeof RAW_TEXT_ELEMENTS[number]} */ (name));\n}\n\n// Matches valid HTML/SVG/MathML element names and custom element names.\n// https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name\n//\n// Standard elements: ASCII alpha start, followed by ASCII alphanumerics.\n// Custom elements: ASCII alpha start, followed by any mix of PCENChar (which\n// includes ASCII alphanumerics, `-`, `.`, `_`, and specified Unicode ranges),\n// with at least one hyphen required somewhere after the first character.\n//\n// Rejects strings containing whitespace, quotes, angle brackets, slashes, equals,\n// or other characters that could break out of a tag-name token and enable markup injection.\nexport const REGEX_VALID_TAG_NAME =\n\t/^[a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9.\\-_\\u00B7\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u203F-\\u2040\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u{10000}-\\u{EFFFF}]+)*$/u;\n\n/**\n * Prevent devtools trying to make `location` a clickable link by inserting a zero-width space\n * @template {string | undefined} T\n * @param {T} location\n * @returns {T};\n */\nexport function sanitize_location(location) {\n\treturn /** @type {T} */ (location?.replace(/\\//g, '/\\u200b'));\n}\n","/** @import { ComponentContext, Effect, EffectNodes, TemplateNode } from '#client' */\n/** @import { Component, ComponentType, SvelteComponent, MountOptions } from '../../index.js' */\nimport { DEV } from 'esm-env';\nimport {\n\tclear_text_content,\n\tcreate_text,\n\tget_first_child,\n\tget_next_sibling,\n\tinit_operations\n} from './dom/operations.js';\nimport { HYDRATION_END, HYDRATION_ERROR, HYDRATION_START } from '../../constants.js';\nimport { active_effect } from './runtime.js';\nimport { push, pop, component_context } from './context.js';\nimport { component_root } from './reactivity/effects.js';\nimport { hydrate_node, hydrating, set_hydrate_node, set_hydrating } from './dom/hydration.js';\nimport { array_from } from '../shared/utils.js';\nimport {\n\tall_registered_events,\n\thandle_event_propagation,\n\troot_event_handles\n} from './dom/elements/events.js';\nimport * as w from './warnings.js';\nimport * as e from './errors.js';\nimport { assign_nodes } from './dom/template.js';\nimport { is_passive_event } from '../../utils.js';\nimport { COMMENT_NODE, STATE_SYMBOL } from './constants.js';\nimport { boundary } from './dom/blocks/boundary.js';\n\n/**\n * This is normally true — block effects should run their intro transitions —\n * but is false during hydration (unless `options.intro` is `true`) and\n * when creating the children of a `<svelte:element>` that just changed tag\n */\nexport let should_intro = true;\n\n/** @param {boolean} value */\nexport function set_should_intro(value) {\n\tshould_intro = value;\n}\n\n/**\n * @param {Element} text\n * @param {string} value\n * @returns {void}\n */\nexport function set_text(text, value) {\n\t// For objects, we apply string coercion (which might make things like $state array references in the template reactive) before diffing\n\tvar str = value == null ? '' : typeof value === 'object' ? `${value}` : value;\n\t// @ts-expect-error\n\tif (str !== (text.__t ??= text.nodeValue)) {\n\t\t// @ts-expect-error\n\t\ttext.__t = str;\n\t\ttext.nodeValue = `${str}`;\n\t}\n}\n\n/**\n * Mounts a component to the given target and returns the exports and potentially the props (if compiled with `accessors: true`) of the component.\n * Transitions will play during the initial render unless the `intro` option is set to `false`.\n *\n * @template {Record<string, any>} Props\n * @template {Record<string, any>} Exports\n * @param {ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>} component\n * @param {MountOptions<Props>} options\n * @returns {Exports}\n */\nexport function mount(component, options) {\n\treturn _mount(component, options);\n}\n\n/**\n * Hydrates a component on the given target and returns the exports and potentially the props (if compiled with `accessors: true`) of the component\n *\n * @template {Record<string, any>} Props\n * @template {Record<string, any>} Exports\n * @param {ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>} component\n * @param {{} extends Props ? {\n * \t\ttarget: Document | Element | ShadowRoot;\n * \t\tprops?: Props;\n * \t\tevents?: Record<string, (e: any) => any>;\n * \tcontext?: Map<any, any>;\n * \t\tintro?: boolean;\n * \t\trecover?: boolean;\n *\t\ttransformError?: (error: unknown) => unknown;\n * \t} : {\n * \t\ttarget: Document | Element | ShadowRoot;\n * \t\tprops: Props;\n * \t\tevents?: Record<string, (e: any) => any>;\n * \tcontext?: Map<any, any>;\n * \t\tintro?: boolean;\n * \t\trecover?: boolean;\n *\t\ttransformError?: (error: unknown) => unknown;\n * \t}} options\n * @returns {Exports}\n */\nexport function hydrate(component, options) {\n\tinit_operations();\n\toptions.intro = options.intro ?? false;\n\tconst target = options.target;\n\tconst was_hydrating = hydrating;\n\tconst previous_hydrate_node = hydrate_node;\n\n\ttry {\n\t\tvar anchor = get_first_child(target);\n\n\t\twhile (\n\t\t\tanchor &&\n\t\t\t(anchor.nodeType !== COMMENT_NODE || /** @type {Comment} */ (anchor).data !== HYDRATION_START)\n\t\t) {\n\t\t\tanchor = get_next_sibling(anchor);\n\t\t}\n\n\t\tif (!anchor) {\n\t\t\tthrow HYDRATION_ERROR;\n\t\t}\n\n\t\tset_hydrating(true);\n\t\tset_hydrate_node(/** @type {Comment} */ (anchor));\n\n\t\tconst instance = _mount(component, { ...options, anchor });\n\n\t\tset_hydrating(false);\n\n\t\treturn /** @type {Exports} */ (instance);\n\t} catch (error) {\n\t\t// re-throw Svelte errors - they are certainly not related to hydration\n\t\tif (\n\t\t\terror instanceof Error &&\n\t\t\terror.message.split('\\n').some((line) => line.startsWith('https://svelte.dev/e/'))\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\t\tif (error !== HYDRATION_ERROR) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.warn('Failed to hydrate: ', error);\n\t\t}\n\n\t\tif (options.recover === false) {\n\t\t\te.hydration_failed();\n\t\t}\n\n\t\t// If an error occurred above, the operations might not yet have been initialised.\n\t\tinit_operations();\n\t\tclear_text_content(target);\n\n\t\tset_hydrating(false);\n\t\treturn mount(component, options);\n\t} finally {\n\t\tset_hydrating(was_hydrating);\n\t\tset_hydrate_node(previous_hydrate_node);\n\t}\n}\n\n/** @type {Map<EventTarget, Map<string, number>>} */\nconst listeners = new Map();\n\n/**\n * @template {Record<string, any>} Exports\n * @param {ComponentType<SvelteComponent<any>> | Component<any>} Component\n * @param {MountOptions} options\n * @returns {Exports}\n */\nfunction _mount(\n\tComponent,\n\t{ target, anchor, props = {}, events, context, intro = true, transformError }\n) {\n\tinit_operations();\n\n\t/** @type {Exports} */\n\t// @ts-expect-error will be defined because the render effect runs synchronously\n\tvar component = undefined;\n\n\tvar unmount = component_root(() => {\n\t\tvar anchor_node = anchor ?? target.appendChild(create_text());\n\n\t\tboundary(\n\t\t\t/** @type {TemplateNode} */ (anchor_node),\n\t\t\t{\n\t\t\t\tpending: () => {}\n\t\t\t},\n\t\t\t(anchor_node) => {\n\t\t\t\tpush({});\n\t\t\t\tvar ctx = /** @type {ComponentContext} */ (component_context);\n\t\t\t\tif (context) ctx.c = context;\n\n\t\t\t\tif (events) {\n\t\t\t\t\t// We can't spread the object or else we'd lose the state proxy stuff, if it is one\n\t\t\t\t\t/** @type {any} */ (props).$$events = events;\n\t\t\t\t}\n\n\t\t\t\tif (hydrating) {\n\t\t\t\t\tassign_nodes(/** @type {TemplateNode} */ (anchor_node), null);\n\t\t\t\t}\n\n\t\t\t\tshould_intro = intro;\n\t\t\t\t// @ts-expect-error the public typings are not what the actual function looks like\n\t\t\t\tcomponent = Component(anchor_node, props) || {};\n\t\t\t\tshould_intro = true;\n\n\t\t\t\tif (hydrating) {\n\t\t\t\t\t/** @type {Effect & { nodes: EffectNodes }} */ (active_effect).nodes.end = hydrate_node;\n\n\t\t\t\t\tif (\n\t\t\t\t\t\thydrate_node === null ||\n\t\t\t\t\t\thydrate_node.nodeType !== COMMENT_NODE ||\n\t\t\t\t\t\t/** @type {Comment} */ (hydrate_node).data !== HYDRATION_END\n\t\t\t\t\t) {\n\t\t\t\t\t\tw.hydration_mismatch();\n\t\t\t\t\t\tthrow HYDRATION_ERROR;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tpop();\n\t\t\t},\n\t\t\ttransformError\n\t\t);\n\n\t\t// Setup event delegation _after_ component is mounted - if an error would happen during mount, it would otherwise not be cleaned up\n\t\t/** @type {Set<string>} */\n\t\tvar registered_events = new Set();\n\n\t\t/** @param {Array<string>} events */\n\t\tvar event_handle = (events) => {\n\t\t\tfor (var i = 0; i < events.length; i++) {\n\t\t\t\tvar event_name = events[i];\n\n\t\t\t\tif (registered_events.has(event_name)) continue;\n\t\t\t\tregistered_events.add(event_name);\n\n\t\t\t\tvar passive = is_passive_event(event_name);\n\n\t\t\t\t// Add the event listener to both the container and the document.\n\t\t\t\t// The container listener ensures we catch events from within in case\n\t\t\t\t// the outer content stops propagation of the event.\n\t\t\t\t//\n\t\t\t\t// The document listener ensures we catch events that originate from elements that were\n\t\t\t\t// manually moved outside of the container (e.g. via manual portals).\n\t\t\t\tfor (const node of [target, document]) {\n\t\t\t\t\tvar counts = listeners.get(node);\n\n\t\t\t\t\tif (counts === undefined) {\n\t\t\t\t\t\tcounts = new Map();\n\t\t\t\t\t\tlisteners.set(node, counts);\n\t\t\t\t\t}\n\n\t\t\t\t\tvar count = counts.get(event_name);\n\n\t\t\t\t\tif (count === undefined) {\n\t\t\t\t\t\tnode.addEventListener(event_name, handle_event_propagation, { passive });\n\t\t\t\t\t\tcounts.set(event_name, 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcounts.set(event_name, count + 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tevent_handle(array_from(all_registered_events));\n\t\troot_event_handles.add(event_handle);\n\n\t\treturn () => {\n\t\t\tfor (var event_name of registered_events) {\n\t\t\t\tfor (const node of [target, document]) {\n\t\t\t\t\tvar counts = /** @type {Map<string, number>} */ (listeners.get(node));\n\t\t\t\t\tvar count = /** @type {number} */ (counts.get(event_name));\n\n\t\t\t\t\tif (--count == 0) {\n\t\t\t\t\t\tnode.removeEventListener(event_name, handle_event_propagation);\n\t\t\t\t\t\tcounts.delete(event_name);\n\n\t\t\t\t\t\tif (counts.size === 0) {\n\t\t\t\t\t\t\tlisteners.delete(node);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcounts.set(event_name, count);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\troot_event_handles.delete(event_handle);\n\n\t\t\tif (anchor_node !== anchor) {\n\t\t\t\tanchor_node.parentNode?.removeChild(anchor_node);\n\t\t\t}\n\t\t};\n\t});\n\n\tmounted_components.set(component, unmount);\n\treturn component;\n}\n\n/**\n * References of the components that were mounted or hydrated.\n * Uses a `WeakMap` to avoid memory leaks.\n */\nlet mounted_components = new WeakMap();\n\n/**\n * Unmounts a component that was previously mounted using `mount` or `hydrate`.\n *\n * Since 5.13.0, if `options.outro` is `true`, [transitions](https://svelte.dev/docs/svelte/transition) will play before the component is removed from the DOM.\n *\n * Returns a `Promise` that resolves after transitions have completed if `options.outro` is true, or immediately otherwise (prior to 5.13.0, returns `void`).\n *\n * ```js\n * import { mount, unmount } from 'svelte';\n * import App from './App.svelte';\n *\n * const app = mount(App, { target: document.body });\n *\n * // later...\n * unmount(app, { outro: true });\n * ```\n * @param {Record<string, any>} component\n * @param {{ outro?: boolean }} [options]\n * @returns {Promise<void>}\n */\nexport function unmount(component, options) {\n\tconst fn = mounted_components.get(component);\n\n\tif (fn) {\n\t\tmounted_components.delete(component);\n\t\treturn fn(options);\n\t}\n\n\tif (DEV) {\n\t\tif (STATE_SYMBOL in component) {\n\t\t\tw.state_proxy_unmount();\n\t\t} else {\n\t\t\tw.lifecycle_double_unmount();\n\t\t}\n\t}\n\n\treturn Promise.resolve();\n}\n","import { is_void } from '../../utils.js';\nimport * as w from './warnings.js';\nimport * as e from './errors.js';\n\nexport { invalid_default_snippet } from './errors.js';\n\n/**\n * @param {() => string} tag_fn\n * @returns {void}\n */\nexport function validate_void_dynamic_element(tag_fn) {\n\tconst tag = tag_fn();\n\tif (tag && is_void(tag)) {\n\t\tw.dynamic_void_element_content(tag);\n\t}\n}\n\n/** @param {() => unknown} tag_fn */\nexport function validate_dynamic_element_tag(tag_fn) {\n\tconst tag = tag_fn();\n\tconst is_string = typeof tag === 'string';\n\tif (tag && !is_string) {\n\t\te.svelte_element_invalid_this_value();\n\t}\n}\n\n/**\n * @param {any} store\n * @param {string} name\n */\nexport function validate_store(store, name) {\n\tif (store != null && typeof store.subscribe !== 'function') {\n\t\te.store_invalid_shape(name);\n\t}\n}\n\n/**\n * @template {(...args: any[]) => unknown} T\n * @param {T} fn\n */\nexport function prevent_snippet_stringification(fn) {\n\tfn.toString = () => {\n\t\te.snippet_without_render_tag();\n\t\treturn '';\n\t};\n\treturn fn;\n}\n","/** @import { Effect, TemplateNode } from '#client' */\nimport { Batch, current_batch } from '../../reactivity/batch.js';\nimport {\n\tbranch,\n\tdestroy_effect,\n\tmove_effect,\n\tpause_effect,\n\tresume_effect\n} from '../../reactivity/effects.js';\nimport { HMR_ANCHOR } from '../../constants.js';\nimport { hydrate_node, hydrating } from '../hydration.js';\nimport { create_text, should_defer_append } from '../operations.js';\nimport { DEV } from 'esm-env';\n\n/**\n * @typedef {{ effect: Effect, fragment: DocumentFragment }} Branch\n */\n\n/**\n * @template Key\n */\nexport class BranchManager {\n\t/** @type {TemplateNode} */\n\tanchor;\n\n\t/** @type {Map<Batch, Key>} */\n\t#batches = new Map();\n\n\t/**\n\t * Map of keys to effects that are currently rendered in the DOM.\n\t * These effects are visible and actively part of the document tree.\n\t * Example:\n\t * ```\n\t * {#if condition}\n\t * \tfoo\n\t * {:else}\n\t * \tbar\n\t * {/if}\n\t * ```\n\t * Can result in the entries `true->Effect` and `false->Effect`\n\t * @type {Map<Key, Effect>}\n\t */\n\t#onscreen = new Map();\n\n\t/**\n\t * Similar to #onscreen with respect to the keys, but contains branches that are not yet\n\t * in the DOM, because their insertion is deferred.\n\t * @type {Map<Key, Branch>}\n\t */\n\t#offscreen = new Map();\n\n\t/**\n\t * Keys of effects that are currently outroing\n\t * @type {Set<Key>}\n\t */\n\t#outroing = new Set();\n\n\t/**\n\t * Whether to pause (i.e. outro) on change, or destroy immediately.\n\t * This is necessary for `<svelte:element>`\n\t */\n\t#transition = true;\n\n\t/**\n\t * @param {TemplateNode} anchor\n\t * @param {boolean} transition\n\t */\n\tconstructor(anchor, transition = true) {\n\t\tthis.anchor = anchor;\n\t\tthis.#transition = transition;\n\t}\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\t#commit = (batch) => {\n\t\t// if this batch was made obsolete, bail\n\t\tif (!this.#batches.has(batch)) return;\n\n\t\tvar key = /** @type {Key} */ (this.#batches.get(batch));\n\n\t\tvar onscreen = this.#onscreen.get(key);\n\n\t\tif (onscreen) {\n\t\t\t// effect is already in the DOM — abort any current outro\n\t\t\tresume_effect(onscreen);\n\t\t\tthis.#outroing.delete(key);\n\t\t} else {\n\t\t\t// effect is currently offscreen. put it in the DOM\n\t\t\tvar offscreen = this.#offscreen.get(key);\n\n\t\t\tif (offscreen) {\n\t\t\t\tthis.#onscreen.set(key, offscreen.effect);\n\t\t\t\tthis.#offscreen.delete(key);\n\n\t\t\t\tif (DEV) {\n\t\t\t\t\t// Tell hmr.js about the anchor it should use for updates,\n\t\t\t\t\t// since the initial one will be removed\n\t\t\t\t\t/** @type {any} */ (offscreen.fragment.lastChild)[HMR_ANCHOR] = this.anchor;\n\t\t\t\t}\n\n\t\t\t\t// remove the anchor...\n\t\t\t\t/** @type {TemplateNode} */ (offscreen.fragment.lastChild).remove();\n\n\t\t\t\t// ...and append the fragment\n\t\t\t\tthis.anchor.before(offscreen.fragment);\n\t\t\t\tonscreen = offscreen.effect;\n\t\t\t}\n\t\t}\n\n\t\tfor (const [b, k] of this.#batches) {\n\t\t\tthis.#batches.delete(b);\n\n\t\t\tif (b === batch) {\n\t\t\t\t// keep values for newer batches\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst offscreen = this.#offscreen.get(k);\n\n\t\t\tif (offscreen) {\n\t\t\t\t// for older batches, destroy offscreen effects\n\t\t\t\t// as they will never be committed\n\t\t\t\tdestroy_effect(offscreen.effect);\n\t\t\t\tthis.#offscreen.delete(k);\n\t\t\t}\n\t\t}\n\n\t\t// outro/destroy all onscreen effects...\n\t\tfor (const [k, effect] of this.#onscreen) {\n\t\t\t// ...except the one that was just committed\n\t\t\t// or those that are already outroing (else the transition is aborted and the effect destroyed right away)\n\t\t\tif (k === key || this.#outroing.has(k)) continue;\n\n\t\t\tconst on_destroy = () => {\n\t\t\t\tconst keys = Array.from(this.#batches.values());\n\n\t\t\t\tif (keys.includes(k)) {\n\t\t\t\t\t// keep the effect offscreen, as another batch will need it\n\t\t\t\t\tvar fragment = document.createDocumentFragment();\n\t\t\t\t\tmove_effect(effect, fragment);\n\n\t\t\t\t\tfragment.append(create_text()); // TODO can we avoid this?\n\n\t\t\t\t\tthis.#offscreen.set(k, { effect, fragment });\n\t\t\t\t} else {\n\t\t\t\t\tdestroy_effect(effect);\n\t\t\t\t}\n\n\t\t\t\tthis.#outroing.delete(k);\n\t\t\t\tthis.#onscreen.delete(k);\n\t\t\t};\n\n\t\t\tif (this.#transition || !onscreen) {\n\t\t\t\tthis.#outroing.add(k);\n\t\t\t\tpause_effect(effect, on_destroy, false);\n\t\t\t} else {\n\t\t\t\ton_destroy();\n\t\t\t}\n\t\t}\n\t};\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\t#discard = (batch) => {\n\t\tthis.#batches.delete(batch);\n\n\t\tconst keys = Array.from(this.#batches.values());\n\n\t\tfor (const [k, branch] of this.#offscreen) {\n\t\t\tif (!keys.includes(k)) {\n\t\t\t\tdestroy_effect(branch.effect);\n\t\t\t\tthis.#offscreen.delete(k);\n\t\t\t}\n\t\t}\n\t};\n\n\t/**\n\t *\n\t * @param {any} key\n\t * @param {null | ((target: TemplateNode) => void)} fn\n\t */\n\tensure(key, fn) {\n\t\tvar batch = /** @type {Batch} */ (current_batch);\n\t\tvar defer = should_defer_append();\n\n\t\tif (fn && !this.#onscreen.has(key) && !this.#offscreen.has(key)) {\n\t\t\tif (defer) {\n\t\t\t\tvar fragment = document.createDocumentFragment();\n\t\t\t\tvar target = create_text();\n\n\t\t\t\tfragment.append(target);\n\n\t\t\t\tthis.#offscreen.set(key, {\n\t\t\t\t\teffect: branch(() => fn(target)),\n\t\t\t\t\tfragment\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tthis.#onscreen.set(\n\t\t\t\t\tkey,\n\t\t\t\t\tbranch(() => fn(this.anchor))\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tthis.#batches.set(batch, key);\n\n\t\tif (defer) {\n\t\t\tfor (const [k, effect] of this.#onscreen) {\n\t\t\t\tif (k === key) {\n\t\t\t\t\tbatch.unskip_effect(effect);\n\t\t\t\t} else {\n\t\t\t\t\tbatch.skip_effect(effect);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const [k, branch] of this.#offscreen) {\n\t\t\t\tif (k === key) {\n\t\t\t\t\tbatch.unskip_effect(branch.effect);\n\t\t\t\t} else {\n\t\t\t\t\tbatch.skip_effect(branch.effect);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbatch.oncommit(this.#commit);\n\t\t\tbatch.ondiscard(this.#discard);\n\t\t} else {\n\t\t\tif (hydrating) {\n\t\t\t\tthis.anchor = hydrate_node;\n\t\t\t}\n\n\t\t\tthis.#commit(batch);\n\t\t}\n\t}\n}\n","/** @import { Snippet } from 'svelte' */\n/** @import { TemplateNode } from '#client' */\n/** @import { Getters } from '#shared' */\nimport { EFFECT_TRANSPARENT, ELEMENT_NODE } from '#client/constants';\nimport { block, teardown } from '../../reactivity/effects.js';\nimport {\n\tdev_current_component_function,\n\tset_dev_current_component_function\n} from '../../context.js';\nimport { hydrate_next, hydrate_node, hydrating } from '../hydration.js';\nimport { create_fragment_from_html } from '../reconciler.js';\nimport { assign_nodes } from '../template.js';\nimport * as w from '../../warnings.js';\nimport * as e from '../../errors.js';\nimport { DEV } from 'esm-env';\nimport { get_first_child, get_next_sibling } from '../operations.js';\nimport { prevent_snippet_stringification } from '../../../shared/validate.js';\nimport { BranchManager } from './branches.js';\n\n/**\n * @template {(node: TemplateNode, ...args: any[]) => void} SnippetFn\n * @param {TemplateNode} node\n * @param {() => SnippetFn | null | undefined} get_snippet\n * @param {(() => any)[]} args\n * @returns {void}\n */\nexport function snippet(node, get_snippet, ...args) {\n\tvar branches = new BranchManager(node);\n\n\tblock(() => {\n\t\tconst snippet = get_snippet() ?? null;\n\n\t\tif (DEV && snippet == null) {\n\t\t\te.invalid_snippet();\n\t\t}\n\n\t\tbranches.ensure(snippet, snippet && ((anchor) => snippet(anchor, ...args)));\n\t}, EFFECT_TRANSPARENT);\n}\n\n/**\n * In development, wrap the snippet function so that it passes validation, and so that the\n * correct component context is set for ownership checks\n * @param {any} component\n * @param {(node: TemplateNode, ...args: any[]) => void} fn\n */\nexport function wrap_snippet(component, fn) {\n\tconst snippet = (/** @type {TemplateNode} */ node, /** @type {any[]} */ ...args) => {\n\t\tvar previous_component_function = dev_current_component_function;\n\t\tset_dev_current_component_function(component);\n\n\t\ttry {\n\t\t\treturn fn(node, ...args);\n\t\t} finally {\n\t\t\tset_dev_current_component_function(previous_component_function);\n\t\t}\n\t};\n\n\tprevent_snippet_stringification(snippet);\n\n\treturn snippet;\n}\n\n/**\n * Create a snippet programmatically\n * @template {unknown[]} Params\n * @param {(...params: Getters<Params>) => {\n * render: () => string\n * setup?: (element: Element) => void | (() => void)\n * }} fn\n * @returns {Snippet<Params>}\n */\nexport function createRawSnippet(fn) {\n\t// @ts-expect-error the types are a lie\n\treturn (/** @type {TemplateNode} */ anchor, /** @type {Getters<Params>} */ ...params) => {\n\t\tvar snippet = fn(...params);\n\n\t\t/** @type {Element} */\n\t\tvar element;\n\n\t\tif (hydrating) {\n\t\t\telement = /** @type {Element} */ (hydrate_node);\n\t\t\thydrate_next();\n\t\t} else {\n\t\t\tvar html = snippet.render().trim();\n\t\t\tvar fragment = create_fragment_from_html(html);\n\t\t\telement = /** @type {Element} */ (get_first_child(fragment));\n\n\t\t\tif (DEV && (get_next_sibling(element) !== null || element.nodeType !== ELEMENT_NODE)) {\n\t\t\t\tw.invalid_raw_snippet_render();\n\t\t\t}\n\n\t\t\tanchor.before(element);\n\t\t}\n\n\t\tconst result = snippet.setup?.(element);\n\t\tassign_nodes(element, element);\n\n\t\tif (typeof result === 'function') {\n\t\t\tteardown(result);\n\t\t}\n\t};\n}\n","/** @import { ComponentContext, ComponentContextLegacy } from '#client' */\n/** @import { EventDispatcher } from './index.js' */\n/** @import { NotFunction } from './internal/types.js' */\nimport { active_reaction, untrack } from './internal/client/runtime.js';\nimport { is_array } from './internal/shared/utils.js';\nimport { user_effect } from './internal/client/index.js';\nimport * as e from './internal/client/errors.js';\nimport { legacy_mode_flag } from './internal/flags/index.js';\nimport { component_context } from './internal/client/context.js';\nimport { DEV } from 'esm-env';\n\nif (DEV) {\n\t/**\n\t * @param {string} rune\n\t */\n\tfunction throw_rune_error(rune) {\n\t\tif (!(rune in globalThis)) {\n\t\t\t// TODO if people start adjusting the \"this can contain runes\" config through v-p-s more, adjust this message\n\t\t\t/** @type {any} */\n\t\t\tlet value; // let's hope noone modifies this global, but belts and braces\n\t\t\tObject.defineProperty(globalThis, rune, {\n\t\t\t\tconfigurable: true,\n\t\t\t\t// eslint-disable-next-line getter-return\n\t\t\t\tget: () => {\n\t\t\t\t\tif (value !== undefined) {\n\t\t\t\t\t\treturn value;\n\t\t\t\t\t}\n\n\t\t\t\t\te.rune_outside_svelte(rune);\n\t\t\t\t},\n\t\t\t\tset: (v) => {\n\t\t\t\t\tvalue = v;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\tthrow_rune_error('$state');\n\tthrow_rune_error('$effect');\n\tthrow_rune_error('$derived');\n\tthrow_rune_error('$inspect');\n\tthrow_rune_error('$props');\n\tthrow_rune_error('$bindable');\n}\n\n/**\n * Returns an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that aborts when the current [derived](https://svelte.dev/docs/svelte/$derived) or [effect](https://svelte.dev/docs/svelte/$effect) re-runs or is destroyed.\n *\n * Must be called while a derived or effect is running.\n *\n * ```svelte\n * <script>\n * \timport { getAbortSignal } from 'svelte';\n *\n * \tlet { id } = $props();\n *\n * \tasync function getData(id) {\n * \t\tconst response = await fetch(`/items/${id}`, {\n * \t\t\tsignal: getAbortSignal()\n * \t\t});\n *\n * \t\treturn await response.json();\n * \t}\n *\n * \tconst data = $derived(await getData(id));\n * </script>\n * ```\n */\nexport function getAbortSignal() {\n\tif (active_reaction === null) {\n\t\te.get_abort_signal_outside_reaction();\n\t}\n\n\treturn (active_reaction.ac ??= new AbortController()).signal;\n}\n\n/**\n * `onMount`, like [`$effect`](https://svelte.dev/docs/svelte/$effect), schedules a function to run as soon as the component has been mounted to the DOM.\n * Unlike `$effect`, the provided function only runs once.\n *\n * It must be called during the component's initialisation (but doesn't need to live _inside_ the component;\n * it can be called from an external module). If a function is returned _synchronously_ from `onMount`,\n * it will be called when the component is unmounted.\n *\n * `onMount` functions do not run during [server-side rendering](https://svelte.dev/docs/svelte/svelte-server#render).\n *\n * @template T\n * @param {() => NotFunction<T> | Promise<NotFunction<T>> | (() => any)} fn\n * @returns {void}\n */\nexport function onMount(fn) {\n\tif (component_context === null) {\n\t\te.lifecycle_outside_component('onMount');\n\t}\n\n\tif (legacy_mode_flag && component_context.l !== null) {\n\t\tinit_update_callbacks(component_context).m.push(fn);\n\t} else {\n\t\tuser_effect(() => {\n\t\t\tconst cleanup = untrack(fn);\n\t\t\tif (typeof cleanup === 'function') return /** @type {() => void} */ (cleanup);\n\t\t});\n\t}\n}\n\n/**\n * Schedules a callback to run immediately before the component is unmounted.\n *\n * Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the\n * only one that runs inside a server-side component.\n *\n * @param {() => any} fn\n * @returns {void}\n */\nexport function onDestroy(fn) {\n\tif (component_context === null) {\n\t\te.lifecycle_outside_component('onDestroy');\n\t}\n\n\tonMount(() => () => untrack(fn));\n}\n\n/**\n * @template [T=any]\n * @param {string} type\n * @param {T} [detail]\n * @param {any}params_0\n * @returns {CustomEvent<T>}\n */\nfunction create_custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {\n\treturn new CustomEvent(type, { detail, bubbles, cancelable });\n}\n\n/**\n * Creates an event dispatcher that can be used to dispatch [component events](https://svelte.dev/docs/svelte/legacy-on#Component-events).\n * Event dispatchers are functions that can take two arguments: `name` and `detail`.\n *\n * Component events created with `createEventDispatcher` create a\n * [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent).\n * These events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture).\n * The `detail` argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail)\n * property and can contain any type of data.\n *\n * The event dispatcher can be typed to narrow the allowed event names and the type of the `detail` argument:\n * ```ts\n * const dispatch = createEventDispatcher<{\n * loaded: null; // does not take a detail argument\n * change: string; // takes a detail argument of type string, which is required\n * optional: number | null; // takes an optional detail argument of type number\n * }>();\n * ```\n *\n * @deprecated Use callback props and/or the `$host()` rune instead — see [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Event-changes-Component-events)\n * @template {Record<string, any>} [EventMap = any]\n * @returns {EventDispatcher<EventMap>}\n */\nexport function createEventDispatcher() {\n\tconst active_component_context = component_context;\n\tif (active_component_context === null) {\n\t\te.lifecycle_outside_component('createEventDispatcher');\n\t}\n\n\t/**\n\t * @param [detail]\n\t * @param [options]\n\t */\n\treturn (type, detail, options) => {\n\t\tconst events = /** @type {Record<string, Function | Function[]>} */ (\n\t\t\tactive_component_context.s.$$events\n\t\t)?.[/** @type {string} */ (type)];\n\n\t\tif (events) {\n\t\t\tconst callbacks = is_array(events) ? events.slice() : [events];\n\t\t\t// TODO are there situations where events could be dispatched\n\t\t\t// in a server (non-DOM) environment?\n\t\t\tconst event = create_custom_event(/** @type {string} */ (type), detail, options);\n\t\t\tfor (const fn of callbacks) {\n\t\t\t\tfn.call(active_component_context.x, event);\n\t\t\t}\n\t\t\treturn !event.defaultPrevented;\n\t\t}\n\n\t\treturn true;\n\t};\n}\n\n// TODO mark beforeUpdate and afterUpdate as deprecated in Svelte 6\n\n/**\n * Schedules a callback to run immediately before the component is updated after any state change.\n *\n * The first time the callback runs will be before the initial `onMount`.\n *\n * In runes mode use `$effect.pre` instead.\n *\n * @deprecated Use [`$effect.pre`](https://svelte.dev/docs/svelte/$effect#$effect.pre) instead\n * @param {() => void} fn\n * @returns {void}\n */\nexport function beforeUpdate(fn) {\n\tif (component_context === null) {\n\t\te.lifecycle_outside_component('beforeUpdate');\n\t}\n\n\tif (component_context.l === null) {\n\t\te.lifecycle_legacy_only('beforeUpdate');\n\t}\n\n\tinit_update_callbacks(component_context).b.push(fn);\n}\n\n/**\n * Schedules a callback to run immediately after the component has been updated.\n *\n * The first time the callback runs will be after the initial `onMount`.\n *\n * In runes mode use `$effect` instead.\n *\n * @deprecated Use [`$effect`](https://svelte.dev/docs/svelte/$effect) instead\n * @param {() => void} fn\n * @returns {void}\n */\nexport function afterUpdate(fn) {\n\tif (component_context === null) {\n\t\te.lifecycle_outside_component('afterUpdate');\n\t}\n\n\tif (component_context.l === null) {\n\t\te.lifecycle_legacy_only('afterUpdate');\n\t}\n\n\tinit_update_callbacks(component_context).a.push(fn);\n}\n\n/**\n * Legacy-mode: Init callbacks object for onMount/beforeUpdate/afterUpdate\n * @param {ComponentContext} context\n */\nfunction init_update_callbacks(context) {\n\tvar l = /** @type {ComponentContextLegacy} */ (context).l;\n\treturn (l.u ??= { a: [], b: [], m: [] });\n}\n\nexport { flushSync, fork } from './internal/client/reactivity/batch.js';\nexport {\n\tcreateContext,\n\tgetContext,\n\tgetAllContexts,\n\thasContext,\n\tsetContext\n} from './internal/client/context.js';\nexport { hydratable } from './internal/client/hydratable.js';\nexport { hydrate, mount, unmount } from './internal/client/render.js';\nexport { tick, untrack, settled } from './internal/client/runtime.js';\nexport { createRawSnippet } from './internal/client/dom/blocks/snippet.js';\n","/** @import { Action, ActionReturn } from '../action/public' */\n/** @import { Attachment } from './public' */\nimport { noop, render_effect } from 'svelte/internal/client';\nimport { ATTACHMENT_KEY } from '../constants.js';\nimport { untrack } from '../index-client.js';\nimport { teardown } from '../internal/client/reactivity/effects.js';\n\n/**\n * Creates an object key that will be recognised as an attachment when the object is spread onto an element,\n * as a programmatic alternative to using `{@attach ...}`. This can be useful for library authors, though\n * is generally not needed when building an app.\n *\n * ```svelte\n * <script>\n * \timport { createAttachmentKey } from 'svelte/attachments';\n *\n * \tconst props = {\n * \t\tclass: 'cool',\n * \t\tonclick: () => alert('clicked'),\n * \t\t[createAttachmentKey()]: (node) => {\n * \t\t\tnode.textContent = 'attached!';\n * \t\t}\n * \t};\n * </script>\n *\n * <button {...props}>click me</button>\n * ```\n * @since 5.29\n */\nexport function createAttachmentKey() {\n\treturn Symbol(ATTACHMENT_KEY);\n}\n\n/**\n * Converts an [action](https://svelte.dev/docs/svelte/use) into an [attachment](https://svelte.dev/docs/svelte/@attach) keeping the same behavior.\n * It's useful if you want to start using attachments on components but you have actions provided by a library.\n *\n * Note that the second argument, if provided, must be a function that _returns_ the argument to the\n * action function, not the argument itself.\n *\n * ```svelte\n * <!-- with an action -->\n * <div use:foo={bar}>...</div>\n *\n * <!-- with an attachment -->\n * <div {@attach fromAction(foo, () => bar)}>...</div>\n * ```\n * @template {EventTarget} E\n * @template {unknown} T\n * @overload\n * @param {Action<E, T> | ((element: E, arg: T) => void | ActionReturn<T>)} action The action function\n * @param {() => T} fn A function that returns the argument for the action\n * @returns {Attachment<E>}\n */\n/**\n * Converts an [action](https://svelte.dev/docs/svelte/use) into an [attachment](https://svelte.dev/docs/svelte/@attach) keeping the same behavior.\n * It's useful if you want to start using attachments on components but you have actions provided by a library.\n *\n * Note that the second argument, if provided, must be a function that _returns_ the argument to the\n * action function, not the argument itself.\n *\n * ```svelte\n * <!-- with an action -->\n * <div use:foo={bar}>...</div>\n *\n * <!-- with an attachment -->\n * <div {@attach fromAction(foo, () => bar)}>...</div>\n * ```\n * @template {EventTarget} E\n * @overload\n * @param {Action<E, void> | ((element: E) => void | ActionReturn<void>)} action The action function\n * @returns {Attachment<E>}\n */\n/**\n * Converts an [action](https://svelte.dev/docs/svelte/use) into an [attachment](https://svelte.dev/docs/svelte/@attach) keeping the same behavior.\n * It's useful if you want to start using attachments on components but you have actions provided by a library.\n *\n * Note that the second argument, if provided, must be a function that _returns_ the argument to the\n * action function, not the argument itself.\n *\n * ```svelte\n * <!-- with an action -->\n * <div use:foo={bar}>...</div>\n *\n * <!-- with an attachment -->\n * <div {@attach fromAction(foo, () => bar)}>...</div>\n * ```\n *\n * @template {EventTarget} E\n * @template {unknown} T\n * @param {Action<E, T> | ((element: E, arg: T) => void | ActionReturn<T>)} action The action function\n * @param {() => T} fn A function that returns the argument for the action\n * @returns {Attachment<E>}\n * @since 5.32\n */\nexport function fromAction(action, fn = /** @type {() => T} */ (noop)) {\n\treturn (element) => {\n\t\tconst { update, destroy } = untrack(() => action(element, fn()) ?? {});\n\n\t\tif (update) {\n\t\t\tvar ran = false;\n\t\t\trender_effect(() => {\n\t\t\t\tconst arg = fn();\n\t\t\t\tif (ran) update(arg);\n\t\t\t});\n\t\t\tran = true;\n\t\t}\n\n\t\tif (destroy) {\n\t\t\tteardown(destroy);\n\t\t}\n\t};\n}\n","import { STATE_SYMBOL } from '#client/constants';\nimport { sanitize_location } from '../../../utils.js';\nimport { untrack } from '../runtime.js';\nimport * as w from '../warnings.js';\n\n/**\n *\n * @param {any} a\n * @param {any} b\n * @param {string} property\n * @param {string} location\n */\nfunction compare(a, b, property, location) {\n\tif (a !== b && typeof b === 'object' && STATE_SYMBOL in b) {\n\t\tw.assignment_value_stale(property, /** @type {string} */ (sanitize_location(location)));\n\t}\n\n\treturn a;\n}\n\n/**\n * @param {any} object\n * @param {string} property\n * @param {string} operator\n * @param {any} rhs\n * @param {string} location\n */\nexport function assign(object, property, operator, rhs, location) {\n\treturn compare(\n\t\toperator === '='\n\t\t\t? (object[property] = rhs)\n\t\t\t: operator === '&&='\n\t\t\t\t? (object[property] &&= rhs())\n\t\t\t\t: operator === '||='\n\t\t\t\t\t? (object[property] ||= rhs())\n\t\t\t\t\t: operator === '??='\n\t\t\t\t\t\t? (object[property] ??= rhs())\n\t\t\t\t\t\t: null,\n\t\tuntrack(() => object[property]),\n\t\tproperty,\n\t\tlocation\n\t);\n}\n\n/**\n * @param {any} object\n * @param {string} property\n * @param {string} operator\n * @param {any} rhs\n * @param {string} location\n */\nexport async function assign_async(object, property, operator, rhs, location) {\n\treturn compare(\n\t\toperator === '='\n\t\t\t? (object[property] = await rhs)\n\t\t\t: operator === '&&='\n\t\t\t\t? (object[property] &&= await rhs())\n\t\t\t\t: operator === '||='\n\t\t\t\t\t? (object[property] ||= await rhs())\n\t\t\t\t\t: operator === '??='\n\t\t\t\t\t\t? (object[property] ??= await rhs())\n\t\t\t\t\t\t: null,\n\t\tuntrack(() => object[property]),\n\t\tproperty,\n\t\tlocation\n\t);\n}\n","/** @type {Map<String, Set<HTMLStyleElement>>} */\nvar all_styles = new Map();\n\n/**\n * @param {String} hash\n * @param {HTMLStyleElement} style\n */\nexport function register_style(hash, style) {\n\tvar styles = all_styles.get(hash);\n\n\tif (!styles) {\n\t\tstyles = new Set();\n\t\tall_styles.set(hash, styles);\n\t}\n\n\tstyles.add(style);\n}\n\n/**\n * @param {String} hash\n */\nexport function cleanup_styles(hash) {\n\tvar styles = all_styles.get(hash);\n\tif (!styles) return;\n\n\tfor (const style of styles) {\n\t\tstyle.remove();\n\t}\n\n\tall_styles.delete(hash);\n}\n","/** @import { SourceLocation } from '#client' */\nimport { COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, ELEMENT_NODE } from '#client/constants';\nimport { HYDRATION_END, HYDRATION_START } from '../../../constants.js';\nimport { hydrating } from '../dom/hydration.js';\nimport { dev_stack } from '../context.js';\n\n/**\n * @param {any} fn\n * @param {string} filename\n * @param {SourceLocation[]} locations\n * @returns {any}\n */\nexport function add_locations(fn, filename, locations) {\n\treturn (/** @type {any[]} */ ...args) => {\n\t\tconst dom = fn(...args);\n\n\t\tvar node = hydrating ? dom : dom.nodeType === DOCUMENT_FRAGMENT_NODE ? dom.firstChild : dom;\n\t\tassign_locations(node, filename, locations);\n\n\t\treturn dom;\n\t};\n}\n\n/**\n * @param {Element} element\n * @param {string} filename\n * @param {SourceLocation} location\n */\nfunction assign_location(element, filename, location) {\n\t// @ts-expect-error\n\telement.__svelte_meta = {\n\t\tparent: dev_stack,\n\t\tloc: { file: filename, line: location[0], column: location[1] }\n\t};\n\n\tif (location[2]) {\n\t\tassign_locations(element.firstChild, filename, location[2]);\n\t}\n}\n\n/**\n * @param {Node | null} node\n * @param {string} filename\n * @param {SourceLocation[]} locations\n */\nfunction assign_locations(node, filename, locations) {\n\tvar i = 0;\n\tvar depth = 0;\n\n\twhile (node && i < locations.length) {\n\t\tif (hydrating && node.nodeType === COMMENT_NODE) {\n\t\t\tvar comment = /** @type {Comment} */ (node);\n\t\t\tif (comment.data[0] === HYDRATION_START) depth += 1;\n\t\t\telse if (comment.data[0] === HYDRATION_END) depth -= 1;\n\t\t}\n\n\t\tif (depth === 0 && node.nodeType === ELEMENT_NODE) {\n\t\t\tassign_location(/** @type {Element} */ (node), filename, locations[i++]);\n\t\t}\n\n\t\tnode = node.nextSibling;\n\t}\n}\n","/** @import { Effect, TemplateNode } from '#client' */\nimport { FILENAME, HMR } from '../../../constants.js';\nimport { EFFECT_TRANSPARENT, HMR_ANCHOR } from '#client/constants';\nimport { hydrate_node, hydrating } from '../dom/hydration.js';\nimport { block, branch, destroy_effect } from '../reactivity/effects.js';\nimport { set, source } from '../reactivity/sources.js';\nimport { set_should_intro } from '../render.js';\nimport { active_effect, get } from '../runtime.js';\n\n/**\n * @template {(anchor: Comment, props: any) => any} Component\n * @param {Component} fn\n */\nexport function hmr(fn) {\n\tconst current = source(fn);\n\n\t/**\n\t * @param {TemplateNode} initial_anchor\n\t * @param {any} props\n\t */\n\tfunction wrapper(initial_anchor, props) {\n\t\tlet component = {};\n\t\tlet instance = {};\n\n\t\t/** @type {Effect} */\n\t\tlet effect;\n\n\t\tlet ran = false;\n\t\tlet anchor = initial_anchor;\n\n\t\tblock(() => {\n\t\t\tif (component === (component = get(current))) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (effect) {\n\t\t\t\t// @ts-ignore\n\t\t\t\tfor (var k in instance) delete instance[k];\n\t\t\t\tdestroy_effect(effect);\n\t\t\t}\n\n\t\t\teffect = branch(() => {\n\t\t\t\tanchor = /** @type {any} */ (anchor)[HMR_ANCHOR] ?? anchor;\n\n\t\t\t\t// when the component is invalidated, replace it without transitions\n\t\t\t\tif (ran) set_should_intro(false);\n\n\t\t\t\t// preserve getters/setters\n\t\t\t\tvar result =\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tnew.target ? new component(anchor, props) : component(anchor, props);\n\t\t\t\t// a component is not guaranteed to return something and we can't invoke getOwnPropertyDescriptors on undefined\n\t\t\t\tif (result) {\n\t\t\t\t\tObject.defineProperties(instance, Object.getOwnPropertyDescriptors(result));\n\t\t\t\t}\n\n\t\t\t\tif (ran) set_should_intro(true);\n\t\t\t});\n\n\t\t\t// Forward the nodes from the inner effect to the outer active effect which would\n\t\t\t// get them if the HMR wrapper wasn't there. Do this inside the block not outside\n\t\t\t// so that HMR updates to the component will also update the nodes on the active effect.\n\t\t\t/** @type {Effect} */ (active_effect).nodes = effect.nodes;\n\t\t}, EFFECT_TRANSPARENT);\n\n\t\tran = true;\n\n\t\tif (hydrating) {\n\t\t\tanchor = hydrate_node;\n\t\t}\n\n\t\treturn instance;\n\t}\n\n\t// @ts-expect-error\n\twrapper[FILENAME] = fn[FILENAME];\n\n\t// @ts-ignore\n\twrapper[HMR] = {\n\t\tfn,\n\t\tcurrent,\n\t\tupdate: (/** @type {any} */ incoming) => {\n\t\t\t// This logic ensures that the first version of the component is the one\n\t\t\t// whose update function and therefore block effect is preserved across updates.\n\t\t\t// If we don't do this dance and instead just use `incoming` as the new component\n\t\t\t// and then update, we'll create an ever-growing stack of block effects.\n\n\t\t\t// Trigger the original block effect\n\t\t\tset(wrapper[HMR].current, incoming[HMR].fn);\n\n\t\t\t// Replace the incoming source with the original one\n\t\t\tincoming[HMR].current = wrapper[HMR].current;\n\t\t}\n\t};\n\n\treturn wrapper;\n}\n","/** @typedef {{ file: string, line: number, column: number }} Location */\n\nimport { get_descriptor } from '../../shared/utils.js';\nimport { LEGACY_PROPS, STATE_SYMBOL } from '#client/constants';\nimport { FILENAME } from '../../../constants.js';\nimport { component_context } from '../context.js';\nimport * as w from '../warnings.js';\nimport { sanitize_location } from '../../../utils.js';\n\n/**\n * Sets up a validator that\n * - traverses the path of a prop to find out if it is allowed to be mutated\n * - checks that the binding chain is not interrupted\n * @param {Record<string, any>} props\n */\nexport function create_ownership_validator(props) {\n\tconst component = component_context?.function;\n\tconst parent = component_context?.p?.function;\n\n\treturn {\n\t\t/**\n\t\t * @param {string} prop\n\t\t * @param {any[]} path\n\t\t * @param {any} result\n\t\t * @param {number} line\n\t\t * @param {number} column\n\t\t */\n\t\tmutation: (prop, path, result, line, column) => {\n\t\t\tconst name = path[0];\n\t\t\tif (is_bound_or_unset(props, name) || !parent) {\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\t/** @type {any} */\n\t\t\tlet value = props;\n\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tvalue = value[path[i]];\n\t\t\t\tif (!value?.[STATE_SYMBOL]) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst location = sanitize_location(`${component[FILENAME]}:${line}:${column}`);\n\n\t\t\tw.ownership_invalid_mutation(name, location, prop, parent[FILENAME]);\n\n\t\t\treturn result;\n\t\t},\n\t\t/**\n\t\t * @param {any} key\n\t\t * @param {any} child_component\n\t\t * @param {() => any} value\n\t\t */\n\t\tbinding: (key, child_component, value) => {\n\t\t\tif (!is_bound_or_unset(props, key) && parent && value()?.[STATE_SYMBOL]) {\n\t\t\t\tw.ownership_invalid_binding(\n\t\t\t\t\tcomponent[FILENAME],\n\t\t\t\t\tkey,\n\t\t\t\t\tchild_component[FILENAME],\n\t\t\t\t\tparent[FILENAME]\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t};\n}\n\n/**\n * @param {Record<string, any>} props\n * @param {string} prop_name\n */\nfunction is_bound_or_unset(props, prop_name) {\n\t// Can be the case when someone does `mount(Component, props)` with `let props = $state({...})`\n\t// or `createClassComponent(Component, props)`\n\tconst is_entry_props = STATE_SYMBOL in props || LEGACY_PROPS in props;\n\treturn (\n\t\t!!get_descriptor(props, prop_name)?.set ||\n\t\t(is_entry_props && prop_name in props) ||\n\t\t!(prop_name in props)\n\t);\n}\n","import * as e from '../errors.js';\nimport { component_context } from '../context.js';\nimport { FILENAME } from '../../../constants.js';\n\n/** @param {Function & { [FILENAME]: string }} target */\nexport function check_target(target) {\n\tif (target) {\n\t\te.component_api_invalid_new(target[FILENAME] ?? 'a component', target.name);\n\t}\n}\n\nexport function legacy_api() {\n\tconst component = component_context?.function;\n\n\t/** @param {string} method */\n\tfunction error(method) {\n\t\te.component_api_changed(method, component[FILENAME]);\n\t}\n\n\treturn {\n\t\t$destroy: () => error('$destroy()'),\n\t\t$on: () => error('$on(...)'),\n\t\t$set: () => error('$set(...)')\n\t};\n}\n","import { UNINITIALIZED } from '../../../constants.js';\nimport { snapshot } from '../../shared/clone.js';\nimport { eager_effect, render_effect, validate_effect } from '../reactivity/effects.js';\nimport { untrack } from '../runtime.js';\nimport { get_error } from '../../shared/dev.js';\n\n/**\n * @param {() => any[]} get_value\n * @param {Function} inspector\n * @param {boolean} show_stack\n */\nexport function inspect(get_value, inspector, show_stack = false) {\n\tvalidate_effect('$inspect');\n\n\tlet initial = true;\n\tlet error = /** @type {any} */ (UNINITIALIZED);\n\n\t// Inspect effects runs synchronously so that we can capture useful\n\t// stack traces. As a consequence, reading the value might result\n\t// in an error (an `$inspect(object.property)` will run before the\n\t// `{#if object}...{/if}` that contains it)\n\teager_effect(() => {\n\t\ttry {\n\t\t\tvar value = get_value();\n\t\t} catch (e) {\n\t\t\terror = e;\n\t\t\treturn;\n\t\t}\n\n\t\tvar snap = snapshot(value, true, true);\n\t\tuntrack(() => {\n\t\t\tif (show_stack) {\n\t\t\t\tinspector(...snap);\n\n\t\t\t\tif (!initial) {\n\t\t\t\t\tconst stack = get_error('$inspect(...)');\n\t\t\t\t\tif (stack) {\n\t\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\t\tconsole.groupCollapsed('stack trace');\n\t\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\t\tconsole.log(stack);\n\t\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\t\tconsole.groupEnd();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tinspector(initial ? 'init' : 'update', ...snap);\n\t\t\t}\n\t\t});\n\n\t\tinitial = false;\n\t});\n\n\t// If an error occurs, we store it (along with its stack trace).\n\t// If the render effect subsequently runs, we log the error,\n\t// but if it doesn't run it's because the `$inspect` was\n\t// destroyed, meaning we don't need to bother\n\trender_effect(() => {\n\t\ttry {\n\t\t\t// call `get_value` so that this runs alongside the inspect effect\n\t\t\tget_value();\n\t\t} catch {\n\t\t\t// ignore\n\t\t}\n\n\t\tif (error !== UNINITIALIZED) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.error(error);\n\t\t\terror = UNINITIALIZED;\n\t\t}\n\t});\n}\n","/** @import { Blocker, TemplateNode, Value } from '#client' */\nimport { flatten, increment_pending } from '../../reactivity/async.js';\nimport { get } from '../../runtime.js';\nimport {\n\thydrate_next,\n\thydrate_node,\n\thydrating,\n\tset_hydrate_node,\n\tset_hydrating,\n\tskip_nodes\n} from '../hydration.js';\n\n/**\n * @param {TemplateNode} node\n * @param {Blocker[]} blockers\n * @param {Array<() => Promise<any>>} expressions\n * @param {(anchor: TemplateNode, ...deriveds: Value[]) => void} fn\n */\nexport function async(node, blockers = [], expressions = [], fn) {\n\tvar was_hydrating = hydrating;\n\tvar end = null;\n\n\tif (was_hydrating) {\n\t\thydrate_next();\n\t\tend = skip_nodes(false);\n\t}\n\n\tif (expressions.length === 0 && blockers.every((b) => b.settled)) {\n\t\tfn(node);\n\n\t\t// This is necessary because it is not guaranteed that the render function will\n\t\t// advance the hydration node to $.async's end marker: it may stop at an inner\n\t\t// block's end marker (in case of an inner if block for example), but it also may\n\t\t// stop at the correct $.async end marker (in case of component child) - hence\n\t\t// we can't just use hydrate_next()\n\t\t// TODO this feels indicative of a bug elsewhere; ideally we wouldn't need\n\t\t// to double-traverse in the already-resolved case\n\t\tif (was_hydrating) {\n\t\t\tset_hydrate_node(end);\n\t\t}\n\n\t\treturn;\n\t}\n\n\tconst decrement_pending = increment_pending();\n\n\tif (was_hydrating) {\n\t\tvar previous_hydrate_node = hydrate_node;\n\t\tset_hydrate_node(end);\n\t}\n\n\tflatten(blockers, [], expressions, (values) => {\n\t\tif (was_hydrating) {\n\t\t\tset_hydrating(true);\n\t\t\tset_hydrate_node(previous_hydrate_node);\n\t\t}\n\n\t\ttry {\n\t\t\t// get values eagerly to avoid creating blocks if they reject\n\t\t\tfor (const d of values) get(d);\n\n\t\t\tfn(node, ...values);\n\t\t} finally {\n\t\t\tif (was_hydrating) {\n\t\t\t\tset_hydrating(false);\n\t\t\t}\n\n\t\t\tdecrement_pending();\n\t\t}\n\t});\n}\n","import * as e from '../errors.js';\n/**\n * @param {Node} anchor\n * @param {...(()=>any)[]} args\n */\nexport function validate_snippet_args(anchor, ...args) {\n\tif (typeof anchor !== 'object' || !(anchor instanceof Node)) {\n\t\te.invalid_snippet_arguments();\n\t}\n\n\tfor (let arg of args) {\n\t\tif (typeof arg !== 'function') {\n\t\t\te.invalid_snippet_arguments();\n\t\t}\n\t}\n}\n","/** @import { Source, TemplateNode } from '#client' */\nimport { is_promise } from '../../../shared/utils.js';\nimport { block } from '../../reactivity/effects.js';\nimport { internal_set, mutable_source, source } from '../../reactivity/sources.js';\nimport {\n\thydrate_next,\n\thydrating,\n\tskip_nodes,\n\tset_hydrate_node,\n\tset_hydrating\n} from '../hydration.js';\nimport { queue_micro_task } from '../task.js';\nimport { HYDRATION_START_ELSE, UNINITIALIZED } from '../../../../constants.js';\nimport { is_runes } from '../../context.js';\nimport { Batch, current_batch, flushSync, is_flushing_sync } from '../../reactivity/batch.js';\nimport { BranchManager } from './branches.js';\nimport { capture, unset_context } from '../../reactivity/async.js';\n\nconst PENDING = 0;\nconst THEN = 1;\nconst CATCH = 2;\n\n/** @typedef {typeof PENDING | typeof THEN | typeof CATCH} AwaitState */\n\n/**\n * @template V\n * @param {TemplateNode} node\n * @param {(() => any)} get_input\n * @param {null | ((anchor: Node) => void)} pending_fn\n * @param {null | ((anchor: Node, value: Source<V>) => void)} then_fn\n * @param {null | ((anchor: Node, error: unknown) => void)} catch_fn\n * @returns {void}\n */\nexport function await_block(node, get_input, pending_fn, then_fn, catch_fn) {\n\tif (hydrating) {\n\t\thydrate_next();\n\t}\n\n\tvar runes = is_runes();\n\n\tvar v = /** @type {V} */ (UNINITIALIZED);\n\tvar value = runes ? source(v) : mutable_source(v, false, false);\n\tvar error = runes ? source(v) : mutable_source(v, false, false);\n\n\tvar branches = new BranchManager(node);\n\n\tblock(() => {\n\t\tvar batch = /** @type {Batch} */ (current_batch);\n\n\t\t// we null out `current_batch` because otherwise `save(...)` will incorrectly restore it —\n\t\t// the batch will already have been committed by the time it resolves\n\t\tbatch.deactivate();\n\t\tvar input = get_input();\n\t\tbatch.activate();\n\n\t\tvar destroyed = false;\n\n\t\t/** Whether or not there was a hydration mismatch. Needs to be a `let` or else it isn't treeshaken out */\n\t\t// @ts-ignore coercing `node` to a `Comment` causes TypeScript and Prettier to fight\n\t\tlet mismatch = hydrating && is_promise(input) === (node.data === HYDRATION_START_ELSE);\n\n\t\tif (mismatch) {\n\t\t\t// Hydration mismatch: remove everything inside the anchor and start fresh\n\t\t\tset_hydrate_node(skip_nodes());\n\t\t\tset_hydrating(false);\n\t\t}\n\n\t\tif (is_promise(input)) {\n\t\t\tvar restore = capture();\n\t\t\tvar resolved = false;\n\n\t\t\t/**\n\t\t\t * @param {() => void} fn\n\t\t\t */\n\t\t\tconst resolve = (fn) => {\n\t\t\t\tif (destroyed) return;\n\n\t\t\t\tresolved = true;\n\t\t\t\t// We don't want to restore the previous batch here; {#await} blocks don't follow the async logic\n\t\t\t\t// we have elsewhere, instead pending/resolve/fail states are each their own batch so to speak.\n\t\t\t\trestore(false);\n\t\t\t\t// Make sure we have a batch, since the branch manager expects one to exist\n\t\t\t\tBatch.ensure();\n\n\t\t\t\tif (hydrating) {\n\t\t\t\t\t// `restore()` could set `hydrating` to `true`, which we very much\n\t\t\t\t\t// don't want — we want to restore everything _except_ this\n\t\t\t\t\tset_hydrating(false);\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tfn();\n\t\t\t\t} finally {\n\t\t\t\t\tunset_context(false);\n\n\t\t\t\t\t// without this, the DOM does not update until two ticks after the promise\n\t\t\t\t\t// resolves, which is unexpected behaviour (and somewhat irksome to test)\n\t\t\t\t\tif (!is_flushing_sync) flushSync();\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tinput.then(\n\t\t\t\t(v) => {\n\t\t\t\t\tresolve(() => {\n\t\t\t\t\t\tinternal_set(value, v);\n\t\t\t\t\t\tbranches.ensure(THEN, then_fn && ((target) => then_fn(target, value)));\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\t(e) => {\n\t\t\t\t\tresolve(() => {\n\t\t\t\t\t\tinternal_set(error, e);\n\t\t\t\t\t\tbranches.ensure(CATCH, catch_fn && ((target) => catch_fn(target, error)));\n\n\t\t\t\t\t\tif (!catch_fn) {\n\t\t\t\t\t\t\t// Rethrow the error if no catch block exists\n\t\t\t\t\t\t\tthrow error.v;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tif (hydrating) {\n\t\t\t\tbranches.ensure(PENDING, pending_fn);\n\t\t\t} else {\n\t\t\t\t// Wait a microtask before checking if we should show the pending state as\n\t\t\t\t// the promise might have resolved by then\n\t\t\t\tqueue_micro_task(() => {\n\t\t\t\t\tif (!resolved) {\n\t\t\t\t\t\tresolve(() => {\n\t\t\t\t\t\t\tbranches.ensure(PENDING, pending_fn);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tinternal_set(value, input);\n\t\t\tbranches.ensure(THEN, then_fn && ((target) => then_fn(target, value)));\n\t\t}\n\n\t\tif (mismatch) {\n\t\t\t// continue in hydration mode\n\t\t\tset_hydrating(true);\n\t\t}\n\n\t\treturn () => {\n\t\t\tdestroyed = true;\n\t\t};\n\t});\n}\n","/** @import { TemplateNode } from '#client' */\nimport { EFFECT_TRANSPARENT } from '#client/constants';\nimport {\n\thydrate_next,\n\thydrating,\n\tread_hydration_instruction,\n\tskip_nodes,\n\tset_hydrate_node,\n\tset_hydrating,\n\thydrate_node\n} from '../hydration.js';\nimport { block } from '../../reactivity/effects.js';\nimport { BranchManager } from './branches.js';\n\n/**\n * @param {TemplateNode} node\n * @param {(branch: (fn: (anchor: Node) => void, key?: number | false) => void) => void} fn\n * @param {boolean} [elseif] True if this is an `{:else if ...}` block rather than an `{#if ...}`, as that affects which transitions are considered 'local'\n * @returns {void}\n */\nexport function if_block(node, fn, elseif = false) {\n\t/** @type {TemplateNode | undefined} */\n\tvar marker;\n\tif (hydrating) {\n\t\tmarker = hydrate_node;\n\t\thydrate_next();\n\t}\n\n\tvar branches = new BranchManager(node);\n\tvar flags = elseif ? EFFECT_TRANSPARENT : 0;\n\n\t/**\n\t * @param {number | false} key\n\t * @param {null | ((anchor: Node) => void)} fn\n\t */\n\tfunction update_branch(key, fn) {\n\t\tif (hydrating) {\n\t\t\tvar data = read_hydration_instruction(/** @type {TemplateNode} */ (marker));\n\n\t\t\t// \"[n\" = branch n, \"[-1\" = else\n\t\t\tif (key !== parseInt(data.substring(1))) {\n\t\t\t\t// Hydration mismatch: remove everything inside the anchor and start fresh.\n\t\t\t\t// This could happen with `{#if browser}...{/if}`, for example\n\t\t\t\tvar anchor = skip_nodes();\n\n\t\t\t\tset_hydrate_node(anchor);\n\t\t\t\tbranches.anchor = anchor;\n\n\t\t\t\tset_hydrating(false);\n\t\t\t\tbranches.ensure(key, fn);\n\t\t\t\tset_hydrating(true);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tbranches.ensure(key, fn);\n\t}\n\n\tblock(() => {\n\t\tvar has_branch = false;\n\n\t\tfn((fn, key = 0) => {\n\t\t\thas_branch = true;\n\t\t\tupdate_branch(key, fn);\n\t\t});\n\n\t\tif (!has_branch) {\n\t\t\tupdate_branch(-1, null);\n\t\t}\n\t}, flags);\n}\n","/** @import { TemplateNode } from '#client' */\nimport { is_runes } from '../../context.js';\nimport { block } from '../../reactivity/effects.js';\nimport { hydrate_next, hydrating } from '../hydration.js';\nimport { BranchManager } from './branches.js';\n\nconst NAN = Symbol('NaN');\n\n/**\n * @template V\n * @param {TemplateNode} node\n * @param {() => V} get_key\n * @param {(anchor: Node) => TemplateNode | void} render_fn\n * @returns {void}\n */\nexport function key(node, get_key, render_fn) {\n\tif (hydrating) {\n\t\thydrate_next();\n\t}\n\n\tvar branches = new BranchManager(node);\n\n\tvar legacy = !is_runes();\n\n\tblock(() => {\n\t\tvar key = get_key();\n\n\t\t// NaN !== NaN, hence we do this workaround to not trigger remounts unnecessarily\n\t\tif (key !== key) {\n\t\t\tkey = /** @type {any} */ (NAN);\n\t\t}\n\n\t\t// key blocks in Svelte <5 had stupid semantics\n\t\tif (legacy && key !== null && typeof key === 'object') {\n\t\t\tkey = /** @type {V} */ ({});\n\t\t}\n\n\t\tbranches.ensure(key, render_fn);\n\t});\n}\n","import { render_effect } from '../../reactivity/effects.js';\nimport { hydrating, set_hydrate_node } from '../hydration.js';\nimport { get_first_child } from '../operations.js';\n\n/**\n * @param {HTMLDivElement | SVGGElement} element\n * @param {() => Record<string, string>} get_styles\n * @returns {void}\n */\nexport function css_props(element, get_styles) {\n\tif (hydrating) {\n\t\tset_hydrate_node(get_first_child(element));\n\t}\n\n\trender_effect(() => {\n\t\tvar styles = get_styles();\n\n\t\tfor (var key in styles) {\n\t\t\tvar value = styles[key];\n\n\t\t\tif (value) {\n\t\t\t\telement.style.setProperty(key, value);\n\t\t\t} else {\n\t\t\t\telement.style.removeProperty(key);\n\t\t\t}\n\t\t}\n\t});\n}\n","/** @import { EachItem, EachOutroGroup, EachState, Effect, EffectNodes, MaybeSource, Source, TemplateNode, TransitionManager, Value } from '#client' */\n/** @import { Batch } from '../../reactivity/batch.js'; */\nimport {\n\tEACH_INDEX_REACTIVE,\n\tEACH_IS_ANIMATED,\n\tEACH_IS_CONTROLLED,\n\tEACH_ITEM_IMMUTABLE,\n\tEACH_ITEM_REACTIVE,\n\tHYDRATION_END,\n\tHYDRATION_START_ELSE\n} from '../../../../constants.js';\nimport {\n\thydrate_next,\n\thydrate_node,\n\thydrating,\n\tread_hydration_instruction,\n\tskip_nodes,\n\tset_hydrate_node,\n\tset_hydrating\n} from '../hydration.js';\nimport {\n\tclear_text_content,\n\tcreate_text,\n\tget_first_child,\n\tget_next_sibling,\n\tshould_defer_append\n} from '../operations.js';\nimport {\n\tblock,\n\tbranch,\n\tdestroy_effect,\n\tmove_effect,\n\tpause_effect,\n\tresume_effect\n} from '../../reactivity/effects.js';\nimport { source, mutable_source, internal_set } from '../../reactivity/sources.js';\nimport { array_from, is_array } from '../../../shared/utils.js';\nimport { BRANCH_EFFECT, COMMENT_NODE, DESTROYED, EFFECT_OFFSCREEN, INERT } from '#client/constants';\nimport { queue_micro_task } from '../task.js';\nimport { get } from '../../runtime.js';\nimport { DEV } from 'esm-env';\nimport { derived_safe_equal } from '../../reactivity/deriveds.js';\nimport { current_batch } from '../../reactivity/batch.js';\nimport * as e from '../../errors.js';\nimport { tag } from '../../dev/tracing.js';\n\n// When making substantive changes to this file, validate them with the each block stress test:\n// https://svelte.dev/playground/1972b2cf46564476ad8c8c6405b23b7b\n// This test also exists in this repo, as `packages/svelte/tests/manual/each-stress-test`\n\n/**\n * @param {any} _\n * @param {number} i\n */\nexport function index(_, i) {\n\treturn i;\n}\n\n/**\n * Pause multiple effects simultaneously, and coordinate their\n * subsequent destruction. Used in each blocks\n * @param {EachState} state\n * @param {Effect[]} to_destroy\n * @param {null | Node} controlled_anchor\n */\nfunction pause_effects(state, to_destroy, controlled_anchor) {\n\t/** @type {TransitionManager[]} */\n\tvar transitions = [];\n\tvar length = to_destroy.length;\n\n\t/** @type {EachOutroGroup} */\n\tvar group;\n\tvar remaining = to_destroy.length;\n\n\tfor (var i = 0; i < length; i++) {\n\t\tlet effect = to_destroy[i];\n\n\t\tpause_effect(\n\t\t\teffect,\n\t\t\t() => {\n\t\t\t\tif (group) {\n\t\t\t\t\tgroup.pending.delete(effect);\n\t\t\t\t\tgroup.done.add(effect);\n\n\t\t\t\t\tif (group.pending.size === 0) {\n\t\t\t\t\t\tvar groups = /** @type {Set<EachOutroGroup>} */ (state.outrogroups);\n\n\t\t\t\t\t\tdestroy_effects(state, array_from(group.done));\n\t\t\t\t\t\tgroups.delete(group);\n\n\t\t\t\t\t\tif (groups.size === 0) {\n\t\t\t\t\t\t\tstate.outrogroups = null;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tremaining -= 1;\n\t\t\t\t}\n\t\t\t},\n\t\t\tfalse\n\t\t);\n\t}\n\n\tif (remaining === 0) {\n\t\t// If we're in a controlled each block (i.e. the block is the only child of an\n\t\t// element), and we are removing all items, _and_ there are no out transitions,\n\t\t// we can use the fast path — emptying the element and replacing the anchor\n\t\tvar fast_path = transitions.length === 0 && controlled_anchor !== null;\n\n\t\tif (fast_path) {\n\t\t\tvar anchor = /** @type {Element} */ (controlled_anchor);\n\t\t\tvar parent_node = /** @type {Element} */ (anchor.parentNode);\n\n\t\t\tclear_text_content(parent_node);\n\t\t\tparent_node.append(anchor);\n\n\t\t\tstate.items.clear();\n\t\t}\n\n\t\tdestroy_effects(state, to_destroy, !fast_path);\n\t} else {\n\t\tgroup = {\n\t\t\tpending: new Set(to_destroy),\n\t\t\tdone: new Set()\n\t\t};\n\n\t\t(state.outrogroups ??= new Set()).add(group);\n\t}\n}\n\n/**\n * @param {EachState} state\n * @param {Effect[]} to_destroy\n * @param {boolean} remove_dom\n */\nfunction destroy_effects(state, to_destroy, remove_dom = true) {\n\t/** @type {Set<Effect> | undefined} */\n\tvar preserved_effects;\n\n\t// The loop-in-a-loop isn't ideal, but we should only hit this in relatively rare cases\n\tif (state.pending.size > 0) {\n\t\tpreserved_effects = new Set();\n\n\t\tfor (const keys of state.pending.values()) {\n\t\t\tfor (const key of keys) {\n\t\t\t\tpreserved_effects.add(/** @type {EachItem} */ (state.items.get(key)).e);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (var i = 0; i < to_destroy.length; i++) {\n\t\tvar e = to_destroy[i];\n\n\t\tif (preserved_effects?.has(e)) {\n\t\t\te.f |= EFFECT_OFFSCREEN;\n\n\t\t\tconst fragment = document.createDocumentFragment();\n\t\t\tmove_effect(e, fragment);\n\t\t} else {\n\t\t\tdestroy_effect(to_destroy[i], remove_dom);\n\t\t}\n\t}\n}\n\n/** @type {TemplateNode} */\nvar offscreen_anchor;\n\n/**\n * @template V\n * @param {Element | Comment} node The next sibling node, or the parent node if this is a 'controlled' block\n * @param {number} flags\n * @param {() => V[]} get_collection\n * @param {(value: V, index: number) => any} get_key\n * @param {(anchor: Node, item: MaybeSource<V>, index: MaybeSource<number>) => void} render_fn\n * @param {null | ((anchor: Node) => void)} fallback_fn\n * @returns {void}\n */\nexport function each(node, flags, get_collection, get_key, render_fn, fallback_fn = null) {\n\tvar anchor = node;\n\n\t/** @type {Map<any, EachItem>} */\n\tvar items = new Map();\n\n\tvar is_controlled = (flags & EACH_IS_CONTROLLED) !== 0;\n\n\tif (is_controlled) {\n\t\tvar parent_node = /** @type {Element} */ (node);\n\n\t\tanchor = hydrating\n\t\t\t? set_hydrate_node(get_first_child(parent_node))\n\t\t\t: parent_node.appendChild(create_text());\n\t}\n\n\tif (hydrating) {\n\t\thydrate_next();\n\t}\n\n\t/** @type {Effect | null} */\n\tvar fallback = null;\n\n\t// TODO: ideally we could use derived for runes mode but because of the ability\n\t// to use a store which can be mutated, we can't do that here as mutating a store\n\t// will still result in the collection array being the same from the store\n\tvar each_array = derived_safe_equal(() => {\n\t\tvar collection = get_collection();\n\n\t\treturn is_array(collection) ? collection : collection == null ? [] : array_from(collection);\n\t});\n\n\tif (DEV) {\n\t\ttag(each_array, '{#each ...}');\n\t}\n\n\t/** @type {V[]} */\n\tvar array;\n\n\t/** @type {Map<Batch, Set<any>>} */\n\tvar pending = new Map();\n\n\tvar first_run = true;\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\tfunction commit(batch) {\n\t\tif ((state.effect.f & DESTROYED) !== 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tstate.pending.delete(batch);\n\n\t\tstate.fallback = fallback;\n\t\treconcile(state, array, anchor, flags, get_key);\n\n\t\tif (fallback !== null) {\n\t\t\tif (array.length === 0) {\n\t\t\t\tif ((fallback.f & EFFECT_OFFSCREEN) === 0) {\n\t\t\t\t\tresume_effect(fallback);\n\t\t\t\t} else {\n\t\t\t\t\tfallback.f ^= EFFECT_OFFSCREEN;\n\t\t\t\t\tmove(fallback, null, anchor);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpause_effect(fallback, () => {\n\t\t\t\t\t// TODO only null out if no pending batch needs it,\n\t\t\t\t\t// otherwise re-add `fallback.fragment` and move the\n\t\t\t\t\t// effect into it\n\t\t\t\t\tfallback = null;\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\tfunction discard(batch) {\n\t\tstate.pending.delete(batch);\n\t}\n\n\tvar effect = block(() => {\n\t\tarray = /** @type {V[]} */ (get(each_array));\n\t\tvar length = array.length;\n\n\t\t/** `true` if there was a hydration mismatch. Needs to be a `let` or else it isn't treeshaken out */\n\t\tlet mismatch = false;\n\n\t\tif (hydrating) {\n\t\t\tvar is_else = read_hydration_instruction(anchor) === HYDRATION_START_ELSE;\n\n\t\t\tif (is_else !== (length === 0)) {\n\t\t\t\t// hydration mismatch — remove the server-rendered DOM and start over\n\t\t\t\tanchor = skip_nodes();\n\n\t\t\t\tset_hydrate_node(anchor);\n\t\t\t\tset_hydrating(false);\n\t\t\t\tmismatch = true;\n\t\t\t}\n\t\t}\n\n\t\tvar keys = new Set();\n\t\tvar batch = /** @type {Batch} */ (current_batch);\n\t\tvar defer = should_defer_append();\n\n\t\tfor (var index = 0; index < length; index += 1) {\n\t\t\tif (\n\t\t\t\thydrating &&\n\t\t\t\thydrate_node.nodeType === COMMENT_NODE &&\n\t\t\t\t/** @type {Comment} */ (hydrate_node).data === HYDRATION_END\n\t\t\t) {\n\t\t\t\t// The server rendered fewer items than expected,\n\t\t\t\t// so break out and continue appending non-hydrated items\n\t\t\t\tanchor = /** @type {Comment} */ (hydrate_node);\n\t\t\t\tmismatch = true;\n\t\t\t\tset_hydrating(false);\n\t\t\t}\n\n\t\t\tvar value = array[index];\n\t\t\tvar key = get_key(value, index);\n\n\t\t\tif (DEV) {\n\t\t\t\t// Check that the key function is idempotent (returns the same value when called twice)\n\t\t\t\tvar key_again = get_key(value, index);\n\t\t\t\tif (key !== key_again) {\n\t\t\t\t\te.each_key_volatile(String(index), String(key), String(key_again));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar item = first_run ? null : items.get(key);\n\n\t\t\tif (item) {\n\t\t\t\t// update before reconciliation, to trigger any async updates\n\t\t\t\tif (item.v) internal_set(item.v, value);\n\t\t\t\tif (item.i) internal_set(item.i, index);\n\n\t\t\t\tif (defer) {\n\t\t\t\t\tbatch.unskip_effect(item.e);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\titem = create_item(\n\t\t\t\t\titems,\n\t\t\t\t\tfirst_run ? anchor : (offscreen_anchor ??= create_text()),\n\t\t\t\t\tvalue,\n\t\t\t\t\tkey,\n\t\t\t\t\tindex,\n\t\t\t\t\trender_fn,\n\t\t\t\t\tflags,\n\t\t\t\t\tget_collection\n\t\t\t\t);\n\n\t\t\t\tif (!first_run) {\n\t\t\t\t\titem.e.f |= EFFECT_OFFSCREEN;\n\t\t\t\t}\n\n\t\t\t\titems.set(key, item);\n\t\t\t}\n\n\t\t\tkeys.add(key);\n\t\t}\n\n\t\tif (length === 0 && fallback_fn && !fallback) {\n\t\t\tif (first_run) {\n\t\t\t\tfallback = branch(() => fallback_fn(anchor));\n\t\t\t} else {\n\t\t\t\tfallback = branch(() => fallback_fn((offscreen_anchor ??= create_text())));\n\t\t\t\tfallback.f |= EFFECT_OFFSCREEN;\n\t\t\t}\n\t\t}\n\n\t\tif (length > keys.size) {\n\t\t\tif (DEV) {\n\t\t\t\tvalidate_each_keys(array, get_key);\n\t\t\t} else {\n\t\t\t\t// in prod, the additional information isn't printed, so don't bother computing it\n\t\t\t\te.each_key_duplicate('', '', '');\n\t\t\t}\n\t\t}\n\n\t\t// remove excess nodes\n\t\tif (hydrating && length > 0) {\n\t\t\tset_hydrate_node(skip_nodes());\n\t\t}\n\n\t\tif (!first_run) {\n\t\t\tpending.set(batch, keys);\n\n\t\t\tif (defer) {\n\t\t\t\tfor (const [key, item] of items) {\n\t\t\t\t\tif (!keys.has(key)) {\n\t\t\t\t\t\tbatch.skip_effect(item.e);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbatch.oncommit(commit);\n\t\t\t\tbatch.ondiscard(discard);\n\t\t\t} else {\n\t\t\t\tcommit(batch);\n\t\t\t}\n\t\t}\n\n\t\tif (mismatch) {\n\t\t\t// continue in hydration mode\n\t\t\tset_hydrating(true);\n\t\t}\n\n\t\t// When we mount the each block for the first time, the collection won't be\n\t\t// connected to this effect as the effect hasn't finished running yet and its deps\n\t\t// won't be assigned. However, it's possible that when reconciling the each block\n\t\t// that a mutation occurred and it's made the collection MAYBE_DIRTY, so reading the\n\t\t// collection again can provide consistency to the reactive graph again as the deriveds\n\t\t// will now be `CLEAN`.\n\t\tget(each_array);\n\t});\n\n\t/** @type {EachState} */\n\tvar state = { effect, flags, items, pending, outrogroups: null, fallback };\n\n\tfirst_run = false;\n\n\tif (hydrating) {\n\t\tanchor = hydrate_node;\n\t}\n}\n\n/**\n * Skip past any non-branch effects (which could be created with `createSubscriber`, for example) to find the next branch effect\n * @param {Effect | null} effect\n * @returns {Effect | null}\n */\nfunction skip_to_branch(effect) {\n\twhile (effect !== null && (effect.f & BRANCH_EFFECT) === 0) {\n\t\teffect = effect.next;\n\t}\n\treturn effect;\n}\n\n/**\n * Add, remove, or reorder items output by an each block as its input changes\n * @template V\n * @param {EachState} state\n * @param {Array<V>} array\n * @param {Element | Comment | Text} anchor\n * @param {number} flags\n * @param {(value: V, index: number) => any} get_key\n * @returns {void}\n */\nfunction reconcile(state, array, anchor, flags, get_key) {\n\tvar is_animated = (flags & EACH_IS_ANIMATED) !== 0;\n\n\tvar length = array.length;\n\tvar items = state.items;\n\tvar current = skip_to_branch(state.effect.first);\n\n\t/** @type {undefined | Set<Effect>} */\n\tvar seen;\n\n\t/** @type {Effect | null} */\n\tvar prev = null;\n\n\t/** @type {undefined | Set<Effect>} */\n\tvar to_animate;\n\n\t/** @type {Effect[]} */\n\tvar matched = [];\n\n\t/** @type {Effect[]} */\n\tvar stashed = [];\n\n\t/** @type {V} */\n\tvar value;\n\n\t/** @type {any} */\n\tvar key;\n\n\t/** @type {Effect | undefined} */\n\tvar effect;\n\n\t/** @type {number} */\n\tvar i;\n\n\tif (is_animated) {\n\t\tfor (i = 0; i < length; i += 1) {\n\t\t\tvalue = array[i];\n\t\t\tkey = get_key(value, i);\n\t\t\teffect = /** @type {EachItem} */ (items.get(key)).e;\n\n\t\t\t// offscreen == coming in now, no animation in that case,\n\t\t\t// else this would happen https://github.com/sveltejs/svelte/issues/17181\n\t\t\tif ((effect.f & EFFECT_OFFSCREEN) === 0) {\n\t\t\t\teffect.nodes?.a?.measure();\n\t\t\t\t(to_animate ??= new Set()).add(effect);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (i = 0; i < length; i += 1) {\n\t\tvalue = array[i];\n\t\tkey = get_key(value, i);\n\n\t\teffect = /** @type {EachItem} */ (items.get(key)).e;\n\n\t\tif (state.outrogroups !== null) {\n\t\t\tfor (const group of state.outrogroups) {\n\t\t\t\tgroup.pending.delete(effect);\n\t\t\t\tgroup.done.delete(effect);\n\t\t\t}\n\t\t}\n\n\t\tif ((effect.f & INERT) !== 0) {\n\t\t\tresume_effect(effect);\n\t\t\tif (is_animated) {\n\t\t\t\teffect.nodes?.a?.unfix();\n\t\t\t\t(to_animate ??= new Set()).delete(effect);\n\t\t\t}\n\t\t}\n\n\t\tif ((effect.f & EFFECT_OFFSCREEN) !== 0) {\n\t\t\teffect.f ^= EFFECT_OFFSCREEN;\n\n\t\t\tif (effect === current) {\n\t\t\t\tmove(effect, null, anchor);\n\t\t\t} else {\n\t\t\t\tvar next = prev ? prev.next : current;\n\n\t\t\t\tif (effect === state.effect.last) {\n\t\t\t\t\tstate.effect.last = effect.prev;\n\t\t\t\t}\n\n\t\t\t\tif (effect.prev) effect.prev.next = effect.next;\n\t\t\t\tif (effect.next) effect.next.prev = effect.prev;\n\t\t\t\tlink(state, prev, effect);\n\t\t\t\tlink(state, effect, next);\n\n\t\t\t\tmove(effect, next, anchor);\n\t\t\t\tprev = effect;\n\n\t\t\t\tmatched = [];\n\t\t\t\tstashed = [];\n\n\t\t\t\tcurrent = skip_to_branch(prev.next);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (effect !== current) {\n\t\t\tif (seen !== undefined && seen.has(effect)) {\n\t\t\t\tif (matched.length < stashed.length) {\n\t\t\t\t\t// more efficient to move later items to the front\n\t\t\t\t\tvar start = stashed[0];\n\t\t\t\t\tvar j;\n\n\t\t\t\t\tprev = start.prev;\n\n\t\t\t\t\tvar a = matched[0];\n\t\t\t\t\tvar b = matched[matched.length - 1];\n\n\t\t\t\t\tfor (j = 0; j < matched.length; j += 1) {\n\t\t\t\t\t\tmove(matched[j], start, anchor);\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (j = 0; j < stashed.length; j += 1) {\n\t\t\t\t\t\tseen.delete(stashed[j]);\n\t\t\t\t\t}\n\n\t\t\t\t\tlink(state, a.prev, b.next);\n\t\t\t\t\tlink(state, prev, a);\n\t\t\t\t\tlink(state, b, start);\n\n\t\t\t\t\tcurrent = start;\n\t\t\t\t\tprev = b;\n\t\t\t\t\ti -= 1;\n\n\t\t\t\t\tmatched = [];\n\t\t\t\t\tstashed = [];\n\t\t\t\t} else {\n\t\t\t\t\t// more efficient to move earlier items to the back\n\t\t\t\t\tseen.delete(effect);\n\t\t\t\t\tmove(effect, current, anchor);\n\n\t\t\t\t\tlink(state, effect.prev, effect.next);\n\t\t\t\t\tlink(state, effect, prev === null ? state.effect.first : prev.next);\n\t\t\t\t\tlink(state, prev, effect);\n\n\t\t\t\t\tprev = effect;\n\t\t\t\t}\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tmatched = [];\n\t\t\tstashed = [];\n\n\t\t\twhile (current !== null && current !== effect) {\n\t\t\t\t(seen ??= new Set()).add(current);\n\t\t\t\tstashed.push(current);\n\t\t\t\tcurrent = skip_to_branch(current.next);\n\t\t\t}\n\n\t\t\tif (current === null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif ((effect.f & EFFECT_OFFSCREEN) === 0) {\n\t\t\tmatched.push(effect);\n\t\t}\n\n\t\tprev = effect;\n\t\tcurrent = skip_to_branch(effect.next);\n\t}\n\n\tif (state.outrogroups !== null) {\n\t\tfor (const group of state.outrogroups) {\n\t\t\tif (group.pending.size === 0) {\n\t\t\t\tdestroy_effects(state, array_from(group.done));\n\t\t\t\tstate.outrogroups?.delete(group);\n\t\t\t}\n\t\t}\n\n\t\tif (state.outrogroups.size === 0) {\n\t\t\tstate.outrogroups = null;\n\t\t}\n\t}\n\n\tif (current !== null || seen !== undefined) {\n\t\t/** @type {Effect[]} */\n\t\tvar to_destroy = [];\n\n\t\tif (seen !== undefined) {\n\t\t\tfor (effect of seen) {\n\t\t\t\tif ((effect.f & INERT) === 0) {\n\t\t\t\t\tto_destroy.push(effect);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\twhile (current !== null) {\n\t\t\t// If the each block isn't inert, then inert effects are currently outroing and will be removed once the transition is finished\n\t\t\tif ((current.f & INERT) === 0 && current !== state.fallback) {\n\t\t\t\tto_destroy.push(current);\n\t\t\t}\n\n\t\t\tcurrent = skip_to_branch(current.next);\n\t\t}\n\n\t\tvar destroy_length = to_destroy.length;\n\n\t\tif (destroy_length > 0) {\n\t\t\tvar controlled_anchor = (flags & EACH_IS_CONTROLLED) !== 0 && length === 0 ? anchor : null;\n\n\t\t\tif (is_animated) {\n\t\t\t\tfor (i = 0; i < destroy_length; i += 1) {\n\t\t\t\t\tto_destroy[i].nodes?.a?.measure();\n\t\t\t\t}\n\n\t\t\t\tfor (i = 0; i < destroy_length; i += 1) {\n\t\t\t\t\tto_destroy[i].nodes?.a?.fix();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpause_effects(state, to_destroy, controlled_anchor);\n\t\t}\n\t}\n\n\tif (is_animated) {\n\t\tqueue_micro_task(() => {\n\t\t\tif (to_animate === undefined) return;\n\t\t\tfor (effect of to_animate) {\n\t\t\t\teffect.nodes?.a?.apply();\n\t\t\t}\n\t\t});\n\t}\n}\n\n/**\n * @template V\n * @param {Map<any, EachItem>} items\n * @param {Node} anchor\n * @param {V} value\n * @param {unknown} key\n * @param {number} index\n * @param {(anchor: Node, item: V | Source<V>, index: number | Value<number>, collection: () => V[]) => void} render_fn\n * @param {number} flags\n * @param {() => V[]} get_collection\n * @returns {EachItem}\n */\nfunction create_item(items, anchor, value, key, index, render_fn, flags, get_collection) {\n\tvar v =\n\t\t(flags & EACH_ITEM_REACTIVE) !== 0\n\t\t\t? (flags & EACH_ITEM_IMMUTABLE) === 0\n\t\t\t\t? mutable_source(value, false, false)\n\t\t\t\t: source(value)\n\t\t\t: null;\n\n\tvar i = (flags & EACH_INDEX_REACTIVE) !== 0 ? source(index) : null;\n\n\tif (DEV && v) {\n\t\t// For tracing purposes, we need to link the source signal we create with the\n\t\t// collection + index so that tracing works as intended\n\t\tv.trace = () => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unused-expressions\n\t\t\tget_collection()[i?.v ?? index];\n\t\t};\n\t}\n\n\treturn {\n\t\tv,\n\t\ti,\n\t\te: branch(() => {\n\t\t\trender_fn(anchor, v ?? value, i ?? index, get_collection);\n\n\t\t\treturn () => {\n\t\t\t\titems.delete(key);\n\t\t\t};\n\t\t})\n\t};\n}\n\n/**\n * @param {Effect} effect\n * @param {Effect | null} next\n * @param {Text | Element | Comment} anchor\n */\nfunction move(effect, next, anchor) {\n\tif (!effect.nodes) return;\n\n\tvar node = effect.nodes.start;\n\tvar end = effect.nodes.end;\n\n\tvar dest =\n\t\tnext && (next.f & EFFECT_OFFSCREEN) === 0\n\t\t\t? /** @type {EffectNodes} */ (next.nodes).start\n\t\t\t: anchor;\n\n\twhile (node !== null) {\n\t\tvar next_node = /** @type {TemplateNode} */ (get_next_sibling(node));\n\t\tdest.before(node);\n\n\t\tif (node === end) {\n\t\t\treturn;\n\t\t}\n\n\t\tnode = next_node;\n\t}\n}\n\n/**\n * @param {EachState} state\n * @param {Effect | null} prev\n * @param {Effect | null} next\n */\nfunction link(state, prev, next) {\n\tif (prev === null) {\n\t\tstate.effect.first = next;\n\t} else {\n\t\tprev.next = next;\n\t}\n\n\tif (next === null) {\n\t\tstate.effect.last = prev;\n\t} else {\n\t\tnext.prev = prev;\n\t}\n}\n\n/**\n * @param {Array<any>} array\n * @param {(item: any, index: number) => string} key_fn\n * @returns {void}\n */\nfunction validate_each_keys(array, key_fn) {\n\tconst keys = new Map();\n\tconst length = array.length;\n\n\tfor (let i = 0; i < length; i++) {\n\t\tconst key = key_fn(array[i], i);\n\n\t\tif (keys.has(key)) {\n\t\t\tconst a = String(keys.get(key));\n\t\t\tconst b = String(i);\n\n\t\t\t/** @type {string | null} */\n\t\t\tlet k = String(key);\n\t\t\tif (k.startsWith('[object ')) k = null;\n\n\t\t\te.each_key_duplicate(a, b, k);\n\t\t}\n\n\t\tkeys.set(key, i);\n\t}\n}\n","/** @import { Effect, TemplateNode } from '#client' */\n/** @import {} from 'trusted-types' */\nimport {\n\tFILENAME,\n\tHYDRATION_ERROR,\n\tNAMESPACE_SVG,\n\tNAMESPACE_MATHML\n} from '../../../../constants.js';\nimport { remove_effect_dom, template_effect } from '../../reactivity/effects.js';\nimport { hydrate_next, hydrate_node, hydrating, set_hydrate_node } from '../hydration.js';\n\nimport { assign_nodes } from '../template.js';\nimport * as w from '../../warnings.js';\nimport { hash, sanitize_location } from '../../../../utils.js';\nimport { DEV } from 'esm-env';\nimport { dev_current_component_function } from '../../context.js';\nimport { create_element, get_first_child, get_next_sibling } from '../operations.js';\nimport { active_effect } from '../../runtime.js';\nimport { COMMENT_NODE } from '#client/constants';\n\n/**\n * @param {Element} element\n * @param {string | null} server_hash\n * @param {string | TrustedHTML} value\n */\nfunction check_hash(element, server_hash, value) {\n\tif (!server_hash || server_hash === hash(String(value ?? ''))) return;\n\n\tlet location;\n\n\t// @ts-expect-error\n\tconst loc = element.__svelte_meta?.loc;\n\tif (loc) {\n\t\tlocation = `near ${loc.file}:${loc.line}:${loc.column}`;\n\t} else if (dev_current_component_function?.[FILENAME]) {\n\t\tlocation = `in ${dev_current_component_function[FILENAME]}`;\n\t}\n\n\tw.hydration_html_changed(sanitize_location(location));\n}\n\n/**\n * @param {Element | Text | Comment} node\n * @param {() => string | TrustedHTML} get_value\n * @param {boolean} [is_controlled]\n * @param {boolean} [svg]\n * @param {boolean} [mathml]\n * @param {boolean} [skip_warning]\n * @returns {void}\n */\nexport function html(\n\tnode,\n\tget_value,\n\tis_controlled = false,\n\tsvg = false,\n\tmathml = false,\n\tskip_warning = false\n) {\n\tvar anchor = node;\n\n\t/** @type {string | TrustedHTML} */\n\tvar value = '';\n\n\tif (is_controlled) {\n\t\tvar parent_node = /** @type {Element} */ (node);\n\n\t\tif (hydrating) {\n\t\t\tanchor = set_hydrate_node(get_first_child(parent_node));\n\t\t}\n\t}\n\n\ttemplate_effect(() => {\n\t\tvar effect = /** @type {Effect} */ (active_effect);\n\n\t\tif (value === (value = get_value() ?? '')) {\n\t\t\tif (hydrating) hydrate_next();\n\t\t\treturn;\n\t\t}\n\n\t\tif (is_controlled && !hydrating) {\n\t\t\t// When @html is the only child, use innerHTML directly.\n\t\t\t// This also handles contenteditable, where the user may delete the anchor comment.\n\t\t\teffect.nodes = null;\n\t\t\tparent_node.innerHTML = /** @type {string} */ (value);\n\n\t\t\tif (value !== '') {\n\t\t\t\tassign_nodes(\n\t\t\t\t\t/** @type {TemplateNode} */ (get_first_child(parent_node)),\n\t\t\t\t\t/** @type {TemplateNode} */ (parent_node.lastChild)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif (effect.nodes !== null) {\n\t\t\tremove_effect_dom(effect.nodes.start, /** @type {TemplateNode} */ (effect.nodes.end));\n\t\t\teffect.nodes = null;\n\t\t}\n\n\t\tif (value === '') return;\n\n\t\tif (hydrating) {\n\t\t\t// We're deliberately not trying to repair mismatches between server and client,\n\t\t\t// as it's costly and error-prone (and it's an edge case to have a mismatch anyway)\n\t\t\tvar hash = /** @type {Comment} */ (hydrate_node).data;\n\n\t\t\t/** @type {TemplateNode | null} */\n\t\t\tvar next = hydrate_next();\n\t\t\tvar last = next;\n\n\t\t\twhile (\n\t\t\t\tnext !== null &&\n\t\t\t\t(next.nodeType !== COMMENT_NODE || /** @type {Comment} */ (next).data !== '')\n\t\t\t) {\n\t\t\t\tlast = next;\n\t\t\t\tnext = get_next_sibling(next);\n\t\t\t}\n\n\t\t\tif (next === null) {\n\t\t\t\tw.hydration_mismatch();\n\t\t\t\tthrow HYDRATION_ERROR;\n\t\t\t}\n\n\t\t\tif (DEV && !skip_warning) {\n\t\t\t\tcheck_hash(/** @type {Element} */ (next.parentNode), hash, value);\n\t\t\t}\n\n\t\t\tassign_nodes(hydrate_node, last);\n\t\t\tanchor = set_hydrate_node(next);\n\t\t\treturn;\n\t\t}\n\n\t\t// Don't use create_fragment_with_script_from_html here because that would mean script tags are executed.\n\t\t// @html is basically `.innerHTML = ...` and that doesn't execute scripts either due to security reasons.\n\t\t// Use a <template>, <svg>, or <math> wrapper depending on context. If value is a TrustedHTML object,\n\t\t// it will be assigned directly to innerHTML without coercion — this allows {@html policy.createHTML(...)} to work.\n\t\tvar ns = svg ? NAMESPACE_SVG : mathml ? NAMESPACE_MATHML : undefined;\n\t\tvar wrapper = /** @type {HTMLTemplateElement | SVGElement | MathMLElement} */ (\n\t\t\tcreate_element(svg ? 'svg' : mathml ? 'math' : 'template', ns)\n\t\t);\n\t\twrapper.innerHTML = /** @type {any} */ (value);\n\n\t\t/** @type {DocumentFragment | Element} */\n\t\tvar node = svg || mathml ? wrapper : /** @type {HTMLTemplateElement} */ (wrapper).content;\n\n\t\tassign_nodes(\n\t\t\t/** @type {TemplateNode} */ (get_first_child(node)),\n\t\t\t/** @type {TemplateNode} */ (node.lastChild)\n\t\t);\n\n\t\tif (svg || mathml) {\n\t\t\twhile (get_first_child(node)) {\n\t\t\t\tanchor.before(/** @type {TemplateNode} */ (get_first_child(node)));\n\t\t\t}\n\t\t} else {\n\t\t\tanchor.before(node);\n\t\t}\n\t});\n}\n","import { hydrate_next, hydrating } from '../hydration.js';\n\n/**\n * @param {Comment} anchor\n * @param {Record<string, any>} $$props\n * @param {string} name\n * @param {Record<string, unknown>} slot_props\n * @param {null | ((anchor: Comment) => void)} fallback_fn\n */\nexport function slot(anchor, $$props, name, slot_props, fallback_fn) {\n\tif (hydrating) {\n\t\thydrate_next();\n\t}\n\n\tvar slot_fn = $$props.$$slots?.[name];\n\t// Interop: Can use snippets to fill slots\n\tvar is_interop = false;\n\tif (slot_fn === true) {\n\t\tslot_fn = $$props[name === 'default' ? 'children' : name];\n\t\tis_interop = true;\n\t}\n\n\tif (slot_fn === undefined) {\n\t\tif (fallback_fn !== null) {\n\t\t\tfallback_fn(anchor);\n\t\t}\n\t} else {\n\t\tslot_fn(anchor, is_interop ? () => slot_props : slot_props);\n\t}\n}\n\n/**\n * @param {Record<string, any>} props\n * @returns {Record<string, boolean>}\n */\nexport function sanitize_slots(props) {\n\t/** @type {Record<string, boolean>} */\n\tconst sanitized = {};\n\tif (props.children) sanitized.default = true;\n\tfor (const key in props.$$slots) {\n\t\tsanitized[key] = true;\n\t}\n\treturn sanitized;\n}\n","/** @import { TemplateNode, Dom } from '#client' */\nimport { EFFECT_TRANSPARENT } from '#client/constants';\nimport { block } from '../../reactivity/effects.js';\nimport {\n\thydrate_next,\n\thydrate_node,\n\thydrating,\n\tread_hydration_instruction,\n\tset_hydrate_node,\n\tset_hydrating,\n\tskip_nodes\n} from '../hydration.js';\nimport { BranchManager } from './branches.js';\nimport { HYDRATION_START, HYDRATION_START_ELSE } from '../../../../constants.js';\n\n/**\n * @template P\n * @template {(props: P) => void} C\n * @param {TemplateNode} node\n * @param {() => C} get_component\n * @param {(anchor: TemplateNode, component: C) => Dom | void} render_fn\n * @returns {void}\n */\nexport function component(node, get_component, render_fn) {\n\t/** @type {TemplateNode | undefined} */\n\tvar hydration_start_node;\n\n\tif (hydrating) {\n\t\thydration_start_node = hydrate_node;\n\t\thydrate_next();\n\t}\n\n\tvar branches = new BranchManager(node);\n\n\tblock(() => {\n\t\tvar component = get_component() ?? null;\n\n\t\tif (hydrating) {\n\t\t\tvar data = read_hydration_instruction(/** @type {TemplateNode} */ (hydration_start_node));\n\n\t\t\tvar server_had_component = data === HYDRATION_START;\n\t\t\tvar client_has_component = component !== null;\n\n\t\t\tif (server_had_component !== client_has_component) {\n\t\t\t\t// Hydration mismatch: skip the server-rendered nodes and render fresh\n\t\t\t\tvar anchor = skip_nodes();\n\n\t\t\t\tset_hydrate_node(anchor);\n\t\t\t\tbranches.anchor = anchor;\n\n\t\t\t\tset_hydrating(false);\n\t\t\t\tbranches.ensure(component, component && ((target) => render_fn(target, component)));\n\t\t\t\tset_hydrating(true);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tbranches.ensure(component, component && ((target) => render_fn(target, component)));\n\t}, EFFECT_TRANSPARENT);\n}\n","/** @import { Raf } from '#client' */\nimport { noop } from '../shared/utils.js';\n\nimport { BROWSER } from 'esm-env';\n\nconst now = BROWSER ? () => performance.now() : () => Date.now();\n\n/** @type {Raf} */\nexport const raf = {\n\t// don't access requestAnimationFrame eagerly outside method\n\t// this allows basic testing of user code without JSDOM\n\t// bunder will eval and remove ternary when the user's app is built\n\ttick: /** @param {any} _ */ (_) => (BROWSER ? requestAnimationFrame : noop)(_),\n\tnow: () => now(),\n\ttasks: new Set()\n};\n","/** @import { TaskCallback, Task, TaskEntry } from '#client' */\nimport { raf } from './timing.js';\n\n// TODO move this into timing.js where it probably belongs\n\n/**\n * @returns {void}\n */\nfunction run_tasks() {\n\t// use `raf.now()` instead of the `requestAnimationFrame` callback argument, because\n\t// otherwise things can get wonky https://github.com/sveltejs/svelte/pull/14541\n\tconst now = raf.now();\n\n\traf.tasks.forEach((task) => {\n\t\tif (!task.c(now)) {\n\t\t\traf.tasks.delete(task);\n\t\t\ttask.f();\n\t\t}\n\t});\n\n\tif (raf.tasks.size !== 0) {\n\t\traf.tick(run_tasks);\n\t}\n}\n\n/**\n * Creates a new task that runs on each raf frame\n * until it returns a falsy value or is aborted\n * @param {TaskCallback} callback\n * @returns {Task}\n */\nexport function loop(callback) {\n\t/** @type {TaskEntry} */\n\tlet task;\n\n\tif (raf.tasks.size === 0) {\n\t\traf.tick(run_tasks);\n\t}\n\n\treturn {\n\t\tpromise: new Promise((fulfill) => {\n\t\t\traf.tasks.add((task = { c: callback, f: fulfill }));\n\t\t}),\n\t\tabort() {\n\t\t\traf.tasks.delete(task);\n\t\t}\n\t};\n}\n","/** @import { AnimateFn, Animation, AnimationConfig, EachItem, Effect, EffectNodes, TransitionFn, TransitionManager } from '#client' */\nimport { noop, is_function } from '../../../shared/utils.js';\nimport { effect } from '../../reactivity/effects.js';\nimport { active_effect, untrack } from '../../runtime.js';\nimport { loop } from '../../loop.js';\nimport { should_intro } from '../../render.js';\nimport { TRANSITION_GLOBAL, TRANSITION_IN, TRANSITION_OUT } from '../../../../constants.js';\nimport { BLOCK_EFFECT, REACTION_RAN, EFFECT_TRANSPARENT } from '#client/constants';\nimport { queue_micro_task } from '../task.js';\nimport { without_reactive_context } from './bindings/shared.js';\n\n/**\n * @param {Element} element\n * @param {'introstart' | 'introend' | 'outrostart' | 'outroend'} type\n * @returns {void}\n */\nfunction dispatch_event(element, type) {\n\twithout_reactive_context(() => {\n\t\telement.dispatchEvent(new CustomEvent(type));\n\t});\n}\n\n/**\n * Converts a property to the camel-case format expected by Element.animate(), KeyframeEffect(), and KeyframeEffect.setKeyframes().\n * @param {string} style\n * @returns {string}\n */\nfunction css_property_to_camelcase(style) {\n\t// in compliance with spec\n\tif (style === 'float') return 'cssFloat';\n\tif (style === 'offset') return 'cssOffset';\n\n\t// do not rename custom @properties\n\tif (style.startsWith('--')) return style;\n\n\tconst parts = style.split('-');\n\tif (parts.length === 1) return parts[0];\n\treturn (\n\t\tparts[0] +\n\t\tparts\n\t\t\t.slice(1)\n\t\t\t.map(/** @param {any} word */ (word) => word[0].toUpperCase() + word.slice(1))\n\t\t\t.join('')\n\t);\n}\n\n/**\n * @param {string} css\n * @returns {Keyframe}\n */\nfunction css_to_keyframe(css) {\n\t/** @type {Keyframe} */\n\tconst keyframe = {};\n\tconst parts = css.split(';');\n\tfor (const part of parts) {\n\t\tconst [property, value] = part.split(':');\n\t\tif (!property || value === undefined) break;\n\n\t\tconst formatted_property = css_property_to_camelcase(property.trim());\n\t\tkeyframe[formatted_property] = value.trim();\n\t}\n\treturn keyframe;\n}\n\n/** @param {number} t */\nconst linear = (t) => t;\n\n/** @type {Effect | null} */\nlet animation_effect_override = null;\n\n/** @param {Effect | null} v */\nexport function set_animation_effect_override(v) {\n\tanimation_effect_override = v;\n}\n\n/**\n * Called inside keyed `{#each ...}` blocks (as `$.animation(...)`). This creates an animation manager\n * and attaches it to the block, so that moves can be animated following reconciliation.\n * @template P\n * @param {Element} element\n * @param {() => AnimateFn<P | undefined>} get_fn\n * @param {(() => P) | null} get_params\n */\nexport function animation(element, get_fn, get_params) {\n\tvar effect = animation_effect_override ?? /** @type {Effect} */ (active_effect);\n\tvar nodes = /** @type {EffectNodes} */ (effect.nodes);\n\n\t/** @type {DOMRect} */\n\tvar from;\n\n\t/** @type {DOMRect} */\n\tvar to;\n\n\t/** @type {Animation | undefined} */\n\tvar animation;\n\n\t/** @type {null | { position: string, width: string, height: string, transform: string }} */\n\tvar original_styles = null;\n\n\tnodes.a ??= {\n\t\telement,\n\t\tmeasure() {\n\t\t\tfrom = this.element.getBoundingClientRect();\n\t\t},\n\t\tapply() {\n\t\t\tanimation?.abort();\n\n\t\t\tto = this.element.getBoundingClientRect();\n\n\t\t\tif (\n\t\t\t\tfrom.left !== to.left ||\n\t\t\t\tfrom.right !== to.right ||\n\t\t\t\tfrom.top !== to.top ||\n\t\t\t\tfrom.bottom !== to.bottom\n\t\t\t) {\n\t\t\t\tconst options = get_fn()(this.element, { from, to }, get_params?.());\n\n\t\t\t\tanimation = animate(this.element, options, undefined, 1, () => {\n\t\t\t\t\tanimation?.abort();\n\t\t\t\t\tanimation = undefined;\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\tfix() {\n\t\t\t// If an animation is already running, transforming the element is likely to fail,\n\t\t\t// because the styles applied by the animation take precedence. In the case of crossfade,\n\t\t\t// that means the `translate(...)` of the crossfade transition overrules the `translate(...)`\n\t\t\t// we would apply below, leading to the element jumping somewhere to the top left.\n\t\t\tif (element.getAnimations().length) return;\n\n\t\t\t// It's important to destructure these to get fixed values - the object itself has getters,\n\t\t\t// and changing the style to 'absolute' can for example influence the width.\n\t\t\tvar { position, width, height } = getComputedStyle(element);\n\n\t\t\tif (position !== 'absolute' && position !== 'fixed') {\n\t\t\t\tvar style = /** @type {HTMLElement | SVGElement} */ (element).style;\n\n\t\t\t\toriginal_styles = {\n\t\t\t\t\tposition: style.position,\n\t\t\t\t\twidth: style.width,\n\t\t\t\t\theight: style.height,\n\t\t\t\t\ttransform: style.transform\n\t\t\t\t};\n\n\t\t\t\tstyle.position = 'absolute';\n\t\t\t\tstyle.width = width;\n\t\t\t\tstyle.height = height;\n\t\t\t\tvar to = element.getBoundingClientRect();\n\n\t\t\t\tif (from.left !== to.left || from.top !== to.top) {\n\t\t\t\t\tvar transform = `translate(${from.left - to.left}px, ${from.top - to.top}px)`;\n\t\t\t\t\tstyle.transform = style.transform ? `${style.transform} ${transform}` : transform;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tunfix() {\n\t\t\tif (original_styles) {\n\t\t\t\tvar style = /** @type {HTMLElement | SVGElement} */ (element).style;\n\n\t\t\t\tstyle.position = original_styles.position;\n\t\t\t\tstyle.width = original_styles.width;\n\t\t\t\tstyle.height = original_styles.height;\n\t\t\t\tstyle.transform = original_styles.transform;\n\t\t\t}\n\t\t}\n\t};\n\n\t// in the case of a `<svelte:element>`, it's possible for `$.animation(...)` to be called\n\t// when an animation manager already exists, if the tag changes. in that case, we need to\n\t// swap out the element rather than creating a new manager, in case it happened at the same\n\t// moment as a reconciliation\n\tnodes.a.element = element;\n}\n\n/**\n * Called inside block effects as `$.transition(...)`. This creates a transition manager and\n * attaches it to the current effect — later, inside `pause_effect` and `resume_effect`, we\n * use this to create `intro` and `outro` transitions.\n * @template P\n * @param {number} flags\n * @param {HTMLElement} element\n * @param {() => TransitionFn<P | undefined>} get_fn\n * @param {(() => P) | null} get_params\n * @returns {void}\n */\nexport function transition(flags, element, get_fn, get_params) {\n\tvar is_intro = (flags & TRANSITION_IN) !== 0;\n\tvar is_outro = (flags & TRANSITION_OUT) !== 0;\n\tvar is_both = is_intro && is_outro;\n\tvar is_global = (flags & TRANSITION_GLOBAL) !== 0;\n\n\t/** @type {'in' | 'out' | 'both'} */\n\tvar direction = is_both ? 'both' : is_intro ? 'in' : 'out';\n\n\t/** @type {AnimationConfig | ((opts: { direction: 'in' | 'out' }) => AnimationConfig) | undefined} */\n\tvar current_options;\n\n\tvar inert = element.inert;\n\n\t/**\n\t * The default overflow style, stashed so we can revert changes during the transition\n\t * that are necessary to work around a Safari <18 bug\n\t * TODO 6.0 remove this, if older versions of Safari have died out enough\n\t */\n\tvar overflow = element.style.overflow;\n\n\t/** @type {Animation | undefined} */\n\tvar intro;\n\n\t/** @type {Animation | undefined} */\n\tvar outro;\n\n\tfunction get_options() {\n\t\treturn without_reactive_context(() => {\n\t\t\t// If a transition is still ongoing, we use the existing options rather than generating\n\t\t\t// new ones. This ensures that reversible transitions reverse smoothly, rather than\n\t\t\t// jumping to a new spot because (for example) a different `duration` was used\n\t\t\treturn (current_options ??= get_fn()(element, get_params?.() ?? /** @type {P} */ ({}), {\n\t\t\t\tdirection\n\t\t\t}));\n\t\t});\n\t}\n\n\t/** @type {TransitionManager} */\n\tvar transition = {\n\t\tis_global,\n\t\tin() {\n\t\t\telement.inert = inert;\n\n\t\t\tif (!is_intro) {\n\t\t\t\toutro?.abort();\n\t\t\t\toutro?.reset?.();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (!is_outro) {\n\t\t\t\t// if we intro then outro then intro again, we want to abort the first intro,\n\t\t\t\t// if it's not a bidirectional transition\n\t\t\t\tintro?.abort();\n\t\t\t}\n\n\t\t\tintro = animate(element, get_options(), outro, 1, () => {\n\t\t\t\tdispatch_event(element, 'introend');\n\n\t\t\t\t// Ensure we cancel the animation to prevent leaking\n\t\t\t\tintro?.abort();\n\t\t\t\tintro = current_options = undefined;\n\n\t\t\t\telement.style.overflow = overflow;\n\t\t\t});\n\t\t},\n\t\tout(fn) {\n\t\t\tif (!is_outro) {\n\t\t\t\tfn?.();\n\t\t\t\tcurrent_options = undefined;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\telement.inert = true;\n\n\t\t\toutro = animate(element, get_options(), intro, 0, () => {\n\t\t\t\tdispatch_event(element, 'outroend');\n\t\t\t\tfn?.();\n\t\t\t});\n\t\t},\n\t\tstop: () => {\n\t\t\tintro?.abort();\n\t\t\toutro?.abort();\n\t\t}\n\t};\n\n\tvar e = /** @type {Effect & { nodes: EffectNodes }} */ (active_effect);\n\n\t(e.nodes.t ??= []).push(transition);\n\n\t// if this is a local transition, we only want to run it if the parent (branch) effect's\n\t// parent (block) effect is where the state change happened. we can determine that by\n\t// looking at whether the block effect is currently initializing\n\tif (is_intro && should_intro) {\n\t\tvar run = is_global;\n\n\t\tif (!run) {\n\t\t\tvar block = /** @type {Effect | null} */ (e.parent);\n\n\t\t\t// skip over transparent blocks (e.g. snippets, else-if blocks)\n\t\t\twhile (block && (block.f & EFFECT_TRANSPARENT) !== 0) {\n\t\t\t\twhile ((block = block.parent)) {\n\t\t\t\t\tif ((block.f & BLOCK_EFFECT) !== 0) break;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\trun = !block || (block.f & REACTION_RAN) !== 0;\n\t\t}\n\n\t\tif (run) {\n\t\t\teffect(() => {\n\t\t\t\tuntrack(() => transition.in());\n\t\t\t});\n\t\t}\n\t}\n}\n\n/**\n * Animates an element, according to the provided configuration\n * @param {Element} element\n * @param {AnimationConfig | ((opts: { direction: 'in' | 'out' }) => AnimationConfig)} options\n * @param {Animation | undefined} counterpart The corresponding intro/outro to this outro/intro\n * @param {number} t2 The target `t` value — `1` for intro, `0` for outro\n * @param {(() => void)} on_finish Called after successfully completing the animation\n * @returns {Animation}\n */\nfunction animate(element, options, counterpart, t2, on_finish) {\n\tvar is_intro = t2 === 1;\n\n\tif (is_function(options)) {\n\t\t// In the case of a deferred transition (such as `crossfade`), `option` will be\n\t\t// a function rather than an `AnimationConfig`. We need to call this function\n\t\t// once the DOM has been updated...\n\t\t/** @type {Animation} */\n\t\tvar a;\n\t\tvar aborted = false;\n\n\t\tqueue_micro_task(() => {\n\t\t\tif (aborted) return;\n\t\t\tvar o = options({ direction: is_intro ? 'in' : 'out' });\n\t\t\ta = animate(element, o, counterpart, t2, on_finish);\n\t\t});\n\n\t\t// ...but we want to do so without using `async`/`await` everywhere, so\n\t\t// we return a facade that allows everything to remain synchronous\n\t\treturn {\n\t\t\tabort: () => {\n\t\t\t\taborted = true;\n\t\t\t\ta?.abort();\n\t\t\t},\n\t\t\tdeactivate: () => a.deactivate(),\n\t\t\treset: () => a.reset(),\n\t\t\tt: () => a.t()\n\t\t};\n\t}\n\n\tcounterpart?.deactivate();\n\n\tif (!options?.duration && !options?.delay) {\n\t\tdispatch_event(element, is_intro ? 'introstart' : 'outrostart');\n\t\ton_finish();\n\n\t\treturn {\n\t\t\tabort: noop,\n\t\t\tdeactivate: noop,\n\t\t\treset: noop,\n\t\t\tt: () => t2\n\t\t};\n\t}\n\n\tconst { delay = 0, css, tick, easing = linear } = options;\n\n\tvar keyframes = [];\n\n\tif (is_intro && counterpart === undefined) {\n\t\tif (tick) {\n\t\t\ttick(0, 1); // TODO put in nested effect, to avoid interleaved reads/writes?\n\t\t}\n\n\t\tif (css) {\n\t\t\tvar styles = css_to_keyframe(css(0, 1));\n\t\t\tkeyframes.push(styles, styles);\n\t\t}\n\t}\n\n\tvar get_t = () => 1 - t2;\n\n\t// create a dummy animation that lasts as long as the delay (but with whatever devtools\n\t// multiplier is in effect). in the common case that it is `0`, we keep it anyway so that\n\t// the CSS keyframes aren't created until the DOM is updated\n\t//\n\t// fill forwards to prevent the element from rendering without styles applied\n\t// see https://github.com/sveltejs/svelte/issues/14732\n\tvar animation = element.animate(keyframes, { duration: delay, fill: 'forwards' });\n\n\tanimation.onfinish = () => {\n\t\t// remove dummy animation from the stack to prevent conflict with main animation\n\t\tanimation.cancel();\n\n\t\tdispatch_event(element, is_intro ? 'introstart' : 'outrostart');\n\n\t\t// for bidirectional transitions, we start from the current position,\n\t\t// rather than doing a full intro/outro\n\t\tvar t1 = counterpart?.t() ?? 1 - t2;\n\t\tcounterpart?.abort();\n\n\t\tvar delta = t2 - t1;\n\t\tvar duration = /** @type {number} */ (options.duration) * Math.abs(delta);\n\t\tvar keyframes = [];\n\n\t\tif (duration > 0) {\n\t\t\t/**\n\t\t\t * Whether or not the CSS includes `overflow: hidden`, in which case we need to\n\t\t\t * add it as an inline style to work around a Safari <18 bug\n\t\t\t * TODO 6.0 remove this, if possible\n\t\t\t */\n\t\t\tvar needs_overflow_hidden = false;\n\n\t\t\tif (css) {\n\t\t\t\tvar n = Math.ceil(duration / (1000 / 60)); // `n` must be an integer, or we risk missing the `t2` value\n\n\t\t\t\tfor (var i = 0; i <= n; i += 1) {\n\t\t\t\t\tvar t = t1 + delta * easing(i / n);\n\t\t\t\t\tvar styles = css_to_keyframe(css(t, 1 - t));\n\t\t\t\t\tkeyframes.push(styles);\n\n\t\t\t\t\tneeds_overflow_hidden ||= styles.overflow === 'hidden';\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (needs_overflow_hidden) {\n\t\t\t\t/** @type {HTMLElement} */ (element).style.overflow = 'hidden';\n\t\t\t}\n\n\t\t\tget_t = () => {\n\t\t\t\tvar time = /** @type {number} */ (\n\t\t\t\t\t/** @type {globalThis.Animation} */ (animation).currentTime\n\t\t\t\t);\n\n\t\t\t\treturn t1 + delta * easing(time / duration);\n\t\t\t};\n\n\t\t\tif (tick) {\n\t\t\t\tloop(() => {\n\t\t\t\t\tif (animation.playState !== 'running') return false;\n\n\t\t\t\t\tvar t = get_t();\n\t\t\t\t\ttick(t, 1 - t);\n\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tanimation = element.animate(keyframes, { duration, fill: 'forwards' });\n\n\t\tanimation.onfinish = () => {\n\t\t\tget_t = () => t2;\n\t\t\ttick?.(t2, 1 - t2);\n\t\t\ton_finish();\n\t\t};\n\t};\n\n\treturn {\n\t\tabort: () => {\n\t\t\tif (animation) {\n\t\t\t\tanimation.cancel();\n\t\t\t\t// This prevents memory leaks in Chromium\n\t\t\t\tanimation.effect = null;\n\t\t\t\t// This prevents onfinish to be launched after cancel(),\n\t\t\t\t// which can happen in some rare cases\n\t\t\t\t// see https://github.com/sveltejs/svelte/issues/13681\n\t\t\t\tanimation.onfinish = noop;\n\t\t\t}\n\t\t},\n\t\tdeactivate: () => {\n\t\t\ton_finish = noop;\n\t\t},\n\t\treset: () => {\n\t\t\tif (t2 === 0) {\n\t\t\t\ttick?.(1, 0);\n\t\t\t}\n\t\t},\n\t\tt: () => get_t()\n\t};\n}\n","/** @import { Effect, EffectNodes, TemplateNode } from '#client' */\nimport { FILENAME, NAMESPACE_SVG } from '../../../../constants.js';\nimport {\n\thydrate_next,\n\thydrate_node,\n\thydrating,\n\tset_hydrate_node,\n\tset_hydrating\n} from '../hydration.js';\nimport { create_element, create_text, get_first_child } from '../operations.js';\nimport { block, teardown } from '../../reactivity/effects.js';\nimport { set_should_intro } from '../../render.js';\nimport { active_effect } from '../../runtime.js';\nimport { component_context, dev_stack } from '../../context.js';\nimport { DEV } from 'esm-env';\nimport { EFFECT_TRANSPARENT, ELEMENT_NODE } from '#client/constants';\nimport { assign_nodes } from '../template.js';\nimport { is_raw_text_element } from '../../../../utils.js';\nimport { BranchManager } from './branches.js';\nimport { set_animation_effect_override } from '../elements/transitions.js';\n\n/**\n * @param {Comment | Element} node\n * @param {() => string} get_tag\n * @param {boolean} is_svg\n * @param {undefined | ((element: Element, anchor: Node | null) => void)} render_fn,\n * @param {undefined | (() => string)} get_namespace\n * @param {undefined | [number, number]} location\n * @returns {void}\n */\nexport function element(node, get_tag, is_svg, render_fn, get_namespace, location) {\n\tlet was_hydrating = hydrating;\n\n\tif (hydrating) {\n\t\thydrate_next();\n\t}\n\n\tvar filename = DEV && location && component_context?.function[FILENAME];\n\n\t/** @type {null | Element} */\n\tvar element = null;\n\n\tif (hydrating && hydrate_node.nodeType === ELEMENT_NODE) {\n\t\telement = /** @type {Element} */ (hydrate_node);\n\t\thydrate_next();\n\t}\n\n\tvar anchor = /** @type {TemplateNode} */ (hydrating ? hydrate_node : node);\n\n\t/**\n\t * We track this so we can set it when changing the element, allowing any\n\t * `animate:` directive to bind itself to the correct block\n\t */\n\tvar parent_effect = /** @type {Effect} */ (active_effect);\n\n\tvar branches = new BranchManager(anchor, false);\n\n\tblock(() => {\n\t\tconst next_tag = get_tag() || null;\n\t\tvar ns = get_namespace\n\t\t\t? get_namespace()\n\t\t\t: is_svg || next_tag === 'svg'\n\t\t\t\t? NAMESPACE_SVG\n\t\t\t\t: undefined;\n\n\t\tif (next_tag === null) {\n\t\t\tbranches.ensure(null, null);\n\t\t\tset_should_intro(true);\n\t\t\treturn;\n\t\t}\n\n\t\tbranches.ensure(next_tag, (anchor) => {\n\t\t\tif (next_tag) {\n\t\t\t\telement = hydrating ? /** @type {Element} */ (element) : create_element(next_tag, ns);\n\n\t\t\t\tif (DEV && location) {\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\telement.__svelte_meta = {\n\t\t\t\t\t\tparent: dev_stack,\n\t\t\t\t\t\tloc: {\n\t\t\t\t\t\t\tfile: filename,\n\t\t\t\t\t\t\tline: location[0],\n\t\t\t\t\t\t\tcolumn: location[1]\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tassign_nodes(element, element);\n\n\t\t\t\tif (render_fn) {\n\t\t\t\t\tif (hydrating && is_raw_text_element(next_tag)) {\n\t\t\t\t\t\t// prevent hydration glitches\n\t\t\t\t\t\telement.append(document.createComment(''));\n\t\t\t\t\t}\n\n\t\t\t\t\t// If hydrating, use the existing ssr comment as the anchor so that the\n\t\t\t\t\t// inner open and close methods can pick up the existing nodes correctly\n\t\t\t\t\tvar child_anchor = hydrating\n\t\t\t\t\t\t? get_first_child(element)\n\t\t\t\t\t\t: element.appendChild(create_text());\n\n\t\t\t\t\tif (hydrating) {\n\t\t\t\t\t\tif (child_anchor === null) {\n\t\t\t\t\t\t\tset_hydrating(false);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tset_hydrate_node(child_anchor);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tset_animation_effect_override(parent_effect);\n\n\t\t\t\t\t// `child_anchor` is undefined if this is a void element, but we still\n\t\t\t\t\t// need to call `render_fn` in order to run actions etc. If the element\n\t\t\t\t\t// contains children, it's a user error (which is warned on elsewhere)\n\t\t\t\t\t// and the DOM will be silently discarded\n\t\t\t\t\trender_fn(element, child_anchor);\n\n\t\t\t\t\tset_animation_effect_override(null);\n\t\t\t\t}\n\n\t\t\t\t// we do this after calling `render_fn` so that child effects don't override `nodes.end`\n\t\t\t\t/** @type {Effect & { nodes: EffectNodes }} */ (active_effect).nodes.end = element;\n\n\t\t\t\tanchor.before(element);\n\t\t\t}\n\n\t\t\tif (hydrating) {\n\t\t\t\tset_hydrate_node(anchor);\n\t\t\t}\n\t\t});\n\n\t\t// revert to the default state after the effect has been created\n\t\tset_should_intro(true);\n\n\t\treturn () => {\n\t\t\tif (next_tag) {\n\t\t\t\t// if we're in this callback because we're re-running the effect,\n\t\t\t\t// disable intros (unless no element is currently displayed)\n\t\t\t\tset_should_intro(false);\n\t\t\t}\n\t\t};\n\t}, EFFECT_TRANSPARENT);\n\n\tteardown(() => {\n\t\tset_should_intro(true);\n\t});\n\n\tif (was_hydrating) {\n\t\tset_hydrating(true);\n\t\tset_hydrate_node(anchor);\n\t}\n}\n","/** @import { TemplateNode } from '#client' */\nimport { hydrate_node, hydrating, set_hydrate_node, set_hydrating } from '../hydration.js';\nimport { create_text, get_first_child, get_next_sibling } from '../operations.js';\nimport { block } from '../../reactivity/effects.js';\nimport { COMMENT_NODE, EFFECT_PRESERVED, HEAD_EFFECT } from '#client/constants';\n\n/**\n * @param {string} hash\n * @param {(anchor: Node) => void} render_fn\n * @returns {void}\n */\nexport function head(hash, render_fn) {\n\t// The head function may be called after the first hydration pass and ssr comment nodes may still be present,\n\t// therefore we need to skip that when we detect that we're not in hydration mode.\n\tlet previous_hydrate_node = null;\n\tlet was_hydrating = hydrating;\n\n\t/** @type {Comment | Text} */\n\tvar anchor;\n\n\tif (hydrating) {\n\t\tprevious_hydrate_node = hydrate_node;\n\n\t\tvar head_anchor = get_first_child(document.head);\n\n\t\t// There might be multiple head blocks in our app, and they could have been\n\t\t// rendered in an arbitrary order — find one corresponding to this component\n\t\twhile (\n\t\t\thead_anchor !== null &&\n\t\t\t(head_anchor.nodeType !== COMMENT_NODE || /** @type {Comment} */ (head_anchor).data !== hash)\n\t\t) {\n\t\t\thead_anchor = get_next_sibling(head_anchor);\n\t\t}\n\n\t\t// If we can't find an opening hydration marker, skip hydration (this can happen\n\t\t// if a framework rendered body but not head content)\n\t\tif (head_anchor === null) {\n\t\t\tset_hydrating(false);\n\t\t} else {\n\t\t\tvar start = /** @type {TemplateNode} */ (get_next_sibling(head_anchor));\n\t\t\thead_anchor.remove(); // in case this component is repeated\n\n\t\t\tset_hydrate_node(start);\n\t\t}\n\t}\n\n\tif (!hydrating) {\n\t\tanchor = document.head.appendChild(create_text());\n\t}\n\n\ttry {\n\t\t// normally a branch is the child of a block and would have the EFFECT_PRESERVED flag,\n\t\t// but since head blocks don't necessarily only have direct branch children we add it on the block itself\n\t\tblock(() => render_fn(anchor), HEAD_EFFECT | EFFECT_PRESERVED);\n\t} finally {\n\t\tif (was_hydrating) {\n\t\t\tset_hydrating(true);\n\t\t\tset_hydrate_node(/** @type {TemplateNode} */ (previous_hydrate_node));\n\t\t}\n\t}\n}\n","import { DEV } from 'esm-env';\nimport { register_style } from '../dev/css.js';\nimport { effect } from '../reactivity/effects.js';\nimport { create_element } from './operations.js';\n\n/**\n * @param {Node} anchor\n * @param {{ hash: string, code: string }} css\n */\nexport function append_styles(anchor, css) {\n\t// Use `queue_micro_task` to ensure `anchor` is in the DOM, otherwise getRootNode() will yield wrong results\n\teffect(() => {\n\t\tvar root = anchor.getRootNode();\n\n\t\tvar target = /** @type {ShadowRoot} */ (root).host\n\t\t\t? /** @type {ShadowRoot} */ (root)\n\t\t\t: /** @type {Document} */ (root).head ?? /** @type {Document} */ (root.ownerDocument).head;\n\n\t\t// Always querying the DOM is roughly the same perf as additionally checking for presence in a map first assuming\n\t\t// that you'll get cache hits half of the time, so we just always query the dom for simplicity and code savings.\n\t\tif (!target.querySelector('#' + css.hash)) {\n\t\t\tconst style = create_element('style');\n\t\t\tstyle.id = css.hash;\n\t\t\tstyle.textContent = css.code;\n\n\t\t\ttarget.appendChild(style);\n\n\t\t\tif (DEV) {\n\t\t\t\tregister_style(css.hash, style);\n\t\t\t}\n\t\t}\n\t});\n}\n","/** @import { ActionPayload } from '#client' */\nimport { effect, render_effect } from '../../reactivity/effects.js';\nimport { safe_not_equal } from '../../reactivity/equality.js';\nimport { deep_read_state, untrack } from '../../runtime.js';\n\n/**\n * @template P\n * @param {Element} dom\n * @param {(dom: Element, value?: P) => ActionPayload<P>} action\n * @param {() => P} [get_value]\n * @returns {void}\n */\nexport function action(dom, action, get_value) {\n\teffect(() => {\n\t\tvar payload = untrack(() => action(dom, get_value?.()) || {});\n\n\t\tif (get_value && payload?.update) {\n\t\t\tvar inited = false;\n\t\t\t/** @type {P} */\n\t\t\tvar prev = /** @type {any} */ ({}); // initialize with something so it's never equal on first run\n\n\t\t\trender_effect(() => {\n\t\t\t\tvar value = get_value();\n\n\t\t\t\t// Action's update method is coarse-grained, i.e. when anything in the passed value changes, update.\n\t\t\t\t// This works in legacy mode because of mutable_source being updated as a whole, but when using $state\n\t\t\t\t// together with actions and mutation, it wouldn't notice the change without a deep read.\n\t\t\t\tdeep_read_state(value);\n\n\t\t\t\tif (inited && safe_not_equal(prev, value)) {\n\t\t\t\t\tprev = value;\n\t\t\t\t\t/** @type {Function} */ (payload.update)(value);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tinited = true;\n\t\t}\n\n\t\tif (payload?.destroy) {\n\t\t\treturn () => /** @type {Function} */ (payload.destroy)();\n\t\t}\n\t});\n}\n","/** @import { Effect } from '#client' */\nimport { branch, effect, destroy_effect, managed } from '../../reactivity/effects.js';\n\n// TODO in 6.0 or 7.0, when we remove legacy mode, we can simplify this by\n// getting rid of the block/branch stuff and just letting the effect rip.\n// see https://github.com/sveltejs/svelte/pull/15962\n\n/**\n * @param {Element} node\n * @param {() => (node: Element) => void} get_fn\n */\nexport function attach(node, get_fn) {\n\t/** @type {false | undefined | ((node: Element) => void)} */\n\tvar fn = undefined;\n\n\t/** @type {Effect | null} */\n\tvar e;\n\n\tmanaged(() => {\n\t\tif (fn !== (fn = get_fn())) {\n\t\t\tif (e) {\n\t\t\t\tdestroy_effect(e);\n\t\t\t\te = null;\n\t\t\t}\n\n\t\t\tif (fn) {\n\t\t\t\te = branch(() => {\n\t\t\t\t\teffect(() => /** @type {(node: Element) => void} */ (fn)(node));\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t});\n}\n","const ATTR_REGEX = /[&\"<]/g;\nconst CONTENT_REGEX = /[&<]/g;\n\n/**\n * @template V\n * @param {V} value\n * @param {boolean} [is_attr]\n */\nexport function escape_html(value, is_attr) {\n\tconst str = String(value ?? '');\n\n\tconst pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX;\n\tpattern.lastIndex = 0;\n\n\tlet escaped = '';\n\tlet last = 0;\n\n\twhile (pattern.test(str)) {\n\t\tconst i = pattern.lastIndex - 1;\n\t\tconst ch = str[i];\n\t\tescaped += str.substring(last, i) + (ch === '&' ? '&amp;' : ch === '\"' ? '&quot;' : '&lt;');\n\t\tlast = i + 1;\n\t}\n\n\treturn escaped + str.substring(last);\n}\n","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=\" \"),n+=f)}else for(f in e)e[f]&&(n&&(n+=\" \"),n+=f);return n}export function clsx(){for(var e,t,f=0,n=\"\",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=\" \"),n+=t);return n}export default clsx;","import { escape_html } from '../../escaping.js';\nimport { clsx as _clsx } from 'clsx';\nimport { has_own_property } from './utils.js';\n\n/**\n * `<div translate={false}>` should be rendered as `<div translate=\"no\">` and _not_\n * `<div translate=\"false\">`, which is equivalent to `<div translate=\"yes\">`. There\n * may be other odd cases that need to be added to this list in future\n * @type {Record<string, Map<any, string>>}\n */\nconst replacements = {\n\ttranslate: new Map([\n\t\t[true, 'yes'],\n\t\t[false, 'no']\n\t])\n};\n\n/**\n * @template V\n * @param {string} name\n * @param {V} value\n * @param {boolean} [is_boolean]\n * @returns {string}\n */\nexport function attr(name, value, is_boolean = false) {\n\t// attribute hidden for values other than \"until-found\" behaves like a boolean attribute\n\tif (name === 'hidden' && value !== 'until-found') {\n\t\tis_boolean = true;\n\t}\n\tif (value == null || (!value && is_boolean)) return '';\n\tconst normalized =\n\t\t(has_own_property.call(replacements, name) && replacements[name].get(value)) || value;\n\tconst assignment = is_boolean ? `=\"\"` : `=\"${escape_html(normalized, true)}\"`;\n\treturn ` ${name}${assignment}`;\n}\n\n/**\n * Small wrapper around clsx to preserve Svelte's (weird) handling of falsy values.\n * TODO Svelte 6 revisit this, and likely turn all falsy values into the empty string (what clsx also does)\n * @param {any} value\n */\nexport function clsx(value) {\n\tif (typeof value === 'object') {\n\t\treturn _clsx(value);\n\t} else {\n\t\treturn value ?? '';\n\t}\n}\n\nconst whitespace = [...' \\t\\n\\r\\f\\u00a0\\u000b\\ufeff'];\n\n/**\n * @param {any} value\n * @param {string | null} [hash]\n * @param {Record<string, boolean>} [directives]\n * @returns {string | null}\n */\nexport function to_class(value, hash, directives) {\n\tvar classname = value == null ? '' : '' + value;\n\n\tif (hash) {\n\t\tclassname = classname ? classname + ' ' + hash : hash;\n\t}\n\n\tif (directives) {\n\t\tfor (var key of Object.keys(directives)) {\n\t\t\tif (directives[key]) {\n\t\t\t\tclassname = classname ? classname + ' ' + key : key;\n\t\t\t} else if (classname.length) {\n\t\t\t\tvar len = key.length;\n\t\t\t\tvar a = 0;\n\n\t\t\t\twhile ((a = classname.indexOf(key, a)) >= 0) {\n\t\t\t\t\tvar b = a + len;\n\n\t\t\t\t\tif (\n\t\t\t\t\t\t(a === 0 || whitespace.includes(classname[a - 1])) &&\n\t\t\t\t\t\t(b === classname.length || whitespace.includes(classname[b]))\n\t\t\t\t\t) {\n\t\t\t\t\t\tclassname = (a === 0 ? '' : classname.substring(0, a)) + classname.substring(b + 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\ta = b;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn classname === '' ? null : classname;\n}\n\n/**\n *\n * @param {Record<string,any>} styles\n * @param {boolean} important\n */\nfunction append_styles(styles, important = false) {\n\tvar separator = important ? ' !important;' : ';';\n\tvar css = '';\n\n\tfor (var key of Object.keys(styles)) {\n\t\tvar value = styles[key];\n\t\tif (value != null && value !== '') {\n\t\t\tcss += ' ' + key + ': ' + value + separator;\n\t\t}\n\t}\n\n\treturn css;\n}\n\n/**\n * @param {string} name\n * @returns {string}\n */\nfunction to_css_name(name) {\n\tif (name[0] !== '-' || name[1] !== '-') {\n\t\treturn name.toLowerCase();\n\t}\n\treturn name;\n}\n\n/**\n * @param {any} value\n * @param {Record<string, any> | [Record<string, any>, Record<string, any>]} [styles]\n * @returns {string | null}\n */\nexport function to_style(value, styles) {\n\tif (styles) {\n\t\tvar new_style = '';\n\n\t\t/** @type {Record<string,any> | undefined} */\n\t\tvar normal_styles;\n\n\t\t/** @type {Record<string,any> | undefined} */\n\t\tvar important_styles;\n\n\t\tif (Array.isArray(styles)) {\n\t\t\tnormal_styles = styles[0];\n\t\t\timportant_styles = styles[1];\n\t\t} else {\n\t\t\tnormal_styles = styles;\n\t\t}\n\n\t\tif (value) {\n\t\t\tvalue = String(value)\n\t\t\t\t.replaceAll(/\\s*\\/\\*.*?\\*\\/\\s*/g, '')\n\t\t\t\t.trim();\n\n\t\t\t/** @type {boolean | '\"' | \"'\"} */\n\t\t\tvar in_str = false;\n\t\t\tvar in_apo = 0;\n\t\t\tvar in_comment = false;\n\n\t\t\tvar reserved_names = [];\n\n\t\t\tif (normal_styles) {\n\t\t\t\treserved_names.push(...Object.keys(normal_styles).map(to_css_name));\n\t\t\t}\n\t\t\tif (important_styles) {\n\t\t\t\treserved_names.push(...Object.keys(important_styles).map(to_css_name));\n\t\t\t}\n\n\t\t\tvar start_index = 0;\n\t\t\tvar name_index = -1;\n\n\t\t\tconst len = value.length;\n\t\t\tfor (var i = 0; i < len; i++) {\n\t\t\t\tvar c = value[i];\n\n\t\t\t\tif (in_comment) {\n\t\t\t\t\tif (c === '/' && value[i - 1] === '*') {\n\t\t\t\t\t\tin_comment = false;\n\t\t\t\t\t}\n\t\t\t\t} else if (in_str) {\n\t\t\t\t\tif (in_str === c) {\n\t\t\t\t\t\tin_str = false;\n\t\t\t\t\t}\n\t\t\t\t} else if (c === '/' && value[i + 1] === '*') {\n\t\t\t\t\tin_comment = true;\n\t\t\t\t} else if (c === '\"' || c === \"'\") {\n\t\t\t\t\tin_str = c;\n\t\t\t\t} else if (c === '(') {\n\t\t\t\t\tin_apo++;\n\t\t\t\t} else if (c === ')') {\n\t\t\t\t\tin_apo--;\n\t\t\t\t}\n\n\t\t\t\tif (!in_comment && in_str === false && in_apo === 0) {\n\t\t\t\t\tif (c === ':' && name_index === -1) {\n\t\t\t\t\t\tname_index = i;\n\t\t\t\t\t} else if (c === ';' || i === len - 1) {\n\t\t\t\t\t\tif (name_index !== -1) {\n\t\t\t\t\t\t\tvar name = to_css_name(value.substring(start_index, name_index).trim());\n\n\t\t\t\t\t\t\tif (!reserved_names.includes(name)) {\n\t\t\t\t\t\t\t\tif (c !== ';') {\n\t\t\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tvar property = value.substring(start_index, i).trim();\n\t\t\t\t\t\t\t\tnew_style += ' ' + property + ';';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstart_index = i + 1;\n\t\t\t\t\t\tname_index = -1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (normal_styles) {\n\t\t\tnew_style += append_styles(normal_styles);\n\t\t}\n\n\t\tif (important_styles) {\n\t\t\tnew_style += append_styles(important_styles, true);\n\t\t}\n\n\t\tnew_style = new_style.trim();\n\t\treturn new_style === '' ? null : new_style;\n\t}\n\n\treturn value == null ? null : String(value);\n}\n","import { to_class } from '../../../shared/attributes.js';\nimport { hydrating } from '../hydration.js';\n\n/**\n * @param {Element} dom\n * @param {boolean | number} is_html\n * @param {string | null} value\n * @param {string} [hash]\n * @param {Record<string, any>} [prev_classes]\n * @param {Record<string, any>} [next_classes]\n * @returns {Record<string, boolean> | undefined}\n */\nexport function set_class(dom, is_html, value, hash, prev_classes, next_classes) {\n\t// @ts-expect-error need to add __className to patched prototype\n\tvar prev = dom.__className;\n\n\tif (\n\t\thydrating ||\n\t\tprev !== value ||\n\t\tprev === undefined // for edge case of `class={undefined}`\n\t) {\n\t\tvar next_class_name = to_class(value, hash, next_classes);\n\n\t\tif (!hydrating || next_class_name !== dom.getAttribute('class')) {\n\t\t\t// Removing the attribute when the value is only an empty string causes\n\t\t\t// performance issues vs simply making the className an empty string. So\n\t\t\t// we should only remove the class if the value is nullish\n\t\t\t// and there no hash/directives :\n\t\t\tif (next_class_name == null) {\n\t\t\t\tdom.removeAttribute('class');\n\t\t\t} else if (is_html) {\n\t\t\t\tdom.className = next_class_name;\n\t\t\t} else {\n\t\t\t\tdom.setAttribute('class', next_class_name);\n\t\t\t}\n\t\t}\n\n\t\t// @ts-expect-error need to add __className to patched prototype\n\t\tdom.__className = value;\n\t} else if (next_classes && prev_classes !== next_classes) {\n\t\tfor (var key in next_classes) {\n\t\t\tvar is_present = !!next_classes[key];\n\n\t\t\tif (prev_classes == null || is_present !== !!prev_classes[key]) {\n\t\t\t\tdom.classList.toggle(key, is_present);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn next_classes;\n}\n","import { to_style } from '../../../shared/attributes.js';\nimport { hydrating } from '../hydration.js';\n\n/**\n * @param {Element & ElementCSSInlineStyle} dom\n * @param {Record<string, any>} prev\n * @param {Record<string, any>} next\n * @param {string} [priority]\n */\nfunction update_styles(dom, prev = {}, next, priority) {\n\tfor (var key in next) {\n\t\tvar value = next[key];\n\n\t\tif (prev[key] !== value) {\n\t\t\tif (next[key] == null) {\n\t\t\t\tdom.style.removeProperty(key);\n\t\t\t} else {\n\t\t\t\tdom.style.setProperty(key, value, priority);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * @param {Element & ElementCSSInlineStyle} dom\n * @param {string | null} value\n * @param {Record<string, any> | [Record<string, any>, Record<string, any>]} [prev_styles]\n * @param {Record<string, any> | [Record<string, any>, Record<string, any>]} [next_styles]\n */\nexport function set_style(dom, value, prev_styles, next_styles) {\n\t// @ts-expect-error\n\tvar prev = dom.__style;\n\n\tif (hydrating || prev !== value) {\n\t\tvar next_style_attr = to_style(value, next_styles);\n\n\t\tif (!hydrating || next_style_attr !== dom.getAttribute('style')) {\n\t\t\tif (next_style_attr == null) {\n\t\t\t\tdom.removeAttribute('style');\n\t\t\t} else {\n\t\t\t\tdom.style.cssText = next_style_attr;\n\t\t\t}\n\t\t}\n\n\t\t// @ts-expect-error\n\t\tdom.__style = value;\n\t} else if (next_styles) {\n\t\tif (Array.isArray(next_styles)) {\n\t\t\tupdate_styles(dom, prev_styles?.[0], next_styles[0]);\n\t\t\tupdate_styles(dom, prev_styles?.[1], next_styles[1], 'important');\n\t\t} else {\n\t\t\tupdate_styles(dom, prev_styles, next_styles);\n\t\t}\n\t}\n\n\treturn next_styles;\n}\n","import { effect, teardown } from '../../../reactivity/effects.js';\nimport { listen_to_event_and_reset_event } from './shared.js';\nimport { is } from '../../../proxy.js';\nimport { is_array } from '../../../../shared/utils.js';\nimport * as w from '../../../warnings.js';\nimport { Batch, current_batch, previous_batch } from '../../../reactivity/batch.js';\nimport { async_mode_flag } from '../../../../flags/index.js';\n\n/**\n * Selects the correct option(s) (depending on whether this is a multiple select)\n * @template V\n * @param {HTMLSelectElement} select\n * @param {V} value\n * @param {boolean} mounting\n */\nexport function select_option(select, value, mounting = false) {\n\tif (select.multiple) {\n\t\t// If value is null or undefined, keep the selection as is\n\t\tif (value == undefined) {\n\t\t\treturn;\n\t\t}\n\n\t\t// If not an array, warn and keep the selection as is\n\t\tif (!is_array(value)) {\n\t\t\treturn w.select_multiple_invalid_value();\n\t\t}\n\n\t\t// Otherwise, update the selection\n\t\tfor (var option of select.options) {\n\t\t\toption.selected = value.includes(get_option_value(option));\n\t\t}\n\n\t\treturn;\n\t}\n\n\tfor (option of select.options) {\n\t\tvar option_value = get_option_value(option);\n\t\tif (is(option_value, value)) {\n\t\t\toption.selected = true;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (!mounting || value !== undefined) {\n\t\tselect.selectedIndex = -1; // no option should be selected\n\t}\n}\n\n/**\n * Selects the correct option(s) if `value` is given,\n * and then sets up a mutation observer to sync the\n * current selection to the dom when it changes. Such\n * changes could for example occur when options are\n * inside an `#each` block.\n * @param {HTMLSelectElement} select\n */\nexport function init_select(select) {\n\tvar observer = new MutationObserver(() => {\n\t\t// @ts-ignore\n\t\tselect_option(select, select.__value);\n\t\t// Deliberately don't update the potential binding value,\n\t\t// the model should be preserved unless explicitly changed\n\t});\n\n\tobserver.observe(select, {\n\t\t// Listen to option element changes\n\t\tchildList: true,\n\t\tsubtree: true, // because of <optgroup>\n\t\t// Listen to option element value attribute changes\n\t\t// (doesn't get notified of select value changes,\n\t\t// because that property is not reflected as an attribute)\n\t\tattributes: true,\n\t\tattributeFilter: ['value']\n\t});\n\n\tteardown(() => {\n\t\tobserver.disconnect();\n\t});\n}\n\n/**\n * @param {HTMLSelectElement} select\n * @param {() => unknown} get\n * @param {(value: unknown) => void} set\n * @returns {void}\n */\nexport function bind_select_value(select, get, set = get) {\n\tvar batches = new WeakSet();\n\tvar mounting = true;\n\n\tlisten_to_event_and_reset_event(select, 'change', (is_reset) => {\n\t\tvar query = is_reset ? '[selected]' : ':checked';\n\t\t/** @type {unknown} */\n\t\tvar value;\n\n\t\tif (select.multiple) {\n\t\t\tvalue = [].map.call(select.querySelectorAll(query), get_option_value);\n\t\t} else {\n\t\t\t/** @type {HTMLOptionElement | null} */\n\t\t\tvar selected_option =\n\t\t\t\tselect.querySelector(query) ??\n\t\t\t\t// will fall back to first non-disabled option if no option is selected\n\t\t\t\tselect.querySelector('option:not([disabled])');\n\t\t\tvalue = selected_option && get_option_value(selected_option);\n\t\t}\n\n\t\tset(value);\n\n\t\t// @ts-ignore\n\t\tselect.__value = value;\n\n\t\tif (current_batch !== null) {\n\t\t\tbatches.add(current_batch);\n\t\t}\n\t});\n\n\t// Needs to be an effect, not a render_effect, so that in case of each loops the logic runs after the each block has updated\n\teffect(() => {\n\t\tvar value = get();\n\n\t\tif (select === document.activeElement) {\n\t\t\t// In sync mode render effects are executed during tree traversal -> needs current_batch\n\t\t\t// In async mode render effects are flushed once batch resolved, at which point current_batch is null -> needs previous_batch\n\t\t\tvar batch = /** @type {Batch} */ (async_mode_flag ? previous_batch : current_batch);\n\n\t\t\t// Don't update the <select> if it is focused. We can get here if, for example,\n\t\t\t// an update is deferred because of async work depending on the select:\n\t\t\t//\n\t\t\t// <select bind:value={selected}>...</select>\n\t\t\t// <p>{await find(selected)}</p>\n\t\t\tif (batches.has(batch)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tselect_option(select, value, mounting);\n\n\t\t// Mounting and value undefined -> take selection from dom\n\t\tif (mounting && value === undefined) {\n\t\t\t/** @type {HTMLOptionElement | null} */\n\t\t\tvar selected_option = select.querySelector(':checked');\n\t\t\tif (selected_option !== null) {\n\t\t\t\tvalue = get_option_value(selected_option);\n\t\t\t\tset(value);\n\t\t\t}\n\t\t}\n\n\t\t// @ts-ignore\n\t\tselect.__value = value;\n\t\tmounting = false;\n\t});\n\n\tinit_select(select);\n}\n\n/** @param {HTMLOptionElement} option */\nfunction get_option_value(option) {\n\t// __value only exists if the <option> has a value attribute\n\tif ('__value' in option) {\n\t\treturn option.__value;\n\t} else {\n\t\treturn option.value;\n\t}\n}\n","/** @import { Blocker, Effect } from '#client' */\nimport { DEV } from 'esm-env';\nimport { hydrating, set_hydrating } from '../hydration.js';\nimport { get_descriptors, get_prototype_of } from '../../../shared/utils.js';\nimport { create_event, delegate, delegated, event, event_symbol } from './events.js';\nimport { add_form_reset_listener, autofocus } from './misc.js';\nimport * as w from '../../warnings.js';\nimport { IS_XHTML, LOADING_ATTR_SYMBOL } from '#client/constants';\nimport { queue_micro_task } from '../task.js';\nimport { is_capture_event, can_delegate_event, normalize_attribute } from '../../../../utils.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tget,\n\tset_active_effect,\n\tset_active_reaction\n} from '../../runtime.js';\nimport { attach } from './attachments.js';\nimport { clsx } from '../../../shared/attributes.js';\nimport { set_class } from './class.js';\nimport { set_style } from './style.js';\nimport { ATTACHMENT_KEY, NAMESPACE_HTML, UNINITIALIZED } from '../../../../constants.js';\nimport { branch, destroy_effect, effect, managed } from '../../reactivity/effects.js';\nimport { init_select, select_option } from './bindings/select.js';\nimport { flatten } from '../../reactivity/async.js';\n\nexport const CLASS = Symbol('class');\nexport const STYLE = Symbol('style');\n\nconst IS_CUSTOM_ELEMENT = Symbol('is custom element');\nconst IS_HTML = Symbol('is html');\n\nconst LINK_TAG = IS_XHTML ? 'link' : 'LINK';\nconst INPUT_TAG = IS_XHTML ? 'input' : 'INPUT';\nconst OPTION_TAG = IS_XHTML ? 'option' : 'OPTION';\nconst SELECT_TAG = IS_XHTML ? 'select' : 'SELECT';\nconst PROGRESS_TAG = IS_XHTML ? 'progress' : 'PROGRESS';\n\n/**\n * The value/checked attribute in the template actually corresponds to the defaultValue property, so we need\n * to remove it upon hydration to avoid a bug when someone resets the form value.\n * @param {HTMLInputElement} input\n * @returns {void}\n */\nexport function remove_input_defaults(input) {\n\tif (!hydrating) return;\n\n\tvar already_removed = false;\n\n\t// We try and remove the default attributes later, rather than sync during hydration.\n\t// Doing it sync during hydration has a negative impact on performance, but deferring the\n\t// work in an idle task alleviates this greatly. If a form reset event comes in before\n\t// the idle callback, then we ensure the input defaults are cleared just before.\n\tvar remove_defaults = () => {\n\t\tif (already_removed) return;\n\t\talready_removed = true;\n\n\t\t// Remove the attributes but preserve the values\n\t\tif (input.hasAttribute('value')) {\n\t\t\tvar value = input.value;\n\t\t\tset_attribute(input, 'value', null);\n\t\t\tinput.value = value;\n\t\t}\n\n\t\tif (input.hasAttribute('checked')) {\n\t\t\tvar checked = input.checked;\n\t\t\tset_attribute(input, 'checked', null);\n\t\t\tinput.checked = checked;\n\t\t}\n\t};\n\n\t// @ts-expect-error\n\tinput.__on_r = remove_defaults;\n\tqueue_micro_task(remove_defaults);\n\tadd_form_reset_listener();\n}\n\n/**\n * @param {Element} element\n * @param {any} value\n */\nexport function set_value(element, value) {\n\tvar attributes = get_attributes(element);\n\n\tif (\n\t\tattributes.value ===\n\t\t\t(attributes.value =\n\t\t\t\t// treat null and undefined the same for the initial value\n\t\t\t\tvalue ?? undefined) ||\n\t\t// @ts-expect-error\n\t\t// `progress` elements always need their value set when it's `0`\n\t\t(element.value === value && (value !== 0 || element.nodeName !== PROGRESS_TAG))\n\t) {\n\t\treturn;\n\t}\n\n\t// @ts-expect-error\n\telement.value = value ?? '';\n}\n\n/**\n * @param {Element} element\n * @param {boolean} checked\n */\nexport function set_checked(element, checked) {\n\tvar attributes = get_attributes(element);\n\n\tif (\n\t\tattributes.checked ===\n\t\t(attributes.checked =\n\t\t\t// treat null and undefined the same for the initial value\n\t\t\tchecked ?? undefined)\n\t) {\n\t\treturn;\n\t}\n\n\t// @ts-expect-error\n\telement.checked = checked;\n}\n\n/**\n * Sets the `selected` attribute on an `option` element.\n * Not set through the property because that doesn't reflect to the DOM,\n * which means it wouldn't be taken into account when a form is reset.\n * @param {HTMLOptionElement} element\n * @param {boolean} selected\n */\nexport function set_selected(element, selected) {\n\tif (selected) {\n\t\t// The selected option could've changed via user selection, and\n\t\t// setting the value without this check would set it back.\n\t\tif (!element.hasAttribute('selected')) {\n\t\t\telement.setAttribute('selected', '');\n\t\t}\n\t} else {\n\t\telement.removeAttribute('selected');\n\t}\n}\n\n/**\n * Applies the default checked property without influencing the current checked property.\n * @param {HTMLInputElement} element\n * @param {boolean} checked\n */\nexport function set_default_checked(element, checked) {\n\tconst existing_value = element.checked;\n\telement.defaultChecked = checked;\n\telement.checked = existing_value;\n}\n\n/**\n * Applies the default value property without influencing the current value property.\n * @param {HTMLInputElement | HTMLTextAreaElement} element\n * @param {string} value\n */\nexport function set_default_value(element, value) {\n\tconst existing_value = element.value;\n\telement.defaultValue = value;\n\telement.value = existing_value;\n}\n\n/**\n * @param {Element} element\n * @param {string} attribute\n * @param {string | null} value\n * @param {boolean} [skip_warning]\n */\nexport function set_attribute(element, attribute, value, skip_warning) {\n\tvar attributes = get_attributes(element);\n\n\tif (hydrating) {\n\t\tattributes[attribute] = element.getAttribute(attribute);\n\n\t\tif (\n\t\t\tattribute === 'src' ||\n\t\t\tattribute === 'srcset' ||\n\t\t\t(attribute === 'href' && element.nodeName === LINK_TAG)\n\t\t) {\n\t\t\tif (!skip_warning) {\n\t\t\t\tcheck_src_in_dev_hydration(element, attribute, value ?? '');\n\t\t\t}\n\n\t\t\t// If we reset these attributes, they would result in another network request, which we want to avoid.\n\t\t\t// We assume they are the same between client and server as checking if they are equal is expensive\n\t\t\t// (we can't just compare the strings as they can be different between client and server but result in the\n\t\t\t// same url, so we would need to create hidden anchor elements to compare them)\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (attributes[attribute] === (attributes[attribute] = value)) return;\n\n\tif (attribute === 'loading') {\n\t\t// @ts-expect-error\n\t\telement[LOADING_ATTR_SYMBOL] = value;\n\t}\n\n\tif (value == null) {\n\t\telement.removeAttribute(attribute);\n\t} else if (typeof value !== 'string' && get_setters(element).includes(attribute)) {\n\t\t// @ts-ignore\n\t\telement[attribute] = value;\n\t} else {\n\t\telement.setAttribute(attribute, value);\n\t}\n}\n\n/**\n * @param {Element} dom\n * @param {string} attribute\n * @param {string} value\n */\nexport function set_xlink_attribute(dom, attribute, value) {\n\tdom.setAttributeNS('http://www.w3.org/1999/xlink', attribute, value);\n}\n\n/**\n * @param {HTMLElement} node\n * @param {string} prop\n * @param {any} value\n */\nexport function set_custom_element_data(node, prop, value) {\n\t// We need to ensure that setting custom element props, which can\n\t// invoke lifecycle methods on other custom elements, does not also\n\t// associate those lifecycle methods with the current active reaction\n\t// or effect\n\tvar previous_reaction = active_reaction;\n\tvar previous_effect = active_effect;\n\n\t// If we're hydrating but the custom element is from Svelte, and it already scaffolded,\n\t// then it might run block logic in hydration mode, which we have to prevent.\n\tlet was_hydrating = hydrating;\n\tif (hydrating) {\n\t\tset_hydrating(false);\n\t}\n\n\tset_active_reaction(null);\n\tset_active_effect(null);\n\n\ttry {\n\t\tif (\n\t\t\t// `style` should use `set_attribute` rather than the setter\n\t\t\tprop !== 'style' &&\n\t\t\t// Don't compute setters for custom elements while they aren't registered yet,\n\t\t\t// because during their upgrade/instantiation they might add more setters.\n\t\t\t// Instead, fall back to a simple \"an object, then set as property\" heuristic.\n\t\t\t(setters_cache.has(node.getAttribute('is') || node.nodeName) ||\n\t\t\t// customElements may not be available in browser extension contexts\n\t\t\t!customElements ||\n\t\t\tcustomElements.get(node.getAttribute('is') || node.nodeName.toLowerCase())\n\t\t\t\t? get_setters(node).includes(prop)\n\t\t\t\t: value && typeof value === 'object')\n\t\t) {\n\t\t\t// @ts-expect-error\n\t\t\tnode[prop] = value;\n\t\t} else {\n\t\t\t// We did getters etc checks already, stringify before passing to set_attribute\n\t\t\t// to ensure it doesn't invoke the same logic again, and potentially populating\n\t\t\t// the setters cache too early.\n\t\t\tset_attribute(node, prop, value == null ? value : String(value));\n\t\t}\n\t} finally {\n\t\tset_active_reaction(previous_reaction);\n\t\tset_active_effect(previous_effect);\n\t\tif (was_hydrating) {\n\t\t\tset_hydrating(true);\n\t\t}\n\t}\n}\n\n/**\n * Spreads attributes onto a DOM element, taking into account the currently set attributes\n * @param {Element & ElementCSSInlineStyle} element\n * @param {Record<string | symbol, any> | undefined} prev\n * @param {Record<string | symbol, any>} next New attributes - this function mutates this object\n * @param {string} [css_hash]\n * @param {boolean} [should_remove_defaults]\n * @param {boolean} [skip_warning]\n * @returns {Record<string, any>}\n */\nfunction set_attributes(\n\telement,\n\tprev,\n\tnext,\n\tcss_hash,\n\tshould_remove_defaults = false,\n\tskip_warning = false\n) {\n\tif (hydrating && should_remove_defaults && element.nodeName === INPUT_TAG) {\n\t\tvar input = /** @type {HTMLInputElement} */ (element);\n\t\tvar attribute = input.type === 'checkbox' ? 'defaultChecked' : 'defaultValue';\n\n\t\tif (!(attribute in next)) {\n\t\t\tremove_input_defaults(input);\n\t\t}\n\t}\n\n\tvar attributes = get_attributes(element);\n\n\tvar is_custom_element = attributes[IS_CUSTOM_ELEMENT];\n\tvar preserve_attribute_case = !attributes[IS_HTML];\n\n\t// If we're hydrating but the custom element is from Svelte, and it already scaffolded,\n\t// then it might run block logic in hydration mode, which we have to prevent.\n\tlet is_hydrating_custom_element = hydrating && is_custom_element;\n\tif (is_hydrating_custom_element) {\n\t\tset_hydrating(false);\n\t}\n\n\tvar current = prev || {};\n\tvar is_option_element = element.nodeName === OPTION_TAG;\n\n\tfor (var key in prev) {\n\t\tif (!(key in next)) {\n\t\t\tnext[key] = null;\n\t\t}\n\t}\n\n\tif (next.class) {\n\t\tnext.class = clsx(next.class);\n\t} else if (css_hash || next[CLASS]) {\n\t\tnext.class = null; /* force call to set_class() */\n\t}\n\n\tif (next[STYLE]) {\n\t\tnext.style ??= null; /* force call to set_style() */\n\t}\n\n\tvar setters = get_setters(element);\n\n\t// since key is captured we use const\n\tfor (const key in next) {\n\t\t// let instead of var because referenced in a closure\n\t\tlet value = next[key];\n\n\t\t// Up here because we want to do this for the initial value, too, even if it's undefined,\n\t\t// and this wouldn't be reached in case of undefined because of the equality check below\n\t\tif (is_option_element && key === 'value' && value == null) {\n\t\t\t// The <option> element is a special case because removing the value attribute means\n\t\t\t// the value is set to the text content of the option element, and setting the value\n\t\t\t// to null or undefined means the value is set to the string \"null\" or \"undefined\".\n\t\t\t// To align with how we handle this case in non-spread-scenarios, this logic is needed.\n\t\t\t// There's a super-edge-case bug here that is left in in favor of smaller code size:\n\t\t\t// Because of the \"set missing props to null\" logic above, we can't differentiate\n\t\t\t// between a missing value and an explicitly set value of null or undefined. That means\n\t\t\t// that once set, the value attribute of an <option> element can't be removed. This is\n\t\t\t// a very rare edge case, and removing the attribute altogether isn't possible either\n\t\t\t// for the <option value={undefined}> case, so we're not losing any functionality here.\n\t\t\t// @ts-ignore\n\t\t\telement.value = element.__value = '';\n\t\t\tcurrent[key] = value;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (key === 'class') {\n\t\t\tvar is_html = element.namespaceURI === 'http://www.w3.org/1999/xhtml';\n\t\t\tset_class(element, is_html, value, css_hash, prev?.[CLASS], next[CLASS]);\n\t\t\tcurrent[key] = value;\n\t\t\tcurrent[CLASS] = next[CLASS];\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (key === 'style') {\n\t\t\tset_style(element, value, prev?.[STYLE], next[STYLE]);\n\t\t\tcurrent[key] = value;\n\t\t\tcurrent[STYLE] = next[STYLE];\n\t\t\tcontinue;\n\t\t}\n\n\t\tvar prev_value = current[key];\n\n\t\t// Skip if value is unchanged, unless it's `undefined` and the element still has the attribute\n\t\tif (value === prev_value && !(value === undefined && element.hasAttribute(key))) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tcurrent[key] = value;\n\n\t\tvar prefix = key[0] + key[1]; // this is faster than key.slice(0, 2)\n\t\tif (prefix === '$$') continue;\n\n\t\tif (prefix === 'on') {\n\t\t\t/** @type {{ capture?: true }} */\n\t\t\tconst opts = {};\n\t\t\tconst event_handle_key = '$$' + key;\n\t\t\tlet event_name = key.slice(2);\n\t\t\tvar is_delegated = can_delegate_event(event_name);\n\n\t\t\tif (is_capture_event(event_name)) {\n\t\t\t\tevent_name = event_name.slice(0, -7);\n\t\t\t\topts.capture = true;\n\t\t\t}\n\n\t\t\tif (!is_delegated && prev_value) {\n\t\t\t\t// Listening to same event but different handler -> our handle function below takes care of this\n\t\t\t\t// If we were to remove and add listeners in this case, it could happen that the event is \"swallowed\"\n\t\t\t\t// (the browser seems to not know yet that a new one exists now) and doesn't reach the handler\n\t\t\t\t// https://github.com/sveltejs/svelte/issues/11903\n\t\t\t\tif (value != null) continue;\n\n\t\t\t\telement.removeEventListener(event_name, current[event_handle_key], opts);\n\t\t\t\tcurrent[event_handle_key] = null;\n\t\t\t}\n\n\t\t\tif (is_delegated) {\n\t\t\t\tdelegated(event_name, element, value);\n\t\t\t\tdelegate([event_name]);\n\t\t\t} else if (value != null) {\n\t\t\t\t/**\n\t\t\t\t * @this {any}\n\t\t\t\t * @param {Event} evt\n\t\t\t\t */\n\t\t\t\tfunction handle(evt) {\n\t\t\t\t\tcurrent[key].call(this, evt);\n\t\t\t\t}\n\n\t\t\t\tcurrent[event_handle_key] = create_event(event_name, element, handle, opts);\n\t\t\t}\n\t\t} else if (key === 'style') {\n\t\t\t// avoid using the setter\n\t\t\tset_attribute(element, key, value);\n\t\t} else if (key === 'autofocus') {\n\t\t\tautofocus(/** @type {HTMLElement} */ (element), Boolean(value));\n\t\t} else if (!is_custom_element && (key === '__value' || (key === 'value' && value != null))) {\n\t\t\t// @ts-ignore We're not running this for custom elements because __value is actually\n\t\t\t// how Lit stores the current value on the element, and messing with that would break things.\n\t\t\telement.value = element.__value = value;\n\t\t} else if (key === 'selected' && is_option_element) {\n\t\t\tset_selected(/** @type {HTMLOptionElement} */ (element), value);\n\t\t} else {\n\t\t\tvar name = key;\n\t\t\tif (!preserve_attribute_case) {\n\t\t\t\tname = normalize_attribute(name);\n\t\t\t}\n\n\t\t\tvar is_default = name === 'defaultValue' || name === 'defaultChecked';\n\n\t\t\tif (value == null && !is_custom_element && !is_default) {\n\t\t\t\tattributes[key] = null;\n\n\t\t\t\tif (name === 'value' || name === 'checked') {\n\t\t\t\t\t// removing value/checked also removes defaultValue/defaultChecked — preserve\n\t\t\t\t\tlet input = /** @type {HTMLInputElement} */ (element);\n\t\t\t\t\tconst use_default = prev === undefined;\n\t\t\t\t\tif (name === 'value') {\n\t\t\t\t\t\tlet previous = input.defaultValue;\n\t\t\t\t\t\tinput.removeAttribute(name);\n\t\t\t\t\t\tinput.defaultValue = previous;\n\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\tinput.value = input.__value = use_default ? previous : null;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlet previous = input.defaultChecked;\n\t\t\t\t\t\tinput.removeAttribute(name);\n\t\t\t\t\t\tinput.defaultChecked = previous;\n\t\t\t\t\t\tinput.checked = use_default ? previous : false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\telement.removeAttribute(key);\n\t\t\t\t}\n\t\t\t} else if (\n\t\t\t\tis_default ||\n\t\t\t\t(setters.includes(name) && (is_custom_element || typeof value !== 'string'))\n\t\t\t) {\n\t\t\t\t// @ts-ignore\n\t\t\t\telement[name] = value;\n\t\t\t\t// remove it from attributes's cache\n\t\t\t\tif (name in attributes) attributes[name] = UNINITIALIZED;\n\t\t\t} else if (typeof value !== 'function') {\n\t\t\t\tset_attribute(element, name, value, skip_warning);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (is_hydrating_custom_element) {\n\t\tset_hydrating(true);\n\t}\n\n\treturn current;\n}\n\n/**\n * @param {Element & ElementCSSInlineStyle} element\n * @param {(...expressions: any) => Record<string | symbol, any>} fn\n * @param {Array<() => any>} sync\n * @param {Array<() => Promise<any>>} async\n * @param {Blocker[]} blockers\n * @param {string} [css_hash]\n * @param {boolean} [should_remove_defaults]\n * @param {boolean} [skip_warning]\n */\nexport function attribute_effect(\n\telement,\n\tfn,\n\tsync = [],\n\tasync = [],\n\tblockers = [],\n\tcss_hash,\n\tshould_remove_defaults = false,\n\tskip_warning = false\n) {\n\tflatten(blockers, sync, async, (values) => {\n\t\t/** @type {Record<string | symbol, any> | undefined} */\n\t\tvar prev = undefined;\n\n\t\t/** @type {Record<symbol, Effect>} */\n\t\tvar effects = {};\n\n\t\tvar is_select = element.nodeName === SELECT_TAG;\n\t\tvar inited = false;\n\n\t\tmanaged(() => {\n\t\t\tvar next = fn(...values.map(get));\n\t\t\t/** @type {Record<string | symbol, any>} */\n\t\t\tvar current = set_attributes(\n\t\t\t\telement,\n\t\t\t\tprev,\n\t\t\t\tnext,\n\t\t\t\tcss_hash,\n\t\t\t\tshould_remove_defaults,\n\t\t\t\tskip_warning\n\t\t\t);\n\n\t\t\tif (inited && is_select && 'value' in next) {\n\t\t\t\tselect_option(/** @type {HTMLSelectElement} */ (element), next.value);\n\t\t\t}\n\n\t\t\tfor (let symbol of Object.getOwnPropertySymbols(effects)) {\n\t\t\t\tif (!next[symbol]) destroy_effect(effects[symbol]);\n\t\t\t}\n\n\t\t\tfor (let symbol of Object.getOwnPropertySymbols(next)) {\n\t\t\t\tvar n = next[symbol];\n\n\t\t\t\tif (symbol.description === ATTACHMENT_KEY && (!prev || n !== prev[symbol])) {\n\t\t\t\t\tif (effects[symbol]) destroy_effect(effects[symbol]);\n\t\t\t\t\teffects[symbol] = branch(() => attach(element, () => n));\n\t\t\t\t}\n\n\t\t\t\tcurrent[symbol] = n;\n\t\t\t}\n\n\t\t\tprev = current;\n\t\t});\n\n\t\tif (is_select) {\n\t\t\tvar select = /** @type {HTMLSelectElement} */ (element);\n\n\t\t\teffect(() => {\n\t\t\t\tselect_option(select, /** @type {Record<string | symbol, any>} */ (prev).value, true);\n\t\t\t\tinit_select(select);\n\t\t\t});\n\t\t}\n\n\t\tinited = true;\n\t});\n}\n\n/**\n *\n * @param {Element} element\n */\nfunction get_attributes(element) {\n\treturn /** @type {Record<string | symbol, unknown>} **/ (\n\t\t// @ts-expect-error\n\t\telement.__attributes ??= {\n\t\t\t[IS_CUSTOM_ELEMENT]: element.nodeName.includes('-'),\n\t\t\t[IS_HTML]: element.namespaceURI === NAMESPACE_HTML\n\t\t}\n\t);\n}\n\n/** @type {Map<string, string[]>} */\nvar setters_cache = new Map();\n\n/** @param {Element} element */\nfunction get_setters(element) {\n\tvar cache_key = element.getAttribute('is') || element.nodeName;\n\tvar setters = setters_cache.get(cache_key);\n\tif (setters) return setters;\n\tsetters_cache.set(cache_key, (setters = []));\n\n\tvar descriptors;\n\tvar proto = element; // In the case of custom elements there might be setters on the instance\n\tvar element_proto = Element.prototype;\n\n\t// Stop at Element, from there on there's only unnecessary setters we're not interested in\n\t// Do not use contructor.name here as that's unreliable in some browser environments\n\twhile (element_proto !== proto) {\n\t\tdescriptors = get_descriptors(proto);\n\n\t\tfor (var key in descriptors) {\n\t\t\tif (descriptors[key].set) {\n\t\t\t\tsetters.push(key);\n\t\t\t}\n\t\t}\n\n\t\tproto = get_prototype_of(proto);\n\t}\n\n\treturn setters;\n}\n\n/**\n * @param {any} element\n * @param {string} attribute\n * @param {string} value\n */\nfunction check_src_in_dev_hydration(element, attribute, value) {\n\tif (!DEV) return;\n\tif (attribute === 'srcset' && srcset_url_equal(element, value)) return;\n\tif (src_url_equal(element.getAttribute(attribute) ?? '', value)) return;\n\n\tw.hydration_attribute_changed(\n\t\tattribute,\n\t\telement.outerHTML.replace(element.innerHTML, element.innerHTML && '...'),\n\t\tString(value)\n\t);\n}\n\n/**\n * @param {string} element_src\n * @param {string} url\n * @returns {boolean}\n */\nfunction src_url_equal(element_src, url) {\n\tif (element_src === url) return true;\n\treturn new URL(element_src, document.baseURI).href === new URL(url, document.baseURI).href;\n}\n\n/** @param {string} srcset */\nfunction split_srcset(srcset) {\n\treturn srcset.split(',').map((src) => src.trim().split(' ').filter(Boolean));\n}\n\n/**\n * @param {HTMLSourceElement | HTMLImageElement} element\n * @param {string} srcset\n * @returns {boolean}\n */\nfunction srcset_url_equal(element, srcset) {\n\tvar element_urls = split_srcset(element.srcset);\n\tvar urls = split_srcset(srcset);\n\n\treturn (\n\t\turls.length === element_urls.length &&\n\t\turls.every(\n\t\t\t([url, width], i) =>\n\t\t\t\twidth === element_urls[i][1] &&\n\t\t\t\t// We need to test both ways because Vite will create an a full URL with\n\t\t\t\t// `new URL(asset, import.meta.url).href` for the client when `base: './'`, and the\n\t\t\t\t// relative URLs inside srcset are not automatically resolved to absolute URLs by\n\t\t\t\t// browsers (in contrast to img.src). This means both SSR and DOM code could\n\t\t\t\t// contain relative or absolute URLs.\n\t\t\t\t(src_url_equal(element_urls[i][0], url) || src_url_equal(url, element_urls[i][0]))\n\t\t)\n\t);\n}\n","import { hydrating, reset, set_hydrate_node, set_hydrating } from '../hydration.js';\nimport { create_comment, create_element } from '../operations.js';\nimport { create_trusted_html } from '../reconciler.js';\nimport { attach } from './attachments.js';\n\n/** @type {boolean | null} */\nlet supported = null;\n\n/**\n * Checks if the browser supports rich HTML content inside `<option>` elements.\n * Modern browsers preserve HTML elements inside options, while older browsers\n * strip them during parsing, leaving only text content.\n * @returns {boolean}\n */\nfunction is_supported() {\n\tif (supported === null) {\n\t\tvar select = create_element('select');\n\t\tselect.innerHTML = create_trusted_html('<option><span>t</span></option>');\n\t\tsupported = /** @type {Element} */ (select.firstChild)?.firstChild?.nodeType === 1;\n\t}\n\n\treturn supported;\n}\n\n/**\n *\n * @param {HTMLElement} element\n * @param {(new_element: HTMLElement) => void} update_element\n */\nexport function selectedcontent(element, update_element) {\n\t// if it's not supported no need for special logic\n\tif (!is_supported()) return;\n\n\t// we use the attach function directly just to make sure is executed when is mounted to the dom\n\tattach(element, () => () => {\n\t\tconst select = element.closest('select');\n\t\tif (!select) return;\n\n\t\tconst observer = new MutationObserver((entries) => {\n\t\t\tvar selected = false;\n\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.target === element) {\n\t\t\t\t\t// the `<selectedcontent>` already changed, no need to replace it\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// if the changes doesn't include the selected `<option>` we don't need to do anything\n\t\t\t\tselected ||= !!entry.target.parentElement?.closest('option')?.selected;\n\t\t\t}\n\n\t\t\tif (selected) {\n\t\t\t\t// replace the `<selectedcontent>` with a clone\n\t\t\t\telement.replaceWith((element = /** @type {HTMLElement} */ (element.cloneNode(true))));\n\t\t\t\tupdate_element(element);\n\t\t\t}\n\t\t});\n\n\t\tobserver.observe(select, {\n\t\t\tchildList: true,\n\t\t\tcharacterData: true,\n\t\t\tsubtree: true\n\t\t});\n\n\t\treturn () => {\n\t\t\tobserver.disconnect();\n\t\t};\n\t});\n}\n\n/**\n * Handles rich HTML content inside `<option>`, `<optgroup>`, or `<select>` elements with browser-specific branching.\n * Modern browsers preserve HTML inside options, while older browsers strip it to text only.\n *\n * @param {HTMLOptionElement | HTMLOptGroupElement | HTMLSelectElement} element The element to process\n * @param {() => void} rich_fn Function to process rich HTML content (modern browsers)\n */\nexport function customizable_select(element, rich_fn) {\n\tvar was_hydrating = hydrating;\n\n\tif (!is_supported()) {\n\t\tset_hydrating(false);\n\t\telement.textContent = '';\n\t\telement.append(create_comment(''));\n\t}\n\n\ttry {\n\t\trich_fn();\n\t} finally {\n\t\tif (was_hydrating) {\n\t\t\tif (hydrating) {\n\t\t\t\treset(element);\n\t\t\t} else {\n\t\t\t\tset_hydrating(true);\n\t\t\t\tset_hydrate_node(element);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { listen } from './shared.js';\n\n/**\n * @param {(activeElement: Element | null) => void} update\n * @returns {void}\n */\nexport function bind_active_element(update) {\n\tlisten(document, ['focusin', 'focusout'], (event) => {\n\t\tif (event && event.type === 'focusout' && /** @type {FocusEvent} */ (event).relatedTarget) {\n\t\t\t// The tests still pass if we remove this, because of JSDOM limitations, but it is necessary\n\t\t\t// to avoid temporarily resetting to `document.body`\n\t\t\treturn;\n\t\t}\n\n\t\tupdate(document.activeElement);\n\t});\n}\n","/** @import { Batch } from '../../../reactivity/batch.js' */\nimport { DEV } from 'esm-env';\nimport { render_effect, teardown } from '../../../reactivity/effects.js';\nimport { listen_to_event_and_reset_event } from './shared.js';\nimport * as e from '../../../errors.js';\nimport { is } from '../../../proxy.js';\nimport { queue_micro_task } from '../../task.js';\nimport { hydrating } from '../../hydration.js';\nimport { tick, untrack } from '../../../runtime.js';\nimport { is_runes } from '../../../context.js';\nimport { current_batch, previous_batch } from '../../../reactivity/batch.js';\nimport { async_mode_flag } from '../../../../flags/index.js';\n\n/**\n * @param {HTMLInputElement} input\n * @param {() => unknown} get\n * @param {(value: unknown) => void} set\n * @returns {void}\n */\nexport function bind_value(input, get, set = get) {\n\tvar batches = new WeakSet();\n\n\tlisten_to_event_and_reset_event(input, 'input', async (is_reset) => {\n\t\tif (DEV && input.type === 'checkbox') {\n\t\t\t// TODO should this happen in prod too?\n\t\t\te.bind_invalid_checkbox_value();\n\t\t}\n\n\t\t/** @type {any} */\n\t\tvar value = is_reset ? input.defaultValue : input.value;\n\t\tvalue = is_numberlike_input(input) ? to_number(value) : value;\n\t\tset(value);\n\n\t\tif (current_batch !== null) {\n\t\t\tbatches.add(current_batch);\n\t\t}\n\n\t\t// Because `{#each ...}` blocks work by updating sources inside the flush,\n\t\t// we need to wait a tick before checking to see if we should forcibly\n\t\t// update the input and reset the selection state\n\t\tawait tick();\n\n\t\t// Respect any validation in accessors\n\t\tif (value !== (value = get())) {\n\t\t\tvar start = input.selectionStart;\n\t\t\tvar end = input.selectionEnd;\n\t\t\tvar length = input.value.length;\n\n\t\t\t// the value is coerced on assignment\n\t\t\tinput.value = value ?? '';\n\n\t\t\t// Restore selection\n\t\t\tif (end !== null) {\n\t\t\t\tvar new_length = input.value.length;\n\t\t\t\t// If cursor was at end and new input is longer, move cursor to new end\n\t\t\t\tif (start === end && end === length && new_length > length) {\n\t\t\t\t\tinput.selectionStart = new_length;\n\t\t\t\t\tinput.selectionEnd = new_length;\n\t\t\t\t} else {\n\t\t\t\t\tinput.selectionStart = start;\n\t\t\t\t\tinput.selectionEnd = Math.min(end, new_length);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n\n\tif (\n\t\t// If we are hydrating and the value has since changed,\n\t\t// then use the updated value from the input instead.\n\t\t(hydrating && input.defaultValue !== input.value) ||\n\t\t// If defaultValue is set, then value == defaultValue\n\t\t// TODO Svelte 6: remove input.value check and set to empty string?\n\t\t(untrack(get) == null && input.value)\n\t) {\n\t\tset(is_numberlike_input(input) ? to_number(input.value) : input.value);\n\n\t\tif (current_batch !== null) {\n\t\t\tbatches.add(current_batch);\n\t\t}\n\t}\n\n\trender_effect(() => {\n\t\tif (DEV && input.type === 'checkbox') {\n\t\t\t// TODO should this happen in prod too?\n\t\t\te.bind_invalid_checkbox_value();\n\t\t}\n\n\t\tvar value = get();\n\n\t\tif (input === document.activeElement) {\n\t\t\t// In sync mode render effects are executed during tree traversal -> needs current_batch\n\t\t\t// In async mode render effects are flushed once batch resolved, at which point current_batch is null -> needs previous_batch\n\t\t\tvar batch = /** @type {Batch} */ (async_mode_flag ? previous_batch : current_batch);\n\n\t\t\t// Never rewrite the contents of a focused input. We can get here if, for example,\n\t\t\t// an update is deferred because of async work depending on the input:\n\t\t\t//\n\t\t\t// <input bind:value={query}>\n\t\t\t// <p>{await find(query)}</p>\n\t\t\tif (batches.has(batch)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (is_numberlike_input(input) && value === to_number(input.value)) {\n\t\t\t// handles 0 vs 00 case (see https://github.com/sveltejs/svelte/issues/9959)\n\t\t\treturn;\n\t\t}\n\n\t\tif (input.type === 'date' && !value && !input.value) {\n\t\t\t// Handles the case where a temporarily invalid date is set (while typing, for example with a leading 0 for the day)\n\t\t\t// and prevents this state from clearing the other parts of the date input (see https://github.com/sveltejs/svelte/issues/7897)\n\t\t\treturn;\n\t\t}\n\n\t\t// don't set the value of the input if it's the same to allow\n\t\t// minlength to work properly\n\t\tif (value !== input.value) {\n\t\t\t// @ts-expect-error the value is coerced on assignment\n\t\t\tinput.value = value ?? '';\n\t\t}\n\t});\n}\n\n/** @type {Set<HTMLInputElement[]>} */\nconst pending = new Set();\n\n/**\n * @param {HTMLInputElement[]} inputs\n * @param {null | [number]} group_index\n * @param {HTMLInputElement} input\n * @param {() => unknown} get\n * @param {(value: unknown) => void} set\n * @returns {void}\n */\nexport function bind_group(inputs, group_index, input, get, set = get) {\n\tvar is_checkbox = input.getAttribute('type') === 'checkbox';\n\tvar binding_group = inputs;\n\n\t// needs to be let or related code isn't treeshaken out if it's always false\n\tlet hydration_mismatch = false;\n\n\tif (group_index !== null) {\n\t\tfor (var index of group_index) {\n\t\t\t// @ts-expect-error\n\t\t\tbinding_group = binding_group[index] ??= [];\n\t\t}\n\t}\n\n\tbinding_group.push(input);\n\n\tlisten_to_event_and_reset_event(\n\t\tinput,\n\t\t'change',\n\t\t() => {\n\t\t\t// @ts-ignore\n\t\t\tvar value = input.__value;\n\n\t\t\tif (is_checkbox) {\n\t\t\t\tvalue = get_binding_group_value(binding_group, value, input.checked);\n\t\t\t}\n\n\t\t\tset(value);\n\t\t},\n\t\t// TODO better default value handling\n\t\t() => set(is_checkbox ? [] : null)\n\t);\n\n\trender_effect(() => {\n\t\tvar value = get();\n\n\t\t// If we are hydrating and the value has since changed, then use the update value\n\t\t// from the input instead.\n\t\tif (hydrating && input.defaultChecked !== input.checked) {\n\t\t\thydration_mismatch = true;\n\t\t\treturn;\n\t\t}\n\n\t\tif (is_checkbox) {\n\t\t\tvalue = value || [];\n\t\t\t// @ts-ignore\n\t\t\tinput.checked = value.includes(input.__value);\n\t\t} else {\n\t\t\t// @ts-ignore\n\t\t\tinput.checked = is(input.__value, value);\n\t\t}\n\t});\n\n\tteardown(() => {\n\t\tvar index = binding_group.indexOf(input);\n\n\t\tif (index !== -1) {\n\t\t\tbinding_group.splice(index, 1);\n\t\t}\n\t});\n\n\tif (!pending.has(binding_group)) {\n\t\tpending.add(binding_group);\n\n\t\tqueue_micro_task(() => {\n\t\t\t// necessary to maintain binding group order in all insertion scenarios\n\t\t\tbinding_group.sort((a, b) => (a.compareDocumentPosition(b) === 4 ? -1 : 1));\n\t\t\tpending.delete(binding_group);\n\t\t});\n\t}\n\n\tqueue_micro_task(() => {\n\t\tif (hydration_mismatch) {\n\t\t\tvar value;\n\n\t\t\tif (is_checkbox) {\n\t\t\t\tvalue = get_binding_group_value(binding_group, value, input.checked);\n\t\t\t} else {\n\t\t\t\tvar hydration_input = binding_group.find((input) => input.checked);\n\t\t\t\t// @ts-ignore\n\t\t\t\tvalue = hydration_input?.__value;\n\t\t\t}\n\n\t\t\tset(value);\n\t\t}\n\t});\n}\n\n/**\n * @param {HTMLInputElement} input\n * @param {() => unknown} get\n * @param {(value: unknown) => void} set\n * @returns {void}\n */\nexport function bind_checked(input, get, set = get) {\n\tlisten_to_event_and_reset_event(input, 'change', (is_reset) => {\n\t\tvar value = is_reset ? input.defaultChecked : input.checked;\n\t\tset(value);\n\t});\n\n\tif (\n\t\t// If we are hydrating and the value has since changed,\n\t\t// then use the update value from the input instead.\n\t\t(hydrating && input.defaultChecked !== input.checked) ||\n\t\t// If defaultChecked is set, then checked == defaultChecked\n\t\tuntrack(get) == null\n\t) {\n\t\tset(input.checked);\n\t}\n\n\trender_effect(() => {\n\t\tvar value = get();\n\t\tinput.checked = Boolean(value);\n\t});\n}\n\n/**\n * @template V\n * @param {Array<HTMLInputElement>} group\n * @param {V} __value\n * @param {boolean} checked\n * @returns {V[]}\n */\nfunction get_binding_group_value(group, __value, checked) {\n\t/** @type {Set<V>} */\n\tvar value = new Set();\n\n\tfor (var i = 0; i < group.length; i += 1) {\n\t\tif (group[i].checked) {\n\t\t\t// @ts-ignore\n\t\t\tvalue.add(group[i].__value);\n\t\t}\n\t}\n\n\tif (!checked) {\n\t\tvalue.delete(__value);\n\t}\n\n\treturn Array.from(value);\n}\n\n/**\n * @param {HTMLInputElement} input\n */\nfunction is_numberlike_input(input) {\n\tvar type = input.type;\n\treturn type === 'number' || type === 'range';\n}\n\n/**\n * @param {string} value\n */\nfunction to_number(value) {\n\treturn value === '' ? null : +value;\n}\n\n/**\n * @param {HTMLInputElement} input\n * @param {() => FileList | null} get\n * @param {(value: FileList | null) => void} set\n */\nexport function bind_files(input, get, set = get) {\n\tlisten_to_event_and_reset_event(input, 'change', () => {\n\t\tset(input.files);\n\t});\n\n\tif (\n\t\t// If we are hydrating and the value has since changed,\n\t\t// then use the updated value from the input instead.\n\t\thydrating &&\n\t\tinput.files\n\t) {\n\t\tset(input.files);\n\t}\n\n\trender_effect(() => {\n\t\tinput.files = get();\n\t});\n}\n","import { render_effect, effect, teardown } from '../../../reactivity/effects.js';\nimport { listen } from './shared.js';\n\n/** @param {TimeRanges} ranges */\nfunction time_ranges_to_array(ranges) {\n\tvar array = [];\n\n\tfor (var i = 0; i < ranges.length; i += 1) {\n\t\tarray.push({ start: ranges.start(i), end: ranges.end(i) });\n\t}\n\n\treturn array;\n}\n\n/**\n * @param {HTMLVideoElement | HTMLAudioElement} media\n * @param {() => number | undefined} get\n * @param {(value: number) => void} set\n * @returns {void}\n */\nexport function bind_current_time(media, get, set = get) {\n\t/** @type {number} */\n\tvar raf_id;\n\t/** @type {number} */\n\tvar value;\n\n\t// Ideally, listening to timeupdate would be enough, but it fires too infrequently for the currentTime\n\t// binding, which is why we use a raf loop, too. We additionally still listen to timeupdate because\n\t// the user could be scrubbing through the video using the native controls when the media is paused.\n\tvar callback = () => {\n\t\tcancelAnimationFrame(raf_id);\n\n\t\tif (!media.paused) {\n\t\t\traf_id = requestAnimationFrame(callback);\n\t\t}\n\n\t\tvar next_value = media.currentTime;\n\t\tif (value !== next_value) {\n\t\t\tset((value = next_value));\n\t\t}\n\t};\n\n\traf_id = requestAnimationFrame(callback);\n\tmedia.addEventListener('timeupdate', callback);\n\n\trender_effect(() => {\n\t\tvar next_value = Number(get());\n\n\t\tif (value !== next_value && !isNaN(/** @type {any} */ (next_value))) {\n\t\t\tmedia.currentTime = value = next_value;\n\t\t}\n\t});\n\n\tteardown(() => {\n\t\tcancelAnimationFrame(raf_id);\n\t\tmedia.removeEventListener('timeupdate', callback);\n\t});\n}\n\n/**\n * @param {HTMLVideoElement | HTMLAudioElement} media\n * @param {(array: Array<{ start: number; end: number }>) => void} set\n */\nexport function bind_buffered(media, set) {\n\t/** @type {{ start: number; end: number; }[]} */\n\tvar current;\n\n\t// `buffered` can update without emitting any event, so we check it on various events.\n\t// By specs, `buffered` always returns a new object, so we have to compare deeply.\n\tlisten(media, ['loadedmetadata', 'progress', 'timeupdate', 'seeking'], () => {\n\t\tvar ranges = media.buffered;\n\n\t\tif (\n\t\t\t!current ||\n\t\t\tcurrent.length !== ranges.length ||\n\t\t\tcurrent.some((range, i) => ranges.start(i) !== range.start || ranges.end(i) !== range.end)\n\t\t) {\n\t\t\tcurrent = time_ranges_to_array(ranges);\n\t\t\tset(current);\n\t\t}\n\t});\n}\n\n/**\n * @param {HTMLVideoElement | HTMLAudioElement} media\n * @param {(array: Array<{ start: number; end: number }>) => void} set\n */\nexport function bind_seekable(media, set) {\n\tlisten(media, ['loadedmetadata'], () => set(time_ranges_to_array(media.seekable)));\n}\n\n/**\n * @param {HTMLVideoElement | HTMLAudioElement} media\n * @param {(array: Array<{ start: number; end: number }>) => void} set\n */\nexport function bind_played(media, set) {\n\tlisten(media, ['timeupdate'], () => set(time_ranges_to_array(media.played)));\n}\n\n/**\n * @param {HTMLVideoElement | HTMLAudioElement} media\n * @param {(seeking: boolean) => void} set\n */\nexport function bind_seeking(media, set) {\n\tlisten(media, ['seeking', 'seeked'], () => set(media.seeking));\n}\n\n/**\n * @param {HTMLVideoElement | HTMLAudioElement} media\n * @param {(seeking: boolean) => void} set\n */\nexport function bind_ended(media, set) {\n\tlisten(media, ['timeupdate', 'ended'], () => set(media.ended));\n}\n\n/**\n * @param {HTMLVideoElement | HTMLAudioElement} media\n * @param {(ready_state: number) => void} set\n */\nexport function bind_ready_state(media, set) {\n\tlisten(\n\t\tmedia,\n\t\t['loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'emptied'],\n\t\t() => set(media.readyState)\n\t);\n}\n\n/**\n * @param {HTMLVideoElement | HTMLAudioElement} media\n * @param {() => number | undefined} get\n * @param {(playback_rate: number) => void} set\n */\nexport function bind_playback_rate(media, get, set = get) {\n\t// Needs to happen after element is inserted into the dom (which is guaranteed by using effect),\n\t// else playback will be set back to 1 by the browser\n\teffect(() => {\n\t\tvar value = Number(get());\n\n\t\tif (value !== media.playbackRate && !isNaN(value)) {\n\t\t\tmedia.playbackRate = value;\n\t\t}\n\t});\n\n\t// Start listening to ratechange events after the element is inserted into the dom,\n\t// else playback will be set to 1 by the browser\n\teffect(() => {\n\t\tlisten(media, ['ratechange'], () => {\n\t\t\tset(media.playbackRate);\n\t\t});\n\t});\n}\n\n/**\n * @param {HTMLVideoElement | HTMLAudioElement} media\n * @param {() => boolean | undefined} get\n * @param {(paused: boolean) => void} set\n */\nexport function bind_paused(media, get, set = get) {\n\tvar paused = get();\n\n\tvar update = () => {\n\t\tif (paused !== media.paused) {\n\t\t\tset((paused = media.paused));\n\t\t}\n\t};\n\n\t// If someone switches the src while media is playing, the player will pause.\n\t// Listen to the canplay event to get notified of this situation.\n\tlisten(media, ['play', 'pause', 'canplay'], update, paused == null);\n\n\t// Needs to be an effect to ensure media element is mounted: else, if paused is `false` (i.e. should play right away)\n\t// a \"The play() request was interrupted by a new load request\" error would be thrown because the resource isn't loaded yet.\n\teffect(() => {\n\t\tif ((paused = !!get()) !== media.paused) {\n\t\t\tif (paused) {\n\t\t\t\tmedia.pause();\n\t\t\t} else {\n\t\t\t\tmedia.play().catch((error) => {\n\t\t\t\t\tset((paused = true));\n\t\t\t\t\tthrow error;\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t});\n}\n\n/**\n * @param {HTMLVideoElement | HTMLAudioElement} media\n * @param {() => number | undefined} get\n * @param {(volume: number) => void} set\n */\nexport function bind_volume(media, get, set = get) {\n\tvar callback = () => {\n\t\tset(media.volume);\n\t};\n\n\tif (get() == null) {\n\t\tcallback();\n\t}\n\n\tlisten(media, ['volumechange'], callback, false);\n\n\trender_effect(() => {\n\t\tvar value = Number(get());\n\n\t\tif (value !== media.volume && !isNaN(value)) {\n\t\t\tmedia.volume = value;\n\t\t}\n\t});\n}\n\n/**\n * @param {HTMLVideoElement | HTMLAudioElement} media\n * @param {() => boolean | undefined} get\n * @param {(muted: boolean) => void} set\n */\nexport function bind_muted(media, get, set = get) {\n\tvar callback = () => {\n\t\tset(media.muted);\n\t};\n\n\tif (get() == null) {\n\t\tcallback();\n\t}\n\n\tlisten(media, ['volumechange'], callback, false);\n\n\trender_effect(() => {\n\t\tvar value = !!get();\n\n\t\tif (media.muted !== value) media.muted = value;\n\t});\n}\n","import { listen } from './shared.js';\n\n/**\n * @param {(online: boolean) => void} update\n * @returns {void}\n */\nexport function bind_online(update) {\n\tlisten(window, ['online', 'offline'], () => {\n\t\tupdate(navigator.onLine);\n\t});\n}\n","import { teardown } from '../../../reactivity/effects.js';\nimport { get_descriptor } from '../../../../shared/utils.js';\n\n/**\n * Makes an `export`ed (non-prop) variable available on the `$$props` object\n * so that consumers can do `bind:x` on the component.\n * @template V\n * @param {Record<string, unknown>} props\n * @param {string} prop\n * @param {V} value\n * @returns {void}\n */\nexport function bind_prop(props, prop, value) {\n\tvar desc = get_descriptor(props, prop);\n\n\tif (desc && desc.set) {\n\t\tprops[prop] = value;\n\t\tteardown(() => {\n\t\t\tprops[prop] = null;\n\t\t});\n\t}\n}\n","import { effect, teardown } from '../../../reactivity/effects.js';\nimport { untrack } from '../../../runtime.js';\n\n/**\n * We create one listener for all elements\n * @see {@link https://groups.google.com/a/chromium.org/g/blink-dev/c/z6ienONUb5A/m/F5-VcUZtBAAJ Explanation}\n */\nclass ResizeObserverSingleton {\n\t/** */\n\t#listeners = new WeakMap();\n\n\t/** @type {ResizeObserver | undefined} */\n\t#observer;\n\n\t/** @type {ResizeObserverOptions} */\n\t#options;\n\n\t/** @static */\n\tstatic entries = new WeakMap();\n\n\t/** @param {ResizeObserverOptions} options */\n\tconstructor(options) {\n\t\tthis.#options = options;\n\t}\n\n\t/**\n\t * @param {Element} element\n\t * @param {(entry: ResizeObserverEntry) => any} listener\n\t */\n\tobserve(element, listener) {\n\t\tvar listeners = this.#listeners.get(element) || new Set();\n\t\tlisteners.add(listener);\n\n\t\tthis.#listeners.set(element, listeners);\n\t\tthis.#getObserver().observe(element, this.#options);\n\n\t\treturn () => {\n\t\t\tvar listeners = this.#listeners.get(element);\n\t\t\tlisteners.delete(listener);\n\n\t\t\tif (listeners.size === 0) {\n\t\t\t\tthis.#listeners.delete(element);\n\t\t\t\t/** @type {ResizeObserver} */ (this.#observer).unobserve(element);\n\t\t\t}\n\t\t};\n\t}\n\n\t#getObserver() {\n\t\treturn (\n\t\t\tthis.#observer ??\n\t\t\t(this.#observer = new ResizeObserver(\n\t\t\t\t/** @param {any} entries */ (entries) => {\n\t\t\t\t\tfor (var entry of entries) {\n\t\t\t\t\t\tResizeObserverSingleton.entries.set(entry.target, entry);\n\t\t\t\t\t\tfor (var listener of this.#listeners.get(entry.target) || []) {\n\t\t\t\t\t\t\tlistener(entry);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t))\n\t\t);\n\t}\n}\n\nvar resize_observer_content_box = /* @__PURE__ */ new ResizeObserverSingleton({\n\tbox: 'content-box'\n});\n\nvar resize_observer_border_box = /* @__PURE__ */ new ResizeObserverSingleton({\n\tbox: 'border-box'\n});\n\nvar resize_observer_device_pixel_content_box = /* @__PURE__ */ new ResizeObserverSingleton({\n\tbox: 'device-pixel-content-box'\n});\n\n/**\n * @param {Element} element\n * @param {'contentRect' | 'contentBoxSize' | 'borderBoxSize' | 'devicePixelContentBoxSize'} type\n * @param {(entry: keyof ResizeObserverEntry) => void} set\n */\nexport function bind_resize_observer(element, type, set) {\n\tvar observer =\n\t\ttype === 'contentRect' || type === 'contentBoxSize'\n\t\t\t? resize_observer_content_box\n\t\t\t: type === 'borderBoxSize'\n\t\t\t\t? resize_observer_border_box\n\t\t\t\t: resize_observer_device_pixel_content_box;\n\n\tvar unsub = observer.observe(element, /** @param {any} entry */ (entry) => set(entry[type]));\n\tteardown(unsub);\n}\n\n/**\n * @param {HTMLElement} element\n * @param {'clientWidth' | 'clientHeight' | 'offsetWidth' | 'offsetHeight'} type\n * @param {(size: number) => void} set\n */\nexport function bind_element_size(element, type, set) {\n\tvar unsub = resize_observer_border_box.observe(element, () => set(element[type]));\n\n\teffect(() => {\n\t\t// The update could contain reads which should be ignored\n\t\tuntrack(() => set(element[type]));\n\t\treturn unsub;\n\t});\n}\n","/** @import { ComponentContext, Effect } from '#client' */\nimport { DESTROYING, STATE_SYMBOL } from '#client/constants';\nimport { component_context } from '../../../context.js';\nimport { effect, render_effect } from '../../../reactivity/effects.js';\nimport { active_effect, untrack } from '../../../runtime.js';\n\n/**\n * @param {any} bound_value\n * @param {Element} element_or_component\n * @returns {boolean}\n */\nfunction is_bound_this(bound_value, element_or_component) {\n\treturn (\n\t\tbound_value === element_or_component || bound_value?.[STATE_SYMBOL] === element_or_component\n\t);\n}\n\n/**\n * @param {any} element_or_component\n * @param {(value: unknown, ...parts: unknown[]) => void} update\n * @param {(...parts: unknown[]) => unknown} get_value\n * @param {() => unknown[]} [get_parts] Set if the this binding is used inside an each block,\n * \t\t\t\t\t\t\t\t\t\treturns all the parts of the each block context that are used in the expression\n * @returns {void}\n */\nexport function bind_this(element_or_component = {}, update, get_value, get_parts) {\n\tvar component_effect = /** @type {ComponentContext} */ (component_context).r;\n\tvar parent = /** @type {Effect} */ (active_effect);\n\n\teffect(() => {\n\t\t/** @type {unknown[]} */\n\t\tvar old_parts;\n\n\t\t/** @type {unknown[]} */\n\t\tvar parts;\n\n\t\trender_effect(() => {\n\t\t\told_parts = parts;\n\t\t\t// We only track changes to the parts, not the value itself to avoid unnecessary reruns.\n\t\t\tparts = get_parts?.() || [];\n\n\t\t\tuntrack(() => {\n\t\t\t\tif (element_or_component !== get_value(...parts)) {\n\t\t\t\t\tupdate(element_or_component, ...parts);\n\t\t\t\t\t// If this is an effect rerun (cause: each block context changes), then nullify the binding at\n\t\t\t\t\t// the previous position if it isn't already taken over by a different effect.\n\t\t\t\t\tif (old_parts && is_bound_this(get_value(...old_parts), element_or_component)) {\n\t\t\t\t\t\tupdate(null, ...old_parts);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\n\t\treturn () => {\n\t\t\t// When the bind:this effect is destroyed, we go up the effect parent chain until we find the last parent effect that is destroyed,\n\t\t\t// or the effect containing the component bind:this is in (whichever comes first). That way we can time the nulling of the binding\n\t\t\t// as close to user/developer expectation as possible.\n\t\t\t// TODO Svelte 6: Decide if we want to keep this logic or just always null the binding in the component effect's teardown\n\t\t\t// (which would be simpler, but less intuitive in some cases, and breaks the `ondestroy-before-cleanup` test)\n\t\t\tlet p = parent;\n\t\t\twhile (p !== component_effect && p.parent !== null && p.parent.f & DESTROYING) {\n\t\t\t\tp = p.parent;\n\t\t\t}\n\t\t\tconst teardown = () => {\n\t\t\t\tif (parts && is_bound_this(get_value(...parts), element_or_component)) {\n\t\t\t\t\tupdate(null, ...parts);\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst original_teardown = p.teardown;\n\t\t\tp.teardown = () => {\n\t\t\t\tteardown();\n\t\t\t\toriginal_teardown?.();\n\t\t\t};\n\t\t};\n\t});\n\n\treturn element_or_component;\n}\n","import { render_effect, teardown } from '../../../reactivity/effects.js';\nimport { listen } from './shared.js';\n\n/**\n * @param {'innerHTML' | 'textContent' | 'innerText'} property\n * @param {HTMLElement} element\n * @param {() => unknown} get\n * @param {(value: unknown) => void} set\n * @returns {void}\n */\nexport function bind_content_editable(property, element, get, set = get) {\n\telement.addEventListener('input', () => {\n\t\t// @ts-ignore\n\t\tset(element[property]);\n\t});\n\n\trender_effect(() => {\n\t\tvar value = get();\n\n\t\tif (element[property] !== value) {\n\t\t\tif (value == null) {\n\t\t\t\t// @ts-ignore\n\t\t\t\tvar non_null_value = element[property];\n\t\t\t\tset(non_null_value);\n\t\t\t} else {\n\t\t\t\t// @ts-ignore\n\t\t\t\telement[property] = value + '';\n\t\t\t}\n\t\t}\n\t});\n}\n\n/**\n * @param {string} property\n * @param {string} event_name\n * @param {Element} element\n * @param {(value: unknown) => void} set\n * @param {() => unknown} [get]\n * @returns {void}\n */\nexport function bind_property(property, event_name, element, set, get) {\n\tvar handler = () => {\n\t\t// @ts-ignore\n\t\tset(element[property]);\n\t};\n\n\telement.addEventListener(event_name, handler);\n\n\tif (get) {\n\t\trender_effect(() => {\n\t\t\t// @ts-ignore\n\t\t\telement[property] = get();\n\t\t});\n\t} else {\n\t\thandler();\n\t}\n\n\t// @ts-ignore\n\tif (element === document.body || element === window || element === document) {\n\t\tteardown(() => {\n\t\t\telement.removeEventListener(event_name, handler);\n\t\t});\n\t}\n}\n\n/**\n * @param {HTMLElement} element\n * @param {(value: unknown) => void} set\n * @returns {void}\n */\nexport function bind_focused(element, set) {\n\tlisten(element, ['focus', 'blur'], () => {\n\t\tset(element === document.activeElement);\n\t});\n}\n","import { effect, render_effect, teardown } from '../../../reactivity/effects.js';\nimport { listen, without_reactive_context } from './shared.js';\n\n/**\n * @param {'x' | 'y'} type\n * @param {() => number} get\n * @param {(value: number) => void} set\n * @returns {void}\n */\nexport function bind_window_scroll(type, get, set = get) {\n\tvar is_scrolling_x = type === 'x';\n\n\tvar target_handler = () =>\n\t\twithout_reactive_context(() => {\n\t\t\tscrolling = true;\n\t\t\tclearTimeout(timeout);\n\t\t\ttimeout = setTimeout(clear, 100); // TODO use scrollend event if supported (or when supported everywhere?)\n\n\t\t\tset(window[is_scrolling_x ? 'scrollX' : 'scrollY']);\n\t\t});\n\n\taddEventListener('scroll', target_handler, {\n\t\tpassive: true\n\t});\n\n\tvar scrolling = false;\n\n\t/** @type {ReturnType<typeof setTimeout>} */\n\tvar timeout;\n\tvar clear = () => {\n\t\tscrolling = false;\n\t};\n\tvar first = true;\n\n\trender_effect(() => {\n\t\tvar latest_value = get();\n\t\t// Don't scroll to the initial value for accessibility reasons\n\t\tif (first) {\n\t\t\tfirst = false;\n\t\t} else if (!scrolling && latest_value != null) {\n\t\t\tscrolling = true;\n\t\t\tclearTimeout(timeout);\n\t\t\tif (is_scrolling_x) {\n\t\t\t\tscrollTo(latest_value, window.scrollY);\n\t\t\t} else {\n\t\t\t\tscrollTo(window.scrollX, latest_value);\n\t\t\t}\n\t\t\ttimeout = setTimeout(clear, 100);\n\t\t}\n\t});\n\n\t// Browsers don't fire the scroll event for the initial scroll position when scroll style isn't set to smooth\n\teffect(target_handler);\n\n\tteardown(() => {\n\t\tremoveEventListener('scroll', target_handler);\n\t});\n}\n\n/**\n * @param {'innerWidth' | 'innerHeight' | 'outerWidth' | 'outerHeight'} type\n * @param {(size: number) => void} set\n */\nexport function bind_window_size(type, set) {\n\tlisten(window, ['resize'], () => without_reactive_context(() => set(window[type])));\n}\n","import { noop } from '../../../shared/utils.js';\nimport { user_pre_effect } from '../../reactivity/effects.js';\nimport { on } from '../elements/events.js';\n\n/**\n * Substitute for the `trusted` event modifier\n * @deprecated\n * @param {(event: Event, ...args: Array<unknown>) => void} fn\n * @returns {(event: Event, ...args: unknown[]) => void}\n */\nexport function trusted(fn) {\n\treturn function (...args) {\n\t\tvar event = /** @type {Event} */ (args[0]);\n\t\tif (event.isTrusted) {\n\t\t\t// @ts-ignore\n\t\t\tfn?.apply(this, args);\n\t\t}\n\t};\n}\n\n/**\n * Substitute for the `self` event modifier\n * @deprecated\n * @param {(event: Event, ...args: Array<unknown>) => void} fn\n * @returns {(event: Event, ...args: unknown[]) => void}\n */\nexport function self(fn) {\n\treturn function (...args) {\n\t\tvar event = /** @type {Event} */ (args[0]);\n\t\t// @ts-ignore\n\t\tif (event.target === this) {\n\t\t\t// @ts-ignore\n\t\t\tfn?.apply(this, args);\n\t\t}\n\t};\n}\n\n/**\n * Substitute for the `stopPropagation` event modifier\n * @deprecated\n * @param {(event: Event, ...args: Array<unknown>) => void} fn\n * @returns {(event: Event, ...args: unknown[]) => void}\n */\nexport function stopPropagation(fn) {\n\treturn function (...args) {\n\t\tvar event = /** @type {Event} */ (args[0]);\n\t\tevent.stopPropagation();\n\t\t// @ts-ignore\n\t\treturn fn?.apply(this, args);\n\t};\n}\n\n/**\n * Substitute for the `once` event modifier\n * @deprecated\n * @param {(event: Event, ...args: Array<unknown>) => void} fn\n * @returns {(event: Event, ...args: unknown[]) => void}\n */\nexport function once(fn) {\n\tvar ran = false;\n\n\treturn function (...args) {\n\t\tif (ran) return;\n\t\tran = true;\n\n\t\t// @ts-ignore\n\t\treturn fn?.apply(this, args);\n\t};\n}\n\n/**\n * Substitute for the `stopImmediatePropagation` event modifier\n * @deprecated\n * @param {(event: Event, ...args: Array<unknown>) => void} fn\n * @returns {(event: Event, ...args: unknown[]) => void}\n */\nexport function stopImmediatePropagation(fn) {\n\treturn function (...args) {\n\t\tvar event = /** @type {Event} */ (args[0]);\n\t\tevent.stopImmediatePropagation();\n\t\t// @ts-ignore\n\t\treturn fn?.apply(this, args);\n\t};\n}\n\n/**\n * Substitute for the `preventDefault` event modifier\n * @deprecated\n * @param {(event: Event, ...args: Array<unknown>) => void} fn\n * @returns {(event: Event, ...args: unknown[]) => void}\n */\nexport function preventDefault(fn) {\n\treturn function (...args) {\n\t\tvar event = /** @type {Event} */ (args[0]);\n\t\tevent.preventDefault();\n\t\t// @ts-ignore\n\t\treturn fn?.apply(this, args);\n\t};\n}\n\n/**\n * Substitute for the `passive` event modifier, implemented as an action\n * @deprecated\n * @param {HTMLElement} node\n * @param {[event: string, handler: () => EventListener]} options\n */\nexport function passive(node, [event, handler]) {\n\tuser_pre_effect(() => {\n\t\treturn on(node, event, handler() ?? noop, {\n\t\t\tpassive: true\n\t\t});\n\t});\n}\n\n/**\n * Substitute for the `nonpassive` event modifier, implemented as an action\n * @deprecated\n * @param {HTMLElement} node\n * @param {[event: string, handler: () => EventListener]} options\n */\nexport function nonpassive(node, [event, handler]) {\n\tuser_pre_effect(() => {\n\t\treturn on(node, event, handler() ?? noop, {\n\t\t\tpassive: false\n\t\t});\n\t});\n}\n","/** @import { ComponentContextLegacy } from '#client' */\nimport { run, run_all } from '../../../shared/utils.js';\nimport { component_context } from '../../context.js';\nimport { derived } from '../../reactivity/deriveds.js';\nimport { user_pre_effect, user_effect } from '../../reactivity/effects.js';\nimport { deep_read_state, get, untrack } from '../../runtime.js';\n\n/**\n * Legacy-mode only: Call `onMount` callbacks and set up `beforeUpdate`/`afterUpdate` effects\n * @param {boolean} [immutable]\n */\nexport function init(immutable = false) {\n\tconst context = /** @type {ComponentContextLegacy} */ (component_context);\n\n\tconst callbacks = context.l.u;\n\tif (!callbacks) return;\n\n\tlet props = () => deep_read_state(context.s);\n\n\tif (immutable) {\n\t\tlet version = 0;\n\t\tlet prev = /** @type {Record<string, any>} */ ({});\n\n\t\t// In legacy immutable mode, before/afterUpdate only fire if the object identity of a prop changes\n\t\tconst d = derived(() => {\n\t\t\tlet changed = false;\n\t\t\tconst props = context.s;\n\t\t\tfor (const key in props) {\n\t\t\t\tif (props[key] !== prev[key]) {\n\t\t\t\t\tprev[key] = props[key];\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (changed) version++;\n\t\t\treturn version;\n\t\t});\n\n\t\tprops = () => get(d);\n\t}\n\n\t// beforeUpdate\n\tif (callbacks.b.length) {\n\t\tuser_pre_effect(() => {\n\t\t\tobserve_all(context, props);\n\t\t\trun_all(callbacks.b);\n\t\t});\n\t}\n\n\t// onMount (must run before afterUpdate)\n\tuser_effect(() => {\n\t\tconst fns = untrack(() => callbacks.m.map(run));\n\t\treturn () => {\n\t\t\tfor (const fn of fns) {\n\t\t\t\tif (typeof fn === 'function') {\n\t\t\t\t\tfn();\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t});\n\n\t// afterUpdate\n\tif (callbacks.a.length) {\n\t\tuser_effect(() => {\n\t\t\tobserve_all(context, props);\n\t\t\trun_all(callbacks.a);\n\t\t});\n\t}\n}\n\n/**\n * Invoke the getter of all signals associated with a component\n * so they can be registered to the effect this function is called in.\n * @param {ComponentContextLegacy} context\n * @param {(() => void)} props\n */\nfunction observe_all(context, props) {\n\tif (context.l.s) {\n\t\tfor (const signal of context.l.s) get(signal);\n\t}\n\n\tprops();\n}\n","import { set, source } from '../../reactivity/sources.js';\nimport { get } from '../../runtime.js';\nimport { is_array } from '../../../shared/utils.js';\n\n/**\n * Under some circumstances, imports may be reactive in legacy mode. In that case,\n * they should be using `reactive_import` as part of the transformation\n * @param {() => any} fn\n */\nexport function reactive_import(fn) {\n\tvar s = source(0);\n\n\treturn function () {\n\t\tif (arguments.length === 1) {\n\t\t\tset(s, get(s) + 1);\n\t\t\treturn arguments[0];\n\t\t} else {\n\t\t\tget(s);\n\t\t\treturn fn();\n\t\t}\n\t};\n}\n\n/**\n * @this {any}\n * @param {Record<string, unknown>} $$props\n * @param {Event} event\n * @returns {void}\n */\nexport function bubble_event($$props, event) {\n\tvar events = /** @type {Record<string, Function[] | Function>} */ ($$props.$$events)?.[\n\t\tevent.type\n\t];\n\n\tvar callbacks = is_array(events) ? events.slice() : events == null ? [] : [events];\n\n\tfor (var fn of callbacks) {\n\t\t// Preserve \"this\" context\n\t\tfn.call(this, event);\n\t}\n}\n\n/**\n * Used to simulate `$on` on a component instance when `compatibility.componentApi === 4`\n * @param {Record<string, any>} $$props\n * @param {string} event_name\n * @param {Function} event_callback\n */\nexport function add_legacy_event_listener($$props, event_name, event_callback) {\n\t$$props.$$events ||= {};\n\t$$props.$$events[event_name] ||= [];\n\t$$props.$$events[event_name].push(event_callback);\n}\n\n/**\n * Used to simulate `$set` on a component instance when `compatibility.componentApi === 4`.\n * Needs component accessors so that it can call the setter of the prop. Therefore doesn't\n * work for updating props in `$$props` or `$$restProps`.\n * @this {Record<string, any>}\n * @param {Record<string, any>} $$new_props\n */\nexport function update_legacy_props($$new_props) {\n\tfor (var key in $$new_props) {\n\t\tif (key in this) {\n\t\t\tthis[key] = $$new_props[key];\n\t\t}\n\t}\n}\n","/** @import { Effect, Source } from './types.js' */\nimport { DEV } from 'esm-env';\nimport {\n\tPROPS_IS_BINDABLE,\n\tPROPS_IS_IMMUTABLE,\n\tPROPS_IS_LAZY_INITIAL,\n\tPROPS_IS_RUNES,\n\tPROPS_IS_UPDATED\n} from '../../../constants.js';\nimport { get_descriptor, is_function } from '../../shared/utils.js';\nimport { set, source, update } from './sources.js';\nimport { derived, derived_safe_equal } from './deriveds.js';\nimport {\n\tactive_effect,\n\tget,\n\tis_destroying_effect,\n\tset_active_effect,\n\tuntrack\n} from '../runtime.js';\nimport * as e from '../errors.js';\nimport { DESTROYED, LEGACY_PROPS, STATE_SYMBOL } from '#client/constants';\nimport { proxy } from '../proxy.js';\nimport { capture_store_binding } from './store.js';\nimport { legacy_mode_flag } from '../../flags/index.js';\nimport { effect, render_effect } from './effects.js';\n\n/**\n * @param {((value?: number) => number)} fn\n * @param {1 | -1} [d]\n * @returns {number}\n */\nexport function update_prop(fn, d = 1) {\n\tconst value = fn();\n\tfn(value + d);\n\treturn value;\n}\n\n/**\n * @param {((value?: number) => number)} fn\n * @param {1 | -1} [d]\n * @returns {number}\n */\nexport function update_pre_prop(fn, d = 1) {\n\tconst value = fn() + d;\n\tfn(value);\n\treturn value;\n}\n\n/**\n * The proxy handler for rest props (i.e. `const { x, ...rest } = $props()`).\n * Is passed the full `$$props` object and excludes the named props.\n * @type {ProxyHandler<{ props: Record<string | symbol, unknown>, exclude: Array<string | symbol>, name?: string }>}}\n */\nconst rest_props_handler = {\n\tget(target, key) {\n\t\tif (target.exclude.includes(key)) return;\n\t\treturn target.props[key];\n\t},\n\tset(target, key) {\n\t\tif (DEV) {\n\t\t\t// TODO should this happen in prod too?\n\t\t\te.props_rest_readonly(`${target.name}.${String(key)}`);\n\t\t}\n\n\t\treturn false;\n\t},\n\tgetOwnPropertyDescriptor(target, key) {\n\t\tif (target.exclude.includes(key)) return;\n\t\tif (key in target.props) {\n\t\t\treturn {\n\t\t\t\tenumerable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t\tvalue: target.props[key]\n\t\t\t};\n\t\t}\n\t},\n\thas(target, key) {\n\t\tif (target.exclude.includes(key)) return false;\n\t\treturn key in target.props;\n\t},\n\townKeys(target) {\n\t\treturn Reflect.ownKeys(target.props).filter((key) => !target.exclude.includes(key));\n\t}\n};\n\n/**\n * @param {Record<string, unknown>} props\n * @param {string[]} exclude\n * @param {string} [name]\n * @returns {Record<string, unknown>}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function rest_props(props, exclude, name) {\n\treturn new Proxy(\n\t\tDEV ? { props, exclude, name, other: {}, to_proxy: [] } : { props, exclude },\n\t\trest_props_handler\n\t);\n}\n\n/**\n * The proxy handler for legacy $$restProps and $$props\n * @type {ProxyHandler<{ props: Record<string | symbol, unknown>, exclude: Array<string | symbol>, special: Record<string | symbol, (v?: unknown) => unknown>, version: Source<number>, parent_effect: Effect }>}}\n */\nconst legacy_rest_props_handler = {\n\tget(target, key) {\n\t\tif (target.exclude.includes(key)) return;\n\t\tget(target.version);\n\t\treturn key in target.special ? target.special[key]() : target.props[key];\n\t},\n\tset(target, key, value) {\n\t\tif (!(key in target.special)) {\n\t\t\tvar previous_effect = active_effect;\n\n\t\t\ttry {\n\t\t\t\tset_active_effect(target.parent_effect);\n\n\t\t\t\t// Handle props that can temporarily get out of sync with the parent\n\t\t\t\t/** @type {Record<string, (v?: unknown) => unknown>} */\n\t\t\t\ttarget.special[key] = prop(\n\t\t\t\t\t{\n\t\t\t\t\t\tget [key]() {\n\t\t\t\t\t\t\treturn target.props[key];\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\t/** @type {string} */ (key),\n\t\t\t\t\tPROPS_IS_UPDATED\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\tset_active_effect(previous_effect);\n\t\t\t}\n\t\t}\n\n\t\ttarget.special[key](value);\n\t\tupdate(target.version); // $$props is coarse-grained: when $$props.x is updated, usages of $$props.y etc are also rerun\n\t\treturn true;\n\t},\n\tgetOwnPropertyDescriptor(target, key) {\n\t\tif (target.exclude.includes(key)) return;\n\t\tif (key in target.props) {\n\t\t\treturn {\n\t\t\t\tenumerable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t\tvalue: target.props[key]\n\t\t\t};\n\t\t}\n\t},\n\tdeleteProperty(target, key) {\n\t\t// Svelte 4 allowed for deletions on $$restProps\n\t\tif (target.exclude.includes(key)) return true;\n\t\ttarget.exclude.push(key);\n\t\tupdate(target.version);\n\t\treturn true;\n\t},\n\thas(target, key) {\n\t\tif (target.exclude.includes(key)) return false;\n\t\treturn key in target.props;\n\t},\n\townKeys(target) {\n\t\treturn Reflect.ownKeys(target.props).filter((key) => !target.exclude.includes(key));\n\t}\n};\n\n/**\n * @param {Record<string, unknown>} props\n * @param {string[]} exclude\n * @returns {Record<string, unknown>}\n */\nexport function legacy_rest_props(props, exclude) {\n\treturn new Proxy(\n\t\t{\n\t\t\tprops,\n\t\t\texclude,\n\t\t\tspecial: {},\n\t\t\tversion: source(0),\n\t\t\t// TODO this is only necessary because we need to track component\n\t\t\t// destruction inside `prop`, because of `bind:this`, but it\n\t\t\t// seems likely that we can simplify `bind:this` instead\n\t\t\tparent_effect: /** @type {Effect} */ (active_effect)\n\t\t},\n\t\tlegacy_rest_props_handler\n\t);\n}\n\n/**\n * The proxy handler for spread props. Handles the incoming array of props\n * that looks like `() => { dynamic: props }, { static: prop }, ..` and wraps\n * them so that the whole thing is passed to the component as the `$$props` argument.\n * @type {ProxyHandler<{ props: Array<Record<string | symbol, unknown> | (() => Record<string | symbol, unknown>)> }>}}\n */\nconst spread_props_handler = {\n\tget(target, key) {\n\t\tlet i = target.props.length;\n\t\twhile (i--) {\n\t\t\tlet p = target.props[i];\n\t\t\tif (is_function(p)) p = p();\n\t\t\tif (typeof p === 'object' && p !== null && key in p) return p[key];\n\t\t}\n\t},\n\tset(target, key, value) {\n\t\tlet i = target.props.length;\n\t\twhile (i--) {\n\t\t\tlet p = target.props[i];\n\t\t\tif (is_function(p)) p = p();\n\t\t\tconst desc = get_descriptor(p, key);\n\t\t\tif (desc && desc.set) {\n\t\t\t\tdesc.set(value);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t},\n\tgetOwnPropertyDescriptor(target, key) {\n\t\tlet i = target.props.length;\n\t\twhile (i--) {\n\t\t\tlet p = target.props[i];\n\t\t\tif (is_function(p)) p = p();\n\t\t\tif (typeof p === 'object' && p !== null && key in p) {\n\t\t\t\tconst descriptor = get_descriptor(p, key);\n\t\t\t\tif (descriptor && !descriptor.configurable) {\n\t\t\t\t\t// Prevent a \"Non-configurability Report Error\": The target is an array, it does\n\t\t\t\t\t// not actually contain this property. If it is now described as non-configurable,\n\t\t\t\t\t// the proxy throws a validation error. Setting it to true avoids that.\n\t\t\t\t\tdescriptor.configurable = true;\n\t\t\t\t}\n\t\t\t\treturn descriptor;\n\t\t\t}\n\t\t}\n\t},\n\thas(target, key) {\n\t\t// To prevent a false positive `is_entry_props` in the `prop` function\n\t\tif (key === STATE_SYMBOL || key === LEGACY_PROPS) return false;\n\n\t\tfor (let p of target.props) {\n\t\t\tif (is_function(p)) p = p();\n\t\t\tif (p != null && key in p) return true;\n\t\t}\n\n\t\treturn false;\n\t},\n\townKeys(target) {\n\t\t/** @type {Array<string | symbol>} */\n\t\tconst keys = [];\n\n\t\tfor (let p of target.props) {\n\t\t\tif (is_function(p)) p = p();\n\t\t\tif (!p) continue;\n\n\t\t\tfor (const key in p) {\n\t\t\t\tif (!keys.includes(key)) keys.push(key);\n\t\t\t}\n\n\t\t\tfor (const key of Object.getOwnPropertySymbols(p)) {\n\t\t\t\tif (!keys.includes(key)) keys.push(key);\n\t\t\t}\n\t\t}\n\n\t\treturn keys;\n\t}\n};\n\n/**\n * @param {Array<Record<string, unknown> | (() => Record<string, unknown>)>} props\n * @returns {any}\n */\nexport function spread_props(...props) {\n\treturn new Proxy({ props }, spread_props_handler);\n}\n\n/**\n * This function is responsible for synchronizing a possibly bound prop with the inner component state.\n * It is used whenever the compiler sees that the component writes to the prop, or when it has a default prop_value.\n * @template V\n * @param {Record<string, unknown>} props\n * @param {string} key\n * @param {number} flags\n * @param {V | (() => V)} [fallback]\n * @returns {(() => V | ((arg: V) => V) | ((arg: V, mutation: boolean) => V))}\n */\nexport function prop(props, key, flags, fallback) {\n\tvar runes = !legacy_mode_flag || (flags & PROPS_IS_RUNES) !== 0;\n\tvar bindable = (flags & PROPS_IS_BINDABLE) !== 0;\n\tvar lazy = (flags & PROPS_IS_LAZY_INITIAL) !== 0;\n\n\tvar fallback_value = /** @type {V} */ (fallback);\n\tvar fallback_dirty = true;\n\n\tvar get_fallback = () => {\n\t\tif (fallback_dirty) {\n\t\t\tfallback_dirty = false;\n\n\t\t\tfallback_value = lazy\n\t\t\t\t? untrack(/** @type {() => V} */ (fallback))\n\t\t\t\t: /** @type {V} */ (fallback);\n\t\t}\n\n\t\treturn fallback_value;\n\t};\n\n\t/** @type {((v: V) => void) | undefined} */\n\tlet setter;\n\n\tif (bindable) {\n\t\t// Can be the case when someone does `mount(Component, props)` with `let props = $state({...})`\n\t\t// or `createClassComponent(Component, props)`\n\t\tvar is_entry_props = STATE_SYMBOL in props || LEGACY_PROPS in props;\n\n\t\tsetter =\n\t\t\tget_descriptor(props, key)?.set ??\n\t\t\t(is_entry_props && key in props ? (v) => (props[key] = v) : undefined);\n\t}\n\n\t/** @type {V} */\n\tvar initial_value;\n\tvar is_store_sub = false;\n\n\tif (bindable) {\n\t\t[initial_value, is_store_sub] = capture_store_binding(() => /** @type {V} */ (props[key]));\n\t} else {\n\t\tinitial_value = /** @type {V} */ (props[key]);\n\t}\n\n\tif (initial_value === undefined && fallback !== undefined) {\n\t\tinitial_value = get_fallback();\n\n\t\tif (setter) {\n\t\t\tif (runes) e.props_invalid_value(key);\n\t\t\tsetter(initial_value);\n\t\t}\n\t}\n\n\t/** @type {() => V} */\n\tvar getter;\n\n\tif (runes) {\n\t\tgetter = () => {\n\t\t\tvar value = /** @type {V} */ (props[key]);\n\t\t\tif (value === undefined) return get_fallback();\n\t\t\tfallback_dirty = true;\n\t\t\treturn value;\n\t\t};\n\t} else {\n\t\tgetter = () => {\n\t\t\tvar value = /** @type {V} */ (props[key]);\n\n\t\t\tif (value !== undefined) {\n\t\t\t\t// in legacy mode, we don't revert to the fallback value\n\t\t\t\t// if the prop goes from defined to undefined. The easiest\n\t\t\t\t// way to model this is to make the fallback undefined\n\t\t\t\t// as soon as the prop has a value\n\t\t\t\tfallback_value = /** @type {V} */ (undefined);\n\t\t\t}\n\n\t\t\treturn value === undefined ? fallback_value : value;\n\t\t};\n\t}\n\n\t// prop is never written to — we only need a getter\n\tif (runes && (flags & PROPS_IS_UPDATED) === 0) {\n\t\treturn getter;\n\t}\n\n\t// prop is written to, but the parent component had `bind:foo` which\n\t// means we can just call `$$props.foo = value` directly\n\tif (setter) {\n\t\tvar legacy_parent = props.$$legacy;\n\t\treturn /** @type {() => V} */ (\n\t\t\tfunction (/** @type {V} */ value, /** @type {boolean} */ mutation) {\n\t\t\t\tif (arguments.length > 0) {\n\t\t\t\t\t// We don't want to notify if the value was mutated and the parent is in runes mode.\n\t\t\t\t\t// In that case the state proxy (if it exists) should take care of the notification.\n\t\t\t\t\t// If the parent is not in runes mode, we need to notify on mutation, too, that the prop\n\t\t\t\t\t// has changed because the parent will not be able to detect the change otherwise.\n\t\t\t\t\tif (!runes || !mutation || legacy_parent || is_store_sub) {\n\t\t\t\t\t\t/** @type {Function} */ (setter)(mutation ? getter() : value);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn value;\n\t\t\t\t}\n\n\t\t\t\treturn getter();\n\t\t\t}\n\t\t);\n\t}\n\n\t// Either prop is written to, but there's no binding, which means we\n\t// create a derived that we can write to locally.\n\t// Or we are in legacy mode where we always create a derived to replicate that\n\t// Svelte 4 did not trigger updates when a primitive value was updated to the same value.\n\tvar overridden = false;\n\n\tvar d = ((flags & PROPS_IS_IMMUTABLE) !== 0 ? derived : derived_safe_equal)(() => {\n\t\toverridden = false;\n\t\treturn getter();\n\t});\n\n\tif (DEV) {\n\t\td.label = key;\n\t}\n\n\t// Capture the initial value if it's bindable\n\tif (bindable) get(d);\n\n\tvar parent_effect = /** @type {Effect} */ (active_effect);\n\n\treturn /** @type {() => V} */ (\n\t\tfunction (/** @type {any} */ value, /** @type {boolean} */ mutation) {\n\t\t\tif (arguments.length > 0) {\n\t\t\t\tconst new_value = mutation ? get(d) : runes && bindable ? proxy(value) : value;\n\n\t\t\t\tset(d, new_value);\n\t\t\t\toverridden = true;\n\n\t\t\t\tif (fallback_value !== undefined) {\n\t\t\t\t\tfallback_value = new_value;\n\t\t\t\t}\n\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\t// special case — avoid recalculating the derived if we're in a\n\t\t\t// teardown function and the prop was overridden locally, or the\n\t\t\t// component was already destroyed (people could access props in a timeout)\n\t\t\tif ((is_destroying_effect && overridden) || (parent_effect.f & DESTROYED) !== 0) {\n\t\t\t\treturn d.v;\n\t\t\t}\n\n\t\t\treturn get(d);\n\t\t}\n\t);\n}\n","/** @import { Blocker } from '#client' */\nimport { dev_current_component_function } from './context.js';\nimport { FILENAME } from '../../constants.js';\nimport { render_effect } from './reactivity/effects.js';\nimport * as w from './warnings.js';\nimport { capture_store_binding } from './reactivity/store.js';\nimport { run_after_blockers } from './reactivity/async.js';\n\n/**\n * @param {string} binding\n * @param {Blocker[]} blockers\n * @param {() => Record<string, any>} get_object\n * @param {() => string} get_property\n * @param {number} line\n * @param {number} column\n */\nexport function validate_binding(binding, blockers, get_object, get_property, line, column) {\n\trun_after_blockers(blockers, () => {\n\t\tvar warned = false;\n\n\t\tvar filename = dev_current_component_function?.[FILENAME];\n\n\t\trender_effect(() => {\n\t\t\tif (warned) return;\n\n\t\t\tvar [object, is_store_sub] = capture_store_binding(get_object);\n\n\t\t\tif (is_store_sub) return;\n\n\t\t\tvar property = get_property();\n\n\t\t\tvar ran = false;\n\n\t\t\t// by making the (possibly false, but it would be an extreme edge case) assumption\n\t\t\t// that a getter has a corresponding setter, we can determine if a property is\n\t\t\t// reactive by seeing if this effect has dependencies\n\t\t\tvar effect = render_effect(() => {\n\t\t\t\tif (ran) return;\n\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unused-expressions\n\t\t\t\tobject[property];\n\t\t\t});\n\n\t\t\tran = true;\n\n\t\t\tif (effect.deps === null) {\n\t\t\t\tvar location = `${filename}:${line}:${column}`;\n\t\t\t\tw.binding_property_non_reactive(binding, location);\n\n\t\t\t\twarned = true;\n\t\t\t}\n\t\t});\n\t});\n}\n","/** @import { ComponentConstructorOptions, ComponentType, SvelteComponent, Component } from 'svelte' */\nimport { DIRTY, LEGACY_PROPS, MAYBE_DIRTY } from '../internal/client/constants.js';\nimport { user_pre_effect } from '../internal/client/reactivity/effects.js';\nimport { mutable_source, set } from '../internal/client/reactivity/sources.js';\nimport { hydrate, mount, unmount } from '../internal/client/render.js';\nimport { active_effect, get } from '../internal/client/runtime.js';\nimport { flushSync } from '../internal/client/reactivity/batch.js';\nimport { define_property, is_array } from '../internal/shared/utils.js';\nimport * as e from '../internal/client/errors.js';\nimport * as w from '../internal/client/warnings.js';\nimport { DEV } from 'esm-env';\nimport { FILENAME } from '../constants.js';\nimport { component_context, dev_current_component_function } from '../internal/client/context.js';\nimport { async_mode_flag } from '../internal/flags/index.js';\nimport { set_signal_status } from '../internal/client/reactivity/status.js';\n\n/**\n * Takes the same options as a Svelte 4 component and the component function and returns a Svelte 4 compatible component.\n *\n * @deprecated Use this only as a temporary solution to migrate your imperative component code to Svelte 5.\n *\n * @template {Record<string, any>} Props\n * @template {Record<string, any>} Exports\n * @template {Record<string, any>} Events\n * @template {Record<string, any>} Slots\n *\n * @param {ComponentConstructorOptions<Props> & {\n * \tcomponent: ComponentType<SvelteComponent<Props, Events, Slots>> | Component<Props>;\n * }} options\n * @returns {SvelteComponent<Props, Events, Slots> & Exports}\n */\nexport function createClassComponent(options) {\n\t// @ts-expect-error $$prop_def etc are not actually defined\n\treturn new Svelte4Component(options);\n}\n\n/**\n * Takes the component function and returns a Svelte 4 compatible component constructor.\n *\n * @deprecated Use this only as a temporary solution to migrate your imperative component code to Svelte 5.\n *\n * @template {Record<string, any>} Props\n * @template {Record<string, any>} Exports\n * @template {Record<string, any>} Events\n * @template {Record<string, any>} Slots\n *\n * @param {SvelteComponent<Props, Events, Slots> | Component<Props>} component\n * @returns {ComponentType<SvelteComponent<Props, Events, Slots> & Exports>}\n */\nexport function asClassComponent(component) {\n\t// @ts-expect-error $$prop_def etc are not actually defined\n\treturn class extends Svelte4Component {\n\t\t/** @param {any} options */\n\t\tconstructor(options) {\n\t\t\tsuper({\n\t\t\t\tcomponent,\n\t\t\t\t...options\n\t\t\t});\n\t\t}\n\t};\n}\n\n/**\n * Support using the component as both a class and function during the transition period\n * @typedef {{new (o: ComponentConstructorOptions): SvelteComponent;(...args: Parameters<Component<Record<string, any>>>): ReturnType<Component<Record<string, any>, Record<string, any>>>;}} LegacyComponentType\n */\n\nclass Svelte4Component {\n\t/** @type {any} */\n\t#events;\n\n\t/** @type {Record<string, any>} */\n\t#instance;\n\n\t/**\n\t * @param {ComponentConstructorOptions & {\n\t * component: any;\n\t * }} options\n\t */\n\tconstructor(options) {\n\t\tvar sources = new Map();\n\n\t\t/**\n\t\t * @param {string | symbol} key\n\t\t * @param {unknown} value\n\t\t */\n\t\tvar add_source = (key, value) => {\n\t\t\tvar s = mutable_source(value, false, false);\n\t\t\tsources.set(key, s);\n\t\t\treturn s;\n\t\t};\n\n\t\t// Replicate coarse-grained props through a proxy that has a version source for\n\t\t// each property, which is incremented on updates to the property itself. Do not\n\t\t// use our $state proxy because that one has fine-grained reactivity.\n\t\tconst props = new Proxy(\n\t\t\t{ ...(options.props || {}), $$events: {} },\n\t\t\t{\n\t\t\t\tget(target, prop) {\n\t\t\t\t\treturn get(sources.get(prop) ?? add_source(prop, Reflect.get(target, prop)));\n\t\t\t\t},\n\t\t\t\thas(target, prop) {\n\t\t\t\t\t// Necessary to not throw \"invalid binding\" validation errors on the component side\n\t\t\t\t\tif (prop === LEGACY_PROPS) return true;\n\n\t\t\t\t\tget(sources.get(prop) ?? add_source(prop, Reflect.get(target, prop)));\n\t\t\t\t\treturn Reflect.has(target, prop);\n\t\t\t\t},\n\t\t\t\tset(target, prop, value) {\n\t\t\t\t\tset(sources.get(prop) ?? add_source(prop, value), value);\n\t\t\t\t\treturn Reflect.set(target, prop, value);\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\n\t\tthis.#instance = (options.hydrate ? hydrate : mount)(options.component, {\n\t\t\ttarget: options.target,\n\t\t\tanchor: options.anchor,\n\t\t\tprops,\n\t\t\tcontext: options.context,\n\t\t\tintro: options.intro ?? false,\n\t\t\trecover: options.recover,\n\t\t\ttransformError: options.transformError\n\t\t});\n\n\t\t// We don't flushSync for custom element wrappers or if the user doesn't want it,\n\t\t// or if we're in async mode since `flushSync()` will fail\n\t\tif (!async_mode_flag && (!options?.props?.$$host || options.sync === false)) {\n\t\t\tflushSync();\n\t\t}\n\n\t\tthis.#events = props.$$events;\n\n\t\tfor (const key of Object.keys(this.#instance)) {\n\t\t\tif (key === '$set' || key === '$destroy' || key === '$on') continue;\n\t\t\tdefine_property(this, key, {\n\t\t\t\tget() {\n\t\t\t\t\treturn this.#instance[key];\n\t\t\t\t},\n\t\t\t\t/** @param {any} value */\n\t\t\t\tset(value) {\n\t\t\t\t\tthis.#instance[key] = value;\n\t\t\t\t},\n\t\t\t\tenumerable: true\n\t\t\t});\n\t\t}\n\n\t\tthis.#instance.$set = /** @param {Record<string, any>} next */ (next) => {\n\t\t\tObject.assign(props, next);\n\t\t};\n\n\t\tthis.#instance.$destroy = () => {\n\t\t\tunmount(this.#instance);\n\t\t};\n\t}\n\n\t/** @param {Record<string, any>} props */\n\t$set(props) {\n\t\tthis.#instance.$set(props);\n\t}\n\n\t/**\n\t * @param {string} event\n\t * @param {(...args: any[]) => any} callback\n\t * @returns {any}\n\t */\n\t$on(event, callback) {\n\t\tthis.#events[event] = this.#events[event] || [];\n\n\t\t/** @param {any[]} args */\n\t\tconst cb = (...args) => callback.call(this, ...args);\n\t\tthis.#events[event].push(cb);\n\t\treturn () => {\n\t\t\tthis.#events[event] = this.#events[event].filter(/** @param {any} fn */ (fn) => fn !== cb);\n\t\t};\n\t}\n\n\t$destroy() {\n\t\tthis.#instance.$destroy();\n\t}\n}\n\n/**\n * Runs the given function once immediately on the server, and works like `$effect.pre` on the client.\n *\n * @deprecated Use this only as a temporary solution to migrate your component code to Svelte 5.\n * @param {() => void | (() => void)} fn\n * @returns {void}\n */\nexport function run(fn) {\n\tuser_pre_effect(() => {\n\t\tfn();\n\t\tvar effect = /** @type {import('#client').Effect} */ (active_effect);\n\t\t// If the effect is immediately made dirty again, mark it as maybe dirty to emulate legacy behaviour\n\t\tif ((effect.f & DIRTY) !== 0) {\n\t\t\tlet filename = \"a file (we can't know which one)\";\n\t\t\tif (DEV) {\n\t\t\t\t// @ts-ignore\n\t\t\t\tfilename = dev_current_component_function?.[FILENAME] ?? filename;\n\t\t\t}\n\t\t\tw.legacy_recursive_reactive_block(filename);\n\t\t\tset_signal_status(effect, MAYBE_DIRTY);\n\t\t}\n\t});\n}\n\n/**\n * Function to mimic the multiple listeners available in svelte 4\n * @deprecated\n * @param {EventListener[]} handlers\n * @returns {EventListener}\n */\nexport function handlers(...handlers) {\n\treturn function (event) {\n\t\tconst { stopImmediatePropagation } = event;\n\t\tlet stopped = false;\n\n\t\tevent.stopImmediatePropagation = () => {\n\t\t\tstopped = true;\n\t\t\tstopImmediatePropagation.call(event);\n\t\t};\n\n\t\tconst errors = [];\n\n\t\tfor (const handler of handlers) {\n\t\t\ttry {\n\t\t\t\t// @ts-expect-error `this` is not typed\n\t\t\t\thandler?.call(this, event);\n\t\t\t} catch (e) {\n\t\t\t\terrors.push(e);\n\t\t\t}\n\n\t\t\tif (stopped) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tfor (let error of errors) {\n\t\t\tqueueMicrotask(() => {\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t}\n\t};\n}\n\n/**\n * Function to create a `bubble` function that mimic the behavior of `on:click` without handler available in svelte 4.\n * @deprecated Use this only as a temporary solution to migrate your automatically delegated events in Svelte 5.\n */\nexport function createBubbler() {\n\tconst active_component_context = component_context;\n\tif (active_component_context === null) {\n\t\te.lifecycle_outside_component('createBubbler');\n\t}\n\n\treturn (/**@type {string}*/ type) => (/**@type {Event}*/ event) => {\n\t\tconst events = /** @type {Record<string, Function | Function[]>} */ (\n\t\t\tactive_component_context.s.$$events\n\t\t)?.[/** @type {any} */ (type)];\n\n\t\tif (events) {\n\t\t\tconst callbacks = is_array(events) ? events.slice() : [events];\n\t\t\tfor (const fn of callbacks) {\n\t\t\t\tfn.call(active_component_context.x, event);\n\t\t\t}\n\t\t\treturn !event.defaultPrevented;\n\t\t}\n\t\treturn true;\n\t};\n}\n\nexport {\n\tonce,\n\tpreventDefault,\n\tself,\n\tstopImmediatePropagation,\n\tstopPropagation,\n\ttrusted,\n\tpassive,\n\tnonpassive\n} from '../internal/client/dom/legacy/event-modifiers.js';\n","import { createClassComponent } from '../../../../legacy/legacy-client.js';\nimport { effect_root, render_effect } from '../../reactivity/effects.js';\nimport { append } from '../template.js';\nimport { define_property, get_descriptor, object_keys } from '../../../shared/utils.js';\nimport { create_element } from '../operations.js';\n\n/**\n * @typedef {Object} CustomElementPropDefinition\n * @property {string} [attribute]\n * @property {boolean} [reflect]\n * @property {'String'|'Boolean'|'Number'|'Array'|'Object'} [type]\n */\n\n/** @type {any} */\nlet SvelteElement;\n\nif (typeof HTMLElement === 'function') {\n\tSvelteElement = class extends HTMLElement {\n\t\t/** The Svelte component constructor */\n\t\t$$ctor;\n\t\t/** Slots */\n\t\t$$s;\n\t\t/** @type {any} The Svelte component instance */\n\t\t$$c;\n\t\t/** Whether or not the custom element is connected */\n\t\t$$cn = false;\n\t\t/** @type {Record<string, any>} Component props data */\n\t\t$$d = {};\n\t\t/** `true` if currently in the process of reflecting component props back to attributes */\n\t\t$$r = false;\n\t\t/** @type {Record<string, CustomElementPropDefinition>} Props definition (name, reflected, type etc) */\n\t\t$$p_d = {};\n\t\t/** @type {Record<string, EventListenerOrEventListenerObject[]>} Event listeners */\n\t\t$$l = {};\n\t\t/** @type {Map<EventListenerOrEventListenerObject, Function>} Event listener unsubscribe functions */\n\t\t$$l_u = new Map();\n\t\t/** @type {any} The managed render effect for reflecting attributes */\n\t\t$$me;\n\t\t/** @type {ShadowRoot | null} The ShadowRoot of the custom element */\n\t\t$$shadowRoot = null;\n\n\t\t/**\n\t\t * @param {*} $$componentCtor\n\t\t * @param {*} $$slots\n\t\t * @param {ShadowRootInit | undefined} shadow_root_init\n\t\t */\n\t\tconstructor($$componentCtor, $$slots, shadow_root_init) {\n\t\t\tsuper();\n\t\t\tthis.$$ctor = $$componentCtor;\n\t\t\tthis.$$s = $$slots;\n\n\t\t\tif (shadow_root_init) {\n\t\t\t\t// We need to store the reference to shadow root, because `closed` shadow root cannot be\n\t\t\t\t// accessed with `this.shadowRoot`.\n\t\t\t\tthis.$$shadowRoot = this.attachShadow(shadow_root_init);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * @param {string} type\n\t\t * @param {EventListenerOrEventListenerObject} listener\n\t\t * @param {boolean | AddEventListenerOptions} [options]\n\t\t */\n\t\taddEventListener(type, listener, options) {\n\t\t\t// We can't determine upfront if the event is a custom event or not, so we have to\n\t\t\t// listen to both. If someone uses a custom event with the same name as a regular\n\t\t\t// browser event, this fires twice - we can't avoid that.\n\t\t\tthis.$$l[type] = this.$$l[type] || [];\n\t\t\tthis.$$l[type].push(listener);\n\t\t\tif (this.$$c) {\n\t\t\t\tconst unsub = this.$$c.$on(type, listener);\n\t\t\t\tthis.$$l_u.set(listener, unsub);\n\t\t\t}\n\t\t\tsuper.addEventListener(type, listener, options);\n\t\t}\n\n\t\t/**\n\t\t * @param {string} type\n\t\t * @param {EventListenerOrEventListenerObject} listener\n\t\t * @param {boolean | AddEventListenerOptions} [options]\n\t\t */\n\t\tremoveEventListener(type, listener, options) {\n\t\t\tsuper.removeEventListener(type, listener, options);\n\t\t\tif (this.$$c) {\n\t\t\t\tconst unsub = this.$$l_u.get(listener);\n\t\t\t\tif (unsub) {\n\t\t\t\t\tunsub();\n\t\t\t\t\tthis.$$l_u.delete(listener);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tasync connectedCallback() {\n\t\t\tthis.$$cn = true;\n\t\t\tif (!this.$$c) {\n\t\t\t\t// We wait one tick to let possible child slot elements be created/mounted\n\t\t\t\tawait Promise.resolve();\n\t\t\t\tif (!this.$$cn || this.$$c) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t/** @param {string} name */\n\t\t\t\tfunction create_slot(name) {\n\t\t\t\t\t/**\n\t\t\t\t\t * @param {Element} anchor\n\t\t\t\t\t */\n\t\t\t\t\treturn (anchor) => {\n\t\t\t\t\t\tconst slot = create_element('slot');\n\t\t\t\t\t\tif (name !== 'default') slot.name = name;\n\n\t\t\t\t\t\tappend(anchor, slot);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\t/** @type {Record<string, any>} */\n\t\t\t\tconst $$slots = {};\n\t\t\t\tconst existing_slots = get_custom_elements_slots(this);\n\t\t\t\tfor (const name of this.$$s) {\n\t\t\t\t\tif (name in existing_slots) {\n\t\t\t\t\t\tif (name === 'default' && !this.$$d.children) {\n\t\t\t\t\t\t\tthis.$$d.children = create_slot(name);\n\t\t\t\t\t\t\t$$slots.default = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$$slots[name] = create_slot(name);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const attribute of this.attributes) {\n\t\t\t\t\t// this.$$data takes precedence over this.attributes\n\t\t\t\t\tconst name = this.$$g_p(attribute.name);\n\t\t\t\t\tif (!(name in this.$$d)) {\n\t\t\t\t\t\tthis.$$d[name] = get_custom_element_value(name, attribute.value, this.$$p_d, 'toProp');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Port over props that were set programmatically before ce was initialized\n\t\t\t\tfor (const key in this.$$p_d) {\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tif (!(key in this.$$d) && this[key] !== undefined) {\n\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\tthis.$$d[key] = this[key]; // don't transform, these were set through JavaScript\n\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\tdelete this[key]; // remove the property that shadows the getter/setter\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.$$c = createClassComponent({\n\t\t\t\t\tcomponent: this.$$ctor,\n\t\t\t\t\ttarget: this.$$shadowRoot || this,\n\t\t\t\t\tprops: {\n\t\t\t\t\t\t...this.$$d,\n\t\t\t\t\t\t$$slots,\n\t\t\t\t\t\t$$host: this\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Reflect component props as attributes\n\t\t\t\tthis.$$me = effect_root(() => {\n\t\t\t\t\trender_effect(() => {\n\t\t\t\t\t\tthis.$$r = true;\n\t\t\t\t\t\tfor (const key of object_keys(this.$$c)) {\n\t\t\t\t\t\t\tif (!this.$$p_d[key]?.reflect) continue;\n\t\t\t\t\t\t\tthis.$$d[key] = this.$$c[key];\n\t\t\t\t\t\t\tconst attribute_value = get_custom_element_value(\n\t\t\t\t\t\t\t\tkey,\n\t\t\t\t\t\t\t\tthis.$$d[key],\n\t\t\t\t\t\t\t\tthis.$$p_d,\n\t\t\t\t\t\t\t\t'toAttribute'\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (attribute_value == null) {\n\t\t\t\t\t\t\t\tthis.removeAttribute(this.$$p_d[key].attribute || key);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tthis.setAttribute(this.$$p_d[key].attribute || key, attribute_value);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.$$r = false;\n\t\t\t\t\t});\n\t\t\t\t});\n\n\t\t\t\tfor (const type in this.$$l) {\n\t\t\t\t\tfor (const listener of this.$$l[type]) {\n\t\t\t\t\t\tconst unsub = this.$$c.$on(type, listener);\n\t\t\t\t\t\tthis.$$l_u.set(listener, unsub);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.$$l = {};\n\t\t\t}\n\t\t}\n\n\t\t// We don't need this when working within Svelte code, but for compatibility of people using this outside of Svelte\n\t\t// and setting attributes through setAttribute etc, this is helpful\n\n\t\t/**\n\t\t * @param {string} attr\n\t\t * @param {string} _oldValue\n\t\t * @param {string} newValue\n\t\t */\n\t\tattributeChangedCallback(attr, _oldValue, newValue) {\n\t\t\tif (this.$$r) return;\n\t\t\tattr = this.$$g_p(attr);\n\t\t\tthis.$$d[attr] = get_custom_element_value(attr, newValue, this.$$p_d, 'toProp');\n\t\t\tthis.$$c?.$set({ [attr]: this.$$d[attr] });\n\t\t}\n\n\t\tdisconnectedCallback() {\n\t\t\tthis.$$cn = false;\n\t\t\t// In a microtask, because this could be a move within the DOM\n\t\t\tPromise.resolve().then(() => {\n\t\t\t\tif (!this.$$cn && this.$$c) {\n\t\t\t\t\tthis.$$c.$destroy();\n\t\t\t\t\tthis.$$me();\n\t\t\t\t\tthis.$$c = undefined;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t/**\n\t\t * @param {string} attribute_name\n\t\t */\n\t\t$$g_p(attribute_name) {\n\t\t\treturn (\n\t\t\t\tobject_keys(this.$$p_d).find(\n\t\t\t\t\t(key) =>\n\t\t\t\t\t\tthis.$$p_d[key].attribute === attribute_name ||\n\t\t\t\t\t\t(!this.$$p_d[key].attribute && key.toLowerCase() === attribute_name)\n\t\t\t\t) || attribute_name\n\t\t\t);\n\t\t}\n\t};\n}\n\n/**\n * @param {string} prop\n * @param {any} value\n * @param {Record<string, CustomElementPropDefinition>} props_definition\n * @param {'toAttribute' | 'toProp'} [transform]\n */\nfunction get_custom_element_value(prop, value, props_definition, transform) {\n\tconst type = props_definition[prop]?.type;\n\tvalue = type === 'Boolean' && typeof value !== 'boolean' ? value != null : value;\n\tif (!transform || !props_definition[prop]) {\n\t\treturn value;\n\t} else if (transform === 'toAttribute') {\n\t\tswitch (type) {\n\t\t\tcase 'Object':\n\t\t\tcase 'Array':\n\t\t\t\treturn value == null ? null : JSON.stringify(value);\n\t\t\tcase 'Boolean':\n\t\t\t\treturn value ? '' : null;\n\t\t\tcase 'Number':\n\t\t\t\treturn value == null ? null : value;\n\t\t\tdefault:\n\t\t\t\treturn value;\n\t\t}\n\t} else {\n\t\tswitch (type) {\n\t\t\tcase 'Object':\n\t\t\tcase 'Array':\n\t\t\t\treturn value && JSON.parse(value);\n\t\t\tcase 'Boolean':\n\t\t\t\treturn value; // conversion already handled above\n\t\t\tcase 'Number':\n\t\t\t\treturn value != null ? +value : value;\n\t\t\tdefault:\n\t\t\t\treturn value;\n\t\t}\n\t}\n}\n\n/**\n * @param {HTMLElement} element\n */\nfunction get_custom_elements_slots(element) {\n\t/** @type {Record<string, true>} */\n\tconst result = {};\n\telement.childNodes.forEach((node) => {\n\t\tresult[/** @type {Element} node */ (node).slot || 'default'] = true;\n\t});\n\treturn result;\n}\n\n/**\n * @internal\n *\n * Turn a Svelte component into a custom element.\n * @param {any} Component A Svelte component function\n * @param {Record<string, CustomElementPropDefinition>} props_definition The props to observe\n * @param {string[]} slots The slots to create\n * @param {string[]} exports Explicitly exported values, other than props\n * @param {ShadowRootInit | undefined} shadow_root_init Options passed to shadow DOM constructor\n * @param {(ce: new () => HTMLElement) => new () => HTMLElement} [extend]\n */\nexport function create_custom_element(\n\tComponent,\n\tprops_definition,\n\tslots,\n\texports,\n\tshadow_root_init,\n\textend\n) {\n\tlet Class = class extends SvelteElement {\n\t\tconstructor() {\n\t\t\tsuper(Component, slots, shadow_root_init);\n\t\t\tthis.$$p_d = props_definition;\n\t\t}\n\t\tstatic get observedAttributes() {\n\t\t\treturn object_keys(props_definition).map((key) =>\n\t\t\t\t(props_definition[key].attribute || key).toLowerCase()\n\t\t\t);\n\t\t}\n\t};\n\tobject_keys(props_definition).forEach((prop) => {\n\t\tdefine_property(Class.prototype, prop, {\n\t\t\tget() {\n\t\t\t\treturn this.$$c && prop in this.$$c ? this.$$c[prop] : this.$$d[prop];\n\t\t\t},\n\t\t\tset(value) {\n\t\t\t\tvalue = get_custom_element_value(prop, value, props_definition);\n\t\t\t\tthis.$$d[prop] = value;\n\t\t\t\tvar component = this.$$c;\n\n\t\t\t\tif (component) {\n\t\t\t\t\t// // If the instance has an accessor, use that instead\n\t\t\t\t\tvar setter = get_descriptor(component, prop)?.get;\n\n\t\t\t\t\tif (setter) {\n\t\t\t\t\t\tcomponent[prop] = value;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcomponent.$set({ [prop]: value });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t});\n\texports.forEach((property) => {\n\t\tdefine_property(Class.prototype, property, {\n\t\t\tget() {\n\t\t\t\treturn this.$$c?.[property];\n\t\t\t}\n\t\t});\n\t});\n\tif (extend) {\n\t\t// @ts-expect-error - assigning here is fine\n\t\tClass = extend(Class);\n\t}\n\tComponent.element = /** @type {any} */ Class;\n\treturn Class;\n}\n","import { STATE_SYMBOL } from '#client/constants';\nimport { snapshot } from '../../shared/clone.js';\nimport * as w from '../warnings.js';\nimport { untrack } from '../runtime.js';\n\n/**\n * @param {string} method\n * @param {...any} objects\n */\nexport function log_if_contains_state(method, ...objects) {\n\tuntrack(() => {\n\t\ttry {\n\t\t\tlet has_state = false;\n\t\t\tconst transformed = [];\n\n\t\t\tfor (const obj of objects) {\n\t\t\t\tif (obj && typeof obj === 'object' && STATE_SYMBOL in obj) {\n\t\t\t\t\ttransformed.push(snapshot(obj, true));\n\t\t\t\t\thas_state = true;\n\t\t\t\t} else {\n\t\t\t\t\ttransformed.push(obj);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (has_state) {\n\t\t\t\tw.console_log_state(method);\n\n\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\tconsole.log('%c[snapshot]', 'color: grey', ...transformed);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Errors can occur when trying to snapshot objects with getters that throw or non-enumerable properties.\n\t\t}\n\t});\n\n\treturn objects;\n}\n","/*\n * Backend implementations for phase 3.\n *\n * MemoryBackend — ephemeral/session zones (and tests)\n * LocalStorageBackend — workspace/user zones on web\n *\n * Tauri FS backends, IndexedDB, and remote sync are deferred per the\n * roadmap. Any future backend need only conform to the `Backend` interface\n * in ./types.ts for shard code to work against it unchanged.\n */\n\nimport type { Backend } from './types';\n\nexport class MemoryBackend implements Backend {\n #map = new Map<string, unknown>();\n\n read(shardId: string): unknown | undefined {\n return this.#map.get(shardId);\n }\n write(shardId: string, value: unknown): void {\n this.#map.set(shardId, value);\n }\n delete(shardId: string): void {\n this.#map.delete(shardId);\n }\n list(): string[] {\n return [...this.#map.keys()];\n }\n}\n\n/**\n * Persists one JSON blob per shardId under a prefixed localStorage key.\n *\n * Keys are of the form `${prefix}${shardId}`. Each zone that uses this\n * backend picks its own prefix so keys don't collide across zones (e.g.\n * `sh3:workspace:` for the workspace zone, `sh3:user:` for the user zone).\n *\n * Values are JSON-serialized; non-serializable values are silently dropped\n * by `JSON.stringify`. Callers are expected to keep zone contents plain.\n */\nexport class LocalStorageBackend implements Backend {\n #prefix: string;\n\n constructor(prefix: string) {\n this.#prefix = prefix;\n }\n\n read(shardId: string): unknown | undefined {\n if (typeof localStorage === 'undefined') return undefined;\n const raw = localStorage.getItem(this.#prefix + shardId);\n if (raw == null) return undefined;\n try {\n return JSON.parse(raw);\n } catch {\n // Corrupt entry — treat as missing rather than crashing the shard.\n return undefined;\n }\n }\n\n write(shardId: string, value: unknown): void {\n if (typeof localStorage === 'undefined') return;\n try {\n localStorage.setItem(this.#prefix + shardId, JSON.stringify(value));\n } catch {\n // Quota exceeded or serialization failure — swallow for phase 3;\n // phase \"post-prototype\" will surface a proper error channel.\n }\n }\n\n delete(shardId: string): void {\n if (typeof localStorage === 'undefined') return;\n localStorage.removeItem(this.#prefix + shardId);\n }\n\n list(): string[] {\n if (typeof localStorage === 'undefined') return [];\n const out: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i);\n if (key && key.startsWith(this.#prefix)) {\n out.push(key.slice(this.#prefix.length));\n }\n }\n return out;\n }\n}\n","/*\n * State zone types — framework plumbing for docs/design/state-zones.md.\n *\n * Phase 3 implements four of the six zones:\n * ephemeral — in-memory, cleared on shard unload\n * session — in-memory, cleared on app close\n * workspace — persisted (localStorage KV for web)\n * user — persisted (localStorage KV for web)\n *\n * Deferred until later phases:\n * document — file-on-disk (phase \"post-prototype\")\n * shared — lives on the bus, not storage (not a zone in the same sense)\n */\n\n/**\n * The four state zones available to shards. Each zone has different lifetime\n * and persistence semantics:\n * - `ephemeral`: in-memory only; cleared when the shard is unloaded.\n * - `session`: in-memory only; cleared when the app is closed.\n * - `workspace`: persisted to localStorage; survives page reload.\n * - `user`: persisted to localStorage; shared across all workspaces for this user.\n */\nexport type ZoneName = 'ephemeral' | 'session' | 'workspace' | 'user';\n\n/** Zones whose contents are flushed to a persistent backend on change. */\nexport const PERSISTENT_ZONES: readonly ZoneName[] = ['workspace', 'user'];\n\n/**\n * A backend is a tiny KV store keyed by shardId. Each zone owns one backend.\n * Values are arbitrary JSON-serializable objects — the backend is responsible\n * for any (de)serialization needed for its medium.\n *\n * Future backends: IndexedDB, Tauri FS, remote sync — all conform to this\n * interface so shard code is unaffected by deployment target.\n */\nexport interface Backend {\n /** Read the stored value for a shard. Returns undefined if not present. */\n read(shardId: string): unknown | undefined;\n /** Write (create or overwrite) the stored value for a shard. */\n write(shardId: string, value: unknown): void;\n /** Delete the stored value for a shard. No-op if not present. */\n delete(shardId: string): void;\n /** Return all shard ids that have stored entries in this backend. */\n list(): string[];\n}\n\n/**\n * A zone schema is a record of zone name → initial state object. Any subset\n * of zones may be declared; unused zones are simply omitted. Values inside\n * each zone object become the defaults used when the backend has no prior\n * entry for this shard.\n */\nexport type ZoneSchema = {\n [K in ZoneName]?: Record<string, unknown>;\n};\n\n/**\n * Cross-shard zone management API. Allows enumeration, inspection, and\n * cleanup of zone data across all shards. Only available on contexts\n * whose manifest declares the `state:manage` permission.\n */\nexport interface ZoneManager {\n /** Return all shard IDs that have data in the given zone. */\n list(zone: ZoneName): string[];\n /** Read a raw zone entry without creating a reactive proxy. Returns undefined if absent. */\n peek(zone: ZoneName, shardId: string): unknown | undefined;\n /** Delete one shard's data from a zone. */\n clear(zone: ZoneName, shardId: string): void;\n /** Delete all entries in a zone. */\n clearAll(zone: ZoneName): void;\n}\n\n/** Permission string for cross-shard zone management access. */\nexport const PERMISSION_STATE_MANAGE = 'state:manage';\n","/*\n * createStateZones — turns a declarative zone schema into live reactive\n * per-zone objects backed by the right store for each zone.\n *\n * Usage (from a shard, or the shell itself):\n *\n * const state = createStateZones('graphlive', {\n * ephemeral: { hoveredId: null as string | null },\n * session: { lastFocus: null as string | null },\n * workspace: { collapsed: false, panelSizes: [0.3, 0.7] },\n * user: { showIcons: true },\n * });\n *\n * state.workspace.collapsed = true; // persists to localStorage\n * state.ephemeral.hoveredId = 'foo'; // in-memory only\n *\n * Guarantees (phase 3 subset of docs/design/state-zones.md):\n * - Hydration before return: persistent zones are populated from the\n * backend before this function returns, so reads in the next line of\n * user code see persisted values.\n * - Debounced flush: writes within the same microtask coalesce to a\n * single backend write per (zone, shardId).\n * - Atomicity per write: each flush serializes a full zone snapshot.\n * - Isolation: zone data is keyed by shardId; shards cannot collide.\n *\n * Lifetime management (tracking teardown on shard deactivation) arrives in\n * phase 4 when the shard contract exists. For phase 3, roots live until the\n * page unloads, which is fine for a single-session shell.\n *\n * This file must be `.svelte.ts` so it can use the Svelte 5 runes\n * `$state`, `$effect.root`, `$effect`, and `$state.snapshot` at module level.\n */\n\nimport { MemoryBackend, LocalStorageBackend } from './backends';\nimport type { Backend, ZoneName, ZoneSchema } from './types';\nimport { PERSISTENT_ZONES } from './types';\n\nexport const backends: Record<ZoneName, Backend> = {\n ephemeral: new MemoryBackend(),\n session: new MemoryBackend(),\n workspace: new LocalStorageBackend('sh3:workspace:'),\n user: new LocalStorageBackend('sh3:user:'),\n};\n\n// ---------- debounced flush ----------------------------------------------\n\ntype PendingWrite = { zone: ZoneName; shardId: string; value: unknown };\n\nconst pending = new Map<string, PendingWrite>();\nlet flushScheduled = false;\n\nfunction scheduleFlush(zone: ZoneName, shardId: string, value: unknown): void {\n pending.set(`${zone}:${shardId}`, { zone, shardId, value });\n if (flushScheduled) return;\n flushScheduled = true;\n queueMicrotask(() => {\n flushScheduled = false;\n for (const { zone, shardId, value } of pending.values()) {\n backends[zone].write(shardId, value);\n }\n pending.clear();\n });\n}\n\n// ---------- factory -------------------------------------------------------\n\n/**\n * Live reactive state object returned by `createStateZones`. Each key\n * mirrors a zone declared in the schema; the value is a deeply-reactive\n * proxy of the same shape. Undeclared zones are absent from the result.\n *\n * @typeParam T - The `ZoneSchema` used to declare zones and their defaults.\n */\nexport type StateZones<T extends ZoneSchema> = {\n [K in keyof T]: T[K];\n};\n\n/**\n * Create live reactive state zones for a shard (or the shell itself).\n *\n * Each zone declared in `schema` is backed by the appropriate store:\n * `ephemeral` and `session` are in-memory; `workspace` and `user` are\n * persisted to localStorage and hydrated before this call returns.\n *\n * Writes to persistent zones are debounced and coalesced per microtask.\n * Zones not declared in `schema` are not created; the result only\n * contains the keys the caller asked for.\n *\n * @param shardId - Unique shard identifier used as the storage namespace.\n * @param schema - Record of zone names to their default values.\n * @returns A reactive `StateZones<T>` object keyed to the declared zones.\n */\nexport function createStateZones<T extends ZoneSchema>(\n shardId: string,\n schema: T,\n): StateZones<T> {\n const result = {} as StateZones<T>;\n\n for (const key of Object.keys(schema) as (keyof T & ZoneName)[]) {\n const defaults = schema[key] as Record<string, unknown>;\n const backend = backends[key];\n\n // Hydrate: shallow-merge stored values over the schema defaults so new\n // fields added to the schema in a later version get their defaults even\n // for shards whose backend entries predate them.\n const stored = backend.read(shardId) as Record<string, unknown> | undefined;\n const initial: Record<string, unknown> = { ...defaults, ...(stored ?? {}) };\n\n // The reactive proxy. Deep reactivity via $state lets shards mutate\n // nested fields (e.g. state.workspace.panelSizes[0] = 0.4) and still\n // trigger the flush effect.\n const proxy = $state(initial);\n (result as Record<string, unknown>)[key] = proxy;\n\n // Set up change tracking for persistent zones. Memory-only zones don't\n // need it: nothing reads from them beyond the in-process proxy.\n if (!PERSISTENT_ZONES.includes(key)) continue;\n\n // $effect.root creates a standalone reactivity scope outside any\n // component. The returned cleanup is intentionally not captured in\n // phase 3 — see the \"Lifetime management\" note at the top of the file.\n $effect.root(() => {\n let first = true;\n $effect(() => {\n // $state.snapshot deeply reads every reactive field, which both\n // establishes dependency tracking and produces a plain-object copy\n // safe to hand to the backend.\n const snap = $state.snapshot(proxy);\n if (first) {\n first = false;\n return; // don't write back the just-hydrated value\n }\n scheduleFlush(key, shardId, snap);\n });\n });\n }\n\n return result;\n}\n\n// ---------- test hooks ----------------------------------------------------\n\n/**\n * Swap a backend implementation. Intended for tests and for phase 4+ when\n * Tauri or IndexedDB backends replace the defaults. Not part of the shard-\n * facing API.\n */\nexport function __setBackend(zone: ZoneName, backend: Backend): void {\n backends[zone] = backend;\n}\n\n/**\n * Read a raw persisted zone entry without creating a reactive proxy.\n *\n * Intended for framework-internal consumers (e.g. the shell's layout\n * persistence) that need to inspect a stored value before deciding\n * whether to pass it to `createStateZones`. Not part of the shard-facing\n * API — shards always go through `createStateZones` so hydration is\n * reactive and debounced-flush applies.\n *\n * Returns `undefined` for missing, corrupt, or memory-only-zone entries\n * that have no stored value.\n */\nexport function peekZone(zone: ZoneName, shardId: string): unknown | undefined {\n return backends[zone].read(shardId);\n}\n\n/**\n * Delete a persisted zone entry. Intended for framework-internal use\n * when a stored value is known to be incompatible (version mismatch,\n * corruption) and should be removed before `createStateZones` hydrates.\n */\nexport function clearZone(zone: ZoneName, shardId: string): void {\n backends[zone].delete(shardId);\n}\n","// generated during release, do not modify\n\n/**\n * The current version, as set in package.json.\n * @type {string}\n */\nexport const VERSION = '5.55.4';\nexport const PUBLIC_VERSION = '5';\n","import { PUBLIC_VERSION } from '../version.js';\n\nif (typeof window !== 'undefined') {\n\t// @ts-expect-error\n\t((window.__svelte ??= {}).v ??= new Set()).add(PUBLIC_VERSION);\n}\n","/*\n * createFocusTrap — minimal Tab-cycling focus trap for modal frames.\n *\n * On install: remembers the currently focused element, moves focus to the\n * first focusable descendant of `container`, and intercepts Tab/Shift+Tab\n * to cycle within the container.\n *\n * On teardown (the returned disposer): removes the listener and restores\n * focus to the previously active element if it's still connected to the DOM.\n *\n * Phase 5 scope is deliberately narrow: no aria-hidden on siblings, no\n * Inert attribute management, no MutationObserver for dynamic content.\n * Those refinements arrive when accessibility work lands post-prototype.\n */\n\nconst FOCUSABLE_SELECTOR = [\n 'a[href]',\n 'button:not([disabled])',\n 'input:not([disabled])',\n 'select:not([disabled])',\n 'textarea:not([disabled])',\n '[tabindex]:not([tabindex=\"-1\"])',\n].join(',');\n\nexport function createFocusTrap(container: HTMLElement): () => void {\n const previouslyFocused = document.activeElement as HTMLElement | null;\n\n function getFocusables(): HTMLElement[] {\n return Array.from(container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR));\n }\n\n function onKeydown(e: KeyboardEvent): void {\n if (e.key !== 'Tab') return;\n const focusables = getFocusables();\n if (focusables.length === 0) {\n // Nothing to focus — swallow Tab so it can't escape the modal.\n e.preventDefault();\n return;\n }\n const first = focusables[0];\n const last = focusables[focusables.length - 1];\n const active = document.activeElement as HTMLElement | null;\n\n if (e.shiftKey && (active === first || !container.contains(active))) {\n e.preventDefault();\n last.focus();\n } else if (!e.shiftKey && (active === last || !container.contains(active))) {\n e.preventDefault();\n first.focus();\n }\n }\n\n container.addEventListener('keydown', onKeydown);\n\n // Defer initial focus to the next microtask so the container contents\n // (which may still be rendering if createFocusTrap was called mid-mount)\n // have a chance to appear in the DOM.\n queueMicrotask(() => {\n const focusables = getFocusables();\n (focusables[0] ?? container).focus();\n });\n\n return () => {\n container.removeEventListener('keydown', onKeydown);\n if (previouslyFocused && document.contains(previouslyFocused)) {\n previouslyFocused.focus();\n }\n };\n}\n","<script lang=\"ts\">\n /*\n * ModalFrame — the internal wrapper that the modal manager mounts into\n * a per-modal host div inside the layer-4 root.\n *\n * Responsibilities:\n * - Span the full layer as a transparent centering container so every\n * modal box renders in the middle of the shell.\n * - Catch pointer events on the area around the box so clicks outside\n * the top modal do not fall through to modals beneath or to the\n * underlying layout.\n * - Dynamically render the caller's content component with its props.\n * - Install a focus trap on the dialog box for as long as the frame\n * lives, restoring previous focus on teardown.\n *\n * The frame does NOT render a backdrop. The modal manager owns a single\n * shared backdrop element under the layer-4 root whose opacity scales\n * (capped) with stack depth — otherwise per-frame backdrops compound\n * into full black once a few modals are stacked, and every layer also\n * pays its own composite cost.\n *\n * Escape-to-close and backdrop-click policy are decided by the manager,\n * not the frame — the manager holds the stack and knows which modal is\n * on top. The frame just receives a `close` callback and invokes it if\n * the caller wants a built-in close button (there is none by default —\n * content owns its chrome).\n */\n\n import type { Component } from 'svelte';\n import { createFocusTrap } from './focusTrap';\n\n let {\n Content,\n contentProps,\n close,\n boxStyle,\n onBackdropClick,\n }: {\n Content: Component<Record<string, unknown>>;\n contentProps: Record<string, unknown>;\n close: () => void;\n boxStyle?: string;\n onBackdropClick?: () => void;\n } = $props();\n\n let box: HTMLDivElement;\n\n $effect(() => {\n if (!box) return;\n return createFocusTrap(box);\n });\n\n function handleFrameClick(ev: MouseEvent): void {\n if (!onBackdropClick) return;\n if (ev.target !== ev.currentTarget) return; // descendant click — let it through\n onBackdropClick();\n }\n</script>\n\n<div class=\"modal-frame\" role=\"presentation\" onclick={handleFrameClick}>\n <div\n class=\"modal-box\"\n role=\"dialog\"\n aria-modal=\"true\"\n tabindex=\"-1\"\n bind:this={box}\n style={boxStyle}\n >\n <Content {...contentProps} {close} />\n </div>\n</div>\n\n<style>\n .modal-frame {\n position: absolute;\n inset: 0;\n display: grid;\n place-items: center;\n /* Transparent but pointer-capturing so clicks around the box are\n swallowed rather than falling through to modals beneath. */\n pointer-events: auto;\n }\n .modal-box {\n background: var(--shell-grad-bg-elevated, var(--shell-bg-elevated));\n color: var(--shell-fg);\n border: 1px solid var(--shell-border-strong);\n border-radius: var(--shell-radius);\n min-width: 320px;\n max-width: min(640px, 90vw);\n max-height: 90vh;\n overflow: auto;\n box-shadow: 0 20px 48px rgba(0, 0, 0, 0.5);\n outline: none;\n }\n</style>\n","/*\n * Layer root registry.\n *\n * Shell.svelte owns the six overlay root <div>s (one per layer). Overlay\n * managers — which are plain TypeScript modules, not Svelte components —\n * need DOM references to those roots so they can append transient content\n * (modals, popups, toasts) into the correct stacking context.\n *\n * Shell.svelte calls `registerLayerRoot(name, el)` on each root during its\n * own mount effect. Managers call `getLayerRoot(name)` lazily the first\n * time they need to open something, which is always *after* Shell has\n * rendered because overlay triggers originate from views mounted into the\n * layout tree. No race; no DOM queries.\n *\n * Unregister is exposed too so tests and hot-reload can reset the registry.\n */\n\nimport type { OverlayLayer } from './types';\n\nconst roots: Partial<Record<OverlayLayer, HTMLElement>> = {};\n\nexport function registerLayerRoot(layer: OverlayLayer, el: HTMLElement): void {\n roots[layer] = el;\n}\n\nexport function unregisterLayerRoot(layer: OverlayLayer): void {\n delete roots[layer];\n}\n\nexport function getLayerRoot(layer: OverlayLayer): HTMLElement {\n const el = roots[layer];\n if (!el) {\n throw new Error(\n `Overlay layer \"${layer}\" root is not registered — ` +\n `Shell.svelte must mount before opening overlays on this layer.`,\n );\n }\n return el;\n}\n","/*\n * App registry — reactive record of every registered app, plus the\n * single slot for the currently-active app.\n *\n * Registration is called from the host (main.ts glob loop or a future\n * runtime loader). The shell home view reads `listRegisteredApps()`\n * reactively so newly-registered apps appear in the list without\n * reboot. `activeApp` tracks which app (if any) is currently launched;\n * phase 8 allows at most one.\n */\n\nimport type { App, AppManifest } from './types';\n\n/**\n * Reactive map of all registered apps keyed by `AppManifest.id`. Populated\n * once at boot by the host's glob-discovery loop via `registerApp`. A future\n * runtime loader may append entries at runtime.\n */\nexport const registeredApps = $state(new Map<string, App>());\n\n/**\n * Reactive slot tracking the currently-active app id. Null when the shell is\n * showing the home screen or no app has been launched yet. Phase 8 allows at\n * most one active app at a time.\n */\nexport const activeApp: { id: string | null } = $state({ id: null });\n\n/**\n * Most recently launched app id this session. Distinct from\n * `lastAppState` in `lifecycle.ts` (which is persisted to the user zone\n * for boot, and cleared by `returnToHome`). The breadcrumb pointer\n * survives `returnToHome` so the top-bar BrandSlot can render\n * `SH3 > [App Name]` and let the user one-click back into the app.\n *\n * In-memory only — page reload resets it to null. No persistence.\n */\nexport const breadcrumbApp: { id: string | null } = $state({ id: null });\n\n/** Read the breadcrumb app id. `null` when no app has launched this session. */\nexport function getBreadcrumbAppId(): string | null {\n return breadcrumbApp.id;\n}\n\n/** @internal — test helper; resets the breadcrumb to null. */\nexport function __resetBreadcrumbForTest(): void {\n breadcrumbApp.id = null;\n}\n\n/**\n * Register (or re-register) an app with the framework.\n *\n * If an app with the same id already exists it is silently replaced,\n * which is the expected path during package updates — the new bundle is\n * loaded and re-registered without requiring a full page reload.\n *\n * @param app - The app module to register.\n */\nexport function registerApp(app: App): void {\n registeredApps.set(app.manifest.id, app);\n}\n\n/**\n * Reactive snapshot of all registered app manifests. Shell home iterates\n * this to populate its launcher list. Returns only manifests so callers\n * don't reach into app bodies (initialLayout, activate hook) — those are\n * launch-time concerns.\n */\nexport function listRegisteredApps(): AppManifest[] {\n return Array.from(registeredApps.values()).map((a) => a.manifest);\n}\n\n/** Reactive current-app manifest (or null when none is active). */\nexport function getActiveApp(): AppManifest | null {\n const id = activeApp.id;\n if (!id) return null;\n return registeredApps.get(id)?.manifest ?? null;\n}\n\n/**\n * Lookup for framework-internal use — returns the full App (not just the\n * manifest) so lifecycle code can reach into `initialLayout` and the\n * activate hook. Not re-exported through `api.ts`.\n */\nexport function getRegisteredApp(id: string): App | undefined {\n return registeredApps.get(id);\n}\n\n/** Test-only reset: clear registered apps, active-app pointer, and breadcrumb. */\nexport function __resetAppRegistryForTest(): void {\n registeredApps.clear();\n activeApp.id = null;\n breadcrumbApp.id = null;\n}\n","/*\n * Navigation back-cascade — global LIFO stacks for dismissable overlays\n * and app-internal nav entries. Drives the response to back/forward\n * signals (delivered by platform emitters in this same module folder).\n *\n * Cascade on back:\n * 1. Top-most dismissable overlay (modal/popup) → close it.\n * 2. Top-most app nav entry → fire its onPop.\n * 3. Active app exists → returnToHome (cancellable suspend hooks).\n * 4. Otherwise → no-op.\n *\n * Forward is asymmetric: only acts on home and only relaunches the\n * breadcrumb app (matches the existing BrandSlot click semantics).\n *\n * Lifecycle handlers (returnToHome, launchApp) are injected during host\n * bootstrap rather than imported directly. This avoids module-eval cycles\n * with apps/lifecycle and keeps this module unit-testable in isolation.\n */\n\nimport { activeApp, breadcrumbApp } from '../apps/registry.svelte';\n\nexport interface NavEntry {\n /** Optional label. Reserved for future breadcrumb extension; not surfaced in v1. */\n label?: string;\n /** Called when this entry is popped via back. Synchronous; not cancellable in v1. */\n onPop: () => void;\n}\n\nexport interface NavEntryHandle {\n /** Pop this entry without firing onPop. Idempotent; no-op if already popped. */\n remove(): void;\n}\n\nexport interface DismissableRegistration {\n /** Remove the dismissable from the cascade. Idempotent. */\n unregister(): void;\n}\n\ninterface NavEntryRecord {\n id: symbol;\n label?: string;\n onPop: () => void;\n}\n\ninterface DismissableRecord {\n id: symbol;\n dismiss: () => void;\n}\n\ninterface LifecycleHandlers {\n returnToHome: () => void | Promise<unknown>;\n launchApp: (id: string) => void | Promise<unknown>;\n}\n\nconst dismissables: DismissableRecord[] = [];\nconst appNavEntries: NavEntryRecord[] = [];\nlet lifecycleHandlers: LifecycleHandlers | null = null;\n\nexport function setLifecycleHandlers(handlers: LifecycleHandlers): void {\n lifecycleHandlers = handlers;\n}\n\nexport function pushNavEntry(entry: NavEntry): NavEntryHandle {\n if (!activeApp.id) {\n throw new Error('pushNavEntry requires an active app');\n }\n const id = Symbol('nav-entry');\n appNavEntries.push({ id, label: entry.label, onPop: entry.onPop });\n return {\n remove() {\n const idx = appNavEntries.findIndex((e) => e.id === id);\n if (idx >= 0) appNavEntries.splice(idx, 1);\n },\n };\n}\n\nexport function registerDismissable(dismiss: () => void): DismissableRegistration {\n const id = Symbol('dismissable');\n dismissables.push({ id, dismiss });\n return {\n unregister() {\n const idx = dismissables.findIndex((d) => d.id === id);\n if (idx >= 0) dismissables.splice(idx, 1);\n },\n };\n}\n\nexport function clearAppNavEntries(): void {\n appNavEntries.length = 0;\n}\n\nexport function dispatchBack(): void {\n if (dismissables.length > 0) {\n const top = dismissables.pop()!;\n top.dismiss();\n return;\n }\n if (appNavEntries.length > 0) {\n const top = appNavEntries.pop()!;\n top.onPop();\n return;\n }\n if (activeApp.id && lifecycleHandlers) {\n void lifecycleHandlers.returnToHome();\n }\n}\n\nexport function dispatchForward(): void {\n if (activeApp.id) return;\n if (!breadcrumbApp.id) return;\n if (!lifecycleHandlers) return;\n void lifecycleHandlers.launchApp(breadcrumbApp.id);\n}\n\n/** @internal — test reset helper used by the central resetFramework. */\nexport function __resetBackStackForTest(): void {\n dismissables.length = 0;\n appNavEntries.length = 0;\n lifecycleHandlers = null;\n}\n\n/** @internal — test injection helper. */\nexport function __setLifecycleHandlersForTest(handlers: LifecycleHandlers): void {\n lifecycleHandlers = handlers;\n}\n","/*\n * Modal manager — stackable, Escape-dismissed, focus-trapped dialogs.\n *\n * Public API:\n * modalManager.open(Content, props?) → ModalHandle\n * modalManager.closeAll()\n *\n * Semantics (from docs/design/layout.md):\n * - Modals stack. Opening a second modal pushes it on top of the first.\n * - Escape pops the topmost modal.\n * - Backdrop click does NOT dismiss by default. Per-modal opt-in via\n * `ModalOptions.dismissOnBackdrop` (used by the command palette and\n * other picker-style modals where outside-click is the expected\n * dismissal gesture). See ADR-005 for the per-layer policy.\n * - Each modal has its own focus trap (installed by ModalFrame).\n *\n * Implementation notes:\n * - Each open() creates a per-modal host <div> under the layer-4 root\n * and mounts a ModalFrame into it. The host isolates modals for clean\n * unmount/remove.\n * - A SINGLE shared backdrop element is inserted into the layer-4 root\n * on the first open and removed on the last close. It is repositioned\n * on every stack change to sit directly BENEATH the topmost modal host\n * (and above all other modal hosts), so stacked modals read as dimmed\n * and clearly non-interactive while the top modal renders clear. The\n * opacity is a single fixed value — depth-scaled opacity (an earlier\n * cut) is no longer meaningful because only the \"layer beneath the\n * top\" is ever being dimmed. Per-modal backdrops were the phase-5\n * first cut; they compounded (2 modals ≈ 0.75, 3 ≈ 0.88, …) and were\n * both unbounded and expensive.\n * - The manager owns a single document-level Escape listener, installed\n * lazily on first open and removed when the stack empties. This is\n * simpler than per-modal listeners and avoids \"which listener wins\"\n * ordering puzzles when modals stack.\n * - close() is idempotent: calling it after the modal has been removed\n * is a no-op, which makes it safe for content components to call from\n * both a close button and an \"async action finished\" callback.\n */\n\nimport { mount, unmount, type Component } from 'svelte';\nimport ModalFrame from './ModalFrame.svelte';\nimport { getLayerRoot } from './roots';\nimport type { ModalHandle, ModalOptions } from './types';\nimport { registerDismissable } from '../navigation/back-stack';\n\ninterface ModalEntry {\n host: HTMLDivElement;\n frame: Record<string, unknown>;\n handle: ModalHandle;\n}\n\nconst stack: ModalEntry[] = [];\nlet escapeInstalled = false;\nlet backdrop: HTMLDivElement | null = null;\n\n/** Single fixed backdrop opacity. The backdrop is repositioned beneath\n * the topmost modal on every stack change, so underlying modals appear\n * dimmed (visually communicating they're non-interactive) while the top\n * modal sits above the dim. Depth-scaled opacity is therefore obsolete:\n * only one \"layer beneath the top\" is ever being dimmed. */\nconst BACKDROP_OPACITY = 0.5;\n\nfunction syncBackdrop(): void {\n const root = getLayerRoot('modal');\n if (stack.length === 0) {\n if (backdrop) {\n backdrop.remove();\n backdrop = null;\n }\n return;\n }\n if (!backdrop) {\n backdrop = document.createElement('div');\n backdrop.className = 'sh3-modal-backdrop';\n backdrop.style.position = 'absolute';\n backdrop.style.inset = '0';\n backdrop.style.pointerEvents = 'auto';\n backdrop.style.transition = 'background-color 120ms ease';\n backdrop.style.background = `rgba(0, 0, 0, ${BACKDROP_OPACITY})`;\n }\n // Place the backdrop directly before the topmost modal host so every\n // modal beneath it is dimmed while the top modal renders clear above.\n const topHost = stack[stack.length - 1].host;\n root.insertBefore(backdrop, topHost);\n}\n\nfunction onDocumentKeydown(e: KeyboardEvent): void {\n if (e.key !== 'Escape') return;\n if (stack.length === 0) return;\n e.stopPropagation();\n e.preventDefault();\n stack[stack.length - 1].handle.close();\n}\n\nfunction ensureEscapeListener(): void {\n if (escapeInstalled) return;\n escapeInstalled = true;\n document.addEventListener('keydown', onDocumentKeydown, true);\n}\n\nfunction removeEscapeListenerIfIdle(): void {\n if (stack.length > 0) return;\n if (!escapeInstalled) return;\n escapeInstalled = false;\n document.removeEventListener('keydown', onDocumentKeydown, true);\n}\n\nfunction removeEntry(entry: ModalEntry): void {\n const idx = stack.indexOf(entry);\n if (idx < 0) return; // already closed — idempotent\n stack.splice(idx, 1);\n unmount(entry.frame);\n entry.host.remove();\n syncBackdrop();\n removeEscapeListenerIfIdle();\n}\n\nfunction openModal<P extends Record<string, unknown>>(\n Content: Component<P & { close: () => void }>,\n props?: P,\n options?: ModalOptions,\n): ModalHandle {\n const root = getLayerRoot('modal');\n const host = document.createElement('div');\n host.className = 'sh3-modal-host';\n host.dataset.shellOverlayHost = 'modal';\n host.style.position = 'absolute';\n host.style.inset = '0';\n host.style.pointerEvents = 'auto';\n root.appendChild(host);\n\n const entry = {} as ModalEntry;\n const handle: ModalHandle = {\n close: () => removeEntry(entry),\n };\n\n const dismissReg = registerDismissable(() => handle.close());\n const originalClose = handle.close;\n handle.close = () => {\n dismissReg.unregister();\n originalClose();\n };\n\n const frame = mount(ModalFrame, {\n target: host,\n props: {\n Content: Content as unknown as Component<Record<string, unknown>>,\n contentProps: (props ?? {}) as Record<string, unknown>,\n close: handle.close,\n boxStyle: options?.boxStyle,\n onBackdropClick: options?.dismissOnBackdrop ? handle.close : undefined,\n },\n });\n\n entry.host = host;\n entry.frame = frame;\n entry.handle = handle;\n stack.push(entry);\n syncBackdrop();\n ensureEscapeListener();\n\n return handle;\n}\n\nfunction closeAll(): void {\n while (stack.length > 0) {\n removeEntry(stack[stack.length - 1]);\n }\n}\n\nexport interface ModalManager {\n open<P extends Record<string, unknown>>(\n Content: Component<P & { close: () => void }>,\n props?: P,\n options?: ModalOptions,\n ): ModalHandle;\n closeAll(): void;\n}\n\nexport const modalManager: ModalManager = {\n open: openModal,\n closeAll,\n};\n","<script lang=\"ts\">\n /*\n * PopupFrame — positioned wrapper for a popup's content component.\n *\n * Takes an anchor rect in viewport coordinates and places itself at\n * bottom-start with a viewport overflow clamp. The measurement happens\n * after mount via an $effect so we can read the real frame size; an\n * initial render off-screen hides the flicker while we measure.\n *\n * Positioning policy for phase 5:\n * - Preferred: bottom-start (top = anchor.bottom + 4, left = anchor.left)\n * - If the frame's right edge would exit the viewport, shift left so it\n * sits flush with the right edge minus a small margin.\n * - If the frame's bottom edge would exit the viewport, flip to above\n * the anchor (top = anchor.top - frameHeight - 4).\n * - If it still doesn't fit, clamp to the viewport.\n *\n * Additional placements (right-start, left-start, etc.) arrive when a\n * real shard needs them; phase 5 doesn't.\n */\n\n import type { Component } from 'svelte';\n\n let {\n Content,\n contentProps,\n anchorRect,\n close,\n }: {\n Content: Component<Record<string, unknown>>;\n contentProps: Record<string, unknown>;\n anchorRect: DOMRect;\n close: () => void;\n } = $props();\n\n let frame: HTMLDivElement;\n let top = $state(-9999);\n let left = $state(-9999);\n\n $effect(() => {\n if (!frame) return;\n const rect = frame.getBoundingClientRect();\n const margin = 4;\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n\n let t = anchorRect.bottom + margin;\n let l = anchorRect.left;\n\n if (l + rect.width > vw - margin) {\n l = Math.max(margin, vw - rect.width - margin);\n }\n if (t + rect.height > vh - margin) {\n const flipped = anchorRect.top - rect.height - margin;\n t = flipped >= margin ? flipped : Math.max(margin, vh - rect.height - margin);\n }\n\n top = t;\n left = l;\n });\n</script>\n\n<div\n class=\"popup-frame\"\n role=\"menu\"\n tabindex=\"-1\"\n style=\"top: {top}px; left: {left}px;\"\n bind:this={frame}\n>\n <Content {...contentProps} {close} />\n</div>\n\n<style>\n .popup-frame {\n position: absolute;\n background: var(--shell-grad-bg-elevated, var(--shell-bg-elevated));\n color: var(--shell-fg);\n border: 1px solid var(--shell-border-strong);\n border-radius: var(--shell-radius-sm);\n box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);\n min-width: 120px;\n outline: none;\n pointer-events: auto;\n }\n</style>\n","/*\n * Popup manager — anchored, non-stacking, outside-click-dismissable.\n *\n * Public API:\n * popupManager.show(Content, { anchor, placement? }, props?) → PopupHandle\n * popupManager.close()\n *\n * Semantics (from docs/design/layout.md):\n * - Popups do NOT stack. Opening a second popup dismisses the first.\n * - Clicking outside the popup dismisses it.\n * - Pressing Escape dismisses it.\n * - The caller provides a PopupAnchor (HTMLElement or {x,y} point);\n * the popup positions itself relative to the anchor's viewport rect.\n *\n * Implementation notes:\n * - The manager keeps at most one active entry. show() closes any\n * prior entry before opening a new one — so callers can wire a\n * menu button to `shell.popup.show(...)` without worrying about\n * toggling themselves.\n * - Dismissal listeners (pointerdown for outside-click, keydown for\n * Escape) are installed when the popup opens and removed on close.\n * Outside-click detection uses the mounted frame element's DOM\n * containment check, so nested popups-inside-content still click-\n * through without closing (there are no nested popups in phase 5,\n * but the check is cheap and correct).\n * - close() is idempotent.\n */\n\nimport { mount, unmount, type Component } from 'svelte';\nimport PopupFrame from './PopupFrame.svelte';\nimport { getLayerRoot } from './roots';\nimport type { PopupAnchor, PopupHandle, PopupOptions } from './types';\nimport { registerDismissable } from '../navigation/back-stack';\n\n/**\n * Convert a PopupAnchor to a DOMRect.\n * - HTMLElement: uses its live bounding rect.\n * - { x, y } virtual point: zero-size rect at the viewport coordinates so\n * PopupFrame places itself at bottom-start of the cursor position.\n */\nfunction anchorRect(anchor: PopupAnchor): DOMRect {\n if (anchor instanceof HTMLElement) return anchor.getBoundingClientRect();\n return new DOMRect(anchor.x, anchor.y, 0, 0);\n}\n\ninterface PopupEntry {\n host: HTMLDivElement;\n frame: Record<string, unknown>;\n handle: PopupHandle;\n}\n\nlet current: PopupEntry | null = null;\n\nfunction onDocumentPointerDown(e: PointerEvent): void {\n if (!current) return;\n const target = e.target as Node | null;\n if (target && current.host.contains(target)) return;\n current.handle.close();\n}\n\nfunction onDocumentKeydown(e: KeyboardEvent): void {\n if (!current) return;\n if (e.key !== 'Escape') return;\n e.stopPropagation();\n e.preventDefault();\n current.handle.close();\n}\n\nfunction installDismissListeners(): void {\n // `true` capture phase so we see the event before view-level handlers\n // that might stopPropagation.\n document.addEventListener('pointerdown', onDocumentPointerDown, true);\n document.addEventListener('keydown', onDocumentKeydown, true);\n}\n\nfunction removeDismissListeners(): void {\n document.removeEventListener('pointerdown', onDocumentPointerDown, true);\n document.removeEventListener('keydown', onDocumentKeydown, true);\n}\n\nfunction removeEntry(entry: PopupEntry): void {\n if (current !== entry) return; // already closed / superseded\n current = null;\n removeDismissListeners();\n unmount(entry.frame);\n entry.host.remove();\n}\n\nfunction showPopup<P extends Record<string, unknown>>(\n Content: Component<P & { close: () => void }>,\n options: PopupOptions,\n props?: P,\n): PopupHandle {\n // Non-stacking: dismiss any existing popup first.\n if (current) removeEntry(current);\n\n const root = getLayerRoot('popup');\n const host = document.createElement('div');\n host.className = 'sh3-popup-host';\n host.dataset.shellOverlayHost = 'popup';\n host.style.position = 'absolute';\n host.style.inset = '0';\n host.style.pointerEvents = 'none'; // only the frame captures pointer events\n root.appendChild(host);\n\n const rect = anchorRect(options.anchor);\n\n const entry = {} as PopupEntry;\n const handle: PopupHandle = {\n close: () => removeEntry(entry),\n };\n\n const dismissReg = registerDismissable(() => handle.close());\n const originalClose = handle.close;\n handle.close = () => {\n dismissReg.unregister();\n originalClose();\n };\n\n const frame = mount(PopupFrame, {\n target: host,\n props: {\n Content: Content as unknown as Component<Record<string, unknown>>,\n contentProps: (props ?? {}) as Record<string, unknown>,\n anchorRect: rect,\n close: handle.close,\n },\n });\n\n entry.host = host;\n entry.frame = frame;\n entry.handle = handle;\n current = entry;\n\n // Defer listener install by a microtask so the same pointerdown that\n // opened the popup (from a button click) doesn't instantly dismiss it.\n queueMicrotask(installDismissListeners);\n\n return handle;\n}\n\nfunction closeCurrent(): void {\n if (current) removeEntry(current);\n}\n\nexport interface PopupManager {\n show<P extends Record<string, unknown>>(\n Content: Component<P & { close: () => void }>,\n options: PopupOptions,\n props?: P,\n ): PopupHandle;\n close(): void;\n}\n\nexport const popupManager: PopupManager = {\n show: showPopup,\n close: closeCurrent,\n};\n\n/** @internal — test helper only. Closes any active popup and resets state. */\nexport function __resetPopupManagerForTest(): void {\n if (current) {\n removeDismissListeners();\n unmount(current.frame);\n current.host.remove();\n current = null;\n }\n}\n","<script lang=\"ts\">\n /*\n * ToastItem — a single auto-dismissing notification.\n *\n * The toast manager mounts one ToastItem per notification into the\n * layer-5 root. The item renders the message, applies level styling,\n * and fades/slides in on mount. The manager (not the item) owns the\n * auto-dismiss timer, so the item stays purely presentational.\n *\n * Dismiss-on-click is built into the item via the close prop so users\n * can dismiss a toast early without waiting for its timer.\n */\n\n import type { ToastLevel } from './types';\n\n let {\n message,\n level,\n close,\n }: {\n message: string;\n level: ToastLevel;\n close: () => void;\n } = $props();\n</script>\n\n<!-- svelte-ignore a11y_click_events_have_key_events -->\n<!-- svelte-ignore a11y_no_static_element_interactions -->\n<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->\n<div\n class=\"toast toast-{level}\"\n role=\"status\"\n aria-live=\"polite\"\n onclick={close}\n>\n <span class=\"toast-level\">{level}</span>\n <span class=\"toast-message\">{message}</span>\n</div>\n\n<style>\n .toast {\n pointer-events: auto;\n display: flex;\n align-items: center;\n gap: var(--shell-pad-md);\n padding: var(--shell-pad-sm) var(--shell-pad-md);\n background: var(--shell-grad-bg-elevated, var(--shell-bg-elevated));\n color: var(--shell-fg);\n border: 1px solid var(--shell-border-strong);\n border-left-width: 3px;\n border-radius: var(--shell-radius-sm);\n box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4);\n font-size: 12px;\n min-width: 220px;\n max-width: 360px;\n cursor: pointer;\n animation: toast-in 160ms ease-out both;\n }\n .toast-level {\n text-transform: uppercase;\n font-family: var(--shell-font-mono);\n font-size: 10px;\n letter-spacing: 0.5px;\n color: var(--shell-fg-muted);\n }\n .toast-message { flex: 1; }\n\n .toast-info { border-left-color: var(--shell-accent); }\n .toast-success { border-left-color: var(--shell-success); }\n .toast-warn { border-left-color: var(--shell-warning); }\n .toast-error { border-left-color: var(--shell-error); }\n\n @keyframes toast-in {\n from { opacity: 0; transform: translateY(8px); }\n to { opacity: 1; transform: translateY(0); }\n }\n</style>\n","/*\n * Toast manager — auto-dismissing non-interactive notifications.\n *\n * Public API:\n * toastManager.notify(message, options?) → ToastHandle\n * toastManager.clear()\n *\n * Semantics (from docs/design/layout.md):\n * - Toasts queue and stack vertically at the bottom-right of the shell.\n * - Each toast auto-dismisses after `duration` ms (default 3000).\n * `duration: Infinity` pins the toast until the caller calls close().\n * - Clicking a toast dismisses it immediately.\n * - Level styling: info / warn / error / success.\n *\n * Implementation notes:\n * - A lazy layout container is appended to the layer-5 root on first\n * notify; it's a flex column anchored to the bottom-right with a\n * small gap between toasts.\n * - Each toast is a standalone mount — simpler than a single list\n * component tracking an array, and naturally handles independent\n * fade-in animations per item.\n * - The manager tracks entries for `clear()` and for idempotent close.\n */\n\nimport { mount, unmount } from 'svelte';\nimport ToastItem from './ToastItem.svelte';\nimport { getLayerRoot } from './roots';\nimport type { ToastHandle, ToastLevel, ToastOptions } from './types';\n\ninterface ToastEntry {\n host: HTMLDivElement;\n instance: Record<string, unknown>;\n timer: ReturnType<typeof setTimeout> | null;\n handle: ToastHandle;\n}\n\nconst entries = new Set<ToastEntry>();\nlet container: HTMLDivElement | null = null;\n\nfunction ensureContainer(): HTMLDivElement {\n if (container && container.isConnected) return container;\n const root = getLayerRoot('toast');\n container = document.createElement('div');\n container.className = 'sh3-toast-stack';\n container.style.position = 'absolute';\n container.style.right = '16px';\n container.style.bottom = '16px';\n container.style.display = 'flex';\n container.style.flexDirection = 'column-reverse';\n container.style.gap = '6px';\n container.style.pointerEvents = 'none';\n root.appendChild(container);\n return container;\n}\n\nfunction removeEntry(entry: ToastEntry): void {\n if (!entries.has(entry)) return;\n entries.delete(entry);\n if (entry.timer !== null) {\n clearTimeout(entry.timer);\n entry.timer = null;\n }\n unmount(entry.instance);\n entry.host.remove();\n}\n\nfunction notify(message: string, options: ToastOptions = {}): ToastHandle {\n const level: ToastLevel = options.level ?? 'info';\n const duration = options.duration ?? 3000;\n\n const parent = ensureContainer();\n const host = document.createElement('div');\n host.className = 'sh3-toast-host';\n parent.appendChild(host);\n\n const entry = {} as ToastEntry;\n const handle: ToastHandle = {\n close: () => removeEntry(entry),\n };\n\n const instance = mount(ToastItem, {\n target: host,\n props: {\n message,\n level,\n close: handle.close,\n },\n });\n\n entry.host = host;\n entry.instance = instance;\n entry.handle = handle;\n entry.timer =\n Number.isFinite(duration) && duration > 0\n ? setTimeout(() => removeEntry(entry), duration)\n : null;\n\n entries.add(entry);\n return handle;\n}\n\nfunction clear(): void {\n for (const entry of [...entries]) removeEntry(entry);\n}\n\nexport interface ToastManager {\n notify(message: string, options?: ToastOptions): ToastHandle;\n clear(): void;\n}\n\nexport const toastManager: ToastManager = {\n notify,\n clear,\n};\n","/*\n * Pure helpers for float content: recursive min-size computation over a\n * LayoutNode subtree, cascade-position generation, and stable id minting.\n *\n * Min-size rule (see spec 2026-04-11-layout-topology-design.md):\n * - slot: framework-constant DEFAULT_SLOT_MIN (120×80). Real per-view\n * min-size reading is a follow-up; see rescoped DF10.\n * - tabs: element-wise max of all tabs' slot minimums (only one visible).\n * - split: sum along the split axis, max on the cross axis.\n */\n\nimport type { LayoutNode, FloatEntry } from './types';\n\nexport const DEFAULT_SLOT_MIN = { w: 120, h: 80 } as const;\n\nexport interface Size {\n w: number;\n h: number;\n}\n\nexport function computeMinSize(node: LayoutNode): Size {\n if (node.type === 'slot') {\n return { ...DEFAULT_SLOT_MIN };\n }\n if (node.type === 'tabs') {\n // All tabs fight for the same area; the min is the element-wise max.\n return { ...DEFAULT_SLOT_MIN };\n }\n // split\n const children = node.children.map(computeMinSize);\n if (node.direction === 'horizontal') {\n return {\n w: children.reduce((a, c) => a + c.w, 0),\n h: children.reduce((a, c) => Math.max(a, c.h), 0),\n };\n }\n return {\n w: children.reduce((a, c) => Math.max(a, c.w), 0),\n h: children.reduce((a, c) => a + c.h, 0),\n };\n}\n\nconst CASCADE_STEP = 32;\nconst CASCADE_BASE = { x: 48, y: 48 };\n\n/**\n * Given the list of currently-open floats, return the position a new\n * float should appear at. Each new float offsets (+32, +32) from the\n * most recently opened one. If the resulting position would push the\n * float's header outside `bounds`, wraps back to CASCADE_BASE.\n */\nexport function cascadePosition(\n existing: FloatEntry[],\n bounds: { w: number; h: number },\n): { x: number; y: number } {\n if (existing.length === 0) return { ...CASCADE_BASE };\n const last = existing[existing.length - 1];\n const next = { x: last.position.x + CASCADE_STEP, y: last.position.y + CASCADE_STEP };\n // Wraparound if the header would leave the tree-allocated area\n if (next.x + 120 > bounds.w || next.y + 32 > bounds.h) {\n return { ...CASCADE_BASE };\n }\n return next;\n}\n\nlet floatIdCounter = 0;\n/** Stable, process-unique float id. Not cryptographic — just unique within a session. */\nexport function generateFloatId(): string {\n floatIdCounter += 1;\n return `float-${Date.now().toString(36)}-${floatIdCounter.toString(36)}`;\n}\n\n/**\n * True if a LayoutNode subtree contains no leaf slot with a bound viewId.\n * Used by the drag-commit auto-close invariant: when the last bound leaf\n * leaves a float, the float is removed from the tree.\n *\n * A tabs node with zero tabs is empty. A split node is empty iff every\n * child is empty. Only leaf slots with a non-null viewId are considered\n * \"filled\".\n */\nexport function isEmptyContent(node: LayoutNode): boolean {\n if (node.type === 'slot') return node.viewId == null;\n if (node.type === 'tabs') return node.tabs.every((t) => t.viewId == null);\n return node.children.every(isEmptyContent);\n}\n","/*\n * Walks up from `anchor` looking for an element marked as an overlay host\n * via `data-shell-overlay-host`. Modal hosts, popup hosts, and float frames\n * tag themselves so anchored overlays (popups, dismissable picker floats)\n * can mount inside their opener's stacking context instead of at a global\n * layer root — which is what the layer-z-index invariant gives us when a\n * popover is logically \"inside\" a modal.\n *\n * Returns null when the anchor lives in the docked tree; callers fall back\n * to their configured layer root in that case. The marker is read via\n * `Element.closest`, so a marker on the anchor itself counts.\n */\n\nexport function findEnclosingOverlayHost(anchor: HTMLElement): HTMLElement | null {\n return anchor.closest<HTMLElement>('[data-shell-overlay-host]');\n}\n","/*\n * Float manager — layer 1 of the overlay stack.\n *\n * Public API (shell.float):\n * open(viewId, options?) → floatId\n * close(floatId)\n * list() → FloatEntry[]\n * focus(floatId) — raise to top of z-order within layer 1\n *\n * Semantics (see docs/design/layout.md layer stack and docs/superpowers/spec/\n * 2026-04-11-layout-topology-design.md):\n * - Float content is drawn by FloatLayer.svelte via the same LayoutRenderer\n * used by the docked tree. The manager only mutates data; rendering is\n * a pure reaction to the LayoutTree's `floats` array.\n * - Cascade default position, default size = max(600x400, computed min).\n * - Click-to-raise z-order: the most recently focused float is the last\n * element of `floats[]` and therefore drawn on top.\n * - Auto-close on empty is enforced by the drag commit path (see Task 3.3),\n * not by this manager.\n * - Multiple floats of the same viewId are allowed; toggle semantics are\n * userland (caller checks list() and decides).\n *\n * Binding:\n * The manager is bound to a live FloatEntry[] (the active LayoutTree's\n * floats) by `bindFloatStore()` during Shell boot. Before binding, an\n * in-memory fallback array is used — this is both the test environment\n * and the pre-boot state.\n */\n\nimport type { LayoutNode, FloatEntry, TabEntry } from '../layout/types';\nimport { computeMinSize, cascadePosition, generateFloatId } from '../layout/floats';\nimport type { Size } from '../layout/floats';\nimport { findEnclosingOverlayHost } from './parentHost';\n\nexport interface FloatOptions {\n title?: string;\n position?: { x: number; y: number };\n size?: Size;\n /** Instance data threaded to the view factory via `MountContext.meta`. */\n meta?: Record<string, unknown>;\n /**\n * When true, the float dismisses on any pointerdown outside its frame,\n * is not dockable, and renders without a header when `title` is unset.\n * See docs/superpowers/specs/2026-04-21-dismissable-float-design.md.\n */\n dismissable?: boolean;\n /**\n * For `dismissable` floats only: anchor element used to determine the\n * mount host. When the anchor is inside another overlay (modal, popup,\n * float frame), the float frame is portaled into that host so it stacks\n * above its opener instead of sitting at layer 1. Without an anchor —\n * or for non-dismissable floats — the frame renders at the FloatLayer\n * root as usual. The anchor isn't stored on FloatEntry (HTMLElement\n * isn't serializable through the workspace-zone proxy); only the\n * resolved parent host is, in a sidecar map keyed by float id.\n */\n anchor?: HTMLElement;\n}\n\nexport interface FloatManager {\n open(viewId: string, options?: FloatOptions): string;\n close(floatId: string): void;\n list(): FloatEntry[];\n focus(floatId: string): void;\n}\n\n// ----- storage binding ---------------------------------------------------\n\nlet fallbackFloats: FloatEntry[] = [];\nlet boundFloats: FloatEntry[] | null = null;\nlet getTreeBounds: () => { w: number; h: number } = () => ({ w: 1600, h: 900 });\n\n/**\n * Bind the manager to the active LayoutTree's `floats` array. Called\n * from Shell.svelte during boot. `getBounds` returns the current\n * tree-allocated area for cascade-position wraparound.\n */\nexport function bindFloatStore(\n floats: FloatEntry[],\n getBounds: () => { w: number; h: number },\n): void {\n boundFloats = floats;\n getTreeBounds = getBounds;\n}\n\nexport function unbindFloatStore(): void {\n boundFloats = null;\n getTreeBounds = () => ({ w: 1600, h: 900 });\n}\n\n/** Test-only reset. Clears in-memory fallback and unbinds any store. */\nexport function __resetFloatManagerForTest(): void {\n fallbackFloats = [];\n boundFloats = null;\n getTreeBounds = () => ({ w: 1600, h: 900 });\n parentHosts.clear();\n}\n\nfunction activeStore(): FloatEntry[] {\n return boundFloats ?? fallbackFloats;\n}\n\n// ----- parent host sidecar ------------------------------------------------\n\n// HTMLElement can't live on FloatEntry (workspace-zone proxy state), so the\n// resolved parent host is stored here keyed by float id and consumed by\n// FloatFrame to portal the rendered DOM into the opener's stacking context.\nconst parentHosts = new Map<string, HTMLElement>();\n\nexport function getFloatParentHost(id: string): HTMLElement | undefined {\n return parentHosts.get(id);\n}\n\n// ----- slot id minting ---------------------------------------------------\n\nlet floatSlotCounter = 0;\nfunction mintFloatSlotId(viewId: string): string {\n floatSlotCounter += 1;\n return `float:${viewId}:${floatSlotCounter}`;\n}\n\n// ----- API ---------------------------------------------------------------\n\nconst DEFAULT_SIZE: Size = { w: 600, h: 400 };\n\nfunction maxSize(a: Size, b: Size): Size {\n return { w: Math.max(a.w, b.w), h: Math.max(a.h, b.h) };\n}\n\nfunction openFloat(viewId: string, options: FloatOptions = {}): string {\n const store = activeStore();\n const id = generateFloatId();\n // Wrap the slot in a single-tab TabsNode so the tab strip acts as a\n // drag handle — that's the only way to drag the view back into the\n // docked tree. The TabsNode's tab strip appears at the top of the\n // float body; the frame header still moves the float as a whole.\n const slotId = mintFloatSlotId(viewId);\n let content: LayoutNode;\n if (options.dismissable) {\n // Picker float: render the view directly as a leaf slot. No tab strip,\n // no tabs wrapper, no drag-to-dock handle. Note: options.meta cannot\n // thread through a bare SlotNode — only TabEntry carries meta.\n content = {\n type: 'slot',\n slotId,\n viewId,\n };\n } else {\n const label = options.title ?? viewId;\n const tab: TabEntry = { slotId, viewId, label };\n if (options.meta) tab.meta = options.meta;\n content = {\n type: 'tabs',\n tabs: [tab],\n activeTab: 0,\n };\n }\n const computedMin = computeMinSize(content);\n const size = options.size ?? maxSize(DEFAULT_SIZE, computedMin);\n const position = options.position ?? cascadePosition(store, getTreeBounds());\n const entry: FloatEntry = {\n id,\n content,\n position,\n size,\n title: options.title,\n };\n if (options.dismissable) entry.dismissable = true;\n if (options.dismissable && options.anchor) {\n const host = findEnclosingOverlayHost(options.anchor);\n if (host) parentHosts.set(id, host);\n }\n store.push(entry);\n return id;\n}\n\nfunction closeFloat(floatId: string): void {\n const store = activeStore();\n const idx = store.findIndex((f) => f.id === floatId);\n if (idx < 0) return;\n store.splice(idx, 1);\n parentHosts.delete(floatId);\n}\n\nfunction listFloats(): FloatEntry[] {\n // Return a snapshot so callers can iterate without racing mutations.\n return activeStore().slice();\n}\n\nfunction focusFloat(floatId: string): void {\n const store = activeStore();\n const idx = store.findIndex((f) => f.id === floatId);\n if (idx < 0 || idx === store.length - 1) return;\n const [entry] = store.splice(idx, 1);\n store.push(entry);\n}\n\nexport const floatManager: FloatManager = {\n open: openFloat,\n close: closeFloat,\n list: listFloats,\n focus: focusFloat,\n};\n","/*\n * Preset manager — controls which named LayoutPreset is currently active\n * for the attached app. Mutations flow through the bound `AppLayoutBlob`\n * proxy (workspace state zone), so switches persist automatically.\n *\n * v1 always reads/writes the 'default' variant; non-default keys sit inert\n * until the rescoped DF10 selection policy lands (ADR-012).\n *\n * Saved-state-per-preset semantics:\n * On switch-out, the current tree is already live-bound to\n * blob.presets[activePreset].default via the layout store — customizations\n * persist without any explicit save step. On switch-in, updating\n * blob.activePreset causes `activeLayout()` in the store to re-drill into\n * the new preset's default variant; reactivity propagates to renderers.\n *\n * Binding lifecycle mirrors the float manager: attachApp() calls\n * bindPresetBlob(proxy), detachApp() calls unbindPresetBlob(). Before binding,\n * all methods throw — there is no pre-boot fallback.\n */\n\nimport type { AppLayoutBlob } from '../layout/types';\n\nexport interface PresetManager {\n /** All known preset names in declaration order. */\n list(): string[];\n /** Currently active preset name. */\n active(): string;\n /** Switch to the named preset. Throws if unknown. */\n switch(name: string): void;\n}\n\nlet boundBlob: AppLayoutBlob | null = null;\n\n/**\n * Bind the manager to the attached app's `AppLayoutBlob` workspace-zone\n * proxy. Called from `attachApp` in the layout store.\n */\nexport function bindPresetBlob(blob: AppLayoutBlob): void {\n boundBlob = blob;\n}\n\n/** Unbind on detach. Called from `detachApp`. */\nexport function unbindPresetBlob(): void {\n boundBlob = null;\n}\n\n/** Test-only bind alias for tests that build a synthetic blob. */\nexport function __bindPresetBlobForTest(blob: AppLayoutBlob): void {\n boundBlob = blob;\n}\n\n/** Test-only reset. Clears the binding. */\nexport function __resetPresetManagerForTest(): void {\n boundBlob = null;\n}\n\nfunction requireBlob(): AppLayoutBlob {\n if (!boundBlob) {\n throw new Error('presetManager: no app attached — bind an AppLayoutBlob first');\n }\n return boundBlob;\n}\n\nfunction listPresets(): string[] {\n return Object.keys(requireBlob().presets);\n}\n\nfunction activePreset(): string {\n return requireBlob().activePreset;\n}\n\nfunction switchPreset(name: string): void {\n const blob = requireBlob();\n if (!(name in blob.presets)) {\n throw new Error(`presetManager.switch: unknown preset \"${name}\"`);\n }\n blob.activePreset = name;\n}\n\nexport const presetManager: PresetManager = {\n list: listPresets,\n active: activePreset,\n switch: switchPreset,\n};\n","/*\n * Contribution point registry — shard-to-shard runtime collaboration.\n *\n * One module-level map holds every point's descriptors. Handles are\n * Symbols so two registrations with identical content stay distinct.\n * Emitters are a Set of zero-arg callbacks; subscribers re-read `list`\n * themselves when notified.\n *\n * No tenant partitioning: the shell is single-tenant per session; a\n * future multi-tenant client would add a tenant dimension to the\n * outer map (see direction spec §5.2).\n */\n\nconst points = new Map<string, Map<symbol, unknown>>();\nconst listeners = new Map<string, Set<() => void>>();\n\nfunction emit(pointId: string): void {\n const set = listeners.get(pointId);\n if (!set) return;\n for (const cb of set) cb();\n}\n\n/**\n * Register a descriptor under the given point. Returns an unregister\n * function; calling it more than once is a safe no-op.\n */\nexport function register<T = unknown>(pointId: string, descriptor: T): () => void {\n const handle = Symbol();\n let map = points.get(pointId);\n if (!map) {\n map = new Map();\n points.set(pointId, map);\n }\n map.set(handle, descriptor);\n emit(pointId);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n const m = points.get(pointId);\n if (!m) return;\n if (m.delete(handle)) {\n if (m.size === 0) points.delete(pointId);\n emit(pointId);\n }\n };\n}\n\n/** Enumerate descriptors at the named point in registration order. */\nexport function list<T = unknown>(pointId: string): T[] {\n const m = points.get(pointId);\n return m ? (Array.from(m.values()) as T[]) : [];\n}\n\n/** Enumerate every point id with at least one registration. */\nexport function listPoints(): string[] {\n return Array.from(points.keys());\n}\n\n/**\n * Subscribe to registration changes at the named point. The callback\n * receives no arguments — subscribers call `list` themselves to read\n * the current state. Returns an unsubscribe; double-unsubscribe is a\n * safe no-op.\n */\nexport function onChange(pointId: string, cb: () => void): () => void {\n let set = listeners.get(pointId);\n if (!set) {\n set = new Set();\n listeners.set(pointId, set);\n }\n set.add(cb);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n set!.delete(cb);\n if (set!.size === 0) listeners.delete(pointId);\n };\n}\n\n/**\n * Test-only reset. Not exported from the barrel; tests import it\n * directly from this module.\n */\nexport function __resetContributionsForTest(): void {\n points.clear();\n listeners.clear();\n}\n","/*\n * Renderer selection for the conflict manager view.\n *\n * Two registration surfaces:\n * - Built-in renderers (TextDiffRenderer, MetaOnlyRenderer) are\n * registered from within sh3-core at first `shell.conflicts` use via\n * ensureBuiltInRenderersRegistered().\n * - Contributed renderers arrive via the ctx.contributions runtime\n * under CONFLICT_RENDERER_POINT. The conflict modal reads the\n * current list from the contributions registry each render.\n *\n * Selection: among renderers whose appliesTo(item) is true, the highest\n * priority wins. Built-in fallback is priority 0 (MetaOnly), built-in\n * text is priority 1, contributed renderers typically >= 10.\n *\n * Renderer appliesTo is wrapped in try/catch; a throwing check excludes\n * that renderer from the match set, never crashes the pick.\n *\n * _resetForTests() clears the built-in set between test runs.\n */\n\nimport type { ConflictItem, ConflictRenderer } from './api';\n\nexport const TEXT_EXTENSIONS: readonly string[] = Object.freeze([\n '.md', '.txt', '.json', '.guml', '.css', '.js', '.ts', '.tsx', '.jsx',\n '.html', '.svg', '.csv', '.yaml', '.yml', '.xml', '.log', '.ini', '.toml',\n]);\n\nexport function inferKind(item: ConflictItem): 'text' | 'binary' | 'custom' {\n if (item.kind) return item.kind;\n if (item.extension && TEXT_EXTENSIONS.includes(item.extension.toLowerCase())) {\n return 'text';\n }\n return 'binary';\n}\n\nconst builtIns: ConflictRenderer[] = [];\n\nexport function registerBuiltInRenderer(r: ConflictRenderer): () => void {\n builtIns.push(r);\n return () => {\n const i = builtIns.indexOf(r);\n if (i >= 0) builtIns.splice(i, 1);\n };\n}\n\nexport function pickRenderer(\n item: ConflictItem,\n contributed: ConflictRenderer[] = [],\n): ConflictRenderer | null {\n const candidates = [...builtIns, ...contributed]\n .filter((r) => {\n try { return r.appliesTo(item); } catch { return false; }\n })\n .sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));\n return candidates[0] ?? null;\n}\n\n/** Test-only helper. */\nexport function _resetForTests(): void {\n builtIns.length = 0;\n}\n","<script lang=\"ts\">\n import type { ConflictItem } from '../api';\n\n interface Props {\n item: ConflictItem;\n selectedOrigin: string;\n onSelect: (origin: string) => void;\n }\n const { item, selectedOrigin, onSelect }: Props = $props();\n\n // 3+ branch mode: user picks a \"reference\" branch to compare against.\n let reference = $state<string>('');\n $effect(() => {\n if (!reference || !item.branches.find((b) => b.origin === reference)) {\n reference = item.branches[0]?.origin ?? 'local';\n }\n });\n const isDualMode = $derived(item.branches.length === 2);\n\n const leftBranch = $derived(\n isDualMode\n ? item.branches[0]\n : (item.branches.find((b) => b.origin === reference) ?? item.branches[0]),\n );\n const rightBranch = $derived(\n isDualMode\n ? item.branches[1]\n : (item.branches.find((b) => b.origin === selectedOrigin) ?? item.branches[1] ?? item.branches[0]),\n );\n\n /** Line-level diff: matches lines at the same index; does not do LCS. */\n function lineDiff(a: string, b: string): Array<{ kind: 'same' | 'left' | 'right'; text: string }> {\n const al = (a ?? '').split(/\\r?\\n/);\n const bl = (b ?? '').split(/\\r?\\n/);\n const out: Array<{ kind: 'same' | 'left' | 'right'; text: string }> = [];\n const max = Math.max(al.length, bl.length);\n for (let i = 0; i < max; i++) {\n const left = al[i];\n const right = bl[i];\n if (left === right) {\n if (typeof left === 'string') out.push({ kind: 'same', text: left });\n } else {\n if (typeof left === 'string') out.push({ kind: 'left', text: left });\n if (typeof right === 'string') out.push({ kind: 'right', text: right });\n }\n }\n return out;\n }\n\n const diff = $derived.by(() => {\n if (!leftBranch || !rightBranch) return [];\n return lineDiff(leftBranch.content ?? '', rightBranch.content ?? '');\n });\n const diffCount = $derived(diff.filter((d) => d.kind !== 'same').length);\n</script>\n\n<div class=\"sh3-conflict-text\">\n {#if isDualMode && leftBranch && rightBranch}\n <div class=\"sh3-conflict-text-dual\">\n <!-- svelte-ignore a11y_click_events_have_key_events -->\n <div\n class=\"sh3-conflict-text-pane\"\n class:selected={leftBranch.origin === selectedOrigin}\n role=\"button\"\n tabindex=\"0\"\n onclick={() => onSelect(leftBranch.origin)}\n onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') onSelect(leftBranch.origin); }}\n >\n <header class=\"sh3-conflict-text-head\">{leftBranch.origin} · v{leftBranch.version}</header>\n <pre class=\"sh3-conflict-text-body\"><code>{leftBranch.content ?? ''}</code></pre>\n </div>\n <!-- svelte-ignore a11y_click_events_have_key_events -->\n <div\n class=\"sh3-conflict-text-pane\"\n class:selected={rightBranch.origin === selectedOrigin}\n role=\"button\"\n tabindex=\"0\"\n onclick={() => onSelect(rightBranch.origin)}\n onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') onSelect(rightBranch.origin); }}\n >\n <header class=\"sh3-conflict-text-head\">{rightBranch.origin} · v{rightBranch.version}</header>\n <pre class=\"sh3-conflict-text-body\"><code>{rightBranch.content ?? ''}</code></pre>\n </div>\n </div>\n <details class=\"sh3-conflict-text-diff\">\n <summary>Line diff ({diffCount} difference{diffCount === 1 ? '' : 's'})</summary>\n <pre><code>{#each diff as d, i (i)}<span class={`diff-${d.kind}`}>{d.kind === 'same' ? ' ' : d.kind === 'left' ? '- ' : '+ '}{d.text}{'\\n'}</span>{/each}</code></pre>\n </details>\n {:else}\n <div class=\"sh3-conflict-text-tabs\">\n <div class=\"sh3-conflict-text-picker\">\n <label>\n Reference:\n <select bind:value={reference}>\n {#each item.branches as b (b.origin)}\n <option value={b.origin}>{b.origin}</option>\n {/each}\n </select>\n </label>\n </div>\n <div class=\"sh3-conflict-text-tablist\">\n {#each item.branches as b (b.origin)}\n <button\n class=\"sh3-conflict-text-tab\"\n class:selected={b.origin === selectedOrigin}\n onclick={() => onSelect(b.origin)}\n >\n {b.origin} · v{b.version}\n </button>\n {/each}\n </div>\n {#if rightBranch}\n <pre class=\"sh3-conflict-text-body\"><code>{rightBranch.content ?? ''}</code></pre>\n {/if}\n </div>\n {/if}\n</div>\n\n<style>\n .sh3-conflict-text { display: flex; flex-direction: column; gap: 12px; padding: 12px; height: 100%; min-height: 0; }\n .sh3-conflict-text-dual { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; min-height: 0; flex: 1; }\n .sh3-conflict-text-pane {\n display: flex; flex-direction: column; min-height: 0;\n border: 1px solid var(--shell-border, #444);\n border-radius: var(--shell-radius-sm);\n background: var(--shell-input-bg, #2a2a2a);\n cursor: pointer;\n }\n .sh3-conflict-text-pane.selected {\n border-color: var(--shell-accent, #007acc);\n box-shadow: 0 0 0 2px var(--shell-focus-ring, rgba(0,122,204,0.3));\n }\n .sh3-conflict-text-head { padding: 6px 10px; font-size: 0.75rem; color: var(--shell-fg-muted, #888); border-bottom: 1px solid var(--shell-border, #444); }\n .sh3-conflict-text-body {\n margin: 0; padding: 10px; flex: 1; overflow: auto;\n font-family: var(--shell-font-mono, monospace); font-size: 0.8125rem;\n }\n .sh3-conflict-text-diff { margin-top: 8px; }\n .sh3-conflict-text-diff pre { background: var(--shell-input-bg, #2a2a2a); padding: 8px; overflow: auto; max-height: 240px; }\n :global(.diff-left) { color: var(--shell-error, #e35); }\n :global(.diff-right) { color: var(--shell-success, #3a3); }\n :global(.diff-same) { opacity: 0.7; }\n .sh3-conflict-text-tabs { display: flex; flex-direction: column; gap: 8px; min-height: 0; flex: 1; }\n .sh3-conflict-text-picker select {\n background: var(--shell-input-bg, #2a2a2a); color: var(--shell-fg, #e0e0e0);\n border: 1px solid var(--shell-border, #444); padding: 2px 6px;\n }\n .sh3-conflict-text-tablist { display: flex; gap: 4px; flex-wrap: wrap; }\n .sh3-conflict-text-tab {\n padding: 4px 10px; background: var(--shell-input-bg, #2a2a2a); border: 1px solid var(--shell-border, #444);\n border-radius: var(--shell-radius-sm); color: var(--shell-fg, #e0e0e0); cursor: pointer; font-size: 0.8125rem;\n }\n .sh3-conflict-text-tab.selected { border-color: var(--shell-accent, #007acc); }\n</style>\n","<script lang=\"ts\">\n import type { ConflictItem } from '../api';\n\n interface Props {\n item: ConflictItem;\n selectedOrigin: string;\n onSelect: (origin: string) => void;\n }\n const { item, selectedOrigin, onSelect }: Props = $props();\n\n function formatSize(n?: number): string {\n if (typeof n !== 'number') return '—';\n if (n < 1024) return `${n} B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;\n return `${(n / (1024 * 1024)).toFixed(2)} MiB`;\n }\n\n function relTime(at: number): string {\n const delta = Date.now() - at;\n if (delta < 60_000) return 'just now';\n if (delta < 3_600_000) return `${Math.floor(delta / 60_000)}m ago`;\n if (delta < 86_400_000) return `${Math.floor(delta / 3_600_000)}h ago`;\n return new Date(at).toLocaleString();\n }\n</script>\n\n<div class=\"sh3-conflict-meta\">\n <div class=\"sh3-conflict-meta-note\">\n No preview available for this content. Pick the branch you want to keep.\n </div>\n <ul class=\"sh3-conflict-meta-list\">\n {#each item.branches as b (b.origin)}\n <li class=\"sh3-conflict-meta-li\">\n <button\n type=\"button\"\n class=\"sh3-conflict-meta-row\"\n class:selected={b.origin === selectedOrigin}\n onclick={() => onSelect(b.origin)}\n >\n <div class=\"sh3-conflict-meta-origin\">{b.origin}</div>\n <div class=\"sh3-conflict-meta-detail\">\n v{b.version} · {relTime(b.at)} · {formatSize(b.sizeBytes)}\n {#if b.hashPreview} · <code>{b.hashPreview}</code>{/if}\n </div>\n </button>\n </li>\n {/each}\n </ul>\n</div>\n\n<style>\n .sh3-conflict-meta { padding: 16px; display: flex; flex-direction: column; gap: 12px; }\n .sh3-conflict-meta-note { color: var(--shell-fg-muted, #888); font-size: 0.875rem; font-style: italic; }\n .sh3-conflict-meta-list { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 8px; }\n .sh3-conflict-meta-li { margin: 0; }\n .sh3-conflict-meta-row {\n width: 100%;\n text-align: left;\n padding: 10px 12px;\n background: var(--shell-input-bg, #2a2a2a);\n color: var(--shell-fg, #e0e0e0);\n border: 1px solid var(--shell-border, #444);\n border-radius: var(--shell-radius-sm);\n cursor: pointer;\n font: inherit;\n }\n .sh3-conflict-meta-row.selected {\n border-color: var(--shell-accent, #007acc);\n box-shadow: 0 0 0 2px var(--shell-focus-ring, rgba(0,122,204,0.3));\n }\n .sh3-conflict-meta-origin { font-weight: 600; font-size: 0.875rem; }\n .sh3-conflict-meta-detail { color: var(--shell-fg-muted, #888); font-size: 0.75rem; margin-top: 2px; }\n</style>\n","/*\n * Built-in renderer registration for the conflict manager view.\n *\n * Two renderers ship with sh3-core:\n * - TextDiffRenderer (priority 1) — text docs within OVERSIZED_TEXT_LIMIT_BYTES\n * - MetaOnlyRenderer (priority 0) — universal fallback (binary, oversized, unknown)\n *\n * Both use Svelte's `mount` / `unmount` to attach to the container the\n * parent provides. They read props reactively; the parent owns\n * selectedOrigin state and updates via the onSelect callback.\n *\n * ensureBuiltInRenderersRegistered() is idempotent; it's called from\n * shell-api.ts on the first shell.conflicts use.\n */\n\nimport { mount, unmount } from 'svelte';\nimport type { ConflictRenderer } from '../api';\nimport { inferKind, registerBuiltInRenderer } from '../renderer-registry';\nimport TextDiffRenderer from './TextDiffRenderer.svelte';\nimport MetaOnlyRenderer from './MetaOnlyRenderer.svelte';\n\n/** Max size per branch before we degrade to MetaOnlyRenderer. */\nexport const OVERSIZED_TEXT_LIMIT_BYTES = 1_048_576; // 1 MiB\n\nfunction isOversized(sizeBytes?: number): boolean {\n return typeof sizeBytes === 'number' && sizeBytes > OVERSIZED_TEXT_LIMIT_BYTES;\n}\n\nexport const textDiffRenderer: ConflictRenderer = {\n id: 'sh3-core.text',\n priority: 1,\n appliesTo: (item) => {\n if (inferKind(item) !== 'text') return false;\n return !item.branches.some((b) => isOversized(b.sizeBytes));\n },\n mount(container, props) {\n const instance = mount(TextDiffRenderer as never, {\n target: container,\n props: props as unknown as Record<string, unknown>,\n });\n return () => { void unmount(instance); };\n },\n};\n\nexport const metaOnlyRenderer: ConflictRenderer = {\n id: 'sh3-core.meta',\n priority: 0,\n appliesTo: () => true,\n mount(container, props) {\n const instance = mount(MetaOnlyRenderer as never, {\n target: container,\n props: props as unknown as Record<string, unknown>,\n });\n return () => { void unmount(instance); };\n },\n};\n\nlet registered = false;\nexport function ensureBuiltInRenderersRegistered(): void {\n if (registered) return;\n registered = true;\n registerBuiltInRenderer(textDiffRenderer);\n registerBuiltInRenderer(metaOnlyRenderer);\n}\n\n/** Test-only: re-enable registration after _resetForTests(). */\nexport function _resetBuiltInRegistrationFlag(): void {\n registered = false;\n}\n","<script lang=\"ts\">\n interface Props {\n count: number;\n onOverwriteMostRecent: () => void;\n onResolveIndividually: () => void;\n onCancel: () => void;\n }\n const { count, onOverwriteMostRecent, onResolveIndividually, onCancel }: Props = $props();\n</script>\n\n<div class=\"sh3-conflict-prompt\">\n <h3 class=\"sh3-conflict-prompt-title\">\n {count} conflict{count === 1 ? '' : 's'} to resolve\n </h3>\n <p class=\"sh3-conflict-prompt-intro\">\n Pick one option for the whole batch, or resolve each conflict individually.\n </p>\n <div class=\"sh3-conflict-prompt-actions\">\n <!-- svelte-ignore a11y_autofocus -->\n <button type=\"button\" class=\"sh3-conflict-prompt-primary\" onclick={onOverwriteMostRecent} autofocus>\n Overwrite with most recent\n </button>\n <button type=\"button\" class=\"sh3-conflict-prompt-secondary\" onclick={onResolveIndividually}>\n Resolve individually\n </button>\n <button type=\"button\" class=\"sh3-conflict-prompt-cancel\" onclick={onCancel}>\n Cancel\n </button>\n </div>\n</div>\n\n<style>\n .sh3-conflict-prompt { padding: 20px; display: flex; flex-direction: column; gap: 14px; min-width: 360px; max-width: 480px; }\n .sh3-conflict-prompt-title { margin: 0; font-size: 1.0625rem; font-weight: 600; color: var(--shell-fg, #e0e0e0); }\n .sh3-conflict-prompt-intro { margin: 0; color: var(--shell-fg-muted, #888); font-size: 0.875rem; }\n .sh3-conflict-prompt-actions { display: flex; flex-direction: column; gap: 8px; }\n .sh3-conflict-prompt-actions button {\n padding: 10px 14px;\n border-radius: var(--shell-radius);\n border: 1px solid var(--shell-border, #444);\n background: var(--shell-input-bg, #2a2a2a);\n color: var(--shell-fg, #e0e0e0);\n font-size: 0.875rem;\n font-family: inherit;\n cursor: pointer;\n text-align: left;\n }\n .sh3-conflict-prompt-primary {\n background: var(--shell-accent, #007acc) !important;\n border-color: var(--shell-accent, #007acc) !important;\n color: #fff !important;\n font-weight: 600;\n }\n .sh3-conflict-prompt-cancel { color: var(--shell-fg-muted, #888) !important; }\n</style>\n","<script lang=\"ts\">\n import type { ConflictItem, ConflictRenderer, ConflictRendererProps } from './api';\n import { pickRenderer } from './renderer-registry';\n\n interface Props {\n items: ConflictItem[];\n selections: Record<string, string>; // itemId → chosen origin\n skipped: Record<string, boolean>; // itemId → true when skipped\n currentIndex: number;\n title: string;\n contributed: ConflictRenderer[];\n onSelect: (itemId: string, origin: string) => void;\n onNavigate: (nextIndex: number) => void;\n onToggleSkip: (itemId: string) => void;\n onDone: () => void;\n onCancel: () => void;\n }\n const props: Props = $props();\n\n const current = $derived(props.items[props.currentIndex]);\n const selectedOrigin = $derived(\n current\n ? (props.selections[current.id] ?? current.branches[0]?.origin ?? '')\n : '',\n );\n const renderer = $derived(current ? pickRenderer(current, props.contributed) : null);\n\n let rendererContainer: HTMLDivElement | undefined = $state();\n let currentUnmount: (() => void) | null = null;\n\n $effect(() => {\n // Depend on current + renderer + selectedOrigin so the effect re-runs\n // whenever any of them changes; parent-owned selection drives re-mount.\n void current;\n void renderer;\n void selectedOrigin;\n if (currentUnmount) { currentUnmount(); currentUnmount = null; }\n if (!rendererContainer || !current || !renderer) return;\n const rendererProps: ConflictRendererProps = {\n item: current,\n selectedOrigin,\n onSelect: (origin) => props.onSelect(current.id, origin),\n };\n currentUnmount = renderer.mount(rendererContainer, rendererProps);\n return () => {\n if (currentUnmount) { currentUnmount(); currentUnmount = null; }\n };\n });\n\n function prev(): void {\n if (props.currentIndex > 0) props.onNavigate(props.currentIndex - 1);\n }\n function next(): void {\n if (props.currentIndex < props.items.length - 1) props.onNavigate(props.currentIndex + 1);\n }\n\n const itemStates = $derived(\n props.items.map((it) => {\n if (props.skipped[it.id]) return 'skipped' as const;\n if (props.selections[it.id]) return 'resolved' as const;\n return 'pending' as const;\n }),\n );\n</script>\n\n<div class=\"sh3-conflict-detail\">\n <header class=\"sh3-conflict-detail-head\">\n <h3>{props.title}</h3>\n {#if props.items.length > 1}\n <span class=\"sh3-conflict-detail-counter\">\n {props.currentIndex + 1} / {props.items.length}\n </span>\n {/if}\n </header>\n\n <div class=\"sh3-conflict-detail-body\">\n {#if props.items.length > 1}\n <aside class=\"sh3-conflict-detail-rail\">\n {#each props.items as it, i (it.id)}\n <button\n type=\"button\"\n class=\"sh3-conflict-detail-rail-item\"\n class:selected={i === props.currentIndex}\n onclick={() => props.onNavigate(i)}\n >\n <span class=\"sh3-conflict-detail-rail-state {itemStates[i]}\">\n {#if itemStates[i] === 'resolved'}✓{:else if itemStates[i] === 'skipped'}⟶{:else}·{/if}\n </span>\n <span class=\"sh3-conflict-detail-rail-label\">{it.label}</span>\n </button>\n {/each}\n </aside>\n {/if}\n\n <section class=\"sh3-conflict-detail-main\">\n {#if current}\n <div class=\"sh3-conflict-detail-branches\">\n {#each current.branches as b (b.origin)}\n <label class=\"sh3-conflict-detail-branch\">\n <input\n type=\"radio\"\n name=\"branch-{current.id}\"\n value={b.origin}\n checked={selectedOrigin === b.origin}\n onchange={() => props.onSelect(current.id, b.origin)}\n />\n <span>{b.origin} · v{b.version}</span>\n </label>\n {/each}\n </div>\n <div bind:this={rendererContainer} class=\"sh3-conflict-detail-renderer\"></div>\n {/if}\n </section>\n </div>\n\n <footer class=\"sh3-conflict-detail-foot\">\n <div class=\"sh3-conflict-detail-nav\">\n <button type=\"button\" onclick={prev} disabled={props.currentIndex === 0}>← Prev</button>\n <button type=\"button\" onclick={() => current && props.onToggleSkip(current.id)}>\n {current && props.skipped[current.id] ? 'Unskip' : 'Skip'}\n </button>\n <button type=\"button\" onclick={next} disabled={props.currentIndex >= props.items.length - 1}>\n Next →\n </button>\n </div>\n <div class=\"sh3-conflict-detail-actions\">\n <button type=\"button\" class=\"sh3-conflict-detail-cancel\" onclick={props.onCancel}>Cancel</button>\n <button type=\"button\" class=\"sh3-conflict-detail-done\" onclick={props.onDone}>Done</button>\n </div>\n </footer>\n</div>\n\n<style>\n .sh3-conflict-detail {\n display: flex; flex-direction: column;\n width: min(920px, 96vw); height: min(640px, 90vh);\n background: var(--shell-bg, #1e1e1e);\n color: var(--shell-fg, #e0e0e0);\n border: 1px solid var(--shell-border, #444);\n border-radius: var(--shell-radius-md);\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);\n }\n .sh3-conflict-detail-head {\n padding: 12px 16px; border-bottom: 1px solid var(--shell-border, #444);\n display: flex; justify-content: space-between; align-items: center;\n }\n .sh3-conflict-detail-head h3 { margin: 0; font-size: 1rem; font-weight: 600; }\n .sh3-conflict-detail-counter { color: var(--shell-fg-muted, #888); font-size: 0.8125rem; }\n .sh3-conflict-detail-body { display: flex; flex: 1; min-height: 0; }\n .sh3-conflict-detail-rail {\n width: 240px; border-right: 1px solid var(--shell-border, #444);\n overflow-y: auto; display: flex; flex-direction: column;\n }\n .sh3-conflict-detail-rail-item {\n display: flex; gap: 8px; align-items: center;\n padding: 6px 12px; text-align: left;\n background: transparent; border: none; color: inherit;\n cursor: pointer; font: inherit; font-size: 0.8125rem;\n }\n .sh3-conflict-detail-rail-item:hover { background: var(--shell-input-bg, #2a2a2a); }\n .sh3-conflict-detail-rail-item.selected { background: var(--shell-input-bg, #2a2a2a); font-weight: 600; }\n .sh3-conflict-detail-rail-state { width: 1em; text-align: center; opacity: 0.7; }\n .sh3-conflict-detail-rail-state.resolved { color: var(--shell-success, #3a3); opacity: 1; }\n .sh3-conflict-detail-rail-state.skipped { color: var(--shell-fg-muted, #888); }\n .sh3-conflict-detail-rail-label {\n flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;\n }\n .sh3-conflict-detail-main { flex: 1; display: flex; flex-direction: column; min-width: 0; }\n .sh3-conflict-detail-branches {\n display: flex; gap: 12px; padding: 8px 16px;\n border-bottom: 1px solid var(--shell-border, #444);\n flex-wrap: wrap;\n }\n .sh3-conflict-detail-branch { display: flex; gap: 6px; align-items: center; font-size: 0.8125rem; }\n .sh3-conflict-detail-renderer { flex: 1; min-height: 0; overflow: auto; }\n .sh3-conflict-detail-foot {\n padding: 10px 16px; border-top: 1px solid var(--shell-border, #444);\n display: flex; justify-content: space-between; gap: 8px;\n }\n .sh3-conflict-detail-nav, .sh3-conflict-detail-actions { display: flex; gap: 8px; }\n .sh3-conflict-detail-nav button, .sh3-conflict-detail-actions button {\n padding: 6px 14px;\n background: var(--shell-input-bg, #2a2a2a);\n color: var(--shell-fg, #e0e0e0);\n border: 1px solid var(--shell-border, #444);\n border-radius: var(--shell-radius);\n font: inherit;\n font-size: 0.8125rem;\n cursor: pointer;\n }\n .sh3-conflict-detail-nav button:disabled { opacity: 0.5; cursor: not-allowed; }\n .sh3-conflict-detail-done {\n background: var(--shell-accent, #007acc) !important;\n color: #fff !important;\n font-weight: 600;\n border-color: var(--shell-accent, #007acc) !important;\n }\n</style>\n","/*\n * Default \"most recent\" comparator + pickMostRecent helper.\n *\n * Default rule: compare by ConflictBranch.at descending (newer wins).\n * Callers can override via ResolveOptions.mostRecentBy; pickMostRecent\n * wraps the comparator in a try/catch so a broken override degrades to\n * the default instead of exploding the batch.\n */\n\nimport type { ConflictBranch } from './api';\n\nexport function defaultMostRecentBy(a: ConflictBranch, b: ConflictBranch): number {\n // Newer (higher `at`) should come first — negative when a is newer.\n return b.at - a.at;\n}\n\nexport function pickMostRecent(\n branches: ConflictBranch[],\n cmp: (a: ConflictBranch, b: ConflictBranch) => number,\n): ConflictBranch | null {\n if (branches.length === 0) return null;\n try {\n return [...branches].sort(cmp)[0];\n } catch (err) {\n console.warn('[sh3-core] mostRecentBy comparator threw; falling back to default', err);\n return [...branches].sort(defaultMostRecentBy)[0];\n }\n}\n","<script lang=\"ts\">\n import { onDestroy } from 'svelte';\n import type { ConflictItem, ConflictRenderer, ConflictBranch } from './api';\n import PromptView from './PromptView.svelte';\n import DetailView from './DetailView.svelte';\n import { pickMostRecent } from './most-recent';\n\n interface Props {\n items: ConflictItem[];\n title: string;\n mostRecentBy: (a: ConflictBranch, b: ConflictBranch) => number;\n requirePrompt: boolean;\n contributed: ConflictRenderer[];\n onResolve: (\n choices: Array<{ itemId: string; chosen: ConflictBranch; meta?: Record<string, unknown> }>,\n skipped: string[],\n ) => void;\n onCancel: () => void;\n /** Provided by shell.modal.open wrapping; we must call to actually close. */\n close: () => void;\n }\n const props: Props = $props();\n\n type Phase = 'prompt' | 'detail';\n // Initial values — items / requirePrompt don't change mid-session.\n // svelte-ignore state_referenced_locally\n const startsInPrompt = props.items.length >= 2 || props.requirePrompt;\n let phase = $state<Phase>(startsInPrompt ? 'prompt' : 'detail');\n\n // Initial selections: most-recent per item. Items don't change mid-session,\n // so using the initial value here is the intended semantics.\n // svelte-ignore state_referenced_locally\n let selections = $state<Record<string, string>>(\n Object.fromEntries(\n props.items.map((it) => {\n const pick = pickMostRecent(it.branches, props.mostRecentBy)?.origin\n ?? it.branches[0]?.origin\n ?? '';\n return [it.id, pick];\n }),\n ),\n );\n let skipped = $state<Record<string, boolean>>({});\n let currentIndex = $state(0);\n\n // Settlement guard — the safety net in onDestroy relies on this to\n // distinguish normal completion from unexpected dismissal (Escape,\n // programmatic closeAll, caller-shard deactivation).\n let settled = false;\n\n onDestroy(() => {\n if (!settled) {\n settled = true;\n props.onCancel();\n }\n });\n\n function finalize(): void {\n if (settled) return;\n settled = true;\n const choices: Array<{ itemId: string; chosen: ConflictBranch; meta?: Record<string, unknown> }> = [];\n const skippedIds: string[] = [];\n for (const it of props.items) {\n if (skipped[it.id]) {\n skippedIds.push(it.id);\n continue;\n }\n const origin = selections[it.id];\n const branch = it.branches.find((b) => b.origin === origin);\n if (branch) choices.push({ itemId: it.id, chosen: branch, meta: it.meta });\n }\n props.onResolve(choices, skippedIds);\n props.close();\n }\n\n function cancel(): void {\n if (settled) return;\n settled = true;\n props.onCancel();\n props.close();\n }\n\n function overwriteMostRecent(): void {\n // Selections are already pre-filled to most-recent; finalize directly.\n finalize();\n }\n\n function resolveIndividually(): void {\n phase = 'detail';\n }\n\n function select(itemId: string, origin: string): void {\n selections = { ...selections, [itemId]: origin };\n if (skipped[itemId]) {\n const nextSkipped = { ...skipped };\n delete nextSkipped[itemId];\n skipped = nextSkipped;\n }\n }\n\n function toggleSkip(itemId: string): void {\n skipped = { ...skipped, [itemId]: !skipped[itemId] };\n }\n\n function navigate(nextIndex: number): void {\n currentIndex = nextIndex;\n }\n</script>\n\n{#if phase === 'prompt'}\n <PromptView\n count={props.items.length}\n onOverwriteMostRecent={overwriteMostRecent}\n onResolveIndividually={resolveIndividually}\n onCancel={cancel}\n />\n{:else}\n <DetailView\n items={props.items}\n {selections}\n {skipped}\n {currentIndex}\n title={props.title}\n contributed={props.contributed}\n onSelect={select}\n onNavigate={navigate}\n onToggleSkip={toggleSkip}\n onDone={finalize}\n onCancel={cancel}\n />\n{/if}\n","/*\n * Public types for the conflict manager view.\n *\n * `shell.conflicts` exposes two entry points:\n * - resolve(items, opts): generic primitive\n * - resolveDocuments(ctx, input, opts): doc-zone adapter\n *\n * Shards construct ConflictItem arrays themselves (generic path) or pass\n * { shardId, paths } to the adapter (doc path). The doc-zone adapter\n * layers on top of the generic primitive — the shell does not know about\n * documents; the adapter does.\n */\n\nimport type { ShardContext } from '../shards/types';\n\nexport interface ConflictItem {\n /** Caller-unique within the batch. */\n id: string;\n /** Shown in the left rail and detail header, e.g. \"notes/meeting.md\". */\n label: string;\n /** Default inferred from `extension`. 'custom' must be set by caller. */\n kind?: 'text' | 'binary' | 'custom';\n /** Hint for renderer selection, e.g. '.md'. Used for kind inference too. */\n extension?: string;\n /** >=1 branch. Doc-zone conflicts produce >=2. */\n branches: ConflictBranch[];\n /** Opaque caller payload; echoed back in output for tracking. */\n meta?: Record<string, unknown>;\n}\n\nexport interface ConflictBranch {\n /** 'local' | peerId | any caller-defined label. */\n origin: string;\n version: number;\n /** Epoch ms of the branch write. */\n at: number;\n /** Text content; absent for binary or not-yet-fetched. */\n content?: string;\n /** Used by oversized-text fallback in MetaOnlyRenderer. */\n sizeBytes?: number;\n /** Short hash display for binary branches. */\n hashPreview?: string;\n}\n\nexport interface ResolveOptions {\n /** Modal title override; defaults to \"Resolve conflict(s)\". */\n title?: string;\n /**\n * Comparator for \"most recent\"; default compares `at` descending.\n * A throwing comparator degrades to the default — never crashes the batch.\n */\n mostRecentBy?: (a: ConflictBranch, b: ConflictBranch) => number;\n /** Force the three-way prompt even for single-item batches. */\n requirePrompt?: boolean;\n}\n\nexport type ResolveOutcome =\n | {\n status: 'resolved';\n choices: Array<{\n itemId: string;\n chosen: ConflictBranch;\n meta?: Record<string, unknown>;\n }>;\n skipped: string[];\n }\n | { status: 'cancelled' };\n\nexport interface ResolveDocumentsInput {\n /** Target shard. Cross-shard requires documents:read + documents:write. */\n shardId: string;\n /** Paths to resolve. Pre-filtered to actual conflicts inside the adapter. */\n paths: string[];\n}\n\nexport type DocsResolveOutcome =\n | {\n status: 'resolved';\n resolved: Array<{ path: string; chosen: ConflictBranch; appliedVersion: number }>;\n failed: Array<{ path: string; error: string }>;\n skipped: string[];\n }\n | { status: 'cancelled' };\n\n/**\n * Public contribution point id — shards register specialized renderers\n * via `ctx.contributions.register(CONFLICT_RENDERER_POINT, descriptor)`.\n * Convention is priority 10+ for contributions; built-ins register at\n * priority 0 (fallback) and 1 (default text renderer).\n */\nexport const CONFLICT_RENDERER_POINT = 'sh3-core.conflictRenderer';\n\nexport interface ConflictRenderer {\n /** Shard-prefixed unique id, e.g. 'sh3-editor.guml-conflict-renderer'. */\n id: string;\n /** Called on every candidate item; the highest-priority truthy one wins. */\n appliesTo(item: ConflictItem): boolean;\n /** Higher wins. Default fallback = 0, default text = 1, contributions ≥ 10. */\n priority?: number;\n /** Mount the renderer into the provided container; return an unmount. */\n mount(container: HTMLElement, props: ConflictRendererProps): () => void;\n}\n\nexport interface ConflictRendererProps {\n item: ConflictItem;\n /** The currently chosen branch origin; mirrors the parent's state. */\n selectedOrigin: string;\n /** Renderers call this to drive selection; parent re-renders with new value. */\n onSelect(origin: string): void;\n}\n\n/** Thrown when the adapter is called cross-shard without the required permissions. */\nexport class ConflictPermissionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConflictPermissionError';\n }\n}\n\n/** Thrown when the caller's shard deactivates while a conflict session is open. */\nexport class ConflictSessionOrphanedError extends Error {\n constructor() {\n super('Caller shard deactivated while conflict session was active');\n this.name = 'ConflictSessionOrphanedError';\n }\n}\n\n/** Runtime shape of `shell.conflicts`. */\nexport interface ConflictsApi {\n resolve(items: ConflictItem[], opts?: ResolveOptions): Promise<ResolveOutcome>;\n resolveDocuments(\n ctx: ShardContext,\n input: ResolveDocumentsInput,\n opts?: ResolveOptions,\n ): Promise<DocsResolveOutcome>;\n}\n","/*\n * Generic conflict-resolve primitive — the modal machinery without the\n * doc-zone adapter. Lives in its own file so `adapter-documents.ts` can\n * import it statically without creating a cycle with the shell runtime.\n */\n\nimport { modalManager } from '../overlays/modal';\nimport { list as listContributions } from '../contributions/registry';\nimport { ensureBuiltInRenderersRegistered } from './renderers';\nimport ConflictModal from './ConflictModal.svelte';\nimport { defaultMostRecentBy } from './most-recent';\nimport {\n CONFLICT_RENDERER_POINT,\n type ConflictItem,\n type ConflictBranch,\n type ConflictRenderer,\n type ResolveOptions,\n type ResolveOutcome,\n} from './api';\n\nfunction getContributedRenderers(): ConflictRenderer[] {\n try {\n return listContributions<ConflictRenderer>(CONFLICT_RENDERER_POINT);\n } catch {\n return [];\n }\n}\n\nexport function resolvePrimitive(\n items: ConflictItem[],\n opts: ResolveOptions = {},\n): Promise<ResolveOutcome> {\n ensureBuiltInRenderersRegistered();\n\n if (items.length === 0) {\n return Promise.resolve({ status: 'resolved', choices: [], skipped: [] });\n }\n\n return new Promise<ResolveOutcome>((settle) => {\n const title = opts.title ?? (items.length === 1 ? 'Resolve conflict' : 'Resolve conflicts');\n const mostRecentBy = opts.mostRecentBy ?? defaultMostRecentBy;\n const requirePrompt = opts.requirePrompt ?? false;\n const contributed = getContributedRenderers();\n\n let settled = false;\n const onResolve = (\n choices: Array<{ itemId: string; chosen: ConflictBranch; meta?: Record<string, unknown> }>,\n skipped: string[],\n ) => {\n if (settled) return;\n settled = true;\n settle({ status: 'resolved', choices, skipped });\n };\n const onCancel = () => {\n if (settled) return;\n settled = true;\n settle({ status: 'cancelled' });\n };\n\n const props = {\n items,\n title,\n mostRecentBy,\n requirePrompt,\n contributed,\n onResolve,\n onCancel,\n };\n modalManager.open<typeof props>(\n ConflictModal as never,\n props,\n { boxStyle: 'max-width: none; min-width: 360px; padding: 0;' },\n );\n });\n}\n","/*\n * Doc-zone adapter for shell.conflicts.\n *\n * Reads DocStatus for each requested path, filters to those actually in\n * conflict, fetches per-branch content for preview, and invokes the\n * generic primitive. On resolve, applies each chosen branch via the\n * appropriate handle (own-shard via ctx.documents(); cross-shard via\n * ctx.browse.resolveConflictFrom).\n *\n * Cross-shard requires the caller's manifest to declare documents:browse\n * + documents:read + documents:write — detected via the presence of the\n * capability methods on ctx.browse. The adapter throws\n * ConflictPermissionError when any required capability is missing.\n *\n * Apply step is sequential; HTTP resolveConflict races the server's\n * per-doc tick counter when parallelized. Failure isolation: one failed\n * resolveConflict does not stop the batch; the caller gets both lists.\n */\n\nimport type { ShardContext } from '../shards/types';\nimport type { DocStatus } from '../documents/sync-types';\nimport {\n ConflictPermissionError,\n type ConflictItem,\n type ConflictBranch,\n type DocsResolveOutcome,\n type ResolveDocumentsInput,\n type ResolveOptions,\n} from './api';\nimport { resolvePrimitive } from './resolve-primitive';\n\ntype Status = DocStatus;\n\ninterface HandleLike {\n status(path: string): Promise<Status | null>;\n readBranch(path: string, origin: string): Promise<string | null>;\n resolveConflict(path: string, choice: { origin: string }): Promise<void>;\n}\n\nfunction ownShardHandle(ctx: ShardContext): HandleLike {\n // No extension filter — the adapter takes caller-supplied paths, any type.\n const h = ctx.documents({ format: 'text' });\n return {\n status: (p) => h.status(p) as Promise<Status | null>,\n readBranch: (p, o) => h.readBranch(p, o),\n resolveConflict: (p, c) => h.resolveConflict(p, c),\n };\n}\n\nfunction crossShardHandle(ctx: ShardContext, shardId: string): HandleLike {\n const b = (ctx as { browse?: unknown }).browse as\n | {\n statusFrom?: (s: string, p: string) => Promise<Status | null>;\n readBranchFrom?: (s: string, p: string, o: string) => Promise<string | null>;\n resolveConflictFrom?: (s: string, p: string, c: { origin: string }) => Promise<void>;\n }\n | undefined;\n if (!b?.statusFrom || !b?.readBranchFrom || !b?.resolveConflictFrom) {\n throw new ConflictPermissionError(\n `Cross-shard resolveDocuments requires documents:browse + documents:read + documents:write (shardId=${shardId})`,\n );\n }\n return {\n status: (p) => b.statusFrom!(shardId, p),\n readBranch: (p, o) => b.readBranchFrom!(shardId, p, o),\n resolveConflict: (p, c) => b.resolveConflictFrom!(shardId, p, c),\n };\n}\n\nfunction extractExtension(path: string): string | undefined {\n const i = path.lastIndexOf('.');\n if (i < 0) return undefined;\n const j = path.lastIndexOf('/');\n if (i < j) return undefined; // dot is in a parent directory\n return path.slice(i);\n}\n\nexport async function resolveDocuments(\n ctx: ShardContext,\n input: ResolveDocumentsInput,\n opts: ResolveOptions = {},\n): Promise<DocsResolveOutcome> {\n const callerShardId = (ctx as { shardId?: string }).shardId;\n const handle: HandleLike =\n input.shardId === callerShardId\n ? ownShardHandle(ctx)\n : crossShardHandle(ctx, input.shardId);\n\n // Pre-filter: keep only paths actually in conflict state.\n const statuses: Array<{ path: string; status: Status }> = [];\n for (const path of input.paths) {\n const s = await handle.status(path);\n if (s && s.syncState === 'conflict' && s.branches && s.branches.length > 0) {\n statuses.push({ path, status: s });\n }\n }\n\n if (statuses.length === 0) {\n return { status: 'resolved', resolved: [], failed: [], skipped: [] };\n }\n\n // Build ConflictItem[] with per-branch content fetched via readBranch.\n const items: ConflictItem[] = [];\n for (const { path, status } of statuses) {\n const extension = extractExtension(path);\n const branches: ConflictBranch[] = [];\n for (const b of status.branches ?? []) {\n const content = await handle.readBranch(path, b.origin).catch(() => null);\n branches.push({\n origin: b.origin,\n version: b.version,\n at: b.at,\n content: content ?? undefined,\n sizeBytes: content ? new TextEncoder().encode(content).length : undefined,\n });\n }\n items.push({\n id: path,\n label: path,\n extension,\n branches,\n meta: { shardId: input.shardId, path, docVersion: status.version },\n });\n }\n\n const outcome = await resolvePrimitive(items, opts);\n if (outcome.status === 'cancelled') return { status: 'cancelled' };\n\n // Apply each chosen branch sequentially.\n const resolvedList: Array<{ path: string; chosen: ConflictBranch; appliedVersion: number }> = [];\n const failedList: Array<{ path: string; error: string }> = [];\n for (const choice of outcome.choices) {\n try {\n await handle.resolveConflict(choice.itemId, { origin: choice.chosen.origin });\n const after = await handle.status(choice.itemId).catch(() => null);\n resolvedList.push({\n path: choice.itemId,\n chosen: choice.chosen,\n appliedVersion: after?.version ?? -1,\n });\n } catch (err) {\n failedList.push({\n path: choice.itemId,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n return {\n status: 'resolved',\n resolved: resolvedList,\n failed: failedList,\n skipped: outcome.skipped,\n };\n}\n","/*\n * shell.conflicts assembled API.\n *\n * The generic primitive lives in resolve-primitive.ts and the doc-zone\n * adapter in adapter-documents.ts; this file just binds them together\n * as the object exposed on the shell singleton.\n */\n\nimport type { ConflictsApi } from './api';\nimport { resolvePrimitive } from './resolve-primitive';\nimport { resolveDocuments } from './adapter-documents';\n\nexport const conflictsApi: ConflictsApi = {\n resolve: resolvePrimitive,\n resolveDocuments,\n};\n","/*\n * Public types for the color-picker contribution point.\n *\n * A contribution registered at COLOR_PICKER_POINT is picked by the\n * primitive in ./primitive.ts when `shell.color.pick()` is called.\n * The native <input type=\"color\"> fallback is inlined there at priority 0;\n * contributed pickers typically register at priority >= 10.\n */\n\n/** Contribution-point id for color pickers. */\nexport const COLOR_PICKER_POINT = 'sh3.color-picker';\n\nexport interface ColorPickOptions {\n /** Initial color as '#rrggbb'. If omitted, contributors choose a default. */\n initial?: string;\n /** Request alpha support. Ignored by contributors that don't support it. */\n alpha?: boolean;\n /** Anchor element for floating/positioned pickers. Native fallback ignores. */\n anchor?: HTMLElement;\n /** Display title (e.g. 'Background color'). Native fallback ignores. */\n title?: string;\n}\n\n/**\n * A color-picker contribution. Higher `priority` wins; the inlined native\n * fallback is priority 0, so contributors typically use >= 10.\n *\n * `open(opts)` resolves with '#rrggbb' (or '#rrggbbaa' when the contributor\n * honors `opts.alpha`) or `null` if the user dismissed.\n */\nexport interface ColorContribution {\n id: string;\n priority?: number;\n open(opts: ColorPickOptions): Promise<string | null>;\n}\n\n/** Shell-level color API, mounted at `shell.color`. */\nexport interface ColorApi {\n /**\n * Open a color picker. Resolves with the chosen color as '#rrggbb'\n * (or '#rrggbbaa' when a contributor honors `opts.alpha === true`),\n * or `null` if the user dismissed.\n *\n * On browsers without `<input type=\"color\">` cancel-event support, the\n * returned promise may not resolve if the user closes the native\n * fallback without committing. Install a color-picker shard (e.g.\n * sh3-editor) to avoid this.\n */\n pick(opts?: ColorPickOptions): Promise<string | null>;\n}\n","/*\n * Color-picker selection primitive.\n *\n * Reads contributions registered at COLOR_PICKER_POINT, sorts by\n * priority descending, and calls `open(opts)` on the winner. The\n * inlined native fallback at priority 0 guarantees there is always\n * at least one candidate.\n */\n\nimport { list } from '../contributions/registry';\nimport { COLOR_PICKER_POINT, type ColorContribution, type ColorPickOptions } from './api';\n\nconst nativeFallback: ColorContribution = {\n id: 'sh3.color-picker.native',\n priority: 0,\n open: ({ initial }: ColorPickOptions) =>\n new Promise<string | null>((resolve) => {\n const el = document.createElement('input');\n el.type = 'color';\n if (initial && /^#[0-9a-f]{6}$/i.test(initial)) el.value = initial;\n\n let settled = false;\n const settle = (v: string | null) => {\n if (settled) return;\n settled = true;\n el.remove();\n resolve(v);\n };\n\n el.addEventListener('change', () => settle(el.value));\n el.addEventListener('cancel', () => settle(null));\n\n el.style.position = 'fixed';\n el.style.left = '-9999px';\n document.body.appendChild(el);\n el.click();\n }),\n};\n\nexport function pickColor(opts: ColorPickOptions = {}): Promise<string | null> {\n const contributed = list<ColorContribution>(COLOR_PICKER_POINT);\n const winner = [...contributed, nativeFallback]\n .sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))[0];\n return winner.open(opts);\n}\n","/*\n * shell.color assembled API.\n *\n * The selector + inlined native fallback live in primitive.ts;\n * this file just binds `pick` onto the object exposed on the shell\n * singleton, mirroring conflicts/shell-api.ts.\n */\n\nimport type { ColorApi } from './api';\nimport { pickColor } from './primitive';\n\nexport const colorApi: ColorApi = {\n pick: pickColor,\n};\n","/*\n * User-binding persistence backed by the __sh3core__ user-zone slot\n * `bindings: { [appId]: { [actionId]: shortcut | null } }`.\n */\n\ntype PerApp = Record<string, string | null>;\ntype AllApps = Record<string, PerApp>;\n\nlet zone: { bindings: AllApps } | null = null;\n\nexport function __setBindingsZone(z: { bindings: AllApps }): void {\n zone = z;\n}\n\nexport async function loadUserBindings(appId: string): Promise<PerApp> {\n if (!zone) return {};\n return { ...(zone.bindings[appId] ?? {}) };\n}\n\nexport async function saveUserBinding(\n appId: string,\n actionId: string,\n shortcut: string | null | undefined,\n): Promise<void> {\n if (!zone) return;\n const forApp = { ...(zone.bindings[appId] ?? {}) };\n if (shortcut === undefined) {\n delete forApp[actionId];\n } else {\n forApp[actionId] = shortcut;\n }\n zone.bindings = { ...zone.bindings, [appId]: forApp };\n}\n","/*\n * Action registry — typed facade over the shared contributions point\n * `sh3.actions`. One entry per (ownerShardId, action) pair. Disposers\n * returned from registerAction clean up the underlying contribution\n * entry; activate.svelte.ts also pushes them into the shard's cleanup\n * queue so deactivate auto-clears.\n */\n\nimport {\n register as contributionsRegister,\n list as contributionsList,\n onChange as contributionsOnChange,\n} from '../contributions/registry';\nimport type { Action } from './types';\n\nexport const ACTIONS_POINT_ID = 'sh3.actions';\n\nexport interface ActionEntry {\n action: Action;\n ownerShardId: string;\n}\n\nconst liveIds = new Set<string>();\n\nexport function registerAction(action: Action, ownerShardId: string): () => void {\n if (typeof action.run !== 'function' && action.submenu !== true) {\n console.warn(\n `[sh3] Action \"${action.id}\" registered by \"${ownerShardId}\" has no \\`run\\` ` +\n `and is not a submenu parent (\\`submenu: true\\`). Registration ignored.`,\n );\n return () => {};\n }\n if (liveIds.has(action.id)) {\n console.warn(\n `[sh3] Duplicate action id \"${action.id}\" registered by \"${ownerShardId}\". ` +\n `First registration wins; second registration still stored but shortcut conflicts may occur.`,\n );\n }\n liveIds.add(action.id);\n const entry: ActionEntry = { action, ownerShardId };\n const dispose = contributionsRegister<ActionEntry>(ACTIONS_POINT_ID, entry);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n dispose();\n liveIds.delete(action.id);\n };\n}\n\nexport function listActions(): ActionEntry[] {\n return contributionsList<ActionEntry>(ACTIONS_POINT_ID);\n}\n\nexport function onActionsChange(cb: () => void): () => void {\n return contributionsOnChange(ACTIONS_POINT_ID, cb);\n}\n\nexport function __resetActionsRegistryForTest(): void {\n liveIds.clear();\n}\n","// packages/sh3-core/src/actions/types.ts\n/*\n * Action primitive — scoped UI operations dispatched by keyboard,\n * context menu, or command palette. See the spec at\n * docs/superpowers/specs/2026-04-22-actions-contexts-design.md.\n */\n\nexport type AtomicScope =\n | 'home'\n | 'app'\n | `view:${string}`\n | `focus:${string}`\n | { element: string };\n\nexport type ActionScope = AtomicScope | AtomicScope[];\n\nexport interface Action {\n id: string;\n /**\n * Display label. May be a function for live-evaluated labels (re-read on\n * each menu derive — same cadence as `disabled`/`checked`). Function form\n * is appropriate for runtime-suffixed labels (e.g. `· admin only`); static\n * strings are still the common case.\n */\n label: string | (() => string);\n scope: ActionScope;\n contextItem?: boolean;\n paletteItem?: boolean;\n /**\n * Optional menu container id. When set and the active app's declared\n * (or canonical fallback) menu list contains this id, the action\n * appears in that container's dropdown. Orphaned values render\n * nowhere in the menu bar; the action remains reachable via\n * palette/hotkey/context menu.\n */\n menuItem?: string;\n defaultShortcut?: string;\n icon?: string;\n /**\n * Optional grouping key. Items inside the same surface (menu bar\n * dropdown, context menu, submenu popup) with distinct `group`\n * values are separated by a divider line in `ActionPanel`. This is\n * the only separator mechanism — there is no explicit separator\n * primitive. Items without a `group` form a single default group.\n */\n group?: string;\n allowInInputs?: boolean;\n /**\n * Toggle-state indicator. Truthy renders a leading ✓ in MenuBar /\n * ContextMenu rows. Function form is re-evaluated on each derive\n * (no re-registration on flip). Ignored in CommandPalette.\n */\n checked?: boolean | (() => boolean);\n /**\n * Visible-but-not-dispatchable. Greyed in MenuBar/ContextMenu,\n * skipped by keyboard nav, click is a no-op, shortcut dispatch is\n * blocked. Hidden from CommandPalette in v1 (a future \"show\n * disabled\" toggle is acknowledged in the spec but out of scope).\n */\n disabled?: boolean | (() => boolean);\n /**\n * Marks this action as a submenu parent. `run` becomes optional —\n * when omitted, the framework provides default drill-down behavior:\n * MenuBar/ContextMenu render the row as actionless+expanding;\n * CommandPalette opens a sub-palette filtered to children\n * (`submenuOf === this.id`).\n */\n submenu?: true;\n /**\n * Marks this action as a child of `submenuOf`'s submenu. Children\n * inherit the parent's surface placement — they do NOT repeat\n * `menuItem`, `contextItem`, or `paletteItem`. Children are excluded\n * from their parent's container's flat list and only appear in the\n * parent's submenu popup or via direct match in the palette.\n */\n submenuOf?: string;\n run?(ctx: ActionDispatchContext): void | Promise<void>;\n}\n\nexport interface Selection {\n type: string;\n ref: unknown;\n ownerShardId: string;\n}\n\nexport interface ActionDispatchContext {\n action: { id: string; label: string };\n appId: string | null;\n viewId?: string;\n selection?: Selection;\n invokedVia: 'keyboard' | 'context-menu' | 'palette' | 'programmatic';\n dispatch(actionId: string): void;\n}\n\nexport interface SelectionApi {\n get(): Selection | null;\n set(sel: { type: string; ref: unknown }): void;\n clear(): void;\n}\n\nexport interface ActionsApi {\n register(action: Action): () => void;\n selection: SelectionApi;\n openContextMenu(opts: { x: number; y: number; scope?: AtomicScope }): void;\n openPalette(opts?: { prefill?: string; filter?: { submenuOf?: string } }): void;\n}\n\nexport interface ResolvedAction {\n action: Action;\n ownerShardId: string;\n effectiveShortcut: string | null;\n}\n\n/**\n * Where an action's effective shortcut came from:\n * - `'default'` — `defaultShortcut` resolved for the current platform\n * - `'user'` — the user supplied an explicit override\n * - `'disabled'` — the user rebound to `null` to disable dispatch\n * - `'none'` — no default and no override\n */\nexport type BindingSource = 'default' | 'user' | 'disabled' | 'none';\n\n/**\n * Read-only snapshot describing one action that is currently active.\n * Produced by `shell.actions.listActive()`. One descriptor per action id,\n * reporting the innermost active scope (same tier order as keyboard\n * dispatch: element > focus > view > app > home).\n */\nexport interface ActiveActionDescriptor {\n /** Stable action id as registered. */\n id: string;\n /** Human-readable label as registered. */\n label: string;\n /**\n * Shortcut string as it would dispatch right now (platform-resolved,\n * user-rebind applied). `null` when `bindingSource` is `'disabled'` or\n * `'none'`.\n */\n effectiveShortcut: string | null;\n /**\n * Where the effective shortcut came from. Help UIs can distinguish\n * user-disabled (render greyed) from no-shortcut (hide).\n */\n bindingSource: BindingSource;\n /** The innermost active tier of the action's scope. */\n scope: AtomicScope;\n /** Display hint: `null` for home/app, else full string or element type. */\n scopeBadge: string | null;\n /** Carried through from the registered action. */\n group?: string;\n icon?: string;\n ownerShardId: string;\n paletteItem: boolean;\n contextItem: boolean;\n}\n\n/**\n * Resolve an Action's label to a string. Function labels are called on each\n * read; string labels are returned unchanged.\n */\nexport function resolveLabel(action: Pick<Action, 'label'>): string {\n return typeof action.label === 'function' ? action.label() : action.label;\n}\n","/*\n * Shortcut normalization — canonical form is \"Mod1+Mod2+...+Key\" with\n * modifiers ordered Ctrl, Alt, Shift, Meta. Single-character keys are\n * uppercased; named keys preserve their .key value.\n *\n * Mod is a pseudo-modifier: Meta on Mac, Ctrl elsewhere. Resolved once,\n * at the moment a default shortcut is written into the tier index (not\n * at match time) — the index stores concrete shortcuts only.\n */\n\nexport type Platform = 'mac' | 'other';\n\nconst MOD_ORDER = ['Ctrl', 'Alt', 'Shift', 'Meta'] as const;\nconst MOD_ALIASES: Record<string, string> = {\n control: 'Ctrl',\n ctrl: 'Ctrl',\n alt: 'Alt',\n option: 'Alt',\n shift: 'Shift',\n meta: 'Meta',\n cmd: 'Meta',\n command: 'Meta',\n super: 'Meta',\n win: 'Meta',\n};\n\nconst PURE_MODIFIER_KEYS = new Set(['Control', 'Alt', 'Shift', 'Meta']);\n\nfunction titleCaseNamedKey(key: string): string {\n if (key.length === 1) return key.toUpperCase();\n // Preserve browser's named-key casing (Enter, Escape, ArrowUp, etc.)\n return key;\n}\n\nexport function canonicalizeShortcut(raw: string): string {\n if (!raw) throw new Error('Empty shortcut');\n const rawParts = raw.split('+');\n // Any empty segment (leading/trailing/consecutive '+') means malformed\n if (rawParts.some((p) => p.trim() === '')) throw new Error(`Malformed shortcut: \"${raw}\"`);\n const parts = rawParts.map((p) => p.trim());\n if (parts.length === 0) throw new Error(`Malformed shortcut: \"${raw}\"`);\n const modifiers = new Set<string>();\n let key: string | undefined;\n for (const part of parts) {\n const lower = part.toLowerCase();\n if (lower in MOD_ALIASES) {\n modifiers.add(MOD_ALIASES[lower]);\n } else {\n if (key !== undefined) throw new Error(`Multiple keys in shortcut: \"${raw}\"`);\n key = titleCaseNamedKey(part);\n }\n }\n if (key === undefined) throw new Error(`No key in shortcut: \"${raw}\"`);\n const ordered = MOD_ORDER.filter((m) => modifiers.has(m));\n return [...ordered, key].join('+');\n}\n\nexport function resolveMod(shortcut: string, platform: Platform): string {\n if (!shortcut.toLowerCase().includes('mod')) return shortcut;\n const parts = shortcut.split('+').map((p) => {\n if (p.toLowerCase() === 'mod') return platform === 'mac' ? 'Meta' : 'Ctrl';\n return p;\n });\n return canonicalizeShortcut(parts.join('+'));\n}\n\nexport function eventToShortcut(ev: KeyboardEvent): string {\n if (PURE_MODIFIER_KEYS.has(ev.key)) return '';\n const mods: string[] = [];\n if (ev.ctrlKey) mods.push('Ctrl');\n if (ev.altKey) mods.push('Alt');\n if (ev.shiftKey) mods.push('Shift');\n if (ev.metaKey) mods.push('Meta');\n const key = titleCaseNamedKey(ev.key);\n return [...mods, key].join('+');\n}\n\nexport function detectPlatform(): Platform {\n if (typeof navigator === 'undefined') return 'other';\n return /Mac|iPhone|iPad|iPod/i.test(navigator.platform) ? 'mac' : 'other';\n}\n","/*\n * Effective-shortcut merge. User overrides live in the user state zone\n * under `bindings.<appId>`; this module is pure — load/persist is done\n * by the dispatcher layer.\n */\n\nimport { canonicalizeShortcut, resolveMod, type Platform } from './shortcuts';\nimport type { Action, BindingSource } from './types';\n\nexport type BindingOverrides = Record<string, string | null>;\n\nexport function effectiveShortcut(\n action: Action,\n overrides: BindingOverrides,\n platform: Platform = 'other',\n): string | null {\n if (action.id in overrides) {\n const o = overrides[action.id];\n if (o === null) return null;\n return canonicalizeShortcut(o);\n }\n if (!action.defaultShortcut) return null;\n return resolveMod(action.defaultShortcut, platform);\n}\n\n/**\n * Like {@link effectiveShortcut}, but also reports the binding source so\n * consumers (e.g., Help views) can distinguish \"no shortcut assigned\"\n * from \"user turned this off\" — both of which yield a `null` shortcut.\n */\nexport function effectiveShortcutWithSource(\n action: Action,\n overrides: BindingOverrides,\n platform: Platform = 'other',\n): { shortcut: string | null; source: BindingSource } {\n if (action.id in overrides) {\n const o = overrides[action.id];\n if (o === null) return { shortcut: null, source: 'disabled' };\n return { shortcut: canonicalizeShortcut(o), source: 'user' };\n }\n if (!action.defaultShortcut) return { shortcut: null, source: 'none' };\n return { shortcut: resolveMod(action.defaultShortcut, platform), source: 'default' };\n}\n","/*\n * Pure scope/tier helpers shared by the dispatcher, context menu,\n * palette, and listActive(). Keep this file side-effect free — it is\n * imported by both reactive and non-reactive modules.\n */\n\nimport type { AtomicScope, ActionScope } from './types';\nimport {\n isScopeActive,\n TIER_ORDER,\n type DispatcherState,\n type TierName,\n} from './dispatcher.svelte';\n\nexport function scopeToTier(scope: AtomicScope): TierName {\n if (scope === 'home') return 'home';\n if (scope === 'app') return 'app';\n if (typeof scope === 'string' && scope.startsWith('view:')) return 'view';\n if (typeof scope === 'string' && scope.startsWith('focus:')) return 'focus';\n return 'element';\n}\n\nexport function normalizeScope(scope: ActionScope): AtomicScope[] {\n return Array.isArray(scope) ? scope : [scope];\n}\n\nexport function scopeBadge(scope: AtomicScope): string | null {\n if (scope === 'home' || scope === 'app') return null;\n if (typeof scope === 'string') return scope;\n return scope.element;\n}\n\n/**\n * Walk TIER_ORDER innermost→outermost; return the first `AtomicScope` of\n * the given action whose tier is currently active. Returns `null` if no\n * scope is active.\n */\nexport function innermostActiveScope(\n scope: ActionScope,\n state: DispatcherState,\n ownerShardId: string,\n): AtomicScope | null {\n const scopes = normalizeScope(scope);\n const buckets: Partial<Record<TierName, AtomicScope[]>> = {};\n for (const s of scopes) {\n const tier = scopeToTier(s);\n (buckets[tier] ??= []).push(s);\n }\n for (const tier of TIER_ORDER) {\n const bucket = buckets[tier];\n if (!bucket) continue;\n for (const s of bucket) {\n if (isScopeActive(s, state, ownerShardId)) return s;\n }\n }\n return null;\n}\n\n/**\n * Value equality for `AtomicScope`. String atoms compare by string equality;\n * element atoms (`{ element: T }`) compare by their `element` field. A string\n * atom is never equal to an element atom.\n */\nexport function scopeEquals(a: AtomicScope, b: AtomicScope): boolean {\n if (typeof a === 'string' || typeof b === 'string') return a === b;\n return a.element === b.element;\n}\n\n/**\n * Canonical string encoding of an `AtomicScope` for transport over surfaces\n * that can only carry strings — most notably `data-sh3-scope` DOM attribute\n * values. String atoms (`home`, `app`, `view:<id>`, `focus:<id>`) pass\n * through unchanged; element atoms encode as `element:<type>`. The element\n * type itself may contain colons (e.g. `shard:type`) — only the leading\n * `element:` is reserved by the encoding.\n */\nexport function scopeToString(scope: AtomicScope): string {\n if (typeof scope === 'string') return scope;\n return `element:${scope.element}`;\n}\n\n/**\n * Inverse of `scopeToString`. Returns `null` for inputs that do not parse to\n * a valid `AtomicScope` so callers (e.g. the contextmenu listener reading\n * `data-sh3-scope` from arbitrary DOM) can fall back gracefully without\n * throwing on a malformed attribute. Empty bodies after a known prefix\n * (`view:`, `focus:`, `element:`) also return null.\n */\nexport function parseScopeString(s: string): AtomicScope | null {\n if (s === 'home' || s === 'app') return s;\n if (s.startsWith('view:')) {\n const rest = s.slice('view:'.length);\n return rest.length > 0 ? (s as AtomicScope) : null;\n }\n if (s.startsWith('focus:')) {\n const rest = s.slice('focus:'.length);\n return rest.length > 0 ? (s as AtomicScope) : null;\n }\n if (s.startsWith('element:')) {\n const rest = s.slice('element:'.length);\n return rest.length > 0 ? { element: rest } : null;\n }\n return null;\n}\n","/*\n * Pure dispatcher — scope activation + tier index build. DOM wiring\n * (keydown, focus tracking, user zone subscribe) lives in listeners.ts.\n * This module exposes testable state transitions; listeners feed it\n * state snapshots.\n */\n\nimport { resolveLabel, type AtomicScope, type Selection } from './types';\nimport type { ActionEntry } from './registry';\nimport { effectiveShortcut } from './bindings';\nimport type { Platform } from './shortcuts';\nimport { scopeToTier, normalizeScope } from './scope-helpers';\n\nexport interface DispatcherState {\n activeAppId: string | null;\n activeAppRequiredShards: Set<string>;\n autostartShards: Set<string>;\n mountedViewIds: Set<string>;\n focusedViewId: string | null;\n selection: Selection | null;\n bindings: Record<string, string | null>;\n platform: Platform;\n}\n\nexport type TierName = 'element' | 'focus' | 'view' | 'app' | 'home';\nexport const TIER_ORDER: readonly TierName[] = ['element', 'focus', 'view', 'app', 'home'] as const;\n\nexport interface TierIndex {\n element: Map<string, string>; // shortcut → actionId\n focus: Map<string, string>;\n view: Map<string, string>;\n app: Map<string, string>;\n home: Map<string, string>;\n}\n\nexport function isScopeActive(\n scope: AtomicScope,\n state: DispatcherState,\n ownerShardId?: string,\n): boolean {\n if (scope === 'home') {\n return state.activeAppId === null;\n }\n if (scope === 'app') {\n if (state.activeAppId === null) return false;\n if (!ownerShardId) return false;\n return (\n state.activeAppRequiredShards.has(ownerShardId) ||\n state.autostartShards.has(ownerShardId)\n );\n }\n if (typeof scope === 'string') {\n if (scope.startsWith('view:')) {\n return state.mountedViewIds.has(scope.slice(5));\n }\n if (scope.startsWith('focus:')) {\n return state.focusedViewId === scope.slice(6);\n }\n }\n if (typeof scope === 'object' && 'element' in scope) {\n return state.selection !== null && state.selection.type === scope.element;\n }\n return false;\n}\n\nexport function buildTierIndex(entries: ActionEntry[], state: DispatcherState): TierIndex {\n const idx: TierIndex = {\n element: new Map(),\n focus: new Map(),\n view: new Map(),\n app: new Map(),\n home: new Map(),\n };\n\n for (const entry of entries) {\n const shortcut = effectiveShortcut(entry.action, state.bindings, state.platform);\n if (!shortcut) continue;\n\n for (const scope of normalizeScope(entry.action.scope)) {\n if (!isScopeActive(scope, state, entry.ownerShardId)) continue;\n const tier = scopeToTier(scope);\n const existing = idx[tier].get(shortcut);\n if (existing && existing !== entry.action.id) {\n console.warn(\n `[sh3] Shortcut \"${shortcut}\" in tier \"${tier}\" is bound to both ` +\n `\"${existing}\" and \"${entry.action.id}\"; first-registered wins. ` +\n `Users can rebind to resolve.`,\n );\n continue;\n }\n idx[tier].set(shortcut, entry.action.id);\n }\n }\n\n return idx;\n}\n\nexport interface KeydownEnv {\n target: EventTarget | null;\n shortcut: string;\n state: DispatcherState;\n entries: ActionEntry[];\n runAction(actionId: string, dispatchCtx: import('./types').ActionDispatchContext): void;\n /** Optional chained-dispatch function passed through to the action's `run` ctx. Noop by default. */\n dispatch?: (actionId: string) => void;\n}\n\nfunction isTextInput(target: EventTarget | null): boolean {\n if (!(target instanceof Element)) return false;\n const tag = target.tagName;\n if (tag === 'INPUT' || tag === 'TEXTAREA') return true;\n const ce = (target as HTMLElement).contentEditable;\n if (ce === 'true' || ce === 'plaintext-only') return true;\n // Fallback: check attribute directly (happy-dom doesn't reflect the property correctly)\n const attr = target.getAttribute('contenteditable');\n if (attr === 'true' || attr === '' || attr === 'plaintext-only') return true;\n return false;\n}\n\nexport function dispatchKeydown(env: KeydownEnv): string | null {\n const idx = buildTierIndex(env.entries, env.state);\n const actionById = new Map(env.entries.map((e) => [e.action.id, e]));\n\n for (const tier of TIER_ORDER) {\n const id = idx[tier].get(env.shortcut);\n if (!id) continue;\n const entry = actionById.get(id);\n if (!entry) continue;\n // Input-target blocking\n if (isTextInput(env.target) && !entry.action.allowInInputs) {\n return null;\n }\n env.runAction(id, {\n action: { id: entry.action.id, label: resolveLabel(entry.action) },\n appId: env.state.activeAppId,\n viewId: env.state.focusedViewId ?? undefined,\n selection: env.state.selection ?? undefined,\n invokedVia: 'keyboard',\n dispatch: env.dispatch ?? (() => {}),\n });\n return id;\n }\n return null;\n}\n","/*\n * Shell-level single-selection state. One selection at a time, reactive.\n * Shards obtain a per-shard SelectionApi via makeSelectionApi(shardId)\n * that stamps ownerShardId on set and checks owner on clear. Shell-level\n * clearSelectionForShard is used when a shard deactivates or an app\n * switches — it only clears if the owner matches, so two-shard\n * interleavings don't accidentally wipe each other.\n */\n\nimport type { Selection, SelectionApi } from './types';\n\nlet current = $state<Selection | null>(null);\n\nexport function getSelection(): Selection | null {\n return current;\n}\n\nexport function makeSelectionApi(shardId: string): SelectionApi {\n return {\n get(): Selection | null {\n return current;\n },\n set(sel: { type: string; ref: unknown }): void {\n current = { type: sel.type, ref: sel.ref, ownerShardId: shardId };\n },\n clear(): void {\n if (!current) return;\n if (current.ownerShardId !== shardId) {\n console.warn(\n `[sh3] Shard \"${shardId}\" tried to clear selection owned by \"${current.ownerShardId}\". Ignoring.`,\n );\n return;\n }\n current = null;\n },\n };\n}\n\n/** Called by the shell on shard deactivate and app switch. */\nexport function clearSelectionForShard(shardId: string): void {\n if (current && current.ownerShardId === shardId) {\n current = null;\n }\n}\n\n/** Called by the shell on app switch (unconditional). */\nexport function clearSelectionUnconditional(): void {\n current = null;\n}\n\nexport function __resetSelectionForTest(): void {\n current = null;\n}\n","/*\n * Contribution registry — views and verbs.\n *\n * Tracks which ViewFactory answers a given viewId. In this phase the\n * registry is a flat module-level Map with no awareness of shard identity;\n * writes come from `activateShard` which additionally remembers which\n * viewIds a given shard registered so they can be torn down in\n * `deactivateShard`.\n *\n * The shape of this registry is deliberately narrow so later phases can\n * expand it without breaking callers:\n * - Resolution by viewId is the only query slots need.\n * - Verbs are the second contribution kind (SH11). Toolbar items, menus,\n * hotkeys get their own sibling maps when those kinds land.\n */\n\nimport type { ViewFactory } from './types';\n\nconst views = new Map<string, ViewFactory>();\n\n/** Listeners called after a new view factory is registered. */\nconst viewRegistrationListeners = new Set<(viewId: string, factory: ViewFactory) => void>();\n\nexport function __addViewRegistrationListener(\n fn: (viewId: string, factory: ViewFactory) => void,\n): void {\n viewRegistrationListeners.add(fn);\n}\n\nexport function __removeViewRegistrationListener(\n fn: (viewId: string, factory: ViewFactory) => void,\n): void {\n viewRegistrationListeners.delete(fn);\n}\n\nexport function registerView(viewId: string, factory: ViewFactory): void {\n if (views.has(viewId)) {\n throw new Error(`View \"${viewId}\" is already registered`);\n }\n views.set(viewId, factory);\n for (const listener of viewRegistrationListeners) {\n listener(viewId, factory);\n }\n}\n\nexport function getView(viewId: string): ViewFactory | undefined {\n return views.get(viewId);\n}\n\nexport function unregisterView(viewId: string): void {\n views.delete(viewId);\n}\n\n/* ── Verbs ────────────────────────────────────────────────────────── */\n\nimport type { Verb } from '../verbs/types';\n\nconst verbs = new Map<string, Verb>();\n\nexport function registerVerb(name: string, verb: Verb): void {\n if (verbs.has(name)) {\n throw new Error(`Verb \"${name}\" is already registered`);\n }\n verbs.set(name, verb);\n}\n\nexport function getVerb(name: string): Verb | undefined {\n return verbs.get(name);\n}\n\nexport function unregisterVerb(name: string): void {\n verbs.delete(name);\n}\n\nexport function listVerbs(): Verb[] {\n return Array.from(verbs.values()).sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/** Test-only reset: clear the view and verb registries. */\nexport function __resetViewRegistryForTest(): void {\n views.clear();\n verbs.clear();\n // Do NOT clear viewRegistrationListeners — they are module-level subscriptions\n // (e.g. slotHostPool's late-factory listener) that must survive registry resets.\n}\n","/*\n * Layout ops — pure(-ish) mutations on a LayoutNode tree.\n *\n * All drag-reorganize gestures commit through this module. The drag\n * engine figures out *what* the user meant (which tab, which target,\n * which drop zone); the ops figure out *how* to edit the tree so the\n * result is well-formed.\n *\n * Mutation style:\n * Trees are mutated in place. The root is a Svelte `$state` object\n * owned by the module-level `layoutStore` (see layout/store.svelte.ts),\n * so in-place edits are observed by the layout renderer automatically.\n * Since phase 7, that store is the workspace state-zone proxy, so each\n * mutation also triggers a debounced flush to localStorage — no action\n * required from op callers. Returning a new\n * tree each time would also work but would force callers to reassign\n * the root — messier and no upside here.\n *\n * Invariants the ops preserve:\n * 1. No empty TabsNode. A tab group that loses its last tab is\n * removed from its parent.\n * 2. No single-child split. A split whose children collapse to one\n * is replaced by that child (direction and proportion of the\n * parent reassert themselves naturally).\n * 3. Sizes array length matches children length. removeAt / insertAt\n * splice the size array alongside the children array.\n * 4. activeTab stays in range after tab removal/insertion. When the\n * active tab itself moves, activeTab follows it.\n *\n * Not enforced (intentionally):\n * - Uniqueness of slotIds across the tree. The slot host pool keys\n * by slotId; duplicates would collide. The ops assume upstream\n * doesn't produce duplicates; the drag engine only moves existing\n * tabs, so no new slotIds are introduced.\n */\n\nimport type {\n LayoutNode,\n SplitNode,\n TabsNode,\n SlotNode,\n TabEntry,\n SplitDirection,\n LayoutTree,\n TreeRootRef,\n} from './types';\n\n// ---------- Search helpers -------------------------------------------------\n\n/** A path down the tree: the list of child indices walked from the root. */\nexport type LayoutPath = number[];\n\n/** A located tab: where it lives and which entry index inside its group. */\nexport interface LocatedTab {\n tabsNode: TabsNode;\n tabsPath: LayoutPath;\n tabIndex: number;\n entry: TabEntry;\n}\n\n/**\n * Find a tab by its slotId anywhere in the tree. Returns null if no\n * tab carries that slotId. Used by the drag engine to look up the\n * source tab before any mutation.\n */\nexport function findTabBySlotId(root: LayoutNode, slotId: string): LocatedTab | null {\n const walk = (node: LayoutNode, path: LayoutPath): LocatedTab | null => {\n if (node.type === 'tabs') {\n const idx = node.tabs.findIndex((t) => t.slotId === slotId);\n if (idx >= 0) {\n return { tabsNode: node, tabsPath: path, tabIndex: idx, entry: node.tabs[idx] };\n }\n } else if (node.type === 'split') {\n for (let i = 0; i < node.children.length; i++) {\n const hit = walk(node.children[i], [...path, i]);\n if (hit) return hit;\n }\n }\n return null;\n };\n return walk(root, []);\n}\n\n/** Find a standalone slot leaf by its slotId (only leaves, not tab entries). */\nexport function findSlotBySlotId(\n root: LayoutNode,\n slotId: string,\n): { node: SlotNode; parent: SplitNode | null; index: number } | null {\n const walk = (\n node: LayoutNode,\n parent: SplitNode | null,\n index: number,\n ): { node: SlotNode; parent: SplitNode | null; index: number } | null => {\n if (node.type === 'slot') {\n if (node.slotId === slotId) return { node, parent, index };\n return null;\n }\n if (node.type === 'split') {\n for (let i = 0; i < node.children.length; i++) {\n const hit = walk(node.children[i], node, i);\n if (hit) return hit;\n }\n }\n return null;\n };\n return walk(root, null, 0);\n}\n\n// ---------- Multi-root search -----------------------------------------------\n\n/** A located tab across all roots of a LayoutTree. */\nexport interface LocatedTabInTree {\n root: TreeRootRef;\n /** The docked-space located tab record from findTabBySlotId. */\n located: LocatedTab;\n}\n\n/**\n * Multi-root version of `findTabBySlotId`: searches the docked tree first,\n * then each float's content in order. Returns the root reference along with\n * the `LocatedTab` so drag commit can route its mutation to the right root.\n * Returns null if the slot id is not present in any root.\n */\nexport function findTabInTree(tree: LayoutTree, slotId: string): LocatedTabInTree | null {\n const inDocked = findTabBySlotId(tree.docked, slotId);\n if (inDocked) return { root: { kind: 'docked' }, located: inDocked };\n for (const f of tree.floats) {\n const hit = findTabBySlotId(f.content, slotId);\n if (hit) return { root: { kind: 'float', floatId: f.id }, located: hit };\n }\n return null;\n}\n\n/**\n * Locate the root a slot currently lives under in the given tree. Handles\n * both tab entries and bare slot leaves, docked first then each float's\n * content. Returns null when the slot is not present anywhere. Pure —\n * takes the tree as input so callers with an in-hand tree (and tests)\n * don't need the layout store.\n */\nexport function locateSlotIn(tree: LayoutTree, slotId: string): TreeRootRef | null {\n if (containsSlot(tree.docked, slotId)) return { kind: 'docked' };\n for (const f of tree.floats) {\n if (containsSlot(f.content, slotId)) return { kind: 'float', floatId: f.id };\n }\n return null;\n}\n\nfunction containsSlot(node: LayoutNode, slotId: string): boolean {\n if (node.type === 'slot') return node.slotId === slotId;\n if (node.type === 'tabs') return node.tabs.some((t) => t.slotId === slotId);\n for (const child of node.children) {\n if (containsSlot(child, slotId)) return true;\n }\n return false;\n}\n\n// ---------- Tab removal ----------------------------------------------------\n\n/**\n * Remove a tab from its current location, returning the removed entry\n * (or null if not found). The tabs group it was in may become empty\n * and is cleaned up by `cleanupTree` after the caller has finished its\n * reinsertion. The two-phase shape (mutate → cleanup) means the caller\n * can remove a tab and re-insert it into the SAME tabs group without\n * the group being collapsed mid-move.\n */\nexport function removeTabBySlotId(root: LayoutNode, slotId: string): TabEntry | null {\n const located = findTabBySlotId(root, slotId);\n if (!located) return null;\n const { tabsNode, tabIndex, entry } = located;\n tabsNode.tabs.splice(tabIndex, 1);\n // Keep activeTab sensible: clamp, and shift down if we removed an\n // earlier tab than the active one.\n if (tabsNode.tabs.length === 0) {\n tabsNode.activeTab = 0;\n } else if (tabIndex < tabsNode.activeTab) {\n tabsNode.activeTab -= 1;\n } else if (tabsNode.activeTab >= tabsNode.tabs.length) {\n tabsNode.activeTab = tabsNode.tabs.length - 1;\n }\n return entry;\n}\n\n// ---------- Tab insertion --------------------------------------------------\n\n/**\n * Insert a tab entry into an existing tabs group at a specific index.\n * Clamps the index into range. The inserted tab becomes active — the\n * user's drag landed there, so they want to see it.\n */\nexport function insertTabIntoTabs(\n tabsNode: TabsNode,\n entry: TabEntry,\n index: number,\n): void {\n const clamped = Math.max(0, Math.min(index, tabsNode.tabs.length));\n tabsNode.tabs.splice(clamped, 0, entry);\n tabsNode.activeTab = clamped;\n}\n\n/**\n * Atomic same-group tab move. Used by the drag engine when the drop\n * target is the tab strip of the same group the source tab lives in.\n *\n * Why atomic: the naive two-step flow (`removeTabBySlotId` then\n * `insertTabIntoTabs`) calls `Array.prototype.splice` twice against the\n * same reactive `$state` array. Splice's internal `[[Delete]]`\n * operations trip Svelte's proxy `deleteProperty` trap during the\n * remove step, which can flush reactive consumers while `tabs.length`\n * is transiently `N - 1`. A LayoutRenderer `$derived` evaluated in that\n * window sees the shrunk array and the index-`N - 1` snippet body\n * dereferences a now-`undefined` entry — crashing at `.slotId`. Going\n * through a fresh non-reactive array and then reassigning `tabs` in\n * one shot means the proxy only ever sees a single atomic transition\n * from the old array to the new one.\n *\n * `postRemovalToIndex` is in post-removal coordinates, which matches\n * the coordinate space drop targets use (see LayoutRenderer's\n * `onStripHover`, which normalizes same-strip indices before setting\n * the drop target).\n */\nexport function moveTabWithinTabs(\n tabsNode: TabsNode,\n fromIndex: number,\n postRemovalToIndex: number,\n): void {\n const next = tabsNode.tabs.slice();\n const [entry] = next.splice(fromIndex, 1);\n const clamped = Math.max(0, Math.min(postRemovalToIndex, next.length));\n next.splice(clamped, 0, entry);\n tabsNode.tabs = next;\n tabsNode.activeTab = clamped;\n}\n\n// ---------- Slot split -----------------------------------------------------\n\n/** Which side of a split the dropped tab should land on. */\nexport type SplitSide = 'left' | 'right' | 'top' | 'bottom';\n\n/**\n * Split a slot-leaf (or tabs-leaf) into a new SplitNode, placing a\n * single-tab group containing `entry` on the requested side and the\n * existing node on the other side. The existing node is preserved\n * as-is (it keeps its slotId, viewId, etc. — critical for re-parenting\n * of the untouched side).\n *\n * Sides map to split direction:\n * left/right → horizontal split, new tab goes left or right\n * top/bottom → vertical split, new tab goes top or bottom\n *\n * The target is identified by a LayoutPath from the root, because\n * splitting requires rewriting the parent's child array and we need\n * the parent reference. If the target IS the root, the root itself is\n * replaced — callers that pass the root by reference need the wrapper\n * form, so this function returns the new subtree and the caller\n * reassigns parent.children[i] = returned value (or reassigns root).\n */\nexport function makeSplitWithNewTab(\n existing: LayoutNode,\n entry: TabEntry,\n side: SplitSide,\n): SplitNode {\n const direction: SplitDirection =\n side === 'left' || side === 'right' ? 'horizontal' : 'vertical';\n const newGroup: TabsNode = {\n type: 'tabs',\n activeTab: 0,\n tabs: [entry],\n };\n const newFirst = side === 'left' || side === 'top';\n const children = newFirst ? [newGroup, existing] : [existing, newGroup];\n return {\n type: 'split',\n direction,\n sizes: [1, 1], // 50/50 by default; splitter drag adjusts from there\n children,\n };\n}\n\n/**\n * Shallow-clone a layout node. Used by splitNodeAtPath's root case to\n * break the circular reference that would occur if the root object\n * (mutated in-place) were embedded as its own child.\n */\nfunction snapshotNode(node: LayoutNode): LayoutNode {\n if (node.type === 'tabs') return { ...node, tabs: [...node.tabs] };\n if (node.type === 'split') {\n const clone: SplitNode = { ...node, children: [...node.children], sizes: [...node.sizes] };\n if (node.pinned) clone.pinned = [...node.pinned];\n if (node.collapsed) clone.collapsed = [...node.collapsed];\n return clone;\n }\n return { ...node }; // slot — plain shallow copy\n}\n\n/**\n * Apply a slot-split as a tree mutation: find the target node at the\n * given path and replace it with a new split. Handles the root case\n * (path = []) by mutating the root's fields in place. The root object\n * identity is preserved so Svelte's $state proxy keeps its reactivity.\n */\nexport function splitNodeAtPath(\n root: LayoutNode,\n path: LayoutPath,\n entry: TabEntry,\n side: SplitSide,\n): void {\n const target = nodeAtPath(root, path);\n if (!target) return;\n if (isPathFixedByParent(root, path)) return;\n\n if (path.length === 0) {\n // Root case: target IS root. Snapshot it so makeSplitWithNewTab\n // embeds the clone, not root itself — avoids a circular reference\n // when we Object.assign the replacement back onto root.\n const snapshot = snapshotNode(target);\n const replacement = makeSplitWithNewTab(snapshot, entry, side);\n const rootAsRecord = root as unknown as Record<string, unknown>;\n delete rootAsRecord.tabs;\n delete rootAsRecord.activeTab;\n delete rootAsRecord.slotId;\n delete rootAsRecord.viewId;\n delete rootAsRecord.direction;\n delete rootAsRecord.sizes;\n delete rootAsRecord.pinned;\n delete rootAsRecord.collapsed;\n delete rootAsRecord.children;\n Object.assign(rootAsRecord, replacement);\n return;\n }\n\n const replacement = makeSplitWithNewTab(target, entry, side);\n const parentPath = path.slice(0, -1);\n const indexInParent = path[path.length - 1];\n const parent = nodeAtPath(root, parentPath);\n if (!parent || parent.type !== 'split') return;\n parent.children[indexInParent] = replacement;\n}\n\n/** Walk a LayoutPath and return the node at its tip, or null. */\nexport function nodeAtPath(root: LayoutNode, path: LayoutPath): LayoutNode | null {\n let cur: LayoutNode = root;\n for (const idx of path) {\n if (cur.type !== 'split') return null;\n if (idx < 0 || idx >= cur.children.length) return null;\n cur = cur.children[idx];\n }\n return cur;\n}\n\n/**\n * True when the parent split of `path` exists and has `fixed[lastIndex] === true`.\n *\n * The drag layer and the ops layer both consult this to decide whether a\n * quadrant-split drop may land at `path`. A `path.length === 0` always returns\n * false: the root has no parent split. If the path leads through a non-split\n * (tabs/slot) ancestor, no parent split exists at the relevant slice and the\n * function returns false.\n */\nexport function isPathFixedByParent(root: LayoutNode, path: LayoutPath): boolean {\n if (path.length === 0) return false;\n const parent = nodeAtPath(root, path.slice(0, -1));\n if (!parent || parent.type !== 'split') return false;\n return parent.fixed?.[path[path.length - 1]] === true;\n}\n\n// ---------- Cleanup --------------------------------------------------------\n\n/**\n * Post-mutation cleanup pass. Removes empty tabs groups from their\n * parents and collapses single-child splits. Runs until the tree\n * stabilizes (a collapse can reveal another single-child split one\n * level up).\n *\n * Called once at the end of every drag commit. Called separately from\n * the mutation primitives so callers can do \"remove then insert into\n * the same group\" without the group being collapsed between calls.\n */\nexport function cleanupTree(root: LayoutNode): void {\n let changed = true;\n while (changed) {\n changed = cleanupPass(root, null, 0);\n }\n}\n\nfunction cleanupPass(\n node: LayoutNode,\n parent: SplitNode | null,\n indexInParent: number,\n): boolean {\n if (node.type === 'split') {\n // Recurse first so we collapse bottom-up.\n let recursed = false;\n for (let i = 0; i < node.children.length; i++) {\n if (cleanupPass(node.children[i], node, i)) recursed = true;\n }\n\n // Drop empty tabs children — unless the tabs node is persistent OR is\n // fixed in its parent. A fixed child must keep its position in the\n // parent split's children array; pruning would mutate that array.\n for (let i = node.children.length - 1; i >= 0; i--) {\n const child = node.children[i];\n if (\n child.type === 'tabs'\n && child.tabs.length === 0\n && !child.persistent\n && !node.fixed?.[i]\n ) {\n node.children.splice(i, 1);\n node.sizes.splice(i, 1);\n if (node.pinned) node.pinned.splice(i, 1);\n if (node.collapsed) node.collapsed.splice(i, 1);\n if (node.fixed) node.fixed.splice(i, 1);\n recursed = true;\n }\n }\n\n // Collapse a split that has one (or zero) children left. With zero\n // children the split is meaningless; with one child, the split is\n // redundant and the surviving child should take its place.\n if (node.children.length <= 1 && parent) {\n if (node.children.length === 1) {\n parent.children[indexInParent] = node.children[0];\n } else {\n // Zero children — shouldn't normally happen, but remove to keep\n // the tree well-formed.\n parent.children.splice(indexInParent, 1);\n parent.sizes.splice(indexInParent, 1);\n if (parent.pinned) parent.pinned.splice(indexInParent, 1);\n if (parent.collapsed) parent.collapsed.splice(indexInParent, 1);\n }\n return true;\n }\n\n // Root-level split with one child: promote the surviving child to\n // root by overwriting the root's fields in place (same technique\n // as splitNodeAtPath's root case — preserves $state proxy identity).\n if (node.children.length === 1 && !parent) {\n const survivor = node.children[0];\n const rootAsRecord = node as unknown as Record<string, unknown>;\n // Clear all split-specific keys.\n delete rootAsRecord.direction;\n delete rootAsRecord.sizes;\n delete rootAsRecord.pinned;\n delete rootAsRecord.collapsed;\n delete rootAsRecord.children;\n Object.assign(rootAsRecord, survivor);\n return true;\n }\n\n return recursed;\n }\n\n if (node.type === 'tabs') {\n // Empty tabs at the root level has no parent to drop it from; the\n // caller is expected to handle the \"layout is empty\" case\n // elsewhere (phase 7). We do nothing here.\n return false;\n }\n\n return false;\n}\n","/*\n * Slot host pool — the re-parenting contract, made operational.\n *\n * docs/design/layout.md:70 — \"the layout engine moves the existing\n * container element rather than destroying and recreating it\". This\n * module is where that happens. Views are mounted into detached\n * `<div.slot-host>` elements owned by the pool, keyed by slotId, and\n * survive across arbitrary Svelte remounts of their containing\n * SlotContainer.\n *\n * Why a pool, not per-component state:\n * When a user drags a tab from one TabbedPanel to another, the slot's\n * SlotContainer leaves one Svelte subtree and reappears in another.\n * Svelte will tear down the old component instance and mount a new one\n * — even though the slot logically hasn't changed. If the view lives\n * inside that component's own DOM, it dies with it. Pooling the host\n * outside the Svelte tree and letting each SlotContainer instance\n * merely *attach* the pooled host to its wrapper decouples the view's\n * lifetime from the component's lifetime.\n *\n * Refcount + deferred destroy:\n * A tab-move produces a teardown/mount pair in the same microtask.\n * Naive lifecycle (destroy on refcount 0) would destroy the view\n * between those two events. Instead, a 0-refcount schedules a\n * destroy in a microtask; if someone re-acquires before the microtask\n * runs, the destroy is cancelled. Result: in-tick moves survive,\n * genuine removals (tab closed, layout discards the slotId) still\n * tear the view down promptly.\n *\n * Opt-out:\n * ViewHandle.remountOnMove (unused in phase 6) is the GL/Safari\n * edge-case escape hatch reserved by the design. Not wired yet —\n * phase 6 has no view that needs it.\n */\n\nimport { getView, __addViewRegistrationListener } from '../shards/registry';\nimport type { ViewHandle, MountContext, ViewFactory } from '../shards/types';\nimport { locateSlotIn } from './ops';\nimport { activeLayout } from './store.svelte';\nimport { scopeToString } from '../actions/scope-helpers';\n\ninterface PooledHost {\n host: HTMLDivElement;\n handle: ViewHandle | undefined;\n viewId: string | null;\n label: string;\n meta: Record<string, unknown> | undefined;\n refcount: number;\n resizeObserver: ResizeObserver | undefined;\n /**\n * Cancels the pending deferred mount (see createHost) if the entry\n * is destroyed before its microtask ever runs. No-op once the mount\n * has completed — teardown then goes through `handle.unmount()`.\n */\n cancelPendingMount: () => void;\n}\n\nconst pool = new Map<string, PooledHost>();\nconst pendingDestroy = new Set<string>();\n\n/**\n * Called by the registry whenever a new ViewFactory is registered.\n * Scans the pool for entries that have the matching viewId but were not\n * mounted (because the factory wasn't available at acquire-time). Mounts\n * them now.\n *\n * This handles the \"late factory registration\" case: a shard activates\n * after the layout has already acquired a slot for its view. Rather than\n * requiring the layout to re-acquire, the pool retries the mount here.\n */\nfunction onViewRegistered(viewId: string, factory: ViewFactory): void {\n for (const [slotId, entry] of pool.entries()) {\n if (entry.viewId !== viewId || entry.handle !== undefined) continue;\n // Entry is in the pool, matches the view, and has no handle yet —\n // the factory wasn't available when the microtask ran. Mount now.\n const ctx: MountContext = {\n slotId,\n viewId,\n label: entry.label,\n meta: entry.meta,\n setDirty(dirty: boolean) {\n dirtyState[slotId] = dirty;\n },\n location() {\n return locateSlotIn(activeLayout(), slotId);\n },\n };\n queueMicrotask(() => {\n // Re-check: entry may have been released before this microtask fires.\n if (!pool.has(slotId)) return;\n if (entry.handle !== undefined) return; // already mounted by a race\n entry.handle = factory.mount(entry.host, ctx);\n if (entry.handle?.closable || slotId.startsWith('float:')) {\n closableState[slotId] = true;\n }\n if (entry.handle?.onResize) {\n const onResize = entry.handle.onResize.bind(entry.handle);\n entry.resizeObserver = new ResizeObserver((entries) => {\n for (const e of entries) {\n const box = e.contentRect;\n onResize(Math.round(box.width), Math.round(box.height));\n }\n });\n entry.resizeObserver.observe(entry.host);\n }\n });\n }\n}\n\n__addViewRegistrationListener(onViewRegistered);\n\n/**\n * Reactive dirty-state map. Keyed by slotId, values are $state so\n * Svelte tracks reads in `isSlotDirty()` and re-renders the tab strip\n * when a shard calls `setDirty()`. Separate from PooledHost because\n * the pool's plain Map is not reactive.\n */\nconst dirtyState: Record<string, boolean> = $state({});\n\n/**\n * Reactive closable-state map. Same pattern as dirtyState — the pool's\n * plain Map is not reactive, so closable flags derived from ViewHandle\n * would never trigger a re-render. This record is $state so Svelte\n * tracks reads in `isSlotClosable()` and re-renders the tab strip once\n * the deferred mount completes and sets the flag.\n */\nconst closableState: Record<string, boolean> = $state({});\n\n/*\n * Detaching the view mount from the caller's effect scope.\n *\n * `acquireSlotHost` is called from inside SlotContainer's `$effect`.\n * Svelte 5 attributes any reactive subscriptions created during that\n * call to the currently-active effect — and `$effect.root` is NOT\n * sufficient to escape this, because `active_effect` is still set\n * when the root scope runs synchronously inline. When the caller's\n * effect is later torn down (because SlotContainer remounts under a\n * new branch of the layout tree), those subscriptions are severed.\n * The pool keeps the view's DOM alive across the remount, but its\n * `$derived`s and `$effect`s stop firing — the exact symptom we hit.\n *\n * Fix: return the host element synchronously, but defer the\n * `factory.mount(host)` call to a `queueMicrotask`. Microtasks run\n * with a clean execution stack, so `active_effect` is null when mount\n * runs — the view's reactive graph is a true top-level root with no\n * ancestor effect to be destroyed by. The one-microtask delay before\n * the view appears is invisible to the user: microtasks run before\n * the browser paints, so the initial frame still shows the view.\n *\n * A `cancelled` flag guards against the edge case where the entry\n * is destroyed before its deferred mount ever runs (e.g. rapid\n * add-then-remove of a slot during a drag).\n */\nfunction createHost(slotId: string, viewId: string | null, label: string, meta?: Record<string, unknown>): PooledHost {\n const host = document.createElement('div');\n host.className = 'slot-host';\n host.dataset.slotId = slotId;\n if (viewId) {\n host.setAttribute('data-sh3-view', viewId);\n host.setAttribute('data-sh3-scope', scopeToString(`focus:${viewId}`));\n }\n // Position:absolute inset:0 so the host fills whichever wrapper it is\n // attached to. The wrapper is what the layout engine sizes; the host\n // just tracks it. Styles are set inline (not in a class) so consumers\n // don't need to import a stylesheet to get correct layout.\n host.style.position = 'absolute';\n host.style.inset = '0';\n host.style.minWidth = '0';\n host.style.minHeight = '0';\n\n let cancelled = false;\n const entry: PooledHost = {\n host,\n handle: undefined,\n viewId,\n label,\n meta,\n refcount: 0,\n resizeObserver: undefined,\n cancelPendingMount: () => {\n cancelled = true;\n },\n };\n\n queueMicrotask(() => {\n if (cancelled) return;\n const factory = viewId ? getView(viewId) : undefined;\n const ctx: MountContext = {\n slotId,\n viewId: viewId ?? '',\n label,\n meta,\n setDirty(dirty: boolean) {\n dirtyState[slotId] = dirty;\n },\n location() {\n return locateSlotIn(activeLayout(), slotId);\n },\n };\n entry.handle = factory?.mount(host, ctx);\n if (entry.handle?.closable || slotId.startsWith('float:')) {\n closableState[slotId] = true;\n }\n\n // The pool owns the ResizeObserver so its lifetime matches the\n // view handle's lifetime, not the containing SlotContainer's.\n // Moving the host between wrappers (drag-reorganize) keeps the\n // same observer, and the view keeps receiving size updates\n // through the move.\n if (entry.handle?.onResize) {\n const onResize = entry.handle.onResize.bind(entry.handle);\n entry.resizeObserver = new ResizeObserver((entries) => {\n for (const e of entries) {\n const box = e.contentRect;\n onResize(Math.round(box.width), Math.round(box.height));\n }\n });\n entry.resizeObserver.observe(host);\n }\n });\n\n return entry;\n}\n\n/**\n * Acquire (or create) the pooled host for a slot. The caller is\n * expected to `appendChild` the returned host into its own wrapper —\n * the pool does not know which wrapper owns the host at any given time,\n * and that is intentional. The same host may be passed around.\n */\nexport function acquireSlotHost(slotId: string, viewId: string | null, label: string, meta?: Record<string, unknown>): HTMLDivElement {\n // If the slot was about to be destroyed, cancel — this acquire is the\n // \"other half\" of a re-parent (teardown was the previous container).\n pendingDestroy.delete(slotId);\n\n let entry = pool.get(slotId);\n if (!entry) {\n entry = createHost(slotId, viewId, label, meta);\n pool.set(slotId, entry);\n } else if (entry.viewId !== viewId) {\n // viewId on an existing slot should be stable — the pool does not support\n // swapping views for the same slotId. Keep the focus-tracking attribute\n // in sync with whatever we have and warn; the underlying view handle will\n // not be reconstructed.\n console.warn(\n `[sh3] acquireSlotHost(\"${slotId}\") called with viewId \"${viewId}\" ` +\n `but existing pooled entry has viewId \"${entry.viewId}\". Attribute synced; ` +\n `view handle unchanged.`,\n );\n entry.viewId = viewId;\n if (viewId) {\n entry.host.setAttribute('data-sh3-view', viewId);\n entry.host.setAttribute('data-sh3-scope', scopeToString(`focus:${viewId}`));\n } else {\n entry.host.removeAttribute('data-sh3-view');\n entry.host.removeAttribute('data-sh3-scope');\n }\n }\n entry.refcount++;\n return entry.host;\n}\n\n/**\n * Release the pooled host. If this was the last reference, a\n * destruction is queued to run in a microtask; a later acquire before\n * that microtask cancels the destroy (the re-parent case).\n *\n * When `fromWrapper` is provided, the host is detached from the DOM only\n * if its current parent is still that wrapper. This guards the same-strip\n * tab reorder scenario (see below) where another caller has already moved\n * the host to a different wrapper before this release fires; an\n * unconditional detach would yank the host out of its new home.\n */\nexport function releaseSlotHost(slotId: string, fromWrapper?: HTMLElement): void {\n const entry = pool.get(slotId);\n if (!entry) return;\n entry.refcount--;\n\n if (entry.refcount > 0) {\n // Refcount remains positive (e.g. acquireAppSlotHolds keeps a hold for\n // every slot in the active layout). Detach the host from its current\n // DOM parent ONLY when that parent is the wrapper the caller is\n // releasing from — i.e. nobody else has moved it elsewhere yet.\n //\n // Same-strip tab reorder is the exact case this guard exists for:\n // Svelte runs the two SlotContainer effects as\n // [cleanup0, body0, cleanup1, body1]. By the time cleanup1 fires,\n // body0 has already `appendChild`'d the host into the OTHER pane's\n // wrapper (move semantics auto-detach from the original). An\n // unconditional `.remove()` would empty the pane that just claimed\n // the host and leave the active tab visibly blank.\n //\n // Same-instance prop change (preset switch on a single SlotContainer)\n // still works correctly: the host's parent is still our wrapper at\n // cleanup time, so the detach runs and the wrapper is empty when the\n // new acquire appends a different host.\n if (fromWrapper && entry.host.parentNode === fromWrapper) {\n entry.host.remove();\n }\n return;\n }\n\n pendingDestroy.add(slotId);\n queueMicrotask(() => {\n if (!pendingDestroy.has(slotId)) return;\n pendingDestroy.delete(slotId);\n const current = pool.get(slotId);\n if (!current || current.refcount > 0) return; // re-acquired, keep\n current.resizeObserver?.disconnect();\n current.handle?.unmount();\n current.cancelPendingMount();\n current.host.remove();\n pool.delete(slotId);\n delete dirtyState[slotId];\n delete closableState[slotId];\n });\n}\n\n/**\n * Test / teardown helper — destroys every pooled host immediately. Used\n * by HMR boundaries and tests; not part of normal runtime flow.\n */\nexport function resetSlotHostPool(): void {\n pendingDestroy.clear();\n for (const entry of pool.values()) {\n entry.resizeObserver?.disconnect();\n entry.handle?.unmount();\n entry.cancelPendingMount();\n entry.host.remove();\n }\n pool.clear();\n for (const key of Object.keys(dirtyState)) delete dirtyState[key];\n for (const key of Object.keys(closableState)) delete closableState[key];\n handleOverrides.clear();\n}\n\n/**\n * Read the current ViewHandle for a slot. Returns undefined if the slot\n * is not in the pool or hasn't finished mounting yet. Used by the close\n * protocol to check closable and call canClose().\n */\nexport function getSlotHandle(slotId: string): ViewHandle | undefined {\n const override = handleOverrides.get(slotId);\n if (override) return override;\n return pool.get(slotId)?.handle;\n}\n\n/**\n * Read the dirty state for a slot. Returns false if the slot is not in\n * the pool. Used by the tab strip to render the dirty indicator.\n */\nexport function isSlotDirty(slotId: string): boolean {\n return dirtyState[slotId] ?? false;\n}\n\n/**\n * Read the closable state for a slot. Returns false if the slot is not\n * in the pool or hasn't finished mounting yet. Reactive — Svelte will\n * re-render when the deferred mount sets the flag.\n */\nexport function isSlotClosable(slotId: string): boolean {\n if (handleOverrides.has(slotId)) {\n const h = handleOverrides.get(slotId)!;\n return !!h.closable;\n }\n return closableState[slotId] ?? false;\n}\n\n// ---------------------------------------------------------------------------\n// Test-only handle override map — lets tests inject closable/canClose policy\n// without needing a real ViewFactory. Not exported from src/index.ts.\n// ---------------------------------------------------------------------------\n\n/**\n * Map of slotId → synthetic ViewHandle injected by tests. These take\n * priority over the pool's real handles in `getSlotHandle` and\n * `isSlotClosable`. Cleared by `resetSlotHostPool`.\n */\nconst handleOverrides = new Map<string, ViewHandle>();\n\n/**\n * Test-only: set the closable policy for a slot without going through a\n * ViewFactory. Call BEFORE launchApp so the tab strip reads the right\n * closable state when it renders.\n *\n * `true` — tab shows a close button and is removed on click.\n * `false` — tab shows no close button (non-closable).\n */\nexport function setSlotClosableForTest(slotId: string, closable: boolean): void {\n const existing = handleOverrides.get(slotId);\n if (existing) {\n (existing as { closable: boolean | { canClose(): Promise<boolean> } }).closable = closable;\n } else {\n handleOverrides.set(slotId, { unmount() {}, closable });\n }\n // Keep reactive closableState in sync so the tab strip re-renders.\n if (closable) {\n closableState[slotId] = true;\n } else {\n delete closableState[slotId];\n }\n}\n\n/**\n * Test-only: attach a canClose guard to a slot. The slot must have been\n * marked closable via `setSlotClosableForTest` first (or the guard will\n * be installed alongside a `true` closable flag).\n */\nexport function setSlotCanCloseForTest(slotId: string, canClose: () => Promise<boolean>): void {\n const existing = handleOverrides.get(slotId);\n if (existing) {\n (existing as { closable: boolean | { canClose(): Promise<boolean> } }).closable = { canClose };\n } else {\n handleOverrides.set(slotId, { unmount() {}, closable: { canClose } });\n }\n // Guarded slots are still considered \"closable\" for tab strip rendering.\n closableState[slotId] = true;\n}\n","/*\n * Initial layout normalization — converts the three accepted input\n * shapes (bare LayoutNode, LayoutTree, LayoutPreset[]) into a canonical\n * CanonicalPreset[] the framework operates on. The ergonomic `tree`\n * field on LayoutPreset is discarded after normalization in favor of\n * `variants.default`. Non-default variant keys are preserved untouched\n * for the rescoped DF10 selection policy.\n */\n\nimport type { LayoutNode, LayoutTree, LayoutPreset, CanonicalPreset } from './types';\n\nfunction isLayoutNode(x: unknown): x is LayoutNode {\n if (!x || typeof x !== 'object') return false;\n const t = (x as { type?: unknown }).type;\n return t === 'split' || t === 'tabs' || t === 'slot';\n}\n\nfunction isLayoutTree(x: unknown): x is LayoutTree {\n if (!x || typeof x !== 'object') return false;\n const o = x as { docked?: unknown; floats?: unknown };\n return isLayoutNode(o.docked) && Array.isArray(o.floats);\n}\n\nfunction wrapNodeAsTree(node: LayoutNode): LayoutTree {\n return { docked: node, floats: [] };\n}\n\nfunction canonicalizePreset(p: LayoutPreset): CanonicalPreset {\n const variants: { [variant: string]: LayoutTree } = {};\n if (p.tree) variants.default = p.tree;\n if (p.variants) {\n for (const key of Object.keys(p.variants)) {\n variants[key] = p.variants[key];\n }\n }\n if (!variants.default) {\n throw new Error(\n `LayoutPreset \"${p.name}\" must provide either 'tree' or 'variants.default'`,\n );\n }\n return { name: p.name, variants };\n}\n\nexport function normalizeInitialLayout(\n input: LayoutNode | LayoutTree | LayoutPreset[],\n): CanonicalPreset[] {\n if (Array.isArray(input)) {\n return input.map(canonicalizePreset);\n }\n if (isLayoutTree(input)) {\n return [{ name: 'default', variants: { default: input } }];\n }\n if (isLayoutNode(input)) {\n return [{ name: 'default', variants: { default: wrapNodeAsTree(input) } }];\n }\n throw new Error('normalizeInitialLayout: input is not a LayoutNode, LayoutTree, or LayoutPreset[]');\n}\n","/*\n * Layout tree traversal utilities shared between the layout manager\n * and other consumers (refcount-hold, diagnostic inspection).\n */\n\nimport type { LayoutNode, LayoutTree } from './types';\n\n/**\n * Collect the slot id / view id pairs of every slot leaf (including the\n * slots embedded inside tabs entries) in a layout tree. Used by the\n * layout manager to hold pool refs for a non-rendered but still-resident\n * app tree. Order is a pre-order walk; the returned list may contain\n * the same slot id twice if the tree is malformed, but ops.ts maintains\n * the invariant that slot ids are unique so that is not a concern in\n * practice.\n */\nexport function collectSlotRefs(\n tree: LayoutNode,\n): { slotId: string; viewId: string | null; label: string; meta?: Record<string, unknown> }[] {\n const out: { slotId: string; viewId: string | null; label: string; meta?: Record<string, unknown> }[] = [];\n const walk = (node: LayoutNode): void => {\n if (node.type === 'slot') {\n out.push({ slotId: node.slotId, viewId: node.viewId, label: node.viewId || node.slotId });\n return;\n }\n if (node.type === 'tabs') {\n for (const t of node.tabs) {\n out.push({ slotId: t.slotId, viewId: t.viewId, label: t.label, meta: t.meta });\n }\n return;\n }\n // split\n for (const c of node.children) walk(c);\n };\n walk(tree);\n return out;\n}\n\n/**\n * Multi-root version of `collectSlotRefs`: walks the docked tree first\n * and then each float's content in order. Used by the layout manager to\n * take refcount holds on slot ids across every tree-owned view when\n * attaching an app whose preset includes floats.\n */\nexport function collectTreeSlotRefs(\n tree: LayoutTree,\n): { slotId: string; viewId: string | null; label: string; meta?: Record<string, unknown> }[] {\n const out = collectSlotRefs(tree.docked);\n for (const f of tree.floats) {\n out.push(...collectSlotRefs(f.content));\n }\n return out;\n}\n","/*\n * Layout manager — owns both the framework-constant shell home layout\n * and the currently-active app's persisted layout, and swaps between\n * them without tearing down the held tree.\n *\n * The manager is the sole owner of \"which layout root is being rendered\n * right now\". LayoutRenderer reads `layoutStore.root` (an alias for\n * `tree.docked`) and `layoutStore.tree`; drag.svelte.ts and any other\n * mutation site do the same. Neither needs to know whether the active\n * tree is home or an app.\n *\n * Refcount-hold discipline:\n * The slot host pool is refcount-based with a microtask-deferred\n * destroy. A root swap (app → home) causes the app's SlotContainers\n * to unmount and release their pool entries; home's slots have\n * different ids, so nothing re-acquires the app's pool entries before\n * the microtask fires, and the app's views would be destroyed. To\n * prevent this, attaching an app calls `acquireSlotHost` for every\n * slot id in the app's current layout tree once (in addition to what\n * the renderer does when the tree is active). That hold keeps\n * refcount ≥ 1 across swaps. Detaching an app releases the holds.\n *\n * Home does not need a hold — it is either rendered or unmounted\n * entirely (there is no \"held home while rendering app\" state).\n *\n * Orphan cleanup:\n * The pre-phase-8 shell wrote to `sh3:workspace:__shell__`. Phase 8\n * switches to per-app keys; the old entry would otherwise sit as dead\n * data. On first load after upgrade, the manager clears that orphan\n * unconditionally (clearing a non-existent entry is a no-op).\n */\n\nimport { createStateZones, peekZone, clearZone } from '../state/zones.svelte';\nimport { acquireSlotHost, releaseSlotHost } from './slotHostPool.svelte';\nimport type { LayoutNode, LayoutTree, FloatEntry, AppLayoutBlob, CanonicalPreset } from './types';\nimport { normalizeInitialLayout } from './presets';\nimport { collectTreeSlotRefs } from './tree-walk';\nimport { bindPresetBlob, unbindPresetBlob } from '../overlays/presets';\nimport type { App } from '../apps/types';\nimport { getRegisteredApp } from '../apps/registry.svelte';\n\n// ---------- orphan cleanup of pre-phase-8 shell layout key ----------------\n\n// Legacy pre-phase-8 orphan cleanup. The literal '__shell__' here is\n// intentional — it clears data written under the old reserved id before\n// this shard was restructured. Do not replace with '__sh3core__'.\nclearZone('workspace', '__shell__');\n\n// ---------- home layout (framework constant, in-memory only) --------------\n\n/**\n * The home layout is a single slot wrapping the sh3core:home view. The\n * slot id is reserved (`sh3core.home`) and stable so the pool entry for\n * home survives across boot/launch cycles.\n */\nconst HOME_LAYOUT: LayoutNode = {\n type: 'slot',\n slotId: 'sh3core.home',\n viewId: 'sh3core:home',\n};\n\nconst HOME_TREE: LayoutTree = $state({\n docked: HOME_LAYOUT,\n floats: [],\n});\n\n// ---------- app layout entry (workspace-zone-backed) ----------------------\n\ninterface AppEntry {\n appId: string;\n /**\n * The live workspace-zone proxy. Mutations to the active preset's tree\n * (from splitter drags, tab clicks, drop commits) flush through the\n * zones machinery as in phase 7.\n */\n proxy: AppLayoutBlob;\n /** Slot ids this entry currently holds refs for. */\n heldSlotIds: string[];\n}\n\nlet appEntry = $state<AppEntry | null>(null);\nlet activeRoot = $state<'home' | 'app'>('home');\n\n// ---------- read-side adapter helpers -------------------------------------\n\n/**\n * Read-side adapter from the legacy phase-7/phase-8 blob shape\n * ({ layoutVersion, root: LayoutNode }) to the new preset-map shape.\n * Returns a normalized AppLayoutBlob. Used only when loading a stored\n * blob that lacks the new `presets` field — fresh writes always use the\n * new shape directly.\n */\nfunction adaptLegacyBlob(stored: unknown): AppLayoutBlob | null {\n if (!stored || typeof stored !== 'object') return null;\n const obj = stored as {\n layoutVersion?: unknown;\n root?: unknown;\n presets?: unknown;\n activePreset?: unknown;\n };\n // If new shape, pass through unchanged.\n if (obj.presets && typeof obj.presets === 'object' && typeof obj.activePreset === 'string') {\n return obj as unknown as AppLayoutBlob;\n }\n // Legacy shape: wrap .root into { default: { default: { docked: root, floats: [] } } }.\n if (obj.root && typeof obj.layoutVersion === 'number') {\n const tree: LayoutTree = { docked: obj.root as LayoutNode, floats: [] };\n return {\n layoutVersion: obj.layoutVersion,\n activePreset: 'default',\n presets: {\n default: { default: tree },\n },\n };\n }\n return null;\n}\n\n/** Helper: read the active preset's default-variant tree out of a blob. */\nfunction currentTree(blob: AppLayoutBlob): LayoutTree {\n const preset = blob.presets[blob.activePreset];\n if (!preset) {\n throw new Error(\n `AppLayoutBlob active preset \"${blob.activePreset}\" not found in presets map`,\n );\n }\n // v1 always uses 'default' variant\n return preset.default;\n}\n\n// ---------- public (within-framework) API ---------------------------------\n\n/**\n * Attach an app: create or hydrate its workspace-zone layout proxy,\n * enforce the blueprint version gate, and take a refcount hold on all\n * of the app's slot ids so root swaps don't destroy its pooled hosts.\n * Does NOT switch the active root. Call switchToApp() separately.\n */\nexport function attachApp(app: App): void {\n if (appEntry) {\n throw new Error(\n `Layout manager cannot attach app \"${app.manifest.id}\": app \"${appEntry.appId}\" is still attached`,\n );\n }\n\n const shardId = `__sh3core__:app:${app.manifest.id}`;\n\n // Normalize the app's initialLayout into canonical presets.\n const canonical: CanonicalPreset[] = normalizeInitialLayout(app.initialLayout);\n if (canonical.length === 0) {\n throw new Error(`App \"${app.manifest.id}\" normalized to zero presets`);\n }\n\n // Build the default blob (used as fallback when nothing is stored or\n // the stored blob's version doesn't match).\n const defaultBlob: AppLayoutBlob = {\n layoutVersion: app.manifest.layoutVersion,\n activePreset: canonical[0].name,\n presets: Object.fromEntries(\n canonical.map((p) => [p.name, { ...p.variants }]),\n ),\n };\n\n // Version gate: if a stored blob's layoutVersion doesn't match, clear\n // and fall back to defaults.\n const stored = peekZone('workspace', shardId);\n const adapted = adaptLegacyBlob(stored);\n if (adapted && adapted.layoutVersion !== app.manifest.layoutVersion) {\n clearZone('workspace', shardId);\n } else if (stored && !adapted) {\n // Unknown/corrupt shape — clear it so createStateZones takes defaults.\n clearZone('workspace', shardId);\n }\n\n const state = createStateZones(shardId, {\n workspace: defaultBlob as unknown as Record<string, unknown>,\n });\n\n const proxy = state.workspace as unknown as AppLayoutBlob;\n\n // Create the entry with no slot holds yet; `acquireAppSlotHolds` does\n // that as a second phase, after shards have had a chance to register\n // their view factories. Binding the preset manager proxy happens here\n // so shards can read/switch presets from their activate() hook.\n appEntry = { appId: app.manifest.id, proxy, heldSlotIds: [] };\n bindPresetBlob(proxy);\n}\n\n/**\n * Second-phase attach: take refcount holds on every slot in the active\n * preset's tree. Must run AFTER required shards have activated (and\n * therefore registered their view factories), so the pool's microtask\n * factory lookup sees them. See the refcount-hold discipline comment at\n * the top of this module and the createHost microtask in slotHostPool.\n *\n * TODO(preset-switch leak): holds are taken for the INITIAL preset only\n * and released only in detachApp. On presetManager.switch(), the old\n * preset's slot hosts stay pool-resident with refcount >= 1 (view handle\n * and ResizeObserver not torn down) for the lifetime of the app attach.\n * Acceptable for small preset sets; revisit if presets become churnier.\n * Proper fix: re-scope holds on preset switch, or make this first-frame\n * only and let renderers own all refcounts.\n */\nexport function acquireAppSlotHolds(): void {\n if (!appEntry) {\n throw new Error('acquireAppSlotHolds: no app attached');\n }\n if (appEntry.heldSlotIds.length > 0) return; // idempotent\n const tree = currentTree(appEntry.proxy);\n const refs = collectTreeSlotRefs(tree);\n for (const { slotId, viewId, label, meta } of refs) {\n acquireSlotHost(slotId, viewId, label, meta);\n appEntry.heldSlotIds.push(slotId);\n }\n}\n\n/**\n * Rebuild the currently-attached app's active preset from a fresh copy\n * of `app.initialLayout`. Discards in-place customizations (split sizes,\n * tab order, drops, floats) and re-scopes slot-host refcount holds so\n * the pool tears down hosts the new tree no longer references.\n *\n * The active preset name is preserved unless the app's initialLayout no\n * longer declares it (the app shipped a new version that dropped the\n * preset name); in that case the active preset is updated to the first\n * canonical preset.\n *\n * Used by the `sh3.app.reset-layout` action — a recovery affordance\n * available from the command palette only. Other presets are left alone;\n * the user's customizations on them survive.\n *\n * Note: this re-scopes holds for the reset path only. The\n * `presetManager.switch` slot-hold leak (TODO above on\n * `acquireAppSlotHolds`) is a separate concern.\n */\nexport function resetActivePresetToDefault(): void {\n if (!appEntry) {\n throw new Error('resetActivePresetToDefault: no app attached');\n }\n const app = getRegisteredApp(appEntry.appId);\n if (!app) {\n throw new Error(\n `resetActivePresetToDefault: attached app \"${appEntry.appId}\" not in registry`,\n );\n }\n\n const canonical = normalizeInitialLayout(app.initialLayout);\n const blob = appEntry.proxy;\n const targetName = blob.activePreset;\n\n let target = canonical.find((p) => p.name === targetName);\n if (!target) {\n target = canonical[0];\n blob.activePreset = target.name;\n }\n\n // Release old slot holds before swapping the tree so the pool's\n // microtask sees no live refs and tears down hosts that the new\n // tree doesn't re-acquire.\n for (const slotId of appEntry.heldSlotIds) {\n releaseSlotHost(slotId);\n }\n appEntry.heldSlotIds = [];\n\n // Deep-clone so the canonical object isn't aliased with future\n // attaches or with the app's source `LayoutPreset` objects.\n const freshTree: LayoutTree = structuredClone(target.variants.default);\n blob.presets[blob.activePreset].default = freshTree;\n\n // Re-acquire holds against the new tree (mirrors acquireAppSlotHolds).\n const refs = collectTreeSlotRefs(freshTree);\n for (const { slotId, viewId, label, meta } of refs) {\n acquireSlotHost(slotId, viewId, label, meta);\n appEntry.heldSlotIds.push(slotId);\n }\n}\n\n/**\n * Detach the currently-attached app. Releases its refcount holds; the\n * pool's microtask cleanup drops the pooled hosts if they also have no\n * active renderer refs. Must be called before attaching a different app.\n */\nexport function detachApp(): void {\n if (!appEntry) return;\n unbindPresetBlob();\n for (const slotId of appEntry.heldSlotIds) {\n releaseSlotHost(slotId);\n }\n appEntry = null;\n // If we detach while the active root is 'app', the renderer now has\n // nothing to show; callers must switchToHome() before or after\n // detachApp. We don't auto-switch here so the ordering is explicit.\n}\n\nexport function switchToHome(): void {\n activeRoot = 'home';\n}\n\nexport function switchToApp(): void {\n if (!appEntry) {\n throw new Error('Cannot switchToApp: no app is attached');\n }\n activeRoot = 'app';\n}\n\n// ---------- `layoutStore` back-compat shim -------------------------------\n\n/**\n * Reactive-derived active LayoutTree. Using `$derived.by` gives us a\n * stable, memoized reactive node that downstream accessors\n * (`layoutStore.root`, `.tree`, `.floats`) all subscribe to once —\n * instead of re-running the proxy-read chain on every access.\n *\n * Reading `blob.activePreset` by name inside this derived is load-bearing:\n * it registers the preset-name signal as a dependency, so\n * `presetManager.switch()` invalidates the derived and triggers re-render.\n * Do not collapse this into a plain function that only reads the preset\n * object — the derived would still recompute, but consumers that cached\n * the result via a different path could miss the invalidation.\n */\nconst activeTree = $derived.by((): LayoutTree => {\n if (activeRoot === 'app' && appEntry) {\n // Read activePreset by name explicitly so Svelte tracks this signal.\n const blob = appEntry.proxy;\n const presetName = blob.activePreset;\n const preset = blob.presets[presetName];\n if (!preset) {\n throw new Error(\n `AppLayoutBlob active preset \"${presetName}\" not found in presets map`,\n );\n }\n return preset.default;\n }\n return HOME_TREE;\n});\n\n/**\n * The currently-rendered LayoutTree. LayoutRenderer reads this via\n * layoutStore.tree. Home uses a framework constant; app reads the\n * currently-active preset from the workspace-zone proxy (reactive, so\n * mutations from splitter/drag/ops reach the renderer unchanged).\n */\nexport function activeLayout(): LayoutTree {\n // Delegates to the $derived.by so callers outside component contexts\n // (e.g. inspection.ts, ops.ts) still read the correct tree. The $derived\n // is recalculated whenever activeRoot, appEntry, or blob.activePreset\n // changes, so these callers always see a fresh snapshot.\n return activeTree;\n}\n\nexport function getActiveRoot(): 'home' | 'app' {\n return activeRoot;\n}\n\nexport function getAttachedAppId(): string | null {\n return appEntry?.appId ?? null;\n}\n\n/**\n * Preserved for callers that still read `layoutStore.root`. The `root`\n * getter is an alias for `tree.docked` so existing callers still compile\n * without changes. The `tree` getter exposes the full LayoutTree for\n * new consumers that also need floats. The `floats` getter is a\n * convenience alias for `tree.floats`.\n *\n * Writes to any of these properties are disallowed (mutation happens on\n * the returned tree's nodes in place — splitter drags mutate `sizes[i]`,\n * tab clicks mutate `activeTab`, drag-commit calls ops.ts functions that\n * mutate children arrays).\n */\nexport const layoutStore = {\n get root(): LayoutNode {\n return activeTree.docked;\n },\n get tree(): LayoutTree {\n return activeTree;\n },\n get floats(): FloatEntry[] {\n return activeTree.floats;\n },\n};\n\n/**\n * Test-only reset. Restores the layout store to its boot state: no app\n * attached, active root = 'home'. Not exported from `src/index.ts` —\n * tests import this submodule path directly.\n */\nexport function __resetLayoutStoreForTest(): void {\n appEntry = null;\n activeRoot = 'home';\n HOME_TREE.floats.length = 0;\n HOME_TREE.docked = HOME_LAYOUT;\n}\n\n/**\n * Test-only inspection: returns a shallow copy of the currently-attached\n * app's held slot ids, in acquisition order. Returns `null` when no app\n * is attached. Not exported from `src/index.ts` — tests import this\n * submodule path directly.\n */\nexport function __inspectAppEntryHeldSlotIdsForTest(): string[] | null {\n return appEntry ? [...appEntry.heldSlotIds] : null;\n}\n","/*\n * Live dispatcher state. The pure dispatcher takes a snapshot; this\n * module maintains one, driven by setters called from listeners.ts,\n * lifecycle hooks, and the selection module.\n *\n * Using primitive setters (rather than $effect chains) keeps the test\n * surface small and lets callers update state in a predictable order\n * during lifecycle transitions.\n */\n\nimport type { DispatcherState } from './dispatcher.svelte';\nimport { getSelection } from './selection.svelte';\nimport { detectPlatform } from './shortcuts';\nimport { layoutStore } from '../layout/store.svelte';\nimport { collectTreeSlotRefs } from '../layout/tree-walk';\n\nlet activeAppId = $state<string | null>(null);\nlet activeAppRequiredShards = $state<Set<string>>(new Set());\nlet autostartShards = $state<Set<string>>(new Set());\nlet mountedViewIds = $state<Set<string>>(new Set());\nlet focusedViewId = $state<string | null>(null);\nlet userBindings = $state<Record<string, string | null>>({});\nconst platform = detectPlatform();\n\nconst activeChangeListeners = new Set<() => void>();\n\nfunction notifyActiveChange(): void {\n for (const cb of activeChangeListeners) {\n try { cb(); } catch (err) {\n console.error('[sh3] onActiveChange listener threw', err);\n }\n }\n}\n\n/**\n * Subscribe to any change that could affect the set of currently-active\n * actions or their resolved shortcuts (app/view/focus/selection/bindings\n * transitions). Call sites outside this module (e.g., the shell\n * assembling registry-change notifications) dispatch via\n * {@link __notifyActiveChange}.\n */\nexport function onActiveChange(cb: () => void): () => void {\n activeChangeListeners.add(cb);\n return () => { activeChangeListeners.delete(cb); };\n}\n\n/** Internal — fired by the shell runtime when the action registry mutates. */\nexport function __notifyActiveChange(): void {\n notifyActiveChange();\n}\n\n/** Test-only alias for the internal notifier. */\nexport const __notifyActiveChangeForTest = __notifyActiveChange;\n\nexport function setActiveApp(appId: string | null, requiredShards: Set<string>): void {\n activeAppId = appId;\n activeAppRequiredShards = new Set(requiredShards);\n notifyActiveChange();\n}\n\nexport function setAutostartShards(shards: Set<string>): void {\n autostartShards = new Set(shards);\n notifyActiveChange();\n}\n\nexport function setMountedViewIds(ids: Set<string>): void {\n mountedViewIds = new Set(ids);\n notifyActiveChange();\n}\n\n/**\n * One-shot snapshot: walk the active layout tree and update\n * `mountedViewIds` to match. Non-reactive — call from an `$effect` that\n * reads `layoutStore.tree` to keep the set in sync as the tree mutates.\n * Shell.svelte owns that effect during boot.\n */\nexport function syncMountedViewIdsFromLayout(): void {\n const refs = collectTreeSlotRefs(layoutStore.tree);\n const ids = new Set<string>();\n for (const r of refs) {\n if (r.viewId !== null) ids.add(r.viewId);\n }\n mountedViewIds = ids;\n notifyActiveChange();\n}\n\nexport function setFocusedViewId(id: string | null): void {\n focusedViewId = id;\n notifyActiveChange();\n}\n\nexport function setUserBindings(bindings: Record<string, string | null>): void {\n userBindings = { ...bindings };\n notifyActiveChange();\n}\n\nexport function getLiveDispatcherState(): DispatcherState {\n return {\n activeAppId,\n activeAppRequiredShards,\n autostartShards,\n mountedViewIds,\n focusedViewId,\n selection: getSelection(),\n bindings: userBindings,\n platform,\n };\n}\n\nexport function addAutostartShard(id: string): void {\n if (!autostartShards.has(id)) {\n autostartShards = new Set([...autostartShards, id]);\n notifyActiveChange();\n }\n}\n\nexport function __resetDispatcherStateForTest(): void {\n activeAppId = null;\n activeAppRequiredShards = new Set();\n autostartShards = new Set();\n mountedViewIds = new Set();\n focusedViewId = null;\n userBindings = {};\n activeChangeListeners.clear();\n}\n","<script lang=\"ts\" module>\n import type { MenuBarItem } from './menuBarModel';\n\n export interface ActionPanelSection {\n id: string;\n items: MenuBarItem[];\n }\n</script>\n\n<script lang=\"ts\">\n /*\n * ActionPanel — shared dropdown body for action lists. Renders sections\n * (each a group of items) with separators between them. Owns: row\n * rendering, hover/focus state, keyboard nav, click-dispatch. Does NOT\n * own: positioning, backdrop, the popover surface itself — those stay\n * with the consumer (ContextMenu, MenuButton, etc.).\n *\n * Visuals:\n * - Reserved leading \"check slot\": ✓ when item.checked, blank otherwise.\n * - Disabled items: aria-disabled, .sh3-ctx-disabled class, click no-op,\n * keyboard skip.\n * - Submenu parents: trailing ▸, no shortcut hint. The submenu drill\n * itself is wired by the consumer (MenuButton / context-menu listener)\n * via onInvoke — this component just emits the parent's id.\n */\n\n let { sections, onInvoke, onDismiss }: {\n sections: ActionPanelSection[];\n onInvoke: (id: string) => void;\n onDismiss: () => void;\n } = $props();\n\n const flatItems: MenuBarItem[] = $derived(sections.flatMap((s) => s.items));\n let cursor = $state(0);\n\n function nextEnabled(start: number, dir: 1 | -1): number {\n if (flatItems.length === 0) return 0;\n let i = start;\n for (let n = 0; n < flatItems.length; n++) {\n i = (i + dir + flatItems.length) % flatItems.length;\n if (!flatItems[i].disabled) return i;\n }\n return start;\n }\n\n function onKeydown(ev: KeyboardEvent) {\n if (ev.key === 'ArrowDown') {\n cursor = nextEnabled(cursor, 1);\n ev.preventDefault();\n } else if (ev.key === 'ArrowUp') {\n cursor = nextEnabled(cursor, -1);\n ev.preventDefault();\n } else if (ev.key === 'Enter') {\n const item = flatItems[cursor];\n if (item && !item.disabled) {\n onInvoke(item.id);\n if (!item.submenu) onDismiss();\n }\n ev.preventDefault();\n } else if (ev.key === 'Escape') {\n onDismiss();\n ev.preventDefault();\n } else if (ev.key.length === 1) {\n const q = ev.key.toLowerCase();\n const start = (cursor + 1) % flatItems.length;\n for (let i = 0; i < flatItems.length; i++) {\n const idx = (start + i) % flatItems.length;\n const item = flatItems[idx];\n if (item.disabled) continue;\n if (item.label.toLowerCase().startsWith(q)) {\n cursor = idx;\n break;\n }\n }\n }\n }\n\n function onItemClick(item: MenuBarItem) {\n if (item.disabled) return;\n onInvoke(item.id);\n if (!item.submenu) onDismiss();\n }\n</script>\n\n<!-- svelte-ignore a11y_autofocus -->\n<div class=\"sh3-context-menu\" role=\"menu\" tabindex=\"0\" onkeydown={onKeydown} autofocus>\n {#each sections as section, sIdx (section.id)}\n {#if sIdx > 0}<div class=\"sh3-ctx-sep\" role=\"separator\"></div>{/if}\n {#each section.items as item (item.id)}\n {@const globalIdx = flatItems.indexOf(item)}\n <button\n class=\"sh3-ctx-item\"\n class:sh3-ctx-active={globalIdx === cursor}\n class:sh3-ctx-disabled={item.disabled}\n role=\"menuitem\"\n aria-disabled={item.disabled || undefined}\n onpointerenter={() => { if (!item.disabled) cursor = globalIdx; }}\n onclick={() => onItemClick(item)}\n >\n <span class=\"sh3-ctx-check\">{item.checked ? '✓' : ''}</span>\n <span class=\"sh3-ctx-label\">{item.label}</span>\n {#if item.submenu}\n <span class=\"sh3-ctx-chevron\">▸</span>\n {:else if item.shortcut}\n <span class=\"sh3-ctx-shortcut\">{item.shortcut}</span>\n {/if}\n </button>\n {/each}\n {/each}\n</div>\n\n<style>\n .sh3-context-menu {\n min-width: 220px;\n background: var(--shell-bg-elevated, #222);\n color: var(--shell-fg, #eee);\n border-radius: 4px;\n padding: 4px 0;\n box-shadow: 0 4px 16px rgba(0, 0, 0, 0.35);\n outline: none;\n }\n .sh3-ctx-item {\n display: flex;\n align-items: center;\n gap: 8px;\n width: 100%;\n padding: 4px 10px;\n background: none;\n border: 0;\n text-align: left;\n color: inherit;\n cursor: default;\n font: inherit;\n }\n .sh3-ctx-active { background: var(--shell-accent, #6ea8fe); color: var(--shell-fg,#e4e6eb); }\n .sh3-ctx-disabled { opacity: 0.45; }\n .sh3-ctx-disabled.sh3-ctx-active { background: transparent; }\n .sh3-ctx-check { display: inline-block; width: 12px; text-align: center; opacity: 0.85; }\n .sh3-ctx-label { flex: 1; }\n .sh3-ctx-chevron { opacity: 0.6; }\n .sh3-ctx-shortcut { opacity: 0.6; font-size: 0.9em; }\n .sh3-ctx-sep { height: 1px; background: rgba(255, 255, 255, 0.1); margin: 4px 0; }\n</style>\n","<script lang=\"ts\">\n /*\n * ContextMenu — popup-rendered, tier-grouped action list. Receives a\n * pre-built model and an onInvoke callback. Dismiss and anchoring are\n * handled by PopupFrame / popupManager. The list rendering, keyboard\n * nav, and click dispatch are delegated to ActionPanel.\n */\n import type { ContextMenuModel } from './contextMenuModel';\n import ActionPanel, { type ActionPanelSection } from './ActionPanel.svelte';\n\n let { model, onInvoke, onClose }: {\n model: ContextMenuModel;\n onInvoke: (id: string) => void;\n onClose: () => void;\n } = $props();\n\n // Adapt ContextMenuModel.tiers → ActionPanel.sections. The MenuItem\n // shape from contextMenuModel already carries id/label/shortcut/group;\n // ActionPanel expects an `icon?` field — context menu items don't carry\n // one today, so it stays undefined.\n const sections: ActionPanelSection[] = $derived(\n model.tiers.map((t) => ({\n id: `tier:${t.tier}`,\n items: t.items.map((i) => ({ ...i, icon: undefined })),\n })),\n );\n</script>\n\n<ActionPanel {sections} {onInvoke} onDismiss={onClose} />\n","/*\n * Pure model layer for the context menu: takes the action registry +\n * dispatcher state + an anchor scope, returns a tier-grouped, deduplicated,\n * flag-annotated item list the Svelte component renders without further\n * logic. Items pass iff their declared scope list contains the anchor;\n * `app`/`home` anchors additionally require the existing owner-shard\n * activation guard.\n */\n\nimport type { ActionEntry } from './registry';\nimport {\n TIER_ORDER,\n isScopeActive,\n type DispatcherState,\n type TierName,\n} from './dispatcher.svelte';\nimport { effectiveShortcut } from './bindings';\nimport {\n scopeToTier,\n innermostActiveScope,\n scopeEquals,\n normalizeScope,\n} from './scope-helpers';\nimport { resolveLabel, type Action, type AtomicScope } from './types';\n\nexport interface MenuItem {\n id: string;\n label: string;\n shortcut: string | null;\n group: string;\n icon: string | undefined;\n checked: boolean;\n disabled: boolean;\n submenu: boolean;\n}\n\nexport interface MenuTier {\n tier: TierName;\n items: MenuItem[];\n}\n\nexport interface ContextMenuModel {\n tiers: MenuTier[];\n}\n\nfunction evalFlag(v: boolean | (() => boolean) | undefined): boolean {\n if (v === undefined) return false;\n return typeof v === 'function' ? !!v() : !!v;\n}\n\nfunction toMenuItem(entry: ActionEntry, state: DispatcherState): MenuItem {\n return {\n id: entry.action.id,\n label: resolveLabel(entry.action),\n shortcut: effectiveShortcut(entry.action, state.bindings, state.platform),\n group: entry.action.group ?? '',\n icon: entry.action.icon,\n checked: evalFlag(entry.action.checked),\n disabled: evalFlag(entry.action.disabled),\n submenu: entry.action.submenu === true,\n };\n}\n\nfunction matchesAnchor(\n action: Action,\n ownerShardId: string,\n anchor: AtomicScope,\n state: DispatcherState,\n): boolean {\n const inList = normalizeScope(action.scope).some((s) => scopeEquals(s, anchor));\n if (!inList) return false;\n if (anchor === 'app' || anchor === 'home') {\n return isScopeActive(anchor, state, ownerShardId);\n }\n // Element anchors require their scope to be active — selection.type must\n // match. Parallel to the resolveAnchor rule that walks past inactive\n // element atoms in the DOM (ADR-021 amendment 2026-05-01). Protects the\n // explicit-anchor path (`openContextMenu({ scope: { element } })`) from\n // surfacing element actions when nothing is selected.\n if (typeof anchor === 'object' && 'element' in anchor) {\n return isScopeActive(anchor, state, ownerShardId);\n }\n return true;\n}\n\nexport function buildContextMenuModel(\n entries: ActionEntry[],\n state: DispatcherState,\n anchor: AtomicScope,\n): ContextMenuModel {\n const byTier: Record<TierName, MenuItem[]> = {\n element: [], focus: [], view: [], app: [], home: [],\n };\n const seen = new Set<string>();\n\n for (const entry of entries) {\n if (!entry.action.contextItem) continue;\n if (entry.action.submenuOf !== undefined) continue;\n if (seen.has(entry.action.id)) continue;\n if (!matchesAnchor(entry.action, entry.ownerShardId, anchor, state)) continue;\n // Tier is determined by the anchor itself; the per-action winning scope\n // is preserved purely for any future tier-aware rendering.\n const winning = innermostActiveScope(entry.action.scope, state, entry.ownerShardId) ?? anchor;\n seen.add(entry.action.id);\n byTier[scopeToTier(winning)].push(toMenuItem(entry, state));\n }\n\n return {\n tiers: TIER_ORDER\n .map((tier) => ({ tier, items: byTier[tier] }))\n .filter((t) => t.items.length > 0),\n };\n}\n\n/**\n * Active children of a context-menu submenu parent. Single flat list,\n * de-duplicated by id, in registration order. The same anchor filter that\n * admitted the parent is applied to children.\n */\nexport function buildContextMenuSubmenu(\n entries: ActionEntry[],\n state: DispatcherState,\n parentId: string,\n anchor: AtomicScope,\n): MenuItem[] {\n const out: MenuItem[] = [];\n const seen = new Set<string>();\n for (const entry of entries) {\n if (entry.action.submenuOf !== parentId) continue;\n if (seen.has(entry.action.id)) continue;\n if (!matchesAnchor(entry.action, entry.ownerShardId, anchor, state)) continue;\n seen.add(entry.action.id);\n out.push(toMenuItem(entry, state));\n }\n return out;\n}\n","/*\n * Fuzzy scorer for the command palette. Subsequence match with\n * prefix-bonus and tight-run scoring. Session-local recency ring\n * breaks ties.\n */\n\nexport interface PaletteCandidate {\n id: string;\n label: string;\n shortcut: string | null;\n scopeBadge: string | null;\n /** True when `Action.submenu === true`. Hint only; ranker treats it like any candidate. */\n submenu: boolean;\n /** Set when this candidate is a child of a submenu parent. Hidden when the palette query is empty. */\n submenuOf?: string;\n}\n\nexport interface RankedCandidate extends PaletteCandidate {\n score: number;\n}\n\nexport function scoreMatch(label: string, query: string): number | null {\n if (!query) return 0;\n const L = label.toLowerCase();\n const Q = query.toLowerCase();\n\n let i = 0, j = 0;\n let score = 0;\n let runLen = 0;\n let prevMatchIdx = -2;\n\n while (i < L.length && j < Q.length) {\n if (L[i] === Q[j]) {\n const prefixBonus = i === 0 ? 5 : 0;\n const runBonus = i === prevMatchIdx + 1 ? ++runLen : (runLen = 1);\n score += 1 + prefixBonus + runBonus;\n prevMatchIdx = i;\n j++;\n } else {\n runLen = 0;\n }\n i++;\n }\n\n return j === Q.length ? score : null;\n}\n\nexport function rankPaletteEntries(\n candidates: PaletteCandidate[],\n query: string,\n recency: string[], // action ids, most recent first\n): RankedCandidate[] {\n const ranked: RankedCandidate[] = [];\n for (const c of candidates) {\n // Hide submenu children from the idle (empty-query) palette so the\n // default view stays uncluttered. A direct text match still surfaces\n // them because the scorer runs once query is non-empty.\n if (query === '' && c.submenuOf !== undefined) continue;\n const s = scoreMatch(c.label, query);\n if (s === null) continue;\n ranked.push({ ...c, score: s });\n }\n const recencyIdx = new Map<string, number>();\n recency.forEach((id, i) => recencyIdx.set(id, recency.length - i));\n ranked.sort((a, b) => {\n if (a.score !== b.score) return b.score - a.score;\n const ra = recencyIdx.get(a.id) ?? 0;\n const rb = recencyIdx.get(b.id) ?? 0;\n return rb - ra;\n });\n return ranked;\n}\n","<script lang=\"ts\">\n import { rankPaletteEntries, type PaletteCandidate } from './palette-scorer';\n\n let { candidates, recency, prefill = '', onInvoke, onClose }: {\n candidates: PaletteCandidate[];\n recency: string[];\n prefill?: string;\n onInvoke: (id: string) => void;\n onClose: () => void;\n } = $props();\n\n let query = $state((() => prefill)());\n let cursor = $state(0);\n const ranked = $derived(rankPaletteEntries(candidates, query, recency));\n\n $effect(() => { if (cursor >= ranked.length) cursor = 0; });\n\n function onKeydown(ev: KeyboardEvent) {\n if (ev.key === 'ArrowDown') {\n cursor = Math.min(cursor + 1, Math.max(0, ranked.length - 1));\n ev.preventDefault();\n } else if (ev.key === 'ArrowUp') {\n cursor = Math.max(cursor - 1, 0);\n ev.preventDefault();\n } else if (ev.key === 'Enter') {\n if (ranked[cursor]) {\n onInvoke(ranked[cursor].id);\n onClose();\n }\n ev.preventDefault();\n } else if (ev.key === 'Escape') {\n onClose();\n ev.preventDefault();\n }\n }\n</script>\n\n<!-- svelte-ignore a11y_autofocus -->\n<div class=\"sh3-palette\" role=\"dialog\" aria-label=\"Command palette\" aria-modal=\"true\" tabindex=\"-1\" onkeydown={onKeydown}>\n <input class=\"sh3-palette-input hell-base-input\" bind:value={query} autofocus placeholder=\"Command…\" />\n <div class=\"sh3-palette-list\" role=\"listbox\">\n {#each ranked as item, i (item.id)}\n <button\n class=\"sh3-palette-item\"\n class:sh3-palette-active={i === cursor}\n role=\"option\"\n aria-selected={i === cursor}\n onpointerenter={() => cursor = i}\n onclick={() => { onInvoke(item.id); onClose(); }}\n >\n <span class=\"sh3-palette-label\">{item.label}</span>\n {#if item.scopeBadge}<span class=\"sh3-palette-badge\">[{item.scopeBadge}]</span>{/if}\n {#if item.shortcut}<span class=\"sh3-palette-shortcut\">{item.shortcut}</span>{/if}\n </button>\n {/each}\n </div>\n</div>\n\n<style>\n .sh3-palette { min-width: 480px; max-width: 640px; background: var(--shell-bg-elevated, #22232a); color: var(--shell-fg, #e4e6eb); border-radius: var(--shell-radius-md, 6px); box-shadow: 0 8px 24px rgba(0,0,0,.4); }\n .sh3-palette-input { width: 100%; padding: 10px; background: none; border: 0; border-bottom: 1px solid rgba(255,255,255,.1); color: inherit; font: inherit; outline: none; }\n .sh3-palette-list { max-height: 320px; overflow-y: auto; padding: 4px 0; }\n .sh3-palette-item { display: flex; align-items: center; gap: 12px; width: 100%; padding: 6px 12px; background: none; border: 0; color: inherit; text-align: left; font: inherit; cursor: default; }\n .sh3-palette-active { background: var(--shell-accent, #4a5); border-radius: 0; color: #fff; }\n .sh3-palette-label { flex: 1; }\n .sh3-palette-badge { opacity: .5; font-size: .85em; }\n .sh3-palette-shortcut { opacity: .6; font-size: .9em; }\n</style>\n","/*\n * Palette candidate builder — returns every active (paletteItem !== false)\n * action, deduplicated, with shortcut and scope badge resolved. Uses\n * innermost-first scope selection so the badge matches keyboard dispatch\n * and context-menu tiering (audit: RFC #24).\n *\n * Submenu rules:\n * - When `opts.filter.submenuOf` is set, return ONLY children whose\n * `submenuOf` matches it. Used by sub-palette drill.\n * - Otherwise return all active candidates. The scorer\n * (`rankPaletteEntries`) is responsible for hiding children when\n * the user's query is empty.\n * - Disabled actions are hidden in all modes (v1 — see spec).\n */\n\nimport type { ActionEntry } from './registry';\nimport type { DispatcherState } from './dispatcher.svelte';\nimport { effectiveShortcut } from './bindings';\nimport { innermostActiveScope, scopeBadge } from './scope-helpers';\nimport { resolveLabel } from './types';\nimport type { PaletteCandidate } from './palette-scorer';\n\nexport interface BuildPaletteOpts {\n /** When set, return only children of the given submenu parent. */\n filter?: { submenuOf?: string };\n}\n\nfunction evalFlag(v: boolean | (() => boolean) | undefined): boolean {\n if (v === undefined) return false;\n return typeof v === 'function' ? !!v() : !!v;\n}\n\nexport function buildPaletteCandidates(\n entries: ActionEntry[],\n state: DispatcherState,\n opts: BuildPaletteOpts = {},\n): PaletteCandidate[] {\n const out: PaletteCandidate[] = [];\n const seen = new Set<string>();\n const filterParent = opts.filter?.submenuOf;\n\n for (const entry of entries) {\n if (entry.action.paletteItem === false) continue;\n if (evalFlag(entry.action.disabled)) continue;\n if (filterParent !== undefined && entry.action.submenuOf !== filterParent) continue;\n if (seen.has(entry.action.id)) continue;\n const winning = innermostActiveScope(entry.action.scope, state, entry.ownerShardId);\n if (!winning) continue;\n seen.add(entry.action.id);\n out.push({\n id: entry.action.id,\n label: resolveLabel(entry.action),\n shortcut: effectiveShortcut(entry.action, state.bindings, state.platform),\n scopeBadge: scopeBadge(winning),\n submenu: entry.action.submenu === true,\n // When a submenuOf-filter is in effect, the resulting candidates are\n // already scoped — they ARE the visible set in this palette, not\n // hidden children of some other parent. Drop the `submenuOf` hint so\n // the ranker doesn't apply its hide-children-on-empty rule to them.\n submenuOf: filterParent !== undefined ? undefined : entry.action.submenuOf,\n });\n }\n return out;\n}\n","/*\n * Document-level listener wiring for actions. Single keydown and single\n * contextmenu listener, attached at shell boot (Task 18) and removed on\n * shell teardown.\n */\n\nimport { mount, type Component } from 'svelte';\nimport { listActions } from './registry';\nimport { dispatchKeydown } from './dispatcher.svelte';\nimport {\n getLiveDispatcherState,\n setFocusedViewId,\n} from './state.svelte';\nimport { eventToShortcut } from './shortcuts';\nimport { resolveLabel, type ActionDispatchContext, type AtomicScope } from './types';\nimport ContextMenu from './ContextMenu.svelte';\nimport { buildContextMenuModel, buildContextMenuSubmenu } from './contextMenuModel';\nimport ActionPanel from './ActionPanel.svelte';\nimport CommandPalette from './CommandPalette.svelte';\nimport { buildPaletteCandidates } from './paletteModel';\nimport { parseScopeString } from './scope-helpers';\nimport { isScopeActive } from './dispatcher.svelte';\nimport { shell } from '../shellRuntime.svelte';\n\nexport interface OpenContextMenuOpts { x: number; y: number; scope?: AtomicScope; }\nexport interface OpenPaletteOpts {\n prefill?: string;\n /** Restrict candidates to children of the given submenu parent (sub-palette drill). */\n filter?: { submenuOf?: string };\n}\n\nlet attached = false;\n\nfunction viewIdOfEl(el: Element | null): string | null {\n if (!el) return null;\n const host = el.closest('[data-sh3-view]');\n return host?.getAttribute('data-sh3-view') ?? null;\n}\n\nfunction resolveAnchor(args: {\n event?: MouseEvent | null;\n explicit?: AtomicScope;\n state: ReturnType<typeof getLiveDispatcherState>;\n}): AtomicScope {\n if (args.explicit !== undefined) return args.explicit;\n const target = args.event?.target;\n if (target instanceof Element) {\n // Preferred path: data-sh3-scope carries the literal AtomicScope encoding\n // (see ADR-021 amendment 2026-05-01). Walk every scope-bearing ancestor\n // so a sub-region can override its enclosing slot host's auto-stamped\n // focus:<viewId>. Element atoms whose scope is not active (no matching\n // selection) are walked past — without an active selection there is no\n // element context, so we fall through to the next ancestor and\n // ultimately the slot host's focus scope.\n let scopeHost: Element | null = target.closest('[data-sh3-scope]');\n while (scopeHost) {\n const parsed = parseScopeString(scopeHost.getAttribute('data-sh3-scope') ?? '');\n if (parsed) {\n const isInactiveElementAtom =\n typeof parsed === 'object' && 'element' in parsed && !isScopeActive(parsed, args.state);\n if (!isInactiveElementAtom) return parsed;\n }\n // Continue walking from above this scopeHost.\n const parent: Element | null = scopeHost.parentElement;\n scopeHost = parent ? parent.closest('[data-sh3-scope]') : null;\n }\n // Fallback: data-sh3-view alone still maps to focus:<viewId>. Defensive\n // for stub views and external callers that haven't adopted the new\n // attribute; framework-stamped slot hosts now carry both.\n const viewId = viewIdOfEl(target);\n if (viewId) return `focus:${viewId}` as AtomicScope;\n }\n return args.state.activeAppId ? 'app' : 'home';\n}\n\nfunction runAction(actionId: string, ctx: ActionDispatchContext): void {\n const entry = listActions().find((e) => e.action.id === actionId);\n if (!entry || typeof entry.action.run !== 'function') return;\n try {\n void entry.action.run(ctx);\n } catch (err) {\n console.error(`[sh3] action \"${actionId}\" threw:`, err);\n }\n}\n\n/**\n * Invoke another action by id from within an action's `run`. Builds a fresh\n * dispatch context using current live state with `invokedVia: 'programmatic'`.\n * Called via `ctx.dispatch(id)` on ActionDispatchContext.\n */\nfunction chainedDispatch(actionId: string): void {\n const entry = listActions().find((e) => e.action.id === actionId);\n if (!entry) {\n console.warn(`[sh3] ctx.dispatch(\"${actionId}\") — no action registered with that id.`);\n return;\n }\n const state = getLiveDispatcherState();\n runAction(actionId, {\n action: { id: entry.action.id, label: resolveLabel(entry.action) },\n appId: state.activeAppId,\n viewId: state.focusedViewId ?? undefined,\n selection: state.selection ?? undefined,\n invokedVia: 'programmatic',\n dispatch: chainedDispatch,\n });\n}\n\nfunction onFocusIn(ev: FocusEvent): void {\n const id = viewIdOfEl(ev.target as Element);\n setFocusedViewId(id);\n}\n\nfunction onFocusOut(_ev: FocusEvent): void {\n // Defer — a focusout is usually followed immediately by focusin on the next element.\n queueMicrotask(() => {\n const id = viewIdOfEl(document.activeElement);\n setFocusedViewId(id);\n });\n}\n\nfunction isNativeOptOut(target: EventTarget | null): boolean {\n if (!(target instanceof Element)) return false;\n return target.closest('[data-sh3-context-menu=\"native\"]') !== null;\n}\n\nfunction openContextSubmenu(\n parentId: string,\n state: ReturnType<typeof getLiveDispatcherState>,\n handle: { close: () => void },\n anchor: AtomicScope,\n): void {\n const root = document.querySelector('.sh3-popup-host') as HTMLElement | null;\n if (!root) return;\n const sub = document.createElement('div');\n sub.className = 'sh3-popup-submenu';\n sub.style.position = 'absolute';\n sub.style.pointerEvents = 'auto';\n const activeRow = root.querySelector('.sh3-ctx-active') as HTMLElement | null;\n const anchorRect = (activeRow ?? root).getBoundingClientRect();\n sub.style.left = `${anchorRect.right + 2}px`;\n sub.style.top = `${anchorRect.top}px`;\n root.appendChild(sub);\n\n const subItems = buildContextMenuSubmenu(listActions(), state, parentId, anchor);\n mount(ActionPanel as unknown as Component<Record<string, unknown>>, {\n target: sub,\n props: {\n sections: [{ id: `submenu:${parentId}`, items: subItems }],\n onInvoke: (cid: string) => {\n const child = listActions().find((e) => e.action.id === cid);\n if (!child || typeof child.action.run !== 'function') return;\n try {\n void child.action.run({\n action: { id: cid, label: resolveLabel(child.action) },\n appId: state.activeAppId,\n viewId: state.focusedViewId ?? undefined,\n selection: state.selection ?? undefined,\n invokedVia: 'context-menu',\n dispatch: chainedDispatch,\n });\n } catch (err) {\n console.error(`[sh3] context-menu submenu action \"${cid}\" threw:`, err);\n }\n handle.close();\n },\n onDismiss: () => handle.close(),\n },\n });\n}\n\nfunction onContextMenu(ev: MouseEvent): void {\n if (isNativeOptOut(ev.target)) return;\n const entries = listActions();\n const state = getLiveDispatcherState();\n const anchor = resolveAnchor({ event: ev, state });\n const model = buildContextMenuModel(entries, state, anchor);\n if (model.tiers.length === 0) return;\n ev.preventDefault();\n const handle = shell.popup.show(\n ContextMenu,\n { anchor: { x: ev.clientX, y: ev.clientY } },\n {\n model,\n onInvoke: (id: string) => {\n const entry = listActions().find((e) => e.action.id === id);\n if (!entry) return;\n if (entry.action.submenu === true) {\n openContextSubmenu(id, state, handle, anchor);\n return;\n }\n if (typeof entry.action.run !== 'function') return;\n try {\n void entry.action.run({\n action: { id, label: resolveLabel(entry.action) },\n appId: state.activeAppId,\n viewId: state.focusedViewId ?? undefined,\n selection: state.selection ?? undefined,\n invokedVia: 'context-menu',\n dispatch: chainedDispatch,\n });\n } catch (err) {\n console.error(`[sh3] context-menu action \"${id}\" threw:`, err);\n }\n },\n onClose: () => handle.close(),\n },\n );\n}\n\nfunction onKeydown(ev: KeyboardEvent): void {\n const shortcut = eventToShortcut(ev);\n if (!shortcut) return; // pure modifier press\n const entries = listActions();\n const state = getLiveDispatcherState();\n const matched = dispatchKeydown({\n target: ev.target,\n shortcut,\n state,\n entries,\n runAction,\n dispatch: chainedDispatch,\n });\n if (matched) ev.preventDefault();\n}\n\nexport function attachGlobalListeners(): void {\n if (attached) return;\n attached = true;\n document.addEventListener('keydown', onKeydown);\n document.addEventListener('focusin', onFocusIn);\n document.addEventListener('focusout', onFocusOut);\n document.addEventListener('contextmenu', onContextMenu);\n}\n\nexport function detachGlobalListeners(): void {\n if (!attached) return;\n attached = false;\n document.removeEventListener('keydown', onKeydown);\n document.removeEventListener('focusin', onFocusIn);\n document.removeEventListener('focusout', onFocusOut);\n document.removeEventListener('contextmenu', onContextMenu);\n}\n\nexport function openContextMenu(opts: OpenContextMenuOpts): void {\n const entries = listActions();\n const state = getLiveDispatcherState();\n const anchor = resolveAnchor({ explicit: opts.scope, state });\n const model = buildContextMenuModel(entries, state, anchor);\n if (model.tiers.length === 0) return;\n const handle = shell.popup.show(\n ContextMenu,\n { anchor: { x: opts.x, y: opts.y } },\n {\n model,\n onInvoke: (id: string) => {\n const entry = listActions().find((e) => e.action.id === id);\n if (!entry) return;\n if (entry.action.submenu === true) {\n openContextSubmenu(id, state, handle, anchor);\n return;\n }\n if (typeof entry.action.run !== 'function') return;\n try {\n void entry.action.run({\n action: { id, label: resolveLabel(entry.action) },\n appId: state.activeAppId,\n viewId: state.focusedViewId ?? undefined,\n selection: state.selection ?? undefined,\n invokedVia: 'context-menu',\n dispatch: chainedDispatch,\n });\n } catch (err) {\n console.error(`[sh3] context-menu action \"${id}\" threw:`, err);\n }\n },\n onClose: () => handle.close(),\n },\n );\n}\nconst RECENCY_CAP = 20;\nlet recency: string[] = [];\n\nfunction recordUse(id: string): void {\n recency = [id, ...recency.filter((x) => x !== id)].slice(0, RECENCY_CAP);\n}\n\nexport function openPalette(opts?: OpenPaletteOpts): void {\n const entries = listActions();\n const state = getLiveDispatcherState();\n const candidates = buildPaletteCandidates(entries, state, { filter: opts?.filter });\n const handle = shell.modal.open(\n CommandPalette,\n {\n candidates,\n recency,\n prefill: opts?.prefill ?? '',\n onInvoke: (id: string) => {\n const entry = listActions().find((e) => e.action.id === id);\n if (!entry) return;\n recordUse(id);\n // Submenu drill: a parent without a run() opens a sub-palette\n // filtered to its children. Apps that supply their own run()\n // keep that behavior — drill is only the default.\n if (entry.action.submenu === true && typeof entry.action.run !== 'function') {\n handle.close();\n openPalette({ filter: { submenuOf: id } });\n return;\n }\n if (typeof entry.action.run !== 'function') return;\n try {\n void entry.action.run({\n action: { id, label: resolveLabel(entry.action) },\n appId: state.activeAppId,\n viewId: state.focusedViewId ?? undefined,\n selection: state.selection ?? undefined,\n invokedVia: 'palette',\n dispatch: chainedDispatch,\n });\n } catch (err) {\n console.error(`[sh3] palette action \"${id}\" threw:`, err);\n }\n },\n onClose: () => handle.close(),\n },\n { dismissOnBackdrop: true },\n );\n}\n","/*\n * Pure read-side producer for `shell.actions.listActive()`.\n *\n * Given a snapshot of the action registry and the dispatcher state,\n * return one `ActiveActionDescriptor` per currently-active action, in\n * tier-innermost-first order (element > focus > view > app > home),\n * with registration order preserved within a tier.\n *\n * The shell's live wrapper calls this with `listActions()` + `getLiveDispatcherState()`.\n */\n\nimport type { ActionEntry } from './registry';\nimport {\n TIER_ORDER,\n type DispatcherState,\n type TierName,\n} from './dispatcher.svelte';\nimport { effectiveShortcutWithSource } from './bindings';\nimport { innermostActiveScope, scopeBadge, scopeToTier } from './scope-helpers';\nimport { resolveLabel, type ActiveActionDescriptor } from './types';\n\nexport function listActiveFromEntries(\n entries: ActionEntry[],\n state: DispatcherState,\n): ActiveActionDescriptor[] {\n const byTier: Record<TierName, ActiveActionDescriptor[]> = {\n element: [], focus: [], view: [], app: [], home: [],\n };\n const seen = new Set<string>();\n\n for (const entry of entries) {\n if (seen.has(entry.action.id)) continue;\n const winning = innermostActiveScope(entry.action.scope, state, entry.ownerShardId);\n if (!winning) continue;\n seen.add(entry.action.id);\n const { shortcut, source } = effectiveShortcutWithSource(\n entry.action, state.bindings, state.platform,\n );\n byTier[scopeToTier(winning)].push({\n id: entry.action.id,\n label: resolveLabel(entry.action),\n effectiveShortcut: shortcut,\n bindingSource: source,\n scope: winning,\n scopeBadge: scopeBadge(winning),\n group: entry.action.group,\n icon: entry.action.icon,\n ownerShardId: entry.ownerShardId,\n paletteItem: entry.action.paletteItem !== false,\n contextItem: entry.action.contextItem !== false,\n });\n }\n\n return TIER_ORDER.flatMap((tier) => byTier[tier]);\n}\n","/*\n * shell — the framework-facing entry point passed to shards.\n *\n * Conceptually this is the object a shard receives from its activation\n * callback; it exposes the APIs the shard is allowed to touch.\n *\n * Phase 3: state zones.\n * Phase 4: registerView (lives on ShardContext, not here).\n * Phase 5: modal / popup / toast overlay managers.\n *\n * For now `shell` is a module-level singleton. Once the shard lifecycle\n * exists in a fuller form, per-shard shells will be constructed per\n * activation with the shardId baked in, so shards no longer need to pass\n * their own id to `state`. Overlay managers stay process-wide because\n * the layer stack is a shell-global resource.\n */\n\nimport { createStateZones } from './state/zones.svelte';\nimport type { StateZones } from './state/zones.svelte';\nimport type { ZoneSchema } from './state/types';\nimport { modalManager, type ModalManager } from './overlays/modal';\nimport { popupManager, type PopupManager } from './overlays/popup';\nimport { toastManager, type ToastManager } from './overlays/toast';\nimport { floatManager, type FloatManager } from './overlays/float';\nimport { presetManager, type PresetManager } from './overlays/presets';\nimport { conflictsApi } from './conflicts/shell-api';\nimport type { ConflictsApi } from './conflicts/api';\nimport { colorApi } from './color/shell-api';\nimport type { ColorApi } from './color/api';\nimport { loadUserBindings, saveUserBinding } from './actions/bindings-store';\nimport {\n openContextMenu as listenersOpenContextMenu,\n openPalette as listenersOpenPalette,\n type OpenContextMenuOpts,\n type OpenPaletteOpts,\n} from './actions/listeners';\nimport {\n setUserBindings,\n getLiveDispatcherState,\n onActiveChange as onActiveChangeState,\n __notifyActiveChange,\n} from './actions/state.svelte';\nimport { listActions, onActionsChange } from './actions/registry';\nimport { listActiveFromEntries } from './actions/listActive';\nimport type { ActiveActionDescriptor } from './actions/types';\n\n/**\n * The process-wide shell singleton exposed to shards and the shell's own\n * internal code. Provides state zone creation and overlay managers.\n * Shards receive a pre-bound version via `ShardContext` rather than\n * accessing `shell` directly.\n */\nexport interface Shell {\n /**\n * Declare the state zones a shard (or the shell itself) wants to use.\n * Returns a live reactive object per declared zone. Persistent zones\n * are hydrated from the backend before the call returns.\n */\n state<T extends ZoneSchema>(shardId: string, schema: T): StateZones<T>;\n\n /** Stackable, focus-trapped dialogs. See overlays/modal.ts. */\n modal: ModalManager;\n\n /** Anchored, single-item, outside-click-dismissable popups. */\n popup: PopupManager;\n\n /** Auto-dismissing notification toasts. */\n toast: ToastManager;\n\n /** Detached floating panels on overlay layer 1. See overlays/float.ts. */\n float: FloatManager;\n\n /** Named layout presets per app. See overlays/presets.ts. */\n presets: PresetManager;\n\n /** Conflict manager view. Shell-owned modal for conflict arbitration. */\n conflicts: ConflictsApi;\n\n /** Color picker. Falls back to native <input type=\"color\"> when no picker shard is contributed. */\n color: ColorApi;\n\n /** Actions facade — rebind keys, query bindings, open menus/palette. */\n actions: ShellActionsApi;\n}\n\n/**\n * API for managing action bindings and triggering menus/palette\n * programmatically (e.g. from a future settings UI shard).\n */\nexport interface ShellActionsApi {\n /** Persist a custom shortcut for an action and refresh live state if the app is active. */\n rebind(appId: string, actionId: string, shortcut: string | null): Promise<void>;\n /** Remove a custom shortcut override and refresh live state if the app is active. */\n resetBinding(appId: string, actionId: string): Promise<void>;\n /** Return all non-null user bindings for an app as a plain string map. */\n bindingsFor(appId: string): Promise<Record<string, string>>;\n /** Open the context menu at the given screen coordinates. */\n openContextMenu(opts: OpenContextMenuOpts): void;\n /** Open the command palette, optionally pre-filled. */\n openPalette(opts?: OpenPaletteOpts): void;\n /**\n * Snapshot of all currently-active actions with resolved shortcuts\n * and badges. One descriptor per action id, in tier-innermost-first\n * order. See {@link ActiveActionDescriptor}.\n *\n * Non-reactive: returns a fresh array on each call. Subscribe via\n * {@link ShellActionsApi.onActiveChange} to re-call when the active\n * set or shortcuts change.\n */\n listActive(): ActiveActionDescriptor[];\n /**\n * Subscribe to active-set changes: action registration/unregistration,\n * active app / view / focus transitions, selection changes, user\n * binding edits. Returns an unsubscribe function.\n */\n onActiveChange(cb: () => void): () => void;\n}\n\nconst shellActions: ShellActionsApi = {\n async rebind(appId, actionId, shortcut) {\n await saveUserBinding(appId, actionId, shortcut);\n const current = getLiveDispatcherState();\n if (current.activeAppId === appId) {\n setUserBindings(await loadUserBindings(appId));\n }\n },\n async resetBinding(appId, actionId) {\n await saveUserBinding(appId, actionId, undefined);\n const current = getLiveDispatcherState();\n if (current.activeAppId === appId) {\n setUserBindings(await loadUserBindings(appId));\n }\n },\n async bindingsFor(appId) {\n const raw = await loadUserBindings(appId);\n const out: Record<string, string> = {};\n for (const [id, v] of Object.entries(raw)) if (v !== null) out[id] = v;\n return out;\n },\n openContextMenu: listenersOpenContextMenu,\n openPalette: listenersOpenPalette,\n listActive() {\n return listActiveFromEntries(listActions(), getLiveDispatcherState());\n },\n onActiveChange(cb) {\n const offState = onActiveChangeState(cb);\n const offRegistry = onActionsChange(() => { __notifyActiveChange(); });\n return () => {\n offState();\n offRegistry();\n };\n },\n};\n\n/** The process-wide shell instance. Framework-internal code uses this directly; shards receive a scoped view via `ShardContext`. */\nexport const shell: Shell = {\n state: createStateZones,\n modal: modalManager,\n popup: popupManager,\n toast: toastManager,\n float: floatManager,\n presets: presetManager,\n conflicts: conflictsApi,\n color: colorApi,\n actions: shellActions,\n};\n","/*\n * Document zone backends — concrete storage implementations.\n *\n * MemoryDocumentBackend: Map-based, for tests and ephemeral use.\n * IndexedDBDocumentBackend: The web default. Lazy-inits on first\n * operation to avoid blocking bootstrap.\n */\n\nimport type { DocumentBackend, DocumentMeta } from './types';\nimport type { DocStatus } from './sync-types';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction compositeKey(tenantId: string, shardId: string, path: string): string {\n return `${tenantId}/${shardId}/${path}`;\n}\n\nfunction keyPrefix(tenantId: string, shardId: string): string {\n return `${tenantId}/${shardId}/`;\n}\n\n// ---------------------------------------------------------------------------\n// MemoryDocumentBackend\n// ---------------------------------------------------------------------------\n\ninterface MemoryEntry {\n content: string | ArrayBuffer;\n size: number;\n lastModified: number;\n}\n\nexport class MemoryDocumentBackend implements DocumentBackend {\n #store = new Map<string, MemoryEntry>();\n\n async read(\n tenantId: string,\n shardId: string,\n path: string,\n ): Promise<string | ArrayBuffer | null> {\n const entry = this.#store.get(compositeKey(tenantId, shardId, path));\n return entry ? entry.content : null;\n }\n\n async write(\n tenantId: string,\n shardId: string,\n path: string,\n content: string | ArrayBuffer,\n ): Promise<void> {\n const size =\n typeof content === 'string' ? new Blob([content]).size : content.byteLength;\n this.#store.set(compositeKey(tenantId, shardId, path), {\n content,\n size,\n lastModified: Date.now(),\n });\n }\n\n async delete(tenantId: string, shardId: string, path: string): Promise<void> {\n this.#store.delete(compositeKey(tenantId, shardId, path));\n }\n\n async rename(\n tenantId: string,\n shardId: string,\n oldPath: string,\n newPath: string,\n ): Promise<void> {\n const oldKey = compositeKey(tenantId, shardId, oldPath);\n const newKey = compositeKey(tenantId, shardId, newPath);\n const entry = this.#store.get(oldKey);\n if (!entry) {\n throw new Error(`Document not found at ${oldPath}`);\n }\n if (this.#store.has(newKey)) {\n throw new Error(`Document already exists at ${newPath}`);\n }\n this.#store.set(newKey, { ...entry, lastModified: Date.now() });\n this.#store.delete(oldKey);\n }\n\n async list(tenantId: string, shardId: string): Promise<DocumentMeta[]> {\n const prefix = keyPrefix(tenantId, shardId);\n const out: DocumentMeta[] = [];\n for (const [key, entry] of this.#store) {\n if (key.startsWith(prefix)) {\n out.push({\n path: key.slice(prefix.length),\n size: entry.size,\n lastModified: entry.lastModified,\n });\n }\n }\n return out;\n }\n\n async exists(tenantId: string, shardId: string, path: string): Promise<boolean> {\n return this.#store.has(compositeKey(tenantId, shardId, path));\n }\n\n async listAllShards(tenantId: string): Promise<string[]> {\n const prefix = `${tenantId}/`;\n const shards = new Set<string>();\n for (const key of this.#store.keys()) {\n if (!key.startsWith(prefix)) continue;\n const rest = key.slice(prefix.length);\n const slash = rest.indexOf('/');\n if (slash < 0) continue;\n shards.add(rest.slice(0, slash));\n }\n return [...shards];\n }\n\n async listAllDocuments(\n tenantId: string,\n ): Promise<Array<DocumentMeta & { shardId: string }>> {\n const prefix = `${tenantId}/`;\n const out: Array<DocumentMeta & { shardId: string }> = [];\n for (const [key, entry] of this.#store) {\n if (!key.startsWith(prefix)) continue;\n const rest = key.slice(prefix.length);\n const slash = rest.indexOf('/');\n if (slash < 0) continue;\n const shardId = rest.slice(0, slash);\n const path = rest.slice(slash + 1);\n out.push({ shardId, path, size: entry.size, lastModified: entry.lastModified });\n }\n return out;\n }\n\n async readMeta(\n tenantId: string,\n shardId: string,\n path: string,\n ): Promise<DocStatus | null> {\n const entry = this.#store.get(compositeKey(tenantId, shardId, path));\n if (!entry) return null;\n return { exists: true, version: 1, syncMode: 'sync', syncState: 'synced' };\n }\n}\n\n// ---------------------------------------------------------------------------\n// IndexedDBDocumentBackend\n// ---------------------------------------------------------------------------\n\nconst IDB_NAME = 'sh3-documents';\nconst IDB_STORE = 'docs';\nconst IDB_VERSION = 2;\n\ninterface IDBEntry {\n content: string | ArrayBuffer;\n size: number;\n lastModified: number;\n}\n\nexport class IndexedDBDocumentBackend implements DocumentBackend {\n #dbPromise: Promise<IDBDatabase> | null = null;\n\n /**\n * Lazy-open the database on first use. The promise is cached so\n * subsequent calls await the same open.\n */\n #db(): Promise<IDBDatabase> {\n if (!this.#dbPromise) {\n this.#dbPromise = new Promise<IDBDatabase>((resolve, reject) => {\n const req = indexedDB.open(IDB_NAME, IDB_VERSION);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(IDB_STORE)) {\n db.createObjectStore(IDB_STORE);\n }\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n }\n return this.#dbPromise;\n }\n\n /** Run a single-store transaction and return the request result. */\n async #tx<T>(\n mode: IDBTransactionMode,\n fn: (store: IDBObjectStore) => IDBRequest<T>,\n ): Promise<T> {\n const db = await this.#db();\n return new Promise<T>((resolve, reject) => {\n const tx = db.transaction(IDB_STORE, mode);\n const store = tx.objectStore(IDB_STORE);\n const req = fn(store);\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n }\n\n async read(\n tenantId: string,\n shardId: string,\n path: string,\n ): Promise<string | ArrayBuffer | null> {\n const key = compositeKey(tenantId, shardId, path);\n const entry = await this.#tx<IDBEntry | undefined>('readonly', (s) => s.get(key));\n return entry ? entry.content : null;\n }\n\n async write(\n tenantId: string,\n shardId: string,\n path: string,\n content: string | ArrayBuffer,\n ): Promise<void> {\n const key = compositeKey(tenantId, shardId, path);\n const size =\n typeof content === 'string' ? new Blob([content]).size : content.byteLength;\n const entry: IDBEntry = { content, size, lastModified: Date.now() };\n await this.#tx('readwrite', (s) => s.put(entry, key));\n }\n\n async delete(tenantId: string, shardId: string, path: string): Promise<void> {\n const key = compositeKey(tenantId, shardId, path);\n await this.#tx('readwrite', (s) => s.delete(key));\n }\n\n async rename(\n tenantId: string,\n shardId: string,\n oldPath: string,\n newPath: string,\n ): Promise<void> {\n const oldKey = compositeKey(tenantId, shardId, oldPath);\n const newKey = compositeKey(tenantId, shardId, newPath);\n const db = await this.#db();\n return new Promise<void>((resolve, reject) => {\n let aborted = false;\n const tx = db.transaction(IDB_STORE, 'readwrite');\n const store = tx.objectStore(IDB_STORE);\n const getOld = store.get(oldKey);\n getOld.onsuccess = () => {\n const entry = getOld.result as IDBEntry | undefined;\n if (!entry) {\n aborted = true;\n tx.abort();\n reject(new Error(`Document not found at ${oldPath}`));\n return;\n }\n const getNew = store.getKey(newKey);\n getNew.onsuccess = () => {\n if (getNew.result !== undefined) {\n aborted = true;\n tx.abort();\n reject(new Error(`Document already exists at ${newPath}`));\n return;\n }\n const renamed: IDBEntry = { ...entry, lastModified: Date.now() };\n store.put(renamed, newKey);\n store.delete(oldKey);\n };\n getNew.onerror = () => reject(getNew.error);\n };\n getOld.onerror = () => reject(getOld.error);\n tx.oncomplete = () => resolve();\n tx.onerror = () => {\n if (!aborted) reject(tx.error);\n };\n tx.onabort = () => {\n // Already rejected above; swallow.\n };\n });\n }\n\n async list(tenantId: string, shardId: string): Promise<DocumentMeta[]> {\n const prefix = keyPrefix(tenantId, shardId);\n const db = await this.#db();\n return new Promise<DocumentMeta[]>((resolve, reject) => {\n const tx = db.transaction(IDB_STORE, 'readonly');\n const store = tx.objectStore(IDB_STORE);\n // IDBKeyRange.bound selects all keys that start with the prefix.\n // The upper bound appends a character beyond '/' to capture all\n // sub-paths without over-selecting.\n const range = IDBKeyRange.bound(prefix, prefix + '\\uffff', false, false);\n const req = store.openCursor(range);\n const out: DocumentMeta[] = [];\n req.onsuccess = () => {\n const cursor = req.result;\n if (cursor) {\n const entry = cursor.value as IDBEntry;\n out.push({\n path: (cursor.key as string).slice(prefix.length),\n size: entry.size,\n lastModified: entry.lastModified,\n });\n cursor.continue();\n } else {\n resolve(out);\n }\n };\n req.onerror = () => reject(req.error);\n });\n }\n\n async exists(tenantId: string, shardId: string, path: string): Promise<boolean> {\n const key = compositeKey(tenantId, shardId, path);\n // getKey is cheaper than get — avoids deserializing the value.\n const result = await this.#tx<IDBValidKey | undefined>(\n 'readonly',\n (s) => s.getKey(key),\n );\n return result !== undefined;\n }\n\n async listAllShards(tenantId: string): Promise<string[]> {\n const prefix = `${tenantId}/`;\n const db = await this.#db();\n return new Promise<string[]>((resolve, reject) => {\n const tx = db.transaction(IDB_STORE, 'readonly');\n const store = tx.objectStore(IDB_STORE);\n const range = IDBKeyRange.bound(prefix, prefix + '\\uffff', false, false);\n const req = store.openKeyCursor(range);\n const shards = new Set<string>();\n req.onsuccess = () => {\n const cursor = req.result;\n if (cursor) {\n const rest = (cursor.key as string).slice(prefix.length);\n const slash = rest.indexOf('/');\n if (slash >= 0) shards.add(rest.slice(0, slash));\n cursor.continue();\n } else {\n resolve([...shards]);\n }\n };\n req.onerror = () => reject(req.error);\n });\n }\n\n async listAllDocuments(\n tenantId: string,\n ): Promise<Array<DocumentMeta & { shardId: string }>> {\n const prefix = `${tenantId}/`;\n const db = await this.#db();\n return new Promise<Array<DocumentMeta & { shardId: string }>>((resolve, reject) => {\n const tx = db.transaction(IDB_STORE, 'readonly');\n const store = tx.objectStore(IDB_STORE);\n const range = IDBKeyRange.bound(prefix, prefix + '\\uffff', false, false);\n const req = store.openCursor(range);\n const out: Array<DocumentMeta & { shardId: string }> = [];\n req.onsuccess = () => {\n const cursor = req.result;\n if (cursor) {\n const rest = (cursor.key as string).slice(prefix.length);\n const slash = rest.indexOf('/');\n if (slash >= 0) {\n const entry = cursor.value as IDBEntry;\n out.push({\n shardId: rest.slice(0, slash),\n path: rest.slice(slash + 1),\n size: entry.size,\n lastModified: entry.lastModified,\n });\n }\n cursor.continue();\n } else {\n resolve(out);\n }\n };\n req.onerror = () => reject(req.error);\n });\n }\n}\n","/**\n * HTTP document backend — connects to sh3-server's document API.\n *\n * Implements the DocumentBackend interface over HTTP. Every request\n * includes credentials (session cookie) so a logged-in user's tenant\n * identity reaches sh3-server; write operations additionally send the\n * API key as a Bearer token. This is the web-hosted equivalent of the\n * Tauri filesystem backend. Server open-mode (auth.required=false)\n * bypasses tenant checks regardless.\n */\n\nimport type { DocumentBackend, DocumentMeta } from './types';\nimport type { DocStatus } from './sync-types';\n\nexport class HttpDocumentBackend implements DocumentBackend {\n #baseUrl: string;\n #apiKey: string | undefined;\n\n /**\n * @param baseUrl - The server origin (e.g. 'http://localhost:3000' or window.location.origin).\n * @param apiKey - Optional API key for write operations.\n */\n constructor(baseUrl: string, apiKey?: string) {\n // Strip trailing slash\n this.#baseUrl = baseUrl.replace(/\\/$/, '');\n this.#apiKey = apiKey;\n }\n\n async read(\n tenantId: string,\n shardId: string,\n path: string,\n ): Promise<string | ArrayBuffer | null> {\n const url = `${this.#baseUrl}/api/docs/${tenantId}/${shardId}/${path}`;\n const res = await fetch(url, { credentials: 'include' });\n if (res.status === 404) return null;\n if (!res.ok) throw new Error(`Document read failed: ${res.status}`);\n\n const ct = res.headers.get('content-type') ?? '';\n if (ct.includes('application/octet-stream')) {\n return res.arrayBuffer();\n }\n return res.text();\n }\n\n async write(\n tenantId: string,\n shardId: string,\n path: string,\n content: string | ArrayBuffer,\n ): Promise<void> {\n const url = `${this.#baseUrl}/api/docs/${tenantId}/${shardId}/${path}`;\n const headers: Record<string, string> = {\n ...this.#authHeaders(),\n 'Content-Type':\n typeof content === 'string' ? 'text/plain' : 'application/octet-stream',\n };\n const res = await fetch(url, { method: 'PUT', headers, body: content, credentials: 'include' });\n if (!res.ok) throw new Error(`Document write failed: ${res.status}`);\n }\n\n async delete(\n tenantId: string,\n shardId: string,\n path: string,\n ): Promise<void> {\n const url = `${this.#baseUrl}/api/docs/${tenantId}/${shardId}/${path}`;\n const res = await fetch(url, { method: 'DELETE', headers: this.#authHeaders(), credentials: 'include' });\n if (!res.ok) throw new Error(`Document delete failed: ${res.status}`);\n }\n\n async list(tenantId: string, shardId: string): Promise<DocumentMeta[]> {\n const url = `${this.#baseUrl}/api/docs/${tenantId}/${shardId}`;\n const res = await fetch(url, { credentials: 'include' });\n if (!res.ok) throw new Error(`Document list failed: ${res.status}`);\n return res.json();\n }\n\n async exists(\n tenantId: string,\n shardId: string,\n path: string,\n ): Promise<boolean> {\n const url = `${this.#baseUrl}/api/docs/${tenantId}/${shardId}/${path}`;\n const res = await fetch(url, { method: 'HEAD', credentials: 'include' });\n return res.ok;\n }\n\n async listAllShards(tenantId: string): Promise<string[]> {\n const url = `${this.#baseUrl}/api/docs/${tenantId}/_shards`;\n const res = await fetch(url, { credentials: 'include' });\n if (!res.ok) throw new Error(`listAllShards failed: ${res.status}`);\n return res.json();\n }\n\n async listAllDocuments(\n tenantId: string,\n ): Promise<Array<DocumentMeta & { shardId: string }>> {\n const url = `${this.#baseUrl}/api/docs/${tenantId}/_all`;\n const res = await fetch(url, { credentials: 'include' });\n if (!res.ok) throw new Error(`listAllDocuments failed: ${res.status}`);\n return res.json();\n }\n\n async readMeta(\n tenantId: string,\n shardId: string,\n path: string,\n ): Promise<DocStatus | null> {\n const url = `${this.#baseUrl}/api/docs/${tenantId}/${shardId}/${path}?meta=1`;\n const res = await fetch(url, { credentials: 'include' });\n if (!res.ok) throw new Error(`readMeta failed: ${res.status}`);\n const body = await res.json() as DocStatus & { exists: boolean };\n if (!body.exists) return null;\n return body;\n }\n\n async resolve(\n tenantId: string,\n shardId: string,\n path: string,\n choice: 'local' | 'remote' | { origin: string } | string,\n ): Promise<void> {\n const url = `${this.#baseUrl}/api/docs/${tenantId}/${shardId}/${path}/resolve`;\n const body =\n typeof choice === 'string'\n ? { choice }\n : { choice: choice.origin };\n const res = await fetch(url, {\n method: 'POST',\n credentials: 'include',\n headers: { ...this.#authHeaders(), 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n if (!res.ok) throw new Error(`resolve failed: ${res.status}`);\n }\n\n async readBranch(\n tenantId: string,\n shardId: string,\n path: string,\n origin: string,\n ): Promise<string | null> {\n const url = `${this.#baseUrl}/api/docs/${tenantId}/${shardId}/${path}/branch?origin=${encodeURIComponent(origin)}`;\n const res = await fetch(url, { credentials: 'include' });\n if (res.status === 404) return null;\n if (!res.ok) throw new Error(`readBranch failed: ${res.status}`);\n return res.text();\n }\n\n async rename(\n tenantId: string,\n shardId: string,\n oldPath: string,\n newPath: string,\n ): Promise<void> {\n const url = `${this.#baseUrl}/api/docs/${tenantId}/${shardId}/${oldPath}/rename`;\n const headers: Record<string, string> = {\n ...this.#authHeaders(),\n 'Content-Type': 'application/json',\n };\n const res = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify({ to: newPath }),\n credentials: 'include',\n });\n if (res.status === 404) {\n throw new Error(`Document not found at ${oldPath}`);\n }\n if (res.status === 409) {\n throw new Error(`Document already exists at ${newPath}`);\n }\n if (!res.ok) {\n throw new Error(`Document rename failed: ${res.status}`);\n }\n }\n\n #authHeaders(): Record<string, string> {\n if (!this.#apiKey) return {};\n return { Authorization: `Bearer ${this.#apiKey}` };\n }\n}\n","/*\n * Document change notification emitter — in-process pub/sub.\n *\n * A single global emitter connects document handles so that a write\n * from one handle (e.g. an editor shard saving a file) is visible to\n * another handle watching the same scope (e.g. a preview shard).\n *\n * Cross-tab sync (BroadcastChannel) is deferred — this emitter is\n * in-process only.\n */\n\nimport type { DocumentChange } from './types';\n\ntype Listener = (change: DocumentChange) => void;\n\nclass DocumentChangeEmitter {\n #listeners = new Set<Listener>();\n\n subscribe(fn: Listener): () => void {\n this.#listeners.add(fn);\n return () => {\n this.#listeners.delete(fn);\n };\n }\n\n emit(change: DocumentChange): void {\n for (const fn of this.#listeners) {\n try {\n fn(change);\n } catch (e) {\n console.error('SH3: document change listener threw', e);\n }\n }\n }\n}\n\nexport const documentChanges = new DocumentChangeEmitter();\n","/*\n * Document handle — the shard-facing API for the document zone.\n *\n * `createDocumentHandle` binds tenant, shard, backend, and options so\n * shard code only deals in paths. Supports explicit save, autosave\n * with debounce, and change notifications via the global emitter.\n */\n\nimport type {\n DocumentBackend,\n DocumentChange,\n DocumentHandle,\n DocumentHandleOptions,\n DocumentMeta,\n AutosaveController,\n} from './types';\nimport { documentChanges } from './notifications';\n\nconst DEFAULT_DEBOUNCE_MS = 1000;\n\n/**\n * Create a document handle scoped to a tenant, shard, and file filter.\n * The framework calls this from `ShardContext.documents()`.\n */\nexport function createDocumentHandle(\n tenantId: string,\n shardId: string,\n backend: DocumentBackend,\n options: DocumentHandleOptions,\n): DocumentHandle {\n const controllers: Set<AutosaveControllerImpl> = new Set();\n const unsubscribers: Set<() => void> = new Set();\n\n function matchesExtensions(path: string): boolean {\n if (!options.extensions || options.extensions.length === 0) return true;\n return options.extensions.some((ext) => path.endsWith(ext));\n }\n\n function emitChange(type: DocumentChange['type'], path: string): void {\n documentChanges.emit({ type, path, tenantId, shardId });\n }\n\n const handle: DocumentHandle = {\n async list(): Promise<DocumentMeta[]> {\n const all = await backend.list(tenantId, shardId);\n if (!options.extensions || options.extensions.length === 0) return all;\n return all.filter((meta) => matchesExtensions(meta.path));\n },\n\n async read(path: string): Promise<string | null> {\n const content = await backend.read(tenantId, shardId, path);\n if (content === null) return null;\n // Phase 1: text format only. Binary returns as-is from the backend\n // but the handle types it as string for text-format handles.\n return typeof content === 'string' ? content : new TextDecoder().decode(content);\n },\n\n async write(path: string, content: string): Promise<void> {\n const existed = await backend.exists(tenantId, shardId, path);\n await backend.write(tenantId, shardId, path, content);\n emitChange(existed ? 'update' : 'create', path);\n },\n\n async delete(path: string): Promise<void> {\n const existed = await backend.exists(tenantId, shardId, path);\n await backend.delete(tenantId, shardId, path);\n if (existed) emitChange('delete', path);\n },\n\n async rename(oldPath: string, newPath: string): Promise<void> {\n if (!matchesExtensions(newPath)) {\n throw new Error(\n `Cannot rename to ${newPath}: violates handle extensions filter`,\n );\n }\n for (const ctrl of controllers) {\n if (ctrl.path === oldPath) {\n throw new Error(\n `Cannot rename: active autosave on ${oldPath}; flush and dispose first`,\n );\n }\n }\n await backend.rename(tenantId, shardId, oldPath, newPath);\n documentChanges.emit({\n type: 'rename',\n path: newPath,\n oldPath,\n tenantId,\n shardId,\n });\n },\n\n async exists(path: string): Promise<boolean> {\n return backend.exists(tenantId, shardId, path);\n },\n\n async status(path) {\n if (!backend.readMeta) throw new Error('Backend does not support status()');\n return backend.readMeta(tenantId, shardId, path);\n },\n\n async resolveConflict(path, choice) {\n if (!backend.resolve) throw new Error('Backend does not support resolveConflict()');\n if (typeof choice !== 'string' && !(typeof choice === 'object' && 'origin' in choice)) {\n throw new Error('choice must be a string or { origin } object');\n }\n return backend.resolve(tenantId, shardId, path, choice);\n },\n\n async readBranch(path: string, origin: string): Promise<string | null> {\n if (!backend.readBranch) throw new Error('Backend does not support readBranch()');\n return backend.readBranch(tenantId, shardId, path, origin);\n },\n\n watch(callback: (change: DocumentChange) => void): () => void {\n // Subscribe to global emitter, filtered to this handle's scope.\n const unsub = documentChanges.subscribe((change) => {\n if (change.tenantId !== tenantId) return;\n if (change.shardId !== shardId) return;\n if (!matchesExtensions(change.path)) return;\n callback(change);\n });\n unsubscribers.add(unsub);\n return () => {\n unsub();\n unsubscribers.delete(unsub);\n };\n },\n\n autosave(path: string, opts?: { debounceMs?: number }): AutosaveController {\n const ctrl = new AutosaveControllerImpl(\n handle,\n path,\n opts?.debounceMs ?? DEFAULT_DEBOUNCE_MS,\n );\n controllers.add(ctrl);\n return ctrl;\n },\n\n async dispose(): Promise<void> {\n // Flush and dispose all active autosave controllers.\n const flushes = [...controllers].map((c) => c.dispose());\n await Promise.all(flushes);\n controllers.clear();\n // Unsubscribe all watchers.\n for (const unsub of unsubscribers) unsub();\n unsubscribers.clear();\n },\n };\n\n return handle;\n}\n\n// ---------------------------------------------------------------------------\n// AutosaveController implementation\n// ---------------------------------------------------------------------------\n\nclass AutosaveControllerImpl implements AutosaveController {\n #handle: DocumentHandle;\n #path: string;\n #debounceMs: number;\n #pending: string | null = null;\n #timer: ReturnType<typeof setTimeout> | null = null;\n #dirty = false;\n #disposed = false;\n\n constructor(handle: DocumentHandle, path: string, debounceMs: number) {\n this.#handle = handle;\n this.#path = path;\n this.#debounceMs = debounceMs;\n }\n\n get dirty(): boolean {\n return this.#dirty;\n }\n\n /** Path this controller writes to. Exposed so DocumentHandle.rename\n * can refuse if a controller is active on the rename source. */\n get path(): string {\n return this.#path;\n }\n\n update(content: string): void {\n if (this.#disposed) return;\n this.#pending = content;\n this.#dirty = true;\n this.#scheduleFlush();\n }\n\n async flush(): Promise<void> {\n this.#clearTimer();\n if (this.#pending !== null) {\n const content = this.#pending;\n this.#pending = null;\n this.#dirty = false;\n await this.#handle.write(this.#path, content);\n }\n }\n\n async dispose(): Promise<void> {\n if (this.#disposed) return;\n this.#disposed = true;\n await this.flush();\n }\n\n #scheduleFlush(): void {\n this.#clearTimer();\n this.#timer = setTimeout(() => {\n this.#timer = null;\n void this.flush();\n }, this.#debounceMs);\n }\n\n #clearTimer(): void {\n if (this.#timer !== null) {\n clearTimeout(this.#timer);\n this.#timer = null;\n }\n }\n}\n","/*\n * Document zone configuration — module-level singletons.\n *\n * Mirrors the __setBackend pattern in state/zones.svelte.ts. The host\n * calls __setActiveScope and __setDocumentBackend before bootstrap() to\n * configure multi-scope routing and swap backends (e.g. Tauri FS).\n *\n * Defaults: scopeId='local' (single-user self-hosted), backend=IndexedDB.\n */\n\nimport type { DocumentBackend } from './types';\nimport { IndexedDBDocumentBackend } from './backends';\n\nconst DEFAULT_SCOPE = 'local';\n\nlet scopeId: string = DEFAULT_SCOPE;\nlet backend: DocumentBackend = new IndexedDBDocumentBackend();\n\nexport function getActiveScopeId(): string {\n return scopeId;\n}\n\n/** @deprecated use getActiveScopeId — kept until callers migrate. */\nexport function getTenantId(): string {\n return scopeId;\n}\n\nexport function getDocumentBackend(): DocumentBackend {\n return backend;\n}\n\n/** Host-only. Set the active scope id before bootstrap(). */\nexport function __setActiveScope(id: string): void {\n scopeId = id;\n}\n\n/** @deprecated use __setActiveScope — kept until callers migrate. */\nexport function __setTenantId(id: string): void {\n __setActiveScope(id);\n}\n\n/** Host-only. Swap the document backend before bootstrap(). */\nexport function __setDocumentBackend(b: DocumentBackend): void {\n backend = b;\n}\n","/*\n * Sync vocabulary — type-only contract surface (ADR-019 revised 2026-04-19).\n *\n * The sync runtime lives in the installable sh3-sync shard. sh3-core exposes\n * only the types that client shards and the shard-facing ServerShardContext\n * share with the runtime. No runtime code in this file.\n */\n\n/** Server-side sync policy (ADR-019 §9). Lives at {tenant}/__sync__/policy.json. */\nexport interface SyncPolicy {\n /** Schema version. Increment when the rule format changes. */\n version: number;\n /** Mode applied when no rule matches. */\n default: 'sync' | 'local-only';\n /** First-match-wins rules. Glob syntax: `*`, `**`, `?`. No regex. */\n rules: SyncPolicyRule[];\n}\n\nexport interface SyncPolicyRule {\n path: string;\n mode: 'sync' | 'local-only';\n}\n\n/** Per-document status, returned by DocumentHandle.status(). */\nexport interface DocStatus {\n exists: boolean;\n version: number;\n syncMode: 'sync' | 'local-only';\n syncState: 'synced' | 'pending' | 'conflict';\n lastSyncedAt?: number;\n origin?: string;\n deleted?: boolean;\n /** Conflict branches, only populated when syncState === 'conflict'. */\n branches?: Array<{ origin: string; version: number; at: number }>;\n}\n\n/** Conflict file shape under {tenant}/__sync__/conflicts/<shardId>/<path>.conflict.json. */\nexport interface ConflictFile {\n path: string;\n shardId: string;\n branches: ConflictBranch[];\n}\n\nexport interface ConflictBranch {\n origin: string;\n version: number;\n content: string;\n at: number;\n}\n\n/** Server-shard permission: Mode B writes + reserved __sync__ read access. */\nexport const PERMISSION_SYNC_PEER = 'sync:peer';\n\n/** Read/write __sync__/policy.json. Grantable to client or server shards. */\nexport const PERMISSION_SYNC_POLICY = 'sync:policy';\n","/**\n * Client-side auth — session-based identity for SH3.\n *\n * The boot flow (createShell) calls initFromBoot() with the server's\n * boot config. After that, login/logout call the server and update\n * the reactive state. isAdmin/isGuest/isAuthenticated are reactive\n * getters consumed by shell components.\n *\n * .svelte.ts because it uses $state for reactive auth status.\n */\n\nimport type { AuthUser, AuthSession, BootConfig } from './types';\n\n/** Reactive auth state. */\nlet currentUser = $state<AuthUser | null>(null);\nlet currentSession = $state<AuthSession | null>(null);\nlet guest = $state(false);\n\n/** Server base URL, set during boot. */\nlet serverUrl = '';\n\n/** Boot auth policy, captured at initFromBoot. Used by logout() to\n * decide whether a post-logout reload is required to re-run the\n * boot-time hard gate. Non-reactive — no consumer observes this. */\nlet authConfig: BootConfig['auth'] | null = null;\n\n/**\n * Initialize auth from boot config. Called once by createShell()\n * after fetching /api/boot.\n */\nexport function initFromBoot(url: string, config: BootConfig): void {\n serverUrl = url;\n authConfig = config.auth;\n currentUser = config.user;\n currentSession = config.session;\n guest = !config.session && !config.user;\n}\n\n/**\n * Log in with username + password. On success, updates reactive state.\n * Returns { ok: true } or { ok: false, error: string }.\n */\nexport async function login(\n username: string,\n password: string,\n): Promise<{ ok: true } | { ok: false; error: string }> {\n try {\n const res = await fetch(`${serverUrl}/api/auth/login`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify({ username, password }),\n });\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n return { ok: false, error: body.error || 'Login failed' };\n }\n const body = await res.json();\n currentUser = body.user;\n currentSession = body.session;\n guest = false;\n return { ok: true };\n } catch {\n return { ok: false, error: 'Network error' };\n }\n}\n\n/**\n * Register a new account (when self-registration is enabled).\n * On success, auto-logs in and updates reactive state.\n */\nexport async function register(\n username: string,\n password: string,\n displayName?: string,\n): Promise<{ ok: true } | { ok: false; error: string }> {\n try {\n const res = await fetch(`${serverUrl}/api/auth/register`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify({ username, password, displayName }),\n });\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n return { ok: false, error: body.error || 'Registration failed' };\n }\n const body = await res.json();\n currentUser = body.user;\n currentSession = body.session;\n guest = false;\n return { ok: true };\n } catch {\n return { ok: false, error: 'Network error' };\n }\n}\n\n/**\n * Log out — clear session on server and client.\n *\n * If the boot policy forbids guest browsing (auth.required &&\n * !auth.guestAllowed), trigger a full page reload so the boot-time\n * hard gate in createShell.ts re-runs and shows the sign-in wall.\n * This keeps the policy authoritative in a single place rather than\n * duplicating it here.\n */\nexport async function logout(): Promise<void> {\n try {\n await fetch(`${serverUrl}/api/auth/logout`, {\n method: 'POST',\n credentials: 'include',\n });\n } catch {\n // Best effort\n }\n\n if (authConfig?.required && !authConfig.guestAllowed) {\n // Policy forbids guest browsing — re-run the boot-time hard gate.\n // Do not touch reactive state: the page is leaving.\n window.location.reload();\n return;\n }\n\n currentUser = null;\n currentSession = null;\n guest = true;\n}\n\n/**\n * Mark this session as local-owner — auto-elevate to admin without\n * server verification. Called by the host in Tauri / dev environments.\n */\nexport function setLocalOwner(): void {\n currentUser = {\n id: 'local',\n username: 'local',\n displayName: 'Local Owner',\n role: 'admin',\n createdAt: '',\n updatedAt: '',\n };\n currentSession = {\n token: 'local',\n userId: 'local',\n role: 'admin',\n expiresAt: Infinity,\n };\n guest = false;\n}\n\n/** Reactive — true when running as local owner (Tauri / dev). */\nexport function isLocalOwner(): boolean {\n return currentSession?.token === 'local';\n}\n\n/** Reactive — true when the user has admin role. */\nexport function isAdmin(): boolean {\n return currentSession?.role === 'admin';\n}\n\n/** Reactive — true when the user has a valid session. */\nexport function isAuthenticated(): boolean {\n return currentSession !== null;\n}\n\n/** Reactive — true when browsing without a session. */\nexport function isGuest(): boolean {\n return guest;\n}\n\n/** Get the current user (reactive). */\nexport function getUser(): AuthUser | null {\n return currentUser;\n}\n\n/** Get the current session (reactive). */\nexport function getSession(): AuthSession | null {\n return currentSession;\n}\n\n/**\n * Build an Authorization header value for authenticated fetch calls\n * that need explicit headers (e.g. non-cookie contexts).\n * Returns null if not authenticated.\n */\nexport function getAuthHeader(): string | null {\n return currentSession ? `Bearer ${currentSession.token}` : null;\n}\n","/**\n * Env state client — fetches and updates per-shard environment state\n * from the server.\n */\n\nimport { getAuthHeader, isAdmin } from '../auth/index';\n\n/** Server base URL, set once during configuration. */\nlet serverUrl = '';\n\n/** Configure the server URL for env state operations. */\nexport function __setEnvServerUrl(url: string): void {\n serverUrl = url;\n}\n\n/** Return the configured server URL. */\nexport function getEnvServerUrl(): string {\n return serverUrl;\n}\n\n/**\n * Fetch env state for a shard from the server.\n * Returns an empty object if the server has no stored state.\n */\nexport async function fetchEnvState(shardId: string): Promise<Record<string, unknown>> {\n const res = await fetch(`${serverUrl}/api/env-state/${encodeURIComponent(shardId)}`);\n if (!res.ok) {\n console.warn(`[sh3] Failed to fetch env state for \"${shardId}\": HTTP ${res.status}`);\n return {};\n }\n return await res.json();\n}\n\n/**\n * Write env state for a shard to the server. Requires admin auth.\n * Throws if not admin or if the server rejects the write.\n */\nexport async function putEnvState(shardId: string, state: Record<string, unknown>): Promise<void> {\n if (!isAdmin()) {\n throw new Error('Cannot update env state: not elevated to admin');\n }\n\n const auth = getAuthHeader();\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (auth) headers['Authorization'] = auth;\n\n const res = await fetch(`${serverUrl}/api/env-state/${encodeURIComponent(shardId)}`, {\n method: 'PUT',\n headers,\n body: JSON.stringify(state),\n });\n\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n throw new Error(`Env state update failed: HTTP ${res.status} — ${(body as Record<string, string>).error ?? 'unknown'}`);\n }\n}\n\n/** Result shape returned by {@link serverInstallPackage}. */\nexport interface ServerInstallResult {\n ok: boolean;\n error?: string;\n code?: string;\n missing?: Array<{ id: string }>;\n}\n\n/**\n * Install a package on the server via multipart upload.\n * The client has already fetched and integrity-verified the client bundle\n * (and the server bundle, if present and serverIntegrity was declared).\n *\n * @param manifest - Package manifest metadata to persist server-side.\n * @param clientBundle - Verified client ESM bundle bytes.\n * @param serverBundle - Optional verified server ESM bundle bytes. When\n * provided, the server writes it to `server.js` and hot-mounts the\n * shard's routes. If the mount fails, the entire install is rolled\n * back server-side.\n */\nexport async function serverInstallPackage(\n manifest: Record<string, unknown>,\n clientBundle: ArrayBuffer,\n serverBundle?: ArrayBuffer,\n): Promise<ServerInstallResult> {\n if (!isAdmin()) throw new Error('Cannot install: not elevated to admin');\n\n const auth = getAuthHeader();\n const form = new FormData();\n form.append('manifest', new Blob([JSON.stringify(manifest)], { type: 'application/json' }), 'manifest.json');\n form.append('client', new Blob([clientBundle], { type: 'application/javascript' }), 'client.js');\n if (serverBundle !== undefined) {\n form.append('server', new Blob([serverBundle], { type: 'application/javascript' }), 'server.js');\n }\n\n const headers: Record<string, string> = {};\n if (auth) headers['Authorization'] = auth;\n\n const res = await fetch(`${serverUrl}/api/packages/install`, {\n method: 'POST',\n headers,\n body: form,\n });\n\n if (!res.ok) {\n let body: Record<string, unknown> = {};\n try { body = await res.json(); } catch { /* non-JSON */ }\n return {\n ok: false,\n error: typeof body.error === 'string' ? body.error : `HTTP ${res.status}`,\n code: typeof body.code === 'string' ? body.code : undefined,\n missing: Array.isArray(body.missing) ? (body.missing as Array<{ id: string }>) : undefined,\n };\n }\n return { ok: true };\n}\n\n/**\n * Uninstall a package from the server.\n */\nexport async function serverUninstallPackage(id: string): Promise<void> {\n if (!isAdmin()) throw new Error('Cannot uninstall: not elevated to admin');\n\n const auth = getAuthHeader();\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (auth) headers['Authorization'] = auth;\n\n const res = await fetch(`${serverUrl}/api/packages/uninstall`, {\n method: 'POST',\n headers,\n body: JSON.stringify({ id }),\n });\n\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n throw new Error(`Uninstall failed: HTTP ${res.status} — ${(body as Record<string, string>).error ?? 'unknown'}`);\n }\n}\n\n/**\n * Fetch the list of packages installed on the server.\n */\nexport async function fetchServerPackages(): Promise<Array<{\n id: string;\n type: string;\n label: string;\n version: string;\n bundleUrl: string;\n sourceRegistry?: string;\n contractVersion?: string;\n installedAt?: string;\n}>> {\n const res = await fetch(`${serverUrl}/api/packages`);\n if (!res.ok) return [];\n return await res.json();\n}\n","/*\n * Zone management — public wrappers over the private backends for\n * cross-shard state inspection and cleanup.\n *\n * These functions are not part of the shard-facing API directly.\n * They are consumed by `createZoneManager()` which builds the\n * `ZoneManager` object conditionally attached to contexts when\n * the manifest declares the `state:manage` permission.\n */\n\nimport { backends } from './zones.svelte';\nimport type { ZoneName, ZoneManager } from './types';\n\n/** Return all shard IDs that have data in the given zone. */\nexport function listZoneEntries(zone: ZoneName): string[] {\n return backends[zone].list();\n}\n\n/** Read a raw zone entry without creating a reactive proxy. */\nexport function peekZoneEntry(zone: ZoneName, shardId: string): unknown | undefined {\n return backends[zone].read(shardId);\n}\n\n/** Delete one shard's data from a zone. */\nexport function clearZoneEntry(zone: ZoneName, shardId: string): void {\n backends[zone].delete(shardId);\n}\n\n/** Delete all entries in a zone. Safe because `list()` returns a snapshot array. */\nexport function clearAllZoneEntries(zone: ZoneName): void {\n for (const id of backends[zone].list()) {\n backends[zone].delete(id);\n }\n}\n\n/**\n * Build a `ZoneManager` object. Called by context factories when the\n * manifest declares the `state:manage` permission.\n */\nexport function createZoneManager(): ZoneManager {\n return {\n list: listZoneEntries,\n peek: peekZoneEntry,\n clear: clearZoneEntry,\n clearAll: clearAllZoneEntries,\n };\n}\n","/*\n * Document zone types — the file-oriented storage subsystem.\n *\n * Unlike the KV state zones (workspace/user) which store opaque blobs\n * per shard, the document zone deals in named files: read, write, list,\n * watch. Every operation is tenant-scoped for multi-user isolation and\n * async because file I/O is inherently async regardless of backend.\n *\n * The document zone is a parallel subsystem — it does not extend\n * ZoneName or ZoneSchema. Shards access it via `ctx.documents()`.\n */\n\n/**\n * Manifest permission string: grants tenant-wide document observation\n * via `ctx.browse` (read-only enumeration and change subscription across\n * every shard's documents for the active tenant). Writes still flow\n * through the owning shard's own `ctx.documents()` handle.\n */\nexport const PERMISSION_DOCUMENTS_BROWSE = 'documents:browse';\n\n/**\n * Manifest permission string: grants the shard the ability to read\n * document content from any shard's namespace within the active tenant\n * via `ctx.browse.readFrom(shardId, path)`. Requires `documents:browse`\n * in the same manifest — the read surface hangs off `ctx.browse`, which\n * only exists when `browse` is granted.\n *\n * `documents:browse` alone is metadata-only (listDocuments, listShards,\n * watchDocuments). `documents:read` is the separate content-read gate so\n * observer shards granted `browse` today do not silently gain content\n * access.\n *\n * Tenant-scoped: reads cannot cross tenants.\n */\nexport const PERMISSION_DOCUMENTS_READ = 'documents:read';\n\n/**\n * Manifest permission string: grants the shard the ability to write\n * documents into any shard's namespace within the active tenant via\n * `ctx.browse.writeTo(shardId, path, content)`. Requires\n * `documents:browse` in the same manifest — the write surface hangs off\n * `ctx.browse`, which only exists when `browse` is granted.\n *\n * Tenant-scoped: writes cannot cross tenants. A shard declaring\n * `browse` + `write` can overwrite any document owned by any shard in\n * the current tenant, which is why the install-time consent modal\n * surfaces this as a distinct line item rather than folding it into\n * `browse`.\n */\nexport const PERMISSION_DOCUMENTS_WRITE = 'documents:write';\n\n/**\n * Format hint for document content. Determines whether reads return a string\n * (`text`) or an `ArrayBuffer` (`binary`).\n */\nexport type DocumentFormat = 'text' | 'binary';\n\n/**\n * Options passed to `ctx.documents()` to scope the handle. The handle\n * only operates on files matching the declared extensions (if provided).\n * Omitting `extensions` means \"all files.\"\n */\nexport interface DocumentHandleOptions {\n format: DocumentFormat;\n /** File extensions this handle operates on, e.g. ['.guml', '.md']. */\n extensions?: string[];\n}\n\n/** Metadata about a stored document. */\nexport interface DocumentMeta {\n path: string;\n size: number;\n /** Last modified timestamp in epoch milliseconds. */\n lastModified: number;\n\n // --- Sync-aware fields (ADR-019). All optional for backward compat.\n // sh3-server populates on every Mode A / Mode B write; older docs\n // without these fields are treated as version=1, syncState=synced.\n /** Monotonic per-document version; primary-authoritative. */\n version?: number;\n /** 'sync' or 'local-only', cached from policy.json at write time. */\n syncMode?: 'sync' | 'local-only';\n /** 'synced' | 'pending' | 'conflict'. */\n syncState?: 'synced' | 'pending' | 'conflict';\n /** Replica's view of primary's version at last confirmed sync. */\n lastKnownVersion?: number;\n /** Epoch ms; when replica/primary last agreed on content. */\n lastSyncedAt?: number;\n /** Peer id that produced this content (set by Mode B). */\n origin?: string;\n /** Tombstone marker for deleted docs. */\n deleted?: boolean;\n}\n\n/** Change notification payload delivered to watch callbacks. */\nexport interface DocumentChange {\n type: 'create' | 'update' | 'delete' | 'rename';\n /**\n * For 'create' / 'update' / 'delete', the affected document path.\n * For 'rename', the new path the document now lives at.\n */\n path: string;\n /**\n * Populated only when type === 'rename'. The path the document\n * used to live at before the rename.\n */\n oldPath?: string;\n tenantId: string;\n shardId: string;\n}\n\n/** Type guard: narrows a DocumentChange to the rename variant. */\nexport function isRename(\n change: DocumentChange,\n): change is DocumentChange & { type: 'rename'; oldPath: string } {\n return change.type === 'rename';\n}\n\nimport type { DocStatus } from './sync-types';\n\n/**\n * File-oriented backend for the document zone.\n *\n * Every method is tenant- and shard-scoped. The backend is responsible\n * for enforcing isolation: a read for tenant A must never return\n * content belonging to tenant B.\n *\n * Logical storage namespace: /{tenantId}/{shardId}/{path}\n */\nexport interface DocumentBackend {\n /**\n * Read a document. Returns the content string (text format) or ArrayBuffer\n * (binary format), or null if the document does not exist.\n */\n read(\n tenantId: string,\n shardId: string,\n path: string,\n ): Promise<string | ArrayBuffer | null>;\n\n /** Write (create or overwrite) a document with the given content. */\n write(\n tenantId: string,\n shardId: string,\n path: string,\n content: string | ArrayBuffer,\n ): Promise<void>;\n\n /** Delete a document. No-op if the document does not exist. */\n delete(tenantId: string, shardId: string, path: string): Promise<void>;\n\n /**\n * Rename a document within a single shard's namespace. Atomic at the\n * backend's storage tier. Throws if newPath already exists or if oldPath\n * does not. Single-document only — does not interpret trailing slashes\n * as folder semantics.\n */\n rename(\n tenantId: string,\n shardId: string,\n oldPath: string,\n newPath: string,\n ): Promise<void>;\n\n /** List all documents stored for this tenant + shard combination. */\n list(tenantId: string, shardId: string): Promise<DocumentMeta[]>;\n\n /** Return true if the document at `path` exists. */\n exists(tenantId: string, shardId: string, path: string): Promise<boolean>;\n\n /**\n * List every shard id that currently has at least one document stored\n * for this tenant. Tenant-wide observation primitive.\n */\n listAllShards(tenantId: string): Promise<string[]>;\n\n /**\n * List every document in the tenant across all shards. Each entry\n * carries the owning `shardId`. Tenant-wide observation primitive.\n */\n listAllDocuments(tenantId: string): Promise<Array<DocumentMeta & { shardId: string }>>;\n\n /**\n * Read sync-state metadata for a doc without fetching content.\n * Returns null if the doc does not exist. Optional because only\n * sync-aware backends (HttpDocumentBackend) support it.\n */\n readMeta?(tenantId: string, shardId: string, path: string): Promise<DocStatus | null>;\n\n /**\n * Resolve a conflict by picking a branch or supplying fresh content.\n * Optional; only supported by HttpDocumentBackend in v1.\n */\n resolve?(\n tenantId: string,\n shardId: string,\n path: string,\n choice: 'local' | 'remote' | { origin: string } | string,\n ): Promise<void>;\n\n /**\n * Read the content of a specific conflict branch without committing it.\n * Returns null if the doc is not in conflict state or the origin is not\n * among the branches. Phase-1 text-only (matches `read` for text docs).\n * Optional; only supported by HttpDocumentBackend in v1.\n */\n readBranch?(\n tenantId: string,\n shardId: string,\n path: string,\n origin: string,\n ): Promise<string | null>;\n}\n\n/**\n * Shard-facing document handle returned by `ctx.documents()`. Binds\n * the tenant, shard, and backend so shard code only deals in paths.\n */\nexport interface DocumentHandle {\n /** List documents matching the handle's extensions filter. */\n list(): Promise<DocumentMeta[]>;\n\n /** Read a document by path. Returns null if not found. */\n read(path: string): Promise<string | null>;\n\n /** Write (create or overwrite) a document. Explicit save. */\n write(path: string, content: string): Promise<void>;\n\n /** Delete a document. */\n delete(path: string): Promise<void>;\n\n /**\n * Rename a document. Throws if there is an active autosave controller\n * for oldPath (caller must flush and dispose first). Throws if newPath\n * already exists or if oldPath does not. Subject to the handle's\n * extensions filter — newPath must satisfy the filter.\n */\n rename(oldPath: string, newPath: string): Promise<void>;\n\n /** Check existence without reading content. */\n exists(path: string): Promise<boolean>;\n\n /** Fetch sync-state metadata for a path. Null if the doc does not exist. */\n status(path: string): Promise<DocStatus | null>;\n\n /**\n * Resolve a conflict. `'local'` keeps the local branch; any other\n * origin string picks the named branch from the conflict bucket.\n */\n resolveConflict(\n path: string,\n choice: 'local' | 'remote' | { origin: string } | string,\n ): Promise<void>;\n\n /**\n * Read the content of a specific conflict branch without committing it.\n * Used by the conflict manager view to populate per-branch preview.\n * Returns null if not in conflict or origin not among branches.\n * Throws if the backend does not support branch reads.\n */\n readBranch(path: string, origin: string): Promise<string | null>;\n\n /**\n * Subscribe to change notifications within this handle's scope.\n * Returns an unsubscribe function.\n */\n watch(callback: (change: DocumentChange) => void): () => void;\n\n /**\n * Enable autosave for a document. Returns a controller that accepts\n * content updates and debounces writes to the backend.\n */\n autosave(path: string, options?: { debounceMs?: number }): AutosaveController;\n\n /**\n * Flush all active autosave controllers and release resources.\n * Called by the framework on shard deactivation.\n */\n dispose(): Promise<void>;\n}\n\n/** Controller for autosaved documents. */\nexport interface AutosaveController {\n /** Feed new content. A debounced write is scheduled automatically. */\n update(content: string): void;\n\n /** Force an immediate flush of pending content. */\n flush(): Promise<void>;\n\n /** Stop autosaving. Flushes pending content first. */\n dispose(): Promise<void>;\n\n /** Whether there are unflushed changes. */\n readonly dirty: boolean;\n}\n","/*\n * BrowseCapability — tenant-wide document observation surface.\n *\n * Exposed on ShardContext as `ctx.browse` when the shard declares the\n * 'documents:browse' permission. Read-only: writes still flow through\n * the owning shard's own ctx.documents() handle.\n */\n\nimport type { DocumentBackend, DocumentChange, DocumentMeta } from './types';\nimport type { DocStatus } from './sync-types';\nimport { documentChanges } from './notifications';\n\nexport interface BrowseCapability {\n /** Every document in the tenant across all shards, each tagged with its owning shardId. */\n listDocuments(): Promise<Array<DocumentMeta & { shardId: string }>>;\n /** Subscribe to tenant-wide document changes. Returns an unsubscribe. */\n watchDocuments(callback: (change: DocumentChange) => void): () => void;\n /** Enumerate shard ids with at least one document in the tenant. */\n listShards(): Promise<string[]>;\n\n /**\n * Read content from any shard's document namespace within the active\n * tenant. Available only when the caller declares both\n * `documents:browse` and `documents:read`. Returns the content string\n * (text-format docs), ArrayBuffer (binary-format docs), or null if the\n * document does not exist. Tenant-scoped — cannot cross tenants.\n *\n * Absent (undefined) on the capability object when `documents:read`\n * is not declared; feature-detect with\n * `typeof ctx.browse.readFrom === 'function'`.\n */\n readFrom?(shardId: string, path: string): Promise<string | ArrayBuffer | null>;\n\n /**\n * Write content into any shard's document namespace within the active\n * tenant. Available only when the caller declares both\n * `documents:browse` and `documents:write`. Emits a normal\n * `DocumentChange` so other shards and the file-explorer pick up the\n * new or updated document. Tenant-scoped — cannot cross tenants.\n *\n * Absent (undefined) on the capability object when `documents:write`\n * is not declared; feature-detect with\n * `typeof ctx.browse.writeTo === 'function'`.\n */\n writeTo?(shardId: string, path: string, content: string | ArrayBuffer): Promise<void>;\n\n /**\n * Read sync-state metadata for any shard's document in the active\n * tenant. Available only when the caller declares both\n * `documents:browse` and `documents:read`. Returns null when the doc\n * does not exist or the backend does not support status reads.\n *\n * Absent (undefined) on the capability object when `documents:read`\n * is not declared.\n */\n statusFrom?(shardId: string, path: string): Promise<DocStatus | null>;\n\n /**\n * Read a single conflict branch's content for any shard's document in\n * the active tenant. Gated identically to `statusFrom`. Returns null\n * when the doc isn't in conflict, the origin isn't among branches, or\n * the backend does not support branch reads.\n */\n readBranchFrom?(shardId: string, path: string, origin: string): Promise<string | null>;\n\n /**\n * Resolve a conflict on any shard's document in the active tenant.\n * Available only when the caller declares both `documents:browse` and\n * `documents:write`. Emits a `DocumentChange` update event on success.\n */\n resolveConflictFrom?(\n shardId: string,\n path: string,\n choice: 'local' | 'remote' | { origin: string } | string,\n ): Promise<void>;\n\n /**\n * Rename a document in another shard's namespace within the active\n * tenant. Available only when the caller declares both\n * `documents:browse` and `documents:write`. Emits a `'rename'`\n * `DocumentChange` so other shards and the file-explorer pick up\n * the move. Tenant-scoped — cannot cross tenants.\n *\n * The optional `opts.newShardId` parameter is reserved for a future\n * cross-shard move operation per ADR-018 amendment 2026-04-27 and\n * throws at runtime if provided.\n *\n * Absent (undefined) on the capability object when `documents:write`\n * is not declared; feature-detect with\n * `typeof ctx.browse.renameFrom === 'function'`.\n */\n renameFrom?(\n shardId: string,\n oldPath: string,\n newPath: string,\n opts?: { newShardId?: string },\n ): Promise<void>;\n\n /**\n * Delete a document in another shard's namespace within the active\n * tenant. Available only when the caller declares both\n * `documents:browse` and `documents:write`. Emits a `'delete'`\n * `DocumentChange` so other shards and the file-explorer pick up\n * the removal. Tenant-scoped — cannot cross tenants.\n *\n * Idempotent: deleting a non-existent path resolves successfully\n * and emits no change event.\n *\n * Absent (undefined) on the capability object when `documents:write`\n * is not declared; feature-detect with\n * `typeof ctx.browse.deleteFrom === 'function'`.\n */\n deleteFrom?(shardId: string, path: string): Promise<void>;\n}\n\nexport interface BrowseCapabilityOptions {\n /** When true, the returned capability exposes `readFrom`. */\n canRead: boolean;\n /** When true, the returned capability exposes `writeTo`. */\n canWrite: boolean;\n}\n\nexport function createBrowseCapability(\n tenantId: string,\n backend: DocumentBackend,\n options: BrowseCapabilityOptions = { canRead: false, canWrite: false },\n): BrowseCapability {\n const capability: BrowseCapability = {\n listDocuments: () => backend.listAllDocuments(tenantId),\n listShards: () => backend.listAllShards(tenantId),\n watchDocuments: (callback) =>\n documentChanges.subscribe((change) => {\n if (change.tenantId !== tenantId) return;\n callback(change);\n }),\n };\n\n if (options.canRead) {\n capability.readFrom = (shardId, path) => backend.read(tenantId, shardId, path);\n capability.statusFrom = async (shardId, path) => {\n if (!backend.readMeta) return null;\n return backend.readMeta(tenantId, shardId, path);\n };\n capability.readBranchFrom = async (shardId, path, origin) => {\n if (!backend.readBranch) return null;\n return backend.readBranch(tenantId, shardId, path, origin);\n };\n }\n\n if (options.canWrite) {\n capability.writeTo = async (shardId, path, content) => {\n const existed = await backend.exists(tenantId, shardId, path);\n await backend.write(tenantId, shardId, path, content);\n documentChanges.emit({\n type: existed ? 'update' : 'create',\n path,\n tenantId,\n shardId,\n });\n };\n capability.resolveConflictFrom = async (shardId, path, choice) => {\n if (!backend.resolve) throw new Error('Backend does not support resolveConflict');\n await backend.resolve(tenantId, shardId, path, choice);\n documentChanges.emit({ type: 'update', path, tenantId, shardId });\n };\n capability.renameFrom = async (shardId, oldPath, newPath, opts) => {\n if (opts?.newShardId !== undefined) {\n throw new Error(\n 'Cross-shard move is not yet supported (ADR-018 amendment 2026-04-27)',\n );\n }\n await backend.rename(tenantId, shardId, oldPath, newPath);\n documentChanges.emit({\n type: 'rename',\n path: newPath,\n oldPath,\n tenantId,\n shardId,\n });\n };\n capability.deleteFrom = async (shardId, path) => {\n const existed = await backend.exists(tenantId, shardId, path);\n await backend.delete(tenantId, shardId, path);\n if (existed) {\n documentChanges.emit({ type: 'delete', path, tenantId, shardId });\n }\n };\n }\n\n return capability;\n}\n","export const PERMISSION_KEYS_MINT = 'keys:mint';\n\nexport interface ApiKeyPublic {\n id: string;\n label: string;\n tenantId: string | null;\n ownerUserId: string | null;\n mintedByShardId: string | null;\n scopes: string[];\n peerRole?: 'primary' | 'replica';\n peerId?: string;\n createdAt: string;\n expiresAt?: string;\n}\n\nexport interface MintOpts {\n label: string;\n scopes: string[];\n peerRole?: 'primary' | 'replica';\n peerId?: string;\n expiresIn?: number;\n}\n\nexport interface ShardContextKeys {\n mint(opts: MintOpts): Promise<{ id: string; key: string }>;\n list(): Promise<ApiKeyPublic[]>;\n revoke(id: string): Promise<void>;\n}\n\nexport class ScopeEscalationError extends Error {\n constructor(scope: string) {\n super(`Shard may not mint a key with scope '${scope}' — not declared in manifest.`);\n this.name = 'ScopeEscalationError';\n }\n}\n\nexport class ConsentDeniedError extends Error {\n constructor() {\n super('User denied key creation.');\n this.name = 'ConsentDeniedError';\n }\n}\n","/**\n * Shell-owned consent runtime — only place that can approve or deny a mint.\n *\n * The client shard calls requestConsent(); the shell shows ConsentDialog.svelte\n * and calls resolveConsent(...) on user action.\n */\n\nimport type { MintOpts } from './types';\n\nexport interface ConsentRequest extends MintOpts {\n requestId: string;\n shardId: string;\n}\n\ntype Listener = (req: ConsentRequest) => void;\n\nconst pending = new Map<string, {\n resolve: (approved: boolean) => void;\n}>();\n\nlet listener: Listener | null = null;\n\nexport function registerConsentListener(fn: Listener): () => void {\n listener = fn;\n return () => { if (listener === fn) listener = null; };\n}\n\nexport async function requestConsent(shardId: string, opts: MintOpts): Promise<boolean> {\n if (!listener) throw new Error('No consent listener registered — the shell must mount ConsentDialog.');\n const requestId = `c_${Math.random().toString(36).slice(2)}${Date.now()}`;\n return new Promise<boolean>((resolve) => {\n pending.set(requestId, { resolve });\n listener!({ ...opts, shardId, requestId });\n });\n}\n\nexport function resolveConsent(requestId: string, approved: boolean): void {\n const entry = pending.get(requestId);\n if (!entry) return;\n pending.delete(requestId);\n entry.resolve(approved);\n}\n","/**\n * Notifies active shards when one of their minted keys is revoked —\n * regardless of whether the revocation was initiated by the shell UI,\n * the shard itself, or another tab.\n *\n * The bus is populated by a server-sent events stream on /api/keys/events\n * (wired by the shell runtime at boot) and/or by local revoke() calls.\n */\n\ntype Handler = (keyId: string) => void;\n\nconst handlersByShard = new Map<string, Set<Handler>>();\n\n/**\n * Recently-emitted (shardId → Set<keyId>) with per-entry TTL timers.\n * Prevents double-firing when a local emit() is followed by the same\n * event arriving via SSE (or vice-versa) within the dedup window.\n */\nconst recentByShard = new Map<string, Set<string>>();\nconst DEDUP_TTL_MS = 5_000;\n\nfunction markRecent(shardId: string, keyId: string): void {\n let set = recentByShard.get(shardId);\n if (!set) { set = new Set(); recentByShard.set(shardId, set); }\n set.add(keyId);\n setTimeout(() => {\n set!.delete(keyId);\n if (set!.size === 0) recentByShard.delete(shardId);\n }, DEDUP_TTL_MS);\n}\n\nfunction isRecent(shardId: string, keyId: string): boolean {\n return recentByShard.get(shardId)?.has(keyId) ?? false;\n}\n\n/**\n * Subscribe to revocation events for a specific shard, or for all shards\n * by passing `'*'` as the shardId.\n * Returns an unsubscribe function.\n */\nexport function subscribe(shardId: string | '*', handler: Handler): () => void {\n const set = handlersByShard.get(shardId) ?? new Set();\n set.add(handler);\n handlersByShard.set(shardId, set);\n return () => { set.delete(handler); };\n}\n\n/**\n * Emit a revocation event for the given shardId.\n * No-op if shardId is null or has no subscribers.\n * Deduplicates events: if the same (shardId, keyId) pair was already emitted\n * within the last 5 s it is silently dropped (covers local-then-SSE and\n * SSE-then-local orderings).\n * Internal use only — called by client.ts and the SSE stream bootstrap.\n */\nexport function emit(shardId: string | null, keyId: string): void {\n if (!shardId) return;\n if (isRecent(shardId, keyId)) return;\n markRecent(shardId, keyId);\n const set = handlersByShard.get(shardId);\n if (set) for (const h of set) h(keyId);\n const star = handlersByShard.get('*');\n if (star) for (const h of star) h(keyId);\n}\n\n/**\n * Open a server-sent events stream at /api/keys/events and forward\n * revocation events into the local bus.\n *\n * Should be called once at shell boot. Returns a cleanup function that\n * closes the EventSource.\n *\n * No-op in environments without EventSource (e.g. Node test runner).\n */\nexport function startServerSideStream(): () => void {\n if (typeof EventSource === 'undefined') return () => {};\n const es = new EventSource('/api/keys/events', { withCredentials: true } as EventSourceInit);\n es.onmessage = (msg) => {\n try {\n const ev = JSON.parse(msg.data) as { id: string; shardId: string | null };\n emit(ev.shardId, ev.id);\n } catch {\n // Ignore malformed messages.\n }\n };\n return () => es.close();\n}\n","/**\n * Client-side ctx.keys factory. Calls /api/keys endpoints with the current\n * session cookie (no bearer token — session auth is the only supported\n * principal for this API).\n *\n * The shard's manifest permissions are enforced here (scope subset check)\n * before the consent dialog is even shown.\n */\n\nimport type { ApiKeyPublic, MintOpts, ShardContextKeys } from './types';\nimport { ConsentDeniedError, ScopeEscalationError } from './types';\nimport { requestConsent } from './consent.svelte';\nimport { emit } from './revocation-bus.svelte';\n\nexport function createShardKeysApi(params: {\n shardId: string;\n shardPermissions: string[];\n}): ShardContextKeys {\n const { shardId, shardPermissions } = params;\n\n const assertScopesSubset = (scopes: string[]) => {\n for (const s of scopes) {\n if (!shardPermissions.includes(s) && !shardPermissions.includes('admin:*')) {\n throw new ScopeEscalationError(s);\n }\n }\n };\n\n return {\n async mint(opts: MintOpts) {\n assertScopesSubset(opts.scopes);\n const approved = await requestConsent(shardId, opts);\n if (!approved) throw new ConsentDeniedError();\n const ticketRes = await fetch('/api/keys/consent', {\n method: 'POST',\n credentials: 'include',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ shardId, ...opts }),\n });\n if (!ticketRes.ok) throw new Error(`Consent ticket failed: ${ticketRes.status}`);\n const { ticket } = await ticketRes.json();\n const mintRes = await fetch('/api/keys', {\n method: 'POST',\n credentials: 'include',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ ticket }),\n });\n if (!mintRes.ok) throw new Error(`Mint failed: ${mintRes.status}`);\n return mintRes.json();\n },\n async list() {\n const res = await fetch('/api/keys', { credentials: 'include' });\n if (!res.ok) throw new Error(`List failed: ${res.status}`);\n const all = (await res.json()) as ApiKeyPublic[];\n return all.filter((k) => k.mintedByShardId === shardId);\n },\n async revoke(id: string) {\n const res = await fetch(`/api/keys/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n credentials: 'include',\n });\n if (!res.ok && res.status !== 404) throw new Error(`Revoke failed: ${res.status}`);\n // Notify local bus immediately so the owning shard's onKeyRevoked fires\n // even if the SSE stream hasn't delivered the server-side echo yet.\n emit(shardId, id);\n },\n };\n}\n","/*\n * Shard lifecycle — phase 8 split into register and activate.\n *\n * registerShard(shard): adds the shard's manifest to the reactive\n * `registeredShards` map. No side effects. The host (main.ts) calls\n * this once per shard via its glob-discovery boot loop. A future\n * runtime loader calls it after fetching a shard module.\n *\n * activateShard(id): looks up a registered shard, builds its\n * ShardContext, runs `activate(ctx)`, verifies every manifest view id\n * received a factory, then runs `autostart(ctx)` if present. The shard\n * moves into the reactive `activeShards` map. Called internally by\n * app launch and by the bootstrap self-starting pass. Not public.\n *\n * deactivateShard(id): inverse of activate. Calls `deactivate()`,\n * unregisters view factories, drops from `activeShards`. The shard\n * stays in `registeredShards` — it's still known, just not running.\n */\n\nimport { shell } from '../shellRuntime.svelte';\nimport { registerView, unregisterView, registerVerb as fwRegisterVerb, unregisterVerb as fwUnregisterVerb } from './registry';\nimport type { Shard, ShardContext } from './types';\nimport { createDocumentHandle, getTenantId, getDocumentBackend } from '../documents';\nimport { fetchEnvState, putEnvState } from '../env/client';\nimport { isAdmin as checkIsAdmin } from '../auth/index';\nimport { createZoneManager } from '../state/manage';\nimport { PERMISSION_STATE_MANAGE } from '../state/types';\nimport {\n PERMISSION_DOCUMENTS_BROWSE,\n PERMISSION_DOCUMENTS_READ,\n PERMISSION_DOCUMENTS_WRITE,\n} from '../documents/types';\nimport { createBrowseCapability } from '../documents/browse';\nimport { createShardKeysApi } from '../keys/client';\nimport { PERMISSION_KEYS_MINT } from '../keys/types';\nimport { subscribe } from '../keys/revocation-bus.svelte';\nimport type { ContributionsApi } from '../contributions/types';\nimport {\n register as contributionsRegister,\n list as contributionsList,\n listPoints as contributionsListPoints,\n onChange as contributionsOnChange,\n} from '../contributions';\nimport { registerAction } from '../actions/registry';\nimport { makeSelectionApi, clearSelectionForShard } from '../actions/selection.svelte';\nimport { openContextMenu as shellOpenContextMenu, openPalette as shellOpenPalette } from '../actions/listeners';\n\ninterface ActiveEntry {\n shard: Shard;\n ctx: ShardContext;\n viewIds: Set<string>;\n verbNames: Set<string>;\n cleanupFns: (() => Promise<void>)[];\n}\n\n/**\n * Reactive registry of every shard known to the host. Keys are shard ids.\n * Populated once at boot by the glob-discovery loop in main.ts (through\n * `registerShard`); a future runtime loader appends late without touching\n * the rest of the framework. Callers that need a live list subscribe via\n * Svelte reactivity (e.g. shell home listing apps cross-references this\n * map to show which shards they require).\n */\nexport const registeredShards = $state(new Map<string, Shard>());\n\n/**\n * Reactive map of currently-active shards. A shard lands here when\n * `activateShard` runs successfully and stays until `deactivateShard`.\n */\nconst active = new Map<string, ActiveEntry>();\nexport const activeShards = $state(new Map<string, Shard>());\n\n/**\n * Reactive map of shard ids that failed to activate. Populated by\n * `activateShard`'s catch block; cleared when the shard is successfully\n * re-registered or activated. Read-only for shards; intended for diagnostic\n * and admin tooling that wants to surface broken shards to the user.\n */\nexport interface ShardErrorEntry {\n id: string;\n error: unknown;\n phase: 'autostart' | 'launch';\n timestamp: number;\n}\n\nexport const erroredShards = $state(new Map<string, ShardErrorEntry>());\n\n/**\n * Register (or re-register) a shard with the framework so it can later be\n * activated. Records the shard in `registeredShards` but does not run\n * `activate` — that happens at app launch (or for self-starting shards).\n *\n * If a shard with the same id already exists it is silently replaced,\n * which is the expected path during package updates. If the old shard was\n * active it is deactivated first so the new version can be cleanly\n * activated on next launch.\n */\nexport function registerShard(shard: Shard): void {\n const id = shard.manifest.id;\n if (registeredShards.has(id) && activeShards.has(id)) {\n deactivateShard(id);\n }\n registeredShards.set(id, shard);\n // Re-registering wipes any prior error: the new shard module gets a\n // clean slate, and a hot-reload of a fixed shard removes the stale entry.\n erroredShards.delete(id);\n}\n\nexport interface ActivateShardOpts {\n /**\n * Where this activation was initiated from. Determines the `phase` field\n * recorded in `erroredShards` if activation fails. Defaults to 'launch'\n * (the common case — required by an app being launched).\n */\n phase?: 'autostart' | 'launch';\n}\n\n/**\n * Activate a registered shard. Builds a `ShardContext`, calls `shard.activate`,\n * verifies that every view declared in the manifest received a factory, then\n * calls `shard.autostart` if defined. Idempotent — calling on an already-active\n * shard is a no-op.\n *\n * If `shard.activate` throws, partial state (registered views, verbs,\n * contributions, document handles, actions, env subscription) is unwound\n * and the failure is recorded in `erroredShards` before the error is\n * re-thrown. Callers in `host.ts` (autostart loop) and `launchApp`\n * (required-shard loop) decide how to react.\n *\n * @param id - The `ShardManifest.id` of the shard to activate. Must be registered.\n * @param opts - Optional. `phase` is recorded in `erroredShards` on failure (default 'launch').\n * @throws If the shard is not registered, if `shard.activate` throws, or if a manifest view has no factory after activation.\n */\nexport async function activateShard(id: string, opts?: ActivateShardOpts): Promise<void> {\n const shard = registeredShards.get(id);\n if (!shard) {\n throw new Error(`Cannot activate shard \"${id}\": not registered`);\n }\n if (active.has(id)) {\n // Already active (e.g. self-starting shard that was activated at boot\n // and is now being required by an app). Idempotent — no error.\n return;\n }\n\n const entry: ActiveEntry = { shard, ctx: undefined!, viewIds: new Set(), verbNames: new Set(), cleanupFns: [] };\n\n // envState holds the reactive env data for this shard.\n // Must be declared with $state at variable declaration time (Svelte 5 rule).\n const envState = $state<{ proxy: Record<string, unknown> | null; defaults: Record<string, unknown> | null }>({\n proxy: null,\n defaults: null,\n });\n\n // Per-shard wrapper: every register/onChange call goes into the\n // global registry, and its disposer is pushed into entry.cleanupFns\n // so deactivate auto-unregisters.\n const contributions: ContributionsApi = {\n register(pointId, descriptor) {\n const dispose = contributionsRegister(pointId, descriptor);\n entry.cleanupFns.push(async () => dispose());\n return dispose;\n },\n list(pointId) {\n return contributionsList(pointId);\n },\n listPoints() {\n return contributionsListPoints();\n },\n onChange(pointId, cb) {\n const off = contributionsOnChange(pointId, cb);\n entry.cleanupFns.push(async () => off());\n return off;\n },\n };\n\n const ctx: ShardContext = {\n state: (schema) => shell.state(id, schema),\n registerView: (viewId, factory) => {\n registerView(viewId, factory);\n entry.viewIds.add(viewId);\n },\n registerVerb: (verb) => {\n const prefixed = id === 'shell' ? verb.name : `${id}:${verb.name}`;\n fwRegisterVerb(prefixed, { ...verb, name: prefixed });\n entry.verbNames.add(prefixed);\n },\n documents: (options) => {\n const handle = createDocumentHandle(\n getTenantId(),\n id,\n getDocumentBackend(),\n options,\n );\n entry.cleanupFns.push(() => handle.dispose());\n return handle;\n },\n env<T extends Record<string, unknown>>(defaults: T): T {\n if (envState.proxy) {\n console.warn(`[sh3] Shard \"${id}\" called ctx.env() more than once; extra calls are ignored.`);\n return envState.proxy as T;\n }\n envState.defaults = defaults;\n envState.proxy = { ...defaults };\n return envState.proxy as T;\n },\n async envUpdate<T extends Record<string, unknown>>(patch: Partial<T>): Promise<void> {\n if (!envState.proxy || !envState.defaults) {\n throw new Error(`Shard \"${id}\" called envUpdate() without declaring env state`);\n }\n const previous = $state.snapshot(envState.proxy) as Record<string, unknown>;\n Object.assign(envState.proxy, patch);\n try {\n const snapshot = $state.snapshot(envState.proxy);\n await putEnvState(id, snapshot as Record<string, unknown>);\n } catch (err) {\n Object.assign(envState.proxy, previous);\n throw err;\n }\n },\n get isAdmin() {\n return checkIsAdmin();\n },\n get tenantId() {\n return getTenantId();\n },\n zones: shard.manifest.permissions?.includes(PERMISSION_STATE_MANAGE)\n ? createZoneManager()\n : undefined,\n browse: shard.manifest.permissions?.includes(PERMISSION_DOCUMENTS_BROWSE)\n ? createBrowseCapability(getTenantId(), getDocumentBackend(), {\n canRead: shard.manifest.permissions.includes(PERMISSION_DOCUMENTS_READ),\n canWrite: shard.manifest.permissions.includes(PERMISSION_DOCUMENTS_WRITE),\n })\n : undefined,\n keys: shard.manifest.permissions?.includes(PERMISSION_KEYS_MINT)\n ? createShardKeysApi({\n shardId: id,\n shardPermissions: shard.manifest.permissions ?? [],\n })\n : undefined,\n contributions,\n actions: {\n register(action) {\n const dispose = registerAction(action, id);\n entry.cleanupFns.push(async () => dispose());\n return dispose;\n },\n selection: makeSelectionApi(id),\n openContextMenu(opts) { shellOpenContextMenu(opts); },\n openPalette(opts) { shellOpenPalette(opts); },\n },\n };\n\n entry.ctx = ctx;\n\n // Wire onKeyRevoked hook: subscribe to the revocation bus for this shard.\n // Only shards that declare the hook incur the subscription overhead.\n if (shard.onKeyRevoked) {\n const off = subscribe(id, async (keyId) => {\n try {\n await shard.onKeyRevoked!(keyId);\n } catch (err) {\n console.error(`[sh3] onKeyRevoked failed in \"${id}\":`, err);\n }\n });\n entry.cleanupFns.push(async () => off());\n }\n\n active.set(id, entry);\n activeShards.set(id, shard);\n\n try {\n await shard.activate(ctx);\n\n for (const view of shard.manifest.views) {\n if (!entry.viewIds.has(view.id)) {\n throw new Error(\n `Shard \"${id}\" declared view \"${view.id}\" in its manifest but registered no factory for it.`,\n );\n }\n }\n\n // Hydrate env state if the shard declared it via ctx.env().\n if (envState.proxy && envState.defaults) {\n try {\n const stored = await fetchEnvState(id);\n const merged = Object.assign({}, envState.defaults, stored);\n Object.assign(envState.proxy, merged);\n } catch (err) {\n console.warn(\n `[sh3] Failed to hydrate env state for shard \"${id}\":`,\n err instanceof Error ? err.message : err,\n );\n }\n }\n } catch (err) {\n // Unwind partial state. Mirror deactivateShard's body, minus the\n // shard.deactivate?.() call — the shard never finished activating.\n // Each cleanup fn runs inside its own swallow so a teardown failure\n // cannot mask the original activation error.\n for (const fn of entry.cleanupFns) {\n try {\n void fn();\n } catch {\n // intentionally swallowed: original error is what matters.\n }\n }\n for (const name of entry.verbNames) fwUnregisterVerb(name);\n for (const viewId of entry.viewIds) unregisterView(viewId);\n clearSelectionForShard(id);\n active.delete(id);\n activeShards.delete(id);\n\n erroredShards.set(id, {\n id,\n error: err,\n phase: opts?.phase ?? 'launch',\n timestamp: Date.now(),\n });\n console.error(`[sh3] Shard \"${id}\" failed to activate:`, err);\n throw err;\n }\n\n // Activation succeeded — clear any prior error record for this shard.\n erroredShards.delete(id);\n\n void shard.autostart?.(ctx);\n}\n\n/**\n * Deactivate an active shard. Calls `shard.deactivate`, flushes and disposes\n * all document handles, unregisters all view factories, and removes the shard\n * from `activeShards`. The shard remains in `registeredShards` and can be\n * re-activated. No-op if the shard is not currently active.\n *\n * @param id - The `ShardManifest.id` of the shard to deactivate.\n */\nexport function deactivateShard(id: string): void {\n const entry = active.get(id);\n if (!entry) return;\n void entry.shard.deactivate?.();\n // Flush and dispose document handles before tearing down views.\n for (const fn of entry.cleanupFns) void fn();\n for (const name of entry.verbNames) fwUnregisterVerb(name);\n for (const viewId of entry.viewIds) unregisterView(viewId);\n clearSelectionForShard(id);\n active.delete(id);\n activeShards.delete(id);\n}\n\n/**\n * Return true if the shard with the given id is currently active.\n *\n * @param id - The `ShardManifest.id` to check.\n */\nexport function isActive(id: string): boolean {\n return active.has(id);\n}\n\n/**\n * Return the ShardContext for an active shard, or undefined if not active.\n * Used by lifecycle.ts to pass context to `shard.resume()`.\n */\nexport function getShardContext(id: string): ShardContext | undefined {\n return active.get(id)?.ctx;\n}\n\n/**\n * Enumerate every view declared as `standalone` across the currently\n * active shards. Intended for the `views --standalone` verb and any\n * launcher UI that wants to surface \"summonable\" primitives. Only\n * pulls from `activeShards` — registered-but-inactive shards aren't\n * ready to mount.\n */\nexport function listStandaloneViews(): Array<{ shardId: string; viewId: string; label: string }> {\n const out: Array<{ shardId: string; viewId: string; label: string }> = [];\n for (const shard of activeShards.values()) {\n for (const view of shard.manifest.views) {\n if (view.standalone) {\n out.push({ shardId: shard.manifest.id, viewId: view.id, label: view.label });\n }\n }\n }\n return out;\n}\n\n/**\n * Test-only reset. Tears down any active shard entries (without running\n * deactivate hooks — tests should run deactivate explicitly if they care)\n * and clears both registered and active maps.\n */\nexport function __resetShardRegistryForTest(): void {\n active.clear();\n activeShards.clear();\n registeredShards.clear();\n erroredShards.clear();\n}\n","/*\n * Session-zone state for the active project scope.\n *\n * `null` means the user is in their personal scope. Otherwise it carries\n * the active project's id. Read at app launch by `launchApp` to bind\n * `ctx.scopeId`, and read by ShellHome / BrandSlot for UX rendering.\n *\n * Setting the slot through `setActiveProjectId` is the only supported\n * mutation path: it clears the breadcrumb pointer (so resuming an app\n * after a scope change can't open a stale doc handle) and unloads any\n * active app (whose scopeId is bound to the old scope).\n */\n\nimport { activeApp, breadcrumbApp } from '../apps/registry.svelte';\n\nexport const sessionState: { activeProjectId: string | null } = $state({\n activeProjectId: null,\n});\n\n/**\n * Set the active project id. Side-effects when the value actually changes:\n * - the active app (if any) is unloaded — its document handles and zone\n * state are bound to the previous scope and cannot follow.\n * - the breadcrumb pointer is cleared so re-entering an app cannot point\n * at the wrong namespace.\n *\n * Setting the same value is a no-op (no app unload, no breadcrumb clear).\n *\n * The unloadApp call is deferred to a dynamic import so this module stays\n * importable from circular-dependency hot-paths (lifecycle imports\n * sessionState; sessionState here would otherwise import lifecycle eagerly).\n */\nexport function setActiveProjectId(id: string | null): void {\n if (sessionState.activeProjectId === id) return;\n const previousActive = activeApp.id;\n sessionState.activeProjectId = id;\n breadcrumbApp.id = null;\n if (previousActive) {\n void import('../apps/lifecycle').then((m) => m.unloadApp(previousActive));\n }\n}\n","/*\n * App lifecycle — launch, unload, return-to-home.\n *\n * All three functions operate on the shared apps registry and the layout\n * manager. `launchApp` is public (shell home calls it); `unloadApp` is\n * internal (called from launchApp when replacing a different app);\n * `returnToHome` is public (shell UI calls it).\n *\n * \"Last active app\" is persisted in the user state zone under the\n * reserved shardId `__sh3core__:last-app`. The value shape is simply\n * `{ id: string | null }`. Writing happens on launch (id) and on\n * return-to-home (null). Boot reads it to decide whether to auto-launch.\n */\n\nimport { createStateZones } from '../state/zones.svelte';\nimport {\n activateShard,\n deactivateShard,\n getShardContext,\n registeredShards,\n} from '../shards/activate.svelte';\nimport {\n attachApp,\n acquireAppSlotHolds,\n detachApp,\n switchToApp,\n switchToHome,\n} from '../layout/store.svelte';\nimport { activeApp, breadcrumbApp, getRegisteredApp, registeredApps } from './registry.svelte';\nimport type { AppContext } from './types';\nimport { createZoneManager } from '../state/manage';\nimport { PERMISSION_STATE_MANAGE } from '../state/types';\nimport { setActiveApp, setUserBindings } from '../actions/state.svelte';\nimport { clearSelectionUnconditional } from '../actions/selection.svelte';\nimport { loadUserBindings } from '../actions/bindings-store';\nimport { toastManager } from '../overlays/toast';\nimport { clearAppNavEntries } from '../navigation/back-stack';\nimport { getActiveScopeId } from '../documents/config';\nimport { sessionState } from '../projects/session-state.svelte';\n\n// ---------- last-active-app user zone ------------------------------------\n\n/**\n * Framework-reserved user-zone slot storing which app to boot into on\n * the next session. Keyed under `__sh3core__:last-app` to avoid collision\n * with any real shard. Reading/writing uses the same zones machinery as\n * any shard — nothing special.\n */\nconst lastAppState = createStateZones('__sh3core__:last-app', {\n user: { id: null as string | null },\n});\n\n/**\n * Read the id of the last-launched app from the user state zone. Used at\n * boot to decide whether to auto-launch. Returns null if the user last\n * returned to home or no app has ever been launched.\n */\nexport function readLastApp(): string | null {\n return lastAppState.user.id;\n}\n\nfunction writeLastApp(id: string | null): void {\n lastAppState.user.id = id;\n}\n\n/**\n * Public reset for the last-active-app user-zone slot. Used by the host's\n * boot sequence to recover from a sticky last-app launch failure: if the\n * auto-launch fails, this clears the slot so the next reload lands on home\n * instead of looping into the same failure.\n */\nexport function clearLastApp(): void {\n writeLastApp(null);\n}\n\n// ---------- app-context state factories ----------------------------------\n\nconst appContexts = new Map<string, AppContext>();\n\nfunction resolveLaunchScope(): string {\n return sessionState.activeProjectId ?? getActiveScopeId();\n}\n\nfunction getOrCreateAppContext(appId: string, scopeId?: string): AppContext {\n let ctx = appContexts.get(appId);\n if (!ctx) {\n const app = getRegisteredApp(appId);\n const scope = scopeId ?? resolveLaunchScope();\n ctx = {\n scopeId: scope,\n state: (schema) =>\n createStateZones(`__app__:${appId}:scope:${scope}`, schema),\n zones: app?.manifest.permissions?.includes(PERMISSION_STATE_MANAGE)\n ? createZoneManager()\n : undefined,\n };\n appContexts.set(appId, ctx);\n }\n return ctx;\n}\n\n// ---------- launch --------------------------------------------------------\n\n/**\n * Launch an app by id. Activates all required shards (idempotent for\n * already-active shards), attaches the app's layout, calls `App.activate`,\n * and switches the rendered root to the app tree.\n *\n * If a different app is already active, it is unloaded first. Launching the\n * same app that is already active is a no-op on shards — it only switches\n * back from the home view if needed.\n *\n * @param id - The `AppManifest.id` of the app to launch. Must be registered.\n * @throws If the app is not registered or a required shard is not registered.\n */\nexport async function launchApp(id: string): Promise<void> {\n const app = getRegisteredApp(id);\n if (!app) {\n throw new Error(`Cannot launch app \"${id}\": not registered`);\n }\n\n // If a different app is already active, unload it first. Relaunching\n // the same app (while it's active) is a no-op on shards and layout;\n // we only swap the rendered root back to 'app' in case the user was\n // on home.\n if (activeApp.id && activeApp.id !== id) {\n unloadApp(activeApp.id);\n } else if (activeApp.id === id) {\n // Re-entering the same app from Home — fire resume hooks.\n for (const shardId of app.manifest.requiredShards) {\n const shard = registeredShards.get(shardId);\n const shardCtx = getShardContext(shardId);\n if (shard && shardCtx) void shard.resume?.(shardCtx);\n }\n void app.resume?.(getOrCreateAppContext(id));\n switchToApp();\n void app.onAppReady?.(getOrCreateAppContext(id));\n writeLastApp(id);\n breadcrumbApp.id = id;\n setActiveApp(id, new Set(app.manifest.requiredShards ?? []));\n void loadUserBindings(id).then(setUserBindings);\n return;\n }\n\n // Validate required shards are registered before attaching anything,\n // so we don't half-attach and leave presetManager bound to a blob for\n // an app whose shards we can't even find.\n for (const shardId of app.manifest.requiredShards) {\n if (!registeredShards.has(shardId)) {\n throw new Error(\n `App \"${id}\" requires shard \"${shardId}\" which is not registered`,\n );\n }\n }\n\n // Attach the layout before activating shards so `presetManager` is\n // bound to this app's AppLayoutBlob during shard activation. Shards\n // legitimately read/switch presets from their activate() hook; the\n // previous order (shards first, attach after) made any such call\n // throw \"no app attached\". If shard activation fails below, we\n // detach to keep the preset manager state consistent.\n attachApp(app);\n try {\n for (const shardId of app.manifest.requiredShards) {\n await activateShard(shardId, { phase: 'launch' });\n }\n } catch (err) {\n detachApp();\n try {\n toastManager.notify(\n `Couldn't launch \"${app.manifest.label ?? id}\": ${err instanceof Error ? err.message : String(err)}`,\n { level: 'error', duration: 6000 },\n );\n } catch {\n // Toast layer not mounted (e.g. early boot, tests without Shell).\n // Best-effort UX — original error must still propagate.\n }\n throw err;\n }\n\n // Shards have registered their view factories — safe to take the\n // refcount holds on the app's slots now (pool's factory lookup\n // happens in a microtask from this call).\n acquireAppSlotHolds();\n\n void app.activate?.(getOrCreateAppContext(id));\n\n activeApp.id = id;\n setActiveApp(id, new Set(app.manifest.requiredShards ?? []));\n void loadUserBindings(id).then(setUserBindings);\n switchToApp();\n void app.onAppReady?.(getOrCreateAppContext(id));\n writeLastApp(id);\n breadcrumbApp.id = id;\n}\n\n// ---------- unload --------------------------------------------------------\n\n/**\n * Unload an active app. Calls `App.deactivate`, detaches the layout, and\n * deactivates the app's non-self-starting required shards. Switches the\n * rendered root to home. No-op if the app is not currently active.\n *\n * @param id - The `AppManifest.id` of the app to unload.\n */\nexport function unloadApp(id: string): void {\n if (activeApp.id !== id) return;\n const app = getRegisteredApp(id);\n if (!app) return;\n\n void app.deactivate?.();\n\n // Detach layout (releases the refcount holds; pool cleanup runs on\n // the next microtask for any slots that no longer have a renderer).\n // Switch to home first so LayoutRenderer stops reading the app's\n // tree before detachApp drops its references.\n switchToHome();\n detachApp();\n\n // Deactivate this app's required shards IF no other consumer needs\n // them. Phase 8 has at most one app active at a time, so \"no other\n // consumer\" reduces to \"not self-starting AND not required by any\n // other registered app that happens to already be active\" — but we\n // don't run multiple apps, so the only survivors are self-starters.\n // The simple rule: deactivate a required shard unless it was\n // self-starting (has an `autostart` field defined).\n for (const shardId of app.manifest.requiredShards) {\n const shard = registeredShards.get(shardId);\n if (!shard) continue;\n if (shard.autostart) continue; // self-starter stays running\n deactivateShard(shardId);\n }\n\n activeApp.id = null;\n setActiveApp(null, new Set());\n clearSelectionUnconditional();\n clearAppNavEntries();\n void loadUserBindings('sh3.home').then(setUserBindings);\n appContexts.delete(id);\n}\n\n// ---------- unregister -------------------------------------------------------\n\n/**\n * Unregister an app and remove it from the registry.\n *\n * If the app is currently active, force-closes (android-style): calls\n * `App.deactivate`, detaches the layout, and deactivates required shards,\n * then clears the active-app pointer. Unlike `returnToHome` this does not\n * run suspend hooks and cannot be cancelled.\n *\n * No-op if the id is not registered.\n */\nexport function unregisterApp(id: string): void {\n if (!registeredApps.has(id)) return;\n if (activeApp.id === id) {\n unloadApp(id);\n writeLastApp(null);\n }\n registeredApps.delete(id);\n}\n\n// ---------- return to home -----------------------------------------------\n\n/**\n * Return to the shell home view without unloading the active app. The\n * app's shards stay running, its layout proxy stays attached with its\n * refcount hold intact, and its view containers stay alive in the pool.\n * Launching the same app again is a root swap only.\n *\n * Fires `suspend` hooks on all required shards (in order), then on the\n * app itself. Any hook returning `false` cancels navigation — the user\n * stays in the app. Returns `true` if navigation succeeded, `false` if\n * cancelled.\n *\n * Writes `null` to `__sh3core__:last-app` so reloading the page while on\n * home lands on home, not on the formerly-active app.\n */\nexport async function returnToHome(): Promise<boolean> {\n const app = activeApp.id ? getRegisteredApp(activeApp.id) : null;\n\n if (app) {\n for (const shardId of app.manifest.requiredShards) {\n const shard = registeredShards.get(shardId);\n if (shard?.suspend && (await shard.suspend()) === false) return false;\n }\n if (app.suspend && (await app.suspend()) === false) return false;\n }\n\n clearAppNavEntries();\n switchToHome();\n // Mirror unregisterApp: clear the dispatcher's active-app pointer so\n // 'app'-scope actions become inactive on home. Without this, any action\n // registered with scope: ['app'] keeps appearing in the palette while\n // the user is on home.\n setActiveApp(null, new Set());\n writeLastApp(null);\n return true;\n}\n","/*\n * Layout inspection / mutation — public API for advanced shards.\n *\n * These helpers are how shards like `diagnostic` inject themselves into\n * the currently-rendered layout. The mutation primitives delegate to\n * ops.ts for the actual tree work; inspection reads through the layout\n * manager so diagnostic content stays live as the user rearranges things.\n *\n * Scope note: `spliceIntoActiveLayout` targets the CURRENTLY-RENDERED\n * root only. Mutating a held-but-not-active app tree (e.g. while the\n * user is on home) is not supported in phase 8. If an advanced shard\n * wants to reach the held tree, it has to do so while the app is\n * rendered.\n */\n\nimport { activeLayout, getActiveRoot } from './store.svelte';\nimport type { LayoutNode, SplitNode, TabEntry, TabsNode, LayoutTree, TreeRootRef } from './types';\nimport {\n nodeAtPath,\n findTabBySlotId,\n removeTabBySlotId,\n cleanupTree,\n splitNodeAtPath,\n locateSlotIn,\n type LayoutPath,\n} from './ops';\nimport { getSlotHandle } from './slotHostPool.svelte';\nimport { floatManager } from '../overlays/float';\n\n/**\n * Read-only snapshot of the currently-rendered layout tree. The return\n * value is the live object — callers MUST NOT mutate it directly;\n * mutations go through `spliceIntoActiveLayout`. Returning the live\n * object (not a deep clone) means reactive consumers can re-read on\n * updates without manual subscription wiring.\n */\nexport function inspectActiveLayout(): { root: LayoutTree; source: 'home' | 'app' } {\n return { root: activeLayout(), source: getActiveRoot() };\n}\n\n/**\n * Add a new tab at the end of the first tabs group found in the\n * currently-rendered layout. If no tabs group exists (e.g. the active\n * root is the single-slot home layout), throws. Phase 8 scope — richer\n * variants arrive later.\n */\nexport function spliceIntoActiveLayout(entry: TabEntry): void {\n const root = activeLayout().docked;\n const target = findFirstTabsNode(root);\n if (!target) {\n throw new Error(\n 'spliceIntoActiveLayout: no tabs group found in the active layout; ' +\n 'phase 8 only supports splicing into an existing tab group.',\n );\n }\n target.tabs.push(entry);\n target.activeTab = target.tabs.length - 1;\n}\n\n/**\n * Activate the tab whose slot matches `slotId` in the currently-rendered\n * layout. Returns `true` if a matching tab was found and activated.\n */\nexport function focusTab(slotId: string): boolean {\n const tree = activeLayout();\n if (focusTabWhere(tree.docked, (entry) => entry.slotId === slotId)) return true;\n return focusTabInFloats(tree, (entry) => entry.slotId === slotId);\n}\n\n/**\n * Activate the first tab whose `viewId` matches in the currently-rendered\n * layout. Returns `true` if a matching tab was found and activated.\n */\nexport function focusView(viewId: string): boolean {\n const tree = activeLayout();\n if (focusTabWhere(tree.docked, (entry) => entry.viewId === viewId)) return true;\n return focusTabInFloats(tree, (entry) => entry.viewId === viewId);\n}\n\n/** Walk the tree looking for a tab entry that satisfies `pred`, activate it. */\nfunction focusTabWhere(\n node: LayoutNode,\n pred: (entry: TabEntry) => boolean,\n): boolean {\n if (node.type === 'tabs') {\n const idx = node.tabs.findIndex(pred);\n if (idx >= 0) {\n node.activeTab = idx;\n return true;\n }\n return false;\n }\n if (node.type === 'split') {\n for (const child of node.children) {\n if (focusTabWhere(child, pred)) return true;\n }\n }\n return false;\n}\n\n/** Search floats for a matching tab; activate it and raise the float. */\nfunction focusTabInFloats(\n tree: LayoutTree,\n pred: (entry: TabEntry) => boolean,\n): boolean {\n for (const floatEntry of tree.floats) {\n if (focusTabWhere(floatEntry.content, pred)) {\n floatManager.focus(floatEntry.id);\n return true;\n }\n }\n return false;\n}\n\n/**\n * Collapse a child of a split node at the given path. Returns true if\n * the split was found and the child was collapsed.\n */\nexport function collapseChild(splitPath: number[], childIndex: number): boolean {\n return setCollapsed(splitPath, childIndex, true);\n}\n\n/**\n * Expand a previously collapsed child of a split node. Returns true if\n * the split was found and the child was expanded.\n */\nexport function expandChild(splitPath: number[], childIndex: number): boolean {\n return setCollapsed(splitPath, childIndex, false);\n}\n\nfunction setCollapsed(splitPath: number[], childIndex: number, value: boolean): boolean {\n const root = activeLayout().docked;\n const node = nodeAtPath(root, splitPath);\n if (!node || node.type !== 'split') return false;\n const split = node as SplitNode;\n if (childIndex < 0 || childIndex >= split.children.length) return false;\n if (!split.collapsed) split.collapsed = split.children.map(() => false);\n split.collapsed[childIndex] = value;\n return true;\n}\n\n/**\n * Request to close a tab by its slot ID. Respects the view's closable\n * policy:\n * - Non-closable (closable undefined/false): returns false immediately.\n * - Pure (closable true): removes the tab, returns true.\n * - Guarded (closable { canClose }): awaits canClose(); removes if\n * resolved true, returns false if resolved false.\n *\n * This is the single entry point for closing tabs — the tab strip's X\n * button and programmatic callers both use it. The layout engine remains\n * the sole authority on tree mutations.\n */\nexport async function closeTab(slotId: string): Promise<boolean> {\n const tree = activeLayout();\n const root = tree.docked;\n const located = findTabBySlotId(root, slotId);\n\n // Not found in docked tree — check floats.\n if (!located) {\n return closeFloatTab(tree, slotId);\n }\n\n const handle = getSlotHandle(slotId);\n const closable = handle?.closable;\n\n // Non-closable: no action.\n if (!closable) return false;\n\n // Guarded: ask the shard.\n if (typeof closable === 'object') {\n const allowed = await closable.canClose();\n if (!allowed) return false;\n // Re-verify the tab still exists after the async gap — another close\n // request or a layout mutation may have removed it while we awaited.\n if (!findTabBySlotId(root, slotId)) return false;\n }\n\n // Remove the tab from the tree. This causes Svelte to tear down the\n // SlotContainer, which calls releaseSlotHost() — the pool's deferred\n // destroy microtask then fires handle.unmount(). We do NOT call\n // releaseSlotHost here; the existing component lifecycle handles it.\n removeTabBySlotId(root, slotId);\n\n // Cleanup: prune empty (non-persistent) tab groups, collapse single-child splits.\n cleanupTree(root);\n\n return true;\n}\n\n/**\n * Close a tab that lives inside a float entry. Float tabs are\n * auto-closable (views gain closability when mounted in a float) but\n * guarded canClose() on the view handle is still respected.\n * Closing the last tab in a float removes the entire float.\n */\nasync function closeFloatTab(tree: LayoutTree, slotId: string): Promise<boolean> {\n for (const entry of tree.floats) {\n const located = findTabBySlotId(entry.content, slotId);\n if (!located) continue;\n\n // Respect guarded canClose() if the view declared one.\n const handle = getSlotHandle(slotId);\n const closable = handle?.closable;\n if (typeof closable === 'object') {\n const allowed = await closable.canClose();\n if (!allowed) return false;\n // Re-verify after async gap.\n if (!findTabBySlotId(entry.content, slotId)) return false;\n }\n\n // Remove the tab from the float's content tree.\n removeTabBySlotId(entry.content, slotId);\n\n // If the float's content is now empty, remove the entire float.\n const tabs = entry.content.type === 'tabs' ? entry.content : null;\n if (!tabs || tabs.tabs.length === 0) {\n floatManager.close(entry.id);\n }\n\n return true;\n }\n return false;\n}\n\n/**\n * Pop a docked tab out into a new float. Locates the tab by `slotId` in\n * the currently-rendered docked tree, removes it (preserving viewId +\n * meta), and opens a float with the same view. Returns the new floatId\n * on success, or null if the slot wasn't found in the docked tree.\n *\n * Guarded canClose() is NOT consulted — popout is not a close. The slot\n * is recreated in the float with a fresh slotId, so the view is remounted.\n */\nexport function popoutView(slotId: string): string | null {\n const tree = activeLayout();\n const located = findTabBySlotId(tree.docked, slotId);\n if (!located) return null;\n const entry = located.entry;\n const viewId = entry.viewId;\n if (!viewId) return null;\n const title = entry.label;\n const meta = entry.meta;\n removeTabBySlotId(tree.docked, slotId);\n cleanupTree(tree.docked);\n return floatManager.open(viewId, { title, meta });\n}\n\n/**\n * Dock a float back into the currently-rendered layout. The float's\n * active tab is appended to the first tabs group (same policy as\n * `dockIntoActiveLayout`). Returns true on success. The float is closed\n * after its content is transferred.\n */\nexport function dockFloat(floatId: string): boolean {\n const tree = activeLayout();\n const floatEntry = tree.floats.find((f) => f.id === floatId);\n if (!floatEntry) return false;\n const content = floatEntry.content;\n const tabs = content.type === 'tabs' ? content : null;\n if (!tabs || tabs.tabs.length === 0) {\n floatManager.close(floatId);\n return false;\n }\n const entry = tabs.tabs[tabs.activeTab ?? 0] ?? tabs.tabs[0];\n const ok = dockIntoActiveLayout({\n slotId: entry.slotId,\n viewId: entry.viewId,\n label: entry.label,\n meta: entry.meta,\n });\n if (ok) floatManager.close(floatId);\n return ok;\n}\n\nfunction findFirstTabsNode(node: LayoutNode): TabsNode | null {\n if (node.type === 'tabs') return node;\n if (node.type === 'split') {\n for (const c of node.children) {\n const hit = findFirstTabsNode(c);\n if (hit) return hit;\n }\n }\n return null;\n}\n\n/** Find the path to the first slot leaf with a bound viewId. */\nfunction findFirstSlotPath(node: LayoutNode, path: LayoutPath = []): LayoutPath | null {\n if (node.type === 'slot') return node.viewId !== null ? path : null;\n if (node.type === 'split') {\n for (let i = 0; i < node.children.length; i++) {\n const hit = findFirstSlotPath(node.children[i], [...path, i]);\n if (hit) return hit;\n }\n }\n return null;\n}\n\n/**\n * Dock a view into the currently-rendered layout without caring which\n * root it is. Used by the Ctrl+` shell hotkey and other \"just put it\n * somewhere sensible\" callers. Policy:\n *\n * 1. If a tab with the same `viewId` already exists, focus it and\n * return. Callers don't want a second instance of a singleton view\n * every time they hit the shortcut.\n * 2. Otherwise, append the entry to the first tabs group found\n * (`spliceIntoActiveLayout` semantics).\n * 3. If there's no tabs group (e.g. the home root is a single slot),\n * split the first slot leaf horizontally and put the entry on the\n * right. This is the \"floating window\" fallback described in\n * roadmap SH9 / DF3 — when floating panels land, callers should\n * prefer that path for ephemeral docks.\n *\n * Returns true if the view was focused or inserted, false if the layout\n * was empty or otherwise un-dockable.\n */\nexport function dockIntoActiveLayout(entry: TabEntry): boolean {\n const root = activeLayout().docked;\n\n // 1. Already present? Focus it.\n if (focusView(entry.viewId ?? '')) return true;\n\n // 2. Existing tabs group wins.\n const tabs = findFirstTabsNode(root);\n if (tabs) {\n tabs.tabs.push(entry);\n tabs.activeTab = tabs.tabs.length - 1;\n return true;\n }\n\n // 3. Fallback: split the first valid slot leaf.\n const slotPath = findFirstSlotPath(root);\n if (!slotPath) return false;\n splitNodeAtPath(root, slotPath, entry, 'right');\n return true;\n}\n\n/**\n * Find which root a slot currently lives under in the active layout.\n * Returns `{ kind: 'docked' }` when the slot is anywhere in the docked\n * tree, `{ kind: 'float', floatId }` when it lives inside a float, or\n * `null` when the slot is not present (stale id, post-unmount, or\n * held-but-not-active app tree). Thin wrapper over the pure\n * `locateSlotIn(tree, slotId)` from `ops.ts` — use this when you only\n * have a slotId in hand; use `locateSlotIn` if you already hold the tree.\n */\nexport function locateSlot(slotId: string): TreeRootRef | null {\n return locateSlotIn(activeLayout(), slotId);\n}\n","/**\n * Runtime validation for registry index JSON.\n *\n * No external schema library — plain runtime checks. The registry index\n * is fetched from untrusted URLs so all fields are validated before any\n * typed access occurs. Validation errors carry a JSON-path string so the\n * caller can surface actionable diagnostics in the store UI.\n *\n * Usage:\n * ```ts\n * const raw = await response.json();\n * const index = validateRegistryIndex(raw); // throws RegistryValidationError on bad input\n * ```\n */\n\nimport type { RegistryIndex, PackageEntry, PackageVersion, RequiredDependency } from './types.js';\n\n/**\n * Thrown when a registry index document fails validation.\n *\n * The `path` property is a JSON-path string pointing to the field that\n * caused the failure (e.g. `\"$.packages[2].versions[0].integrity\"`).\n * Consumers may display this directly in diagnostic/error UI.\n */\nexport class RegistryValidationError extends Error {\n /**\n * JSON-path of the failing field (e.g. `\"$.packages[0].type\"`).\n */\n readonly path: string;\n\n /**\n * @param path - JSON-path string of the failing field.\n * @param message - Human-readable description of why validation failed.\n */\n constructor(path: string, message: string) {\n super(`Registry validation error at ${path}: ${message}`);\n this.name = 'RegistryValidationError';\n this.path = path;\n }\n}\n\n/**\n * Validate an unknown value as a `RegistryIndex`.\n *\n * Performs a full deep validation of all required fields and their types.\n * Returns a correctly typed `RegistryIndex` on success.\n * Throws `RegistryValidationError` on the first validation failure.\n *\n * Call this immediately after `response.json()` before touching any field.\n *\n * @param data - The raw parsed JSON value from a registry fetch.\n * @returns A fully validated `RegistryIndex`.\n * @throws `RegistryValidationError` if any field is missing or has the wrong type.\n */\nexport function validateRegistryIndex(data: unknown): RegistryIndex {\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n throw new RegistryValidationError('$', 'expected an object');\n }\n const obj = data as Record<string, unknown>;\n\n if (obj['version'] !== 1) {\n throw new RegistryValidationError(\n '$.version',\n `expected 1, got ${JSON.stringify(obj['version'])}`,\n );\n }\n\n if (!Array.isArray(obj['packages'])) {\n throw new RegistryValidationError('$.packages', 'expected an array');\n }\n\n const packages = (obj['packages'] as unknown[]).map((p, i) =>\n validatePackageEntry(p, `$.packages[${i}]`),\n );\n\n return { version: 1, packages };\n}\n\n/**\n * Validate a single package entry object.\n *\n * @param data - Raw value from the `packages` array.\n * @param path - JSON-path prefix used in error messages.\n * @returns Validated `PackageEntry`.\n * @throws `RegistryValidationError` on any field failure.\n */\nfunction validatePackageEntry(data: unknown, path: string): PackageEntry {\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n throw new RegistryValidationError(path, 'expected an object');\n }\n const obj = data as Record<string, unknown>;\n\n requireString(obj, 'id', path);\n requireOneOf(obj, 'type', ['shard', 'app', 'combo'], path);\n requireString(obj, 'label', path);\n requireString(obj, 'description', path);\n\n // author: { name: string }\n const authorPath = `${path}.author`;\n if (!obj['author'] || typeof obj['author'] !== 'object' || Array.isArray(obj['author'])) {\n throw new RegistryValidationError(authorPath, 'expected an object');\n }\n const author = obj['author'] as Record<string, unknown>;\n if (typeof author['name'] !== 'string' || author['name'].length === 0) {\n throw new RegistryValidationError(`${authorPath}.name`, 'expected a non-empty string');\n }\n\n // versions: non-empty array\n if (!Array.isArray(obj['versions']) || obj['versions'].length === 0) {\n throw new RegistryValidationError(`${path}.versions`, 'expected a non-empty array');\n }\n const versions = (obj['versions'] as unknown[]).map((v, i) =>\n validatePackageVersion(v, `${path}.versions[${i}]`),\n );\n\n return {\n id: obj['id'] as string,\n type: obj['type'] as 'shard' | 'app' | 'combo',\n label: obj['label'] as string,\n description: obj['description'] as string,\n author: { name: author['name'] as string },\n icon: typeof obj['icon'] === 'string' ? obj['icon'] : undefined,\n versions,\n };\n}\n\n/**\n * Validate a single package version object.\n *\n * @param data - Raw value from a `versions` array.\n * @param path - JSON-path prefix used in error messages.\n * @returns Validated `PackageVersion`.\n * @throws `RegistryValidationError` on any field failure.\n */\nfunction validatePackageVersion(data: unknown, path: string): PackageVersion {\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n throw new RegistryValidationError(path, 'expected an object');\n }\n const obj = data as Record<string, unknown>;\n\n requireString(obj, 'version', path);\n requireString(obj, 'contractVersion', path);\n\n // Client bundle fields — optional individually, but if either is present both must be.\n const hasBundleUrl = 'bundleUrl' in obj && obj.bundleUrl !== undefined;\n const hasIntegrity = 'integrity' in obj && obj.integrity !== undefined;\n if (hasBundleUrl) requireString(obj, 'bundleUrl', path);\n if (hasIntegrity) requireString(obj, 'integrity', path);\n if (hasBundleUrl !== hasIntegrity) {\n throw new RegistryValidationError(\n path,\n 'bundleUrl and integrity must be provided together',\n );\n }\n\n // Optional server bundle URL.\n const hasServerBundleUrl = 'serverBundleUrl' in obj && obj.serverBundleUrl !== undefined;\n if (hasServerBundleUrl) {\n requireString(obj, 'serverBundleUrl', path);\n }\n\n // Optional server bundle integrity hash — provisional, see ADR-015.\n if ('serverIntegrity' in obj && obj.serverIntegrity !== undefined) {\n requireString(obj, 'serverIntegrity', path);\n }\n\n // A version must ship at least one bundle.\n if (!hasBundleUrl && !hasServerBundleUrl) {\n throw new RegistryValidationError(\n path,\n 'expected at least one of bundleUrl+integrity or serverBundleUrl',\n );\n }\n\n let requires: RequiredDependency[] | undefined;\n if (obj['requires'] !== undefined) {\n if (!Array.isArray(obj['requires'])) {\n throw new RegistryValidationError(`${path}.requires`, 'expected an array');\n }\n requires = (obj['requires'] as unknown[]).map((r, i) =>\n validateRequiredDependency(r, `${path}.requires[${i}]`),\n );\n }\n\n return {\n version: obj['version'] as string,\n contractVersion: obj['contractVersion'] as string,\n bundleUrl: typeof obj['bundleUrl'] === 'string' ? obj['bundleUrl'] : undefined,\n integrity: typeof obj['integrity'] === 'string' ? obj['integrity'] : undefined,\n serverBundleUrl: typeof obj['serverBundleUrl'] === 'string' ? obj['serverBundleUrl'] : undefined,\n serverIntegrity: typeof obj['serverIntegrity'] === 'string' ? obj['serverIntegrity'] : undefined,\n requires,\n };\n}\n\n/**\n * Validate a single dependency entry in a `requires` array.\n *\n * @param data - Raw value from a `requires` array.\n * @param path - JSON-path prefix used in error messages.\n * @returns Validated `RequiredDependency`.\n * @throws `RegistryValidationError` on any field failure.\n */\nfunction validateRequiredDependency(data: unknown, path: string): RequiredDependency {\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n throw new RegistryValidationError(path, 'expected an object');\n }\n const obj = data as Record<string, unknown>;\n\n requireString(obj, 'id', path);\n requireString(obj, 'versionRange', path);\n\n return {\n id: obj['id'] as string,\n versionRange: obj['versionRange'] as string,\n };\n}\n\n/**\n * Assert that `obj[field]` is a non-empty string.\n *\n * @param obj - Parent object being validated.\n * @param field - Field name to check.\n * @param path - JSON-path of the parent object (field name is appended on error).\n * @throws `RegistryValidationError` if the field is missing, not a string, or empty.\n */\nfunction requireString(obj: Record<string, unknown>, field: string, path: string): void {\n const value = obj[field];\n if (typeof value !== 'string' || value.length === 0) {\n throw new RegistryValidationError(\n `${path}.${field}`,\n 'expected a non-empty string',\n );\n }\n}\n\n/**\n * Assert that `obj[field]` is one of the allowed string values.\n *\n * @param obj - Parent object being validated.\n * @param field - Field name to check.\n * @param values - Allowed values.\n * @param path - JSON-path of the parent object (field name is appended on error).\n * @throws `RegistryValidationError` if the field value is not in `values`.\n */\nfunction requireOneOf(\n obj: Record<string, unknown>,\n field: string,\n values: readonly string[],\n path: string,\n): void {\n if (!values.includes(obj[field] as string)) {\n throw new RegistryValidationError(\n `${path}.${field}`,\n `expected one of: ${values.join(', ')}`,\n );\n }\n}\n","/**\n * SRI integrity verification for downloaded bundles.\n *\n * Uses the Web Crypto API (available in browsers and Tauri WebView).\n * Accepts \"sha384-<base64>\" format matching the W3C SRI spec.\n * See: https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity\n */\n\nconst SUPPORTED_ALGORITHMS = ['sha256', 'sha384', 'sha512'] as const;\ntype SriAlgorithm = (typeof SUPPORTED_ALGORITHMS)[number];\n\n/**\n * Parse an SRI integrity string into its algorithm and base64 hash components.\n *\n * @param integrity - SRI string in the form `\"<algorithm>-<base64hash>\"`.\n * @returns Object with `algorithm` and `hash` fields.\n * @throws If the format is invalid or the algorithm is not supported.\n */\nfunction parseSri(integrity: string): { algorithm: SriAlgorithm; hash: string } {\n const dashIndex = integrity.indexOf('-');\n if (dashIndex === -1) {\n throw new Error(`Invalid SRI format: ${integrity}`);\n }\n const algorithm = integrity.slice(0, dashIndex) as SriAlgorithm;\n const hash = integrity.slice(dashIndex + 1);\n\n if (!SUPPORTED_ALGORITHMS.includes(algorithm)) {\n throw new Error(\n `Unsupported SRI algorithm: ${algorithm}. Supported: ${SUPPORTED_ALGORITHMS.join(', ')}`,\n );\n }\n if (!hash) {\n throw new Error(`Empty hash in SRI: ${integrity}`);\n }\n return { algorithm, hash };\n}\n\n/**\n * Map an SRI algorithm name to its Web Crypto API equivalent.\n *\n * @param alg - SRI algorithm name (`\"sha256\"`, `\"sha384\"`, `\"sha512\"`).\n * @returns Web Crypto algorithm name (e.g. `\"SHA-384\"`).\n */\nfunction algorithmToWebCrypto(alg: SriAlgorithm): string {\n return `SHA-${alg.slice(3)}`;\n}\n\n/**\n * Encode an `ArrayBuffer` as a base64 string.\n *\n * @param buffer - Raw bytes to encode.\n * @returns Base64 string representation of `buffer`.\n */\nfunction bufferToBase64(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer);\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n/**\n * Verify that `data` matches the expected SRI integrity string.\n *\n * Uses the Web Crypto API to compute the digest and compares it against the\n * base64 hash in `integrity`. Throws with a descriptive message on any\n * mismatch, invalid format, or unsupported algorithm.\n *\n * @param data - Raw bytes of the downloaded bundle.\n * @param integrity - SRI hash string, e.g. `\"sha384-abc123...\"`.\n * @returns Resolves on success; throws on mismatch or bad format.\n * @throws If the format is invalid, the algorithm is unsupported, or the hash does not match.\n */\nexport async function verifyIntegrity(data: ArrayBuffer, integrity: string): Promise<void> {\n const { algorithm, hash: expectedHash } = parseSri(integrity);\n const webCryptoAlg = algorithmToWebCrypto(algorithm);\n const digest = await crypto.subtle.digest(webCryptoAlg, data);\n const actualHash = bufferToBase64(digest);\n\n if (actualHash !== expectedHash) {\n throw new Error(\n `Integrity check failed for ${algorithm}. ` +\n `Expected: ${expectedHash}, got: ${actualHash}`,\n );\n }\n}\n\n/**\n * Compute an SRI hash for the given data.\n *\n * Useful for publishing tools that need to generate the `integrity` field\n * for a `registry.json` entry. Defaults to `sha384`, which is the recommended\n * algorithm for the SH3 registry protocol.\n *\n * @param data - Raw bytes of the bundle to hash.\n * @param algorithm - Hash algorithm to use. Defaults to `\"sha384\"`.\n * @returns SRI string in the form `\"<algorithm>-<base64hash>\"`.\n */\nexport async function computeIntegrity(\n data: ArrayBuffer,\n algorithm: 'sha256' | 'sha384' | 'sha512' = 'sha384',\n): Promise<string> {\n const webCryptoAlg = algorithmToWebCrypto(algorithm);\n const digest = await crypto.subtle.digest(webCryptoAlg, data);\n const hash = bufferToBase64(digest);\n return `${algorithm}-${hash}`;\n}\n","/**\n * Registry client -- fetches and merges registry indices, resolves\n * packages, and downloads bundles with integrity verification.\n *\n * Typical usage:\n * ```ts\n * const packages = await fetchRegistries(['https://example.com/registry.json']);\n * const pkg = packages.find(p => p.entry.id === 'my-shard');\n * if (pkg) {\n * const data = await fetchBundle(pkg.latest);\n * const meta = buildPackageMeta(pkg, pkg.latest);\n * }\n * ```\n */\n\nimport type { PackageEntry, PackageVersion, PackageMeta } from './types.js';\nimport { validateRegistryIndex } from './schema.js';\nimport { verifyIntegrity } from './integrity.js';\n\n/**\n * A `PackageEntry` annotated with its source registry URL and resolved latest version.\n *\n * Returned by `fetchRegistries` so callers can display package cards and\n * initiate installs without needing to re-parse the raw index document.\n */\nexport interface ResolvedPackage {\n /** The raw package entry from the registry index. */\n entry: PackageEntry;\n /**\n * The latest version of this package.\n * By convention this is `entry.versions[0]` — registries publish newest-first.\n */\n latest: PackageVersion;\n /** URL of the registry index this package was found in. */\n sourceRegistry: string;\n}\n\n/**\n * Fetch and merge multiple registry indices into a single package catalog.\n *\n * Registries are fetched in order. If the same package id appears in more\n * than one registry, the first registry wins (left-to-right priority).\n * Fetch or validation failures for individual registries are logged as\n * warnings and skipped — the function always returns the packages that\n * could be resolved successfully.\n *\n * @param urls - Ordered list of `registry.json` URLs to fetch.\n * @returns Merged list of resolved packages, deduplicated by package id.\n */\nexport async function fetchRegistries(urls: string[]): Promise<ResolvedPackage[]> {\n const seen = new Set<string>();\n const results: ResolvedPackage[] = [];\n\n for (const url of urls) {\n let raw: unknown;\n try {\n const response = await fetch(url);\n if (!response.ok) {\n console.warn(`[sh3] Registry fetch failed for ${url}: HTTP ${response.status}`);\n continue;\n }\n raw = await response.json();\n } catch (err) {\n console.warn(\n `[sh3] Registry ${url}: ${err instanceof Error ? err.message : String(err)}`,\n );\n continue;\n }\n\n let index;\n try {\n index = validateRegistryIndex(raw);\n } catch (err) {\n console.warn(\n `[sh3] Registry ${url} failed validation: ${err instanceof Error ? err.message : String(err)}`,\n );\n continue;\n }\n\n for (const entry of index.packages) {\n if (seen.has(entry.id)) continue;\n seen.add(entry.id);\n results.push({\n entry,\n latest: entry.versions[0],\n sourceRegistry: url,\n });\n }\n }\n\n return results;\n}\n\n/**\n * Download a bundle and verify its SRI integrity hash.\n *\n * Fetches `version.bundleUrl`, reads the response as an `ArrayBuffer`, then\n * calls `verifyIntegrity` before returning. Throws on any network error,\n * non-OK HTTP status, or integrity mismatch — the caller must not execute\n * a bundle for which this function threw.\n *\n * If `bundleUrl` is relative (starts with `/`), it is resolved against\n * `sourceRegistry` so cross-origin installs hit the correct server.\n *\n * @param version - The `PackageVersion` describing the bundle to download.\n * @param sourceRegistry - The registry URL this package came from (used to resolve relative bundle paths).\n * @returns Raw bundle bytes, verified against `version.integrity`.\n * @throws If the fetch fails, the server returns a non-OK status, or the integrity check fails.\n */\nexport async function fetchBundle(version: PackageVersion, sourceRegistry?: string): Promise<ArrayBuffer> {\n if (!version.bundleUrl || !version.integrity) {\n throw new Error('fetchBundle called on a version with no client bundle');\n }\n let url = version.bundleUrl;\n if (sourceRegistry && !/^https?:\\/\\//i.test(url)) {\n url = new URL(url, sourceRegistry).href;\n }\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(\n `Bundle fetch failed: HTTP ${response.status} ${response.statusText} from ${url}`,\n );\n }\n const data = await response.arrayBuffer();\n await verifyIntegrity(data, version.integrity);\n return data;\n}\n\n/**\n * Download a server-side bundle and optionally verify its SRI integrity.\n *\n * Mirrors `fetchBundle` except `serverIntegrity` is optional in contract v1\n * (see ADR-015 proposal). When absent, the download is returned without\n * verification and a warning is logged so operators notice provisional\n * registries. When present, an integrity mismatch throws.\n *\n * @param version - The `PackageVersion` describing the server bundle.\n * @param sourceRegistry - The registry URL (used to resolve relative paths).\n * @returns Raw server bundle bytes.\n * @throws If `serverBundleUrl` is absent, the fetch fails, or an integrity mismatch occurs.\n */\nexport async function fetchServerBundle(\n version: PackageVersion,\n sourceRegistry?: string,\n): Promise<ArrayBuffer> {\n if (!version.serverBundleUrl) {\n throw new Error('fetchServerBundle called on a version with no serverBundleUrl');\n }\n let url = version.serverBundleUrl;\n if (sourceRegistry && !/^https?:\\/\\//i.test(url)) {\n url = new URL(url, sourceRegistry).href;\n }\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(\n `Server bundle fetch failed: HTTP ${response.status} ${response.statusText} from ${url}`,\n );\n }\n const data = await response.arrayBuffer();\n if (version.serverIntegrity) {\n await verifyIntegrity(data, version.serverIntegrity);\n } else {\n console.warn(\n `[sh3] Server bundle at ${url} has no serverIntegrity declared — skipping SRI check. `\n + 'This will become an error once the formal registry spec (ADR-015) lands.',\n );\n }\n return data;\n}\n\n/**\n * Build a `PackageMeta` record from a resolved package and a chosen version.\n *\n * Combines identity fields from the `PackageEntry` with provenance and\n * integrity fields from the selected `PackageVersion`. The result is passed\n * to the framework install API alongside the raw bundle bytes.\n *\n * @param resolved - The resolved package, as returned by `fetchRegistries`.\n * @param version - The specific version to install (e.g. `resolved.latest`).\n * @returns A `PackageMeta` ready to be handed to the install API.\n */\nexport function buildPackageMeta(resolved: ResolvedPackage, version: PackageVersion): PackageMeta {\n return {\n id: resolved.entry.id,\n type: resolved.entry.type,\n version: version.version,\n contractVersion: version.contractVersion,\n sourceRegistry: resolved.sourceRegistry,\n integrity: version.integrity,\n requires: version.requires,\n hasServerBundle: Boolean(version.serverBundleUrl),\n serverIntegrity: version.serverIntegrity,\n };\n}\n","/** Auto-generated from package.json — do not edit manually. */\nexport const VERSION = '0.13.3';\n","/*\n * Token override API — allows external packages (like sh3-style) to\n * dynamically change shell CSS tokens and persist the selection to\n * the User zone.\n *\n * The shell reads persisted overrides at boot (see createShell.ts) so\n * themes survive page reloads. This module provides the write path.\n */\n\nconst STORAGE_KEY = 'sh3:user:__sh3core__:theme';\n\n/** Keys currently set on :root by setTokenOverrides, tracked for clearTokenOverrides. */\nlet appliedKeys: string[] = [];\n\n/**\n * Apply CSS token overrides to :root and persist to User zone.\n *\n * Keys are token names without the `--` prefix (e.g. `'shell-accent'`).\n * Values are any valid CSS value string.\n *\n * Calling this replaces ALL previous overrides — tokens not present in\n * the new map are removed from :root.\n */\nexport function setTokenOverrides(overrides: Record<string, string>): void {\n // Remove previously applied keys that are not in the new set\n const newKeys = Object.keys(overrides);\n for (const key of appliedKeys) {\n if (!newKeys.includes(key)) {\n document.documentElement.style.removeProperty(`--${key}`);\n }\n }\n\n // Apply new overrides\n for (const [key, value] of Object.entries(overrides)) {\n document.documentElement.style.setProperty(`--${key}`, value);\n }\n appliedKeys = newKeys;\n\n // Persist\n try {\n localStorage.setItem(STORAGE_KEY, JSON.stringify(overrides));\n } catch {\n // Storage full or unavailable — theme applies for this session only\n }\n}\n\n/**\n * Remove all token overrides from :root and clear persisted state.\n * The shell reverts to the default tokens defined in tokens.css.\n */\nexport function clearTokenOverrides(): void {\n for (const key of appliedKeys) {\n document.documentElement.style.removeProperty(`--${key}`);\n }\n appliedKeys = [];\n\n try {\n localStorage.removeItem(STORAGE_KEY);\n } catch {\n // Ignore\n }\n}\n\n/**\n * Read the currently persisted token overrides.\n * Returns an empty object if no overrides are stored.\n */\nexport function getTokenOverrides(): Record<string, string> {\n try {\n const raw = localStorage.getItem(STORAGE_KEY);\n if (!raw) return {};\n const parsed = JSON.parse(raw);\n if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {\n return parsed as Record<string, string>;\n }\n return {};\n } catch {\n return {};\n }\n}\n\n/**\n * Apply persisted token overrides to :root. Called once during shell boot\n * before any component mounts, so the themed colors are visible from the\n * first frame.\n *\n * This is framework-internal — not part of the shard-facing API.\n */\nexport function hydrateTokenOverrides(): void {\n const overrides = getTokenOverrides();\n if (Object.keys(overrides).length === 0) return;\n for (const [key, value] of Object.entries(overrides)) {\n document.documentElement.style.setProperty(`--${key}`, value);\n }\n appliedKeys = Object.keys(overrides);\n}\n","export default \"__VITE_ASSET__CMaiXz4u__\"","/*\n * Icon sprite context — lets a view opt all descendant <Button> (and any\n * future icon-consuming primitive) into using a different sprite sheet\n * than sh3-core's default assets/icons.svg.\n *\n * Resolution order inside Button is:\n * 1. `sprite` prop on the Button (explicit one-off override)\n * 2. nearest `provideIcons(url)` call up the Svelte tree (this module)\n * 3. sh3-core's bundled sprite (fallback)\n *\n * This is tree-scoped (Svelte context), so it does not cross custom\n * element / iframe boundaries. Shards that render inside such boundaries\n * should pass `sprite` explicitly or call provideIcons() from their own\n * root component.\n */\n\nimport { getContext, setContext } from 'svelte';\n\n/**\n * Visual variants for <Button>. Exported from this module (rather than\n * from Button.svelte itself) so TypeDoc, which only sees `.svelte`\n * imports through the ambient `*.svelte` asset declaration, can\n * discover it. Button.svelte re-imports this type.\n */\nexport type ButtonVariant = 'default' | 'alert' | 'ghost' | 'icon';\n\nconst ICON_SPRITE_KEY = Symbol('sh3.icon-sprite');\n\n/**\n * Register an icon sprite URL for this subtree. Call from a view's\n * <script> block to have every descendant <Button icon=\"...\"/> resolve\n * the icon name against this sprite.\n */\nexport function provideIcons(spriteUrl: string): void {\n setContext(ICON_SPRITE_KEY, spriteUrl);\n}\n\n/** Read the currently-active sprite URL, or undefined if none set. */\nexport function getIconSprite(): string | undefined {\n return getContext<string | undefined>(ICON_SPRITE_KEY);\n}\n","<script lang=\"ts\">\n /*\n * Button — themed button primitive for shards and apps.\n *\n * Icons resolve via a three-tier lookup (see primitives/icon-context.ts).\n * `icon` accepts either a sprite symbol id (\"save\") or a direct URL\n * ending in .svg / containing a slash (\"./foo.svg\"); the URL form\n * bypasses the active sprite entirely.\n *\n * `loading` flips the button into a pending state: spinner takes the\n * icon slot, label stays put, button is disabled, aria-busy is set.\n */\n\n import type { Snippet } from 'svelte';\n import coreSpriteUrl from '../assets/icons.svg';\n import { getIconSprite, type ButtonVariant } from './icon-context';\n\n let {\n variant = 'default',\n icon,\n sprite,\n disabled = false,\n loading,\n type = 'button',\n title,\n ariaLabel,\n onclick,\n children,\n }: {\n variant?: ButtonVariant;\n /** Sprite symbol id, or a direct .svg URL. */\n icon?: string;\n /** Override the sprite sheet URL for this button only. */\n sprite?: string;\n disabled?: boolean;\n /** Controlled pending state. When true, spinner + disabled + aria-busy. */\n loading?: boolean;\n type?: 'button' | 'submit' | 'reset';\n title?: string;\n ariaLabel?: string;\n onclick?: (event: MouseEvent) => void | Promise<unknown>;\n children?: Snippet;\n } = $props();\n\n const contextSprite = getIconSprite();\n\n function isDirectUrl(value: string): boolean {\n return value.includes('/') || value.endsWith('.svg');\n }\n\n const iconHref = $derived.by(() => {\n if (!icon) return undefined;\n if (isDirectUrl(icon)) return icon;\n const base = sprite ?? contextSprite ?? coreSpriteUrl;\n return `${base}#${icon}`;\n });\n\n let autoPending = $state(false);\n const pending = $derived(loading ?? autoPending);\n const iconOnly = $derived(variant === 'icon' || (!!icon && !children));\n\n async function handleClick(event: MouseEvent) {\n if (!onclick) return;\n const result = onclick(event);\n if (result && typeof (result as PromiseLike<unknown>).then === 'function') {\n autoPending = true;\n try {\n await result;\n } finally {\n autoPending = false;\n }\n }\n }\n</script>\n\n<button\n {type}\n class=\"sh3-btn sh3-btn--{variant}\"\n class:sh3-btn--icon-only={iconOnly}\n disabled={disabled || pending}\n aria-busy={pending || undefined}\n {title}\n aria-label={ariaLabel ?? (iconOnly ? title : undefined)}\n onclick={handleClick}\n>\n {#if pending}\n <svg class=\"sh3-btn__spinner\" aria-hidden=\"true\" viewBox=\"0 0 16 16\">\n <circle\n cx=\"8\"\n cy=\"8\"\n r=\"6\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-dasharray=\"30 10\"\n />\n </svg>\n {:else if iconHref}\n <svg class=\"sh3-btn__icon\" aria-hidden=\"true\">\n <use href={iconHref} />\n </svg>\n {/if}\n {#if children}\n <span class=\"sh3-btn__label\">{@render children()}</span>\n {/if}\n</button>\n\n<style>\n .sh3-btn {\n appearance: none;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: var(--shell-pad-sm);\n padding: 6px 14px;\n background: var(--shell-accent);\n color: var(--shell-fg-on-accent);\n border: none;\n border-radius: var(--shell-radius);\n cursor: pointer;\n font-family: inherit;\n font-size: 0.875rem;\n line-height: var(--shell-line);\n }\n .sh3-btn:hover:not(:disabled) { filter: brightness(1.12); }\n .sh3-btn:active:not(:disabled) { filter: brightness(0.92); }\n .sh3-btn:focus-visible {\n box-shadow: var(--shell-focus-ring);\n outline: none;\n }\n .sh3-btn:disabled {\n opacity: 0.55;\n cursor: not-allowed;\n }\n\n .sh3-btn--alert {\n background: var(--shell-error);\n color: var(--shell-fg-on-error);\n }\n\n .sh3-btn--ghost {\n background: transparent;\n color: var(--shell-fg);\n border: 1px solid var(--shell-border);\n }\n .sh3-btn--ghost:hover:not(:disabled) {\n background: var(--shell-bg-elevated);\n filter: none;\n }\n\n .sh3-btn--icon {\n background: transparent;\n color: var(--shell-fg-muted);\n padding: var(--shell-pad-sm);\n }\n .sh3-btn--icon:hover:not(:disabled) {\n background: var(--shell-bg-elevated);\n color: var(--shell-fg);\n filter: none;\n }\n\n .sh3-btn--icon-only {\n padding: var(--shell-pad-sm);\n width: 26px;\n height: 26px;\n }\n\n .sh3-btn__icon {\n width: 16px;\n height: 16px;\n flex-shrink: 0;\n }\n\n .sh3-btn__label {\n display: inline-flex;\n white-space: nowrap;\n }\n\n .sh3-btn__spinner {\n width: 16px;\n height: 16px;\n flex-shrink: 0;\n animation: sh3-btn-spin 0.8s linear infinite;\n }\n\n @keyframes sh3-btn-spin {\n to { transform: rotate(360deg); }\n }\n</style>\n","<script lang=\"ts\">\n /*\n * Collapsible — structural primitive for show/hide sections.\n *\n * Body is conditionally rendered (not just hidden) so heavy children\n * don't stay live when collapsed. Defaults to closed. No collapse/expand\n * animation in v1 — caret rotates 90° via CSS, but no transitions\n * (waiting on the motion RFC).\n *\n * `header` snippet, when provided, replaces the `title` string.\n */\n\n import type { Snippet } from 'svelte';\n\n let {\n open = $bindable(false),\n title,\n header,\n children,\n onopenchange,\n }: {\n /** Bindable; defaults to false. */\n open?: boolean;\n /** Plain text header. Ignored if `header` snippet is provided. */\n title?: string;\n /** Snippet alternative to `title` for richer headers. */\n header?: Snippet;\n children: Snippet;\n onopenchange?: (open: boolean) => void;\n } = $props();\n\n function toggle() {\n open = !open;\n onopenchange?.(open);\n }\n</script>\n\n<div class=\"sh3-collapsible\" class:sh3-collapsible--open={open}>\n <button\n class=\"sh3-collapsible__head\"\n type=\"button\"\n aria-expanded={open}\n onclick={toggle}\n >\n <svg class=\"sh3-collapsible__caret\" aria-hidden=\"true\" viewBox=\"0 0 16 16\">\n <path\n d=\"M5 3l6 5-6 5\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n />\n </svg>\n {#if header}\n {@render header()}\n {:else if title}\n <span class=\"sh3-collapsible__title\">{title}</span>\n {/if}\n </button>\n {#if open}\n <div class=\"sh3-collapsible__body\">{@render children()}</div>\n {/if}\n</div>\n\n<style>\n .sh3-collapsible {\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius);\n background: transparent;\n }\n .sh3-collapsible__head {\n appearance: none;\n width: 100%;\n display: inline-flex;\n align-items: center;\n gap: var(--shell-pad-sm);\n padding: var(--shell-pad-sm) 12px;\n background: transparent;\n color: var(--shell-fg);\n border: none;\n border-radius: inherit;\n cursor: pointer;\n font-family: inherit;\n font-size: 0.875rem;\n line-height: var(--shell-line);\n text-align: left;\n }\n .sh3-collapsible__head:hover { background: var(--shell-bg-elevated); }\n .sh3-collapsible__head:focus-visible {\n box-shadow: var(--shell-focus-ring);\n outline: none;\n }\n .sh3-collapsible__caret {\n width: 12px;\n height: 12px;\n flex-shrink: 0;\n color: var(--shell-fg-muted);\n }\n .sh3-collapsible--open .sh3-collapsible__caret {\n transform: rotate(90deg);\n }\n .sh3-collapsible__title {\n flex: 1;\n }\n .sh3-collapsible__body {\n padding: var(--shell-pad-sm) 12px;\n border-top: 1px solid var(--shell-border);\n }\n</style>\n","<script lang=\"ts\">\n import type { Snippet } from 'svelte';\n import type { LiveInputEvents } from './_contract';\n\n let {\n value = $bindable(''),\n type = 'text',\n label,\n placeholder,\n prefix,\n suffix,\n helper,\n error,\n disabled = false,\n invalid = false,\n size = 'md',\n required = false,\n autocomplete,\n oninput,\n onchange,\n }: {\n value?: string;\n type?: 'text' | 'email' | 'password' | 'search' | 'url' | 'tel';\n label?: string;\n placeholder?: string;\n prefix?: Snippet;\n suffix?: Snippet;\n helper?: string;\n error?: string;\n disabled?: boolean;\n invalid?: boolean;\n size?: 'sm' | 'md';\n required?: boolean;\n autocomplete?: AutoFill;\n } & LiveInputEvents<string> = $props();\n\n const showError = $derived(invalid && !!error);\n const helperText = $derived(showError ? error : helper);\n</script>\n\n<label class=\"sh3-field\" class:sh3-field--invalid={invalid} class:sh3-field--sm={size === 'sm'}>\n {#if label}<span class=\"sh3-field__label\">{label}{#if required}<span aria-hidden=\"true\"> *</span>{/if}</span>{/if}\n <span class=\"sh3-field__row\">\n {#if prefix}<span class=\"sh3-field__affix\">{@render prefix()}</span>{/if}\n <input\n class=\"sh3-field__input\"\n {type}\n {placeholder}\n {disabled}\n {required}\n {autocomplete}\n aria-invalid={invalid || undefined}\n bind:value\n oninput={() => oninput?.(value)}\n onblur={() => onchange?.(value)}\n />\n {#if suffix}<span class=\"sh3-field__affix\">{@render suffix()}</span>{/if}\n </span>\n {#if helperText}<span class=\"sh3-field__helper\" class:sh3-field__helper--error={showError}>{helperText}</span>{/if}\n</label>\n\n<style>\n .sh3-field {\n display: inline-flex;\n flex-direction: column;\n gap: 4px;\n font-family: var(--shell-font-ui);\n font-size: 0.8125rem;\n color: var(--shell-fg);\n }\n .sh3-field__label {\n color: var(--shell-fg-muted);\n font-size: 0.75rem;\n }\n .sh3-field__row {\n display: inline-flex;\n align-items: stretch;\n background: var(--shell-input-bg);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-widget-radius);\n height: var(--shell-field-height-md);\n transition: border-color var(--shell-motion-fast) var(--shell-ease-standard),\n box-shadow var(--shell-motion-fast) var(--shell-ease-standard);\n }\n .sh3-field--sm .sh3-field__row { height: var(--shell-field-height-sm); }\n .sh3-field__row:focus-within {\n border-color: var(--shell-input-border-focus);\n box-shadow: var(--shell-focus-ring);\n }\n .sh3-field--invalid .sh3-field__row {\n border-color: var(--shell-error);\n }\n .sh3-field--invalid .sh3-field__row:focus-within {\n box-shadow: 0 0 0 2px color-mix(in srgb, var(--shell-error) 40%, transparent);\n }\n .sh3-field__input {\n flex: 1 1 auto;\n height: 100%;\n padding: 0 var(--shell-field-pad-x);\n background: transparent;\n border: none;\n color: inherit;\n font: inherit;\n outline: none;\n }\n /* The .sh3-field__row owns the focus ring; suppress base.css's\n global input:focus-visible box-shadow so it doesn't double up. */\n .sh3-field__input:focus,\n .sh3-field__input:focus-visible {\n outline: none;\n box-shadow: none;\n border: none;\n }\n .sh3-field__input:disabled { color: var(--shell-fg-muted); cursor: not-allowed; }\n .sh3-field__affix {\n display: inline-flex;\n align-items: center;\n padding: 0 var(--shell-field-pad-x);\n color: var(--shell-fg-muted);\n flex-shrink: 0;\n }\n .sh3-field__affix:first-child { padding-right: 0; }\n .sh3-field__affix:last-child { padding-left: 0; }\n .sh3-field__helper {\n color: var(--shell-fg-muted);\n font-size: 0.75rem;\n }\n .sh3-field__helper--error { color: var(--shell-error); }\n</style>\n","<script lang=\"ts\">\n import type { LiveInputEvents } from './_contract';\n\n let {\n value = $bindable(''),\n label,\n placeholder,\n helper,\n error,\n disabled = false,\n invalid = false,\n size = 'md',\n required = false,\n rows = 3,\n resize = 'vertical',\n oninput,\n onchange,\n }: {\n value?: string;\n label?: string;\n placeholder?: string;\n helper?: string;\n error?: string;\n disabled?: boolean;\n invalid?: boolean;\n size?: 'sm' | 'md';\n required?: boolean;\n rows?: number;\n resize?: 'none' | 'vertical' | 'both';\n } & LiveInputEvents<string> = $props();\n\n const showError = $derived(invalid && !!error);\n const helperText = $derived(showError ? error : helper);\n</script>\n\n<label class=\"sh3-textarea\" class:sh3-textarea--invalid={invalid} class:sh3-textarea--sm={size === 'sm'}>\n {#if label}<span class=\"sh3-textarea__label\">{label}{#if required}<span aria-hidden=\"true\"> *</span>{/if}</span>{/if}\n <textarea\n class=\"sh3-textarea__input\"\n style:resize\n {placeholder}\n {disabled}\n {required}\n {rows}\n aria-invalid={invalid || undefined}\n bind:value\n oninput={() => oninput?.(value)}\n onblur={() => onchange?.(value)}\n ></textarea>\n {#if helperText}<span class=\"sh3-textarea__helper\" class:sh3-textarea__helper--error={showError}>{helperText}</span>{/if}\n</label>\n\n<style>\n .sh3-textarea {\n display: inline-flex;\n flex-direction: column;\n gap: 4px;\n font-family: var(--shell-font-ui);\n font-size: 0.8125rem;\n }\n .sh3-textarea__label {\n color: var(--shell-fg-muted);\n font-size: 0.75rem;\n }\n .sh3-textarea__input {\n background: var(--shell-input-bg);\n color: var(--shell-fg);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-widget-radius);\n padding: var(--shell-pad-sm) var(--shell-field-pad-x);\n font: inherit;\n outline: none;\n transition: border-color var(--shell-motion-fast) var(--shell-ease-standard);\n }\n .sh3-textarea__input:focus {\n border-color: var(--shell-input-border-focus);\n box-shadow: var(--shell-focus-ring);\n }\n .sh3-textarea--invalid .sh3-textarea__input {\n border-color: var(--shell-error);\n }\n .sh3-textarea__helper {\n color: var(--shell-fg-muted);\n font-size: 0.75rem;\n }\n .sh3-textarea__helper--error { color: var(--shell-error); }\n</style>\n","export function clamp(value: number, min: number | undefined, max: number | undefined): number {\n let v = value;\n if (min !== undefined && v < min) v = min;\n if (max !== undefined && v > max) v = max;\n return v;\n}\n\nexport function applyStep(value: number, opts: { min?: number; step: number }): number {\n const base = opts.min ?? 0;\n const k = Math.round((value - base) / opts.step);\n return base + k * opts.step;\n}\n\nexport function formatNumber(value: number, precision: number | undefined): string {\n if (precision === undefined) return String(value);\n return value.toFixed(precision);\n}\n","<script lang=\"ts\">\n import type { Snippet } from 'svelte';\n import type { LiveInputEvents } from './_contract';\n import { clamp, applyStep } from './NumberInput';\n\n let {\n value = $bindable(0),\n min,\n max,\n step = 1,\n precision,\n label,\n prefix,\n suffix,\n disabled = false,\n invalid = false,\n size = 'md',\n oninput,\n onchange,\n }: {\n value?: number;\n min?: number;\n max?: number;\n step?: number;\n precision?: number;\n label?: string;\n prefix?: Snippet;\n suffix?: Snippet;\n disabled?: boolean;\n invalid?: boolean;\n size?: 'sm' | 'md';\n } & LiveInputEvents<number> = $props();\n\n function commit(next: number) {\n if (Number.isNaN(next)) return;\n let v = clamp(applyStep(next, { min, step }), min, max);\n if (precision !== undefined) v = Number(v.toFixed(precision));\n value = v;\n }\n\n function bump(direction: 1 | -1) {\n commit(value + direction * step);\n oninput?.(value);\n }\n\n let holdTimer: ReturnType<typeof setTimeout> | null = null;\n let holdInterval: ReturnType<typeof setInterval> | null = null;\n let bumping = false;\n function startHold(direction: 1 | -1) {\n if (disabled) return;\n bumping = true;\n bump(direction);\n holdTimer = setTimeout(() => {\n let elapsed = 0;\n holdInterval = setInterval(() => {\n bump(direction);\n elapsed += 60;\n if (elapsed > 1500 && holdInterval) {\n clearInterval(holdInterval);\n holdInterval = setInterval(() => bump(direction), 20);\n }\n }, 60);\n }, 350);\n }\n function stopHold() {\n if (holdTimer) { clearTimeout(holdTimer); holdTimer = null; }\n if (holdInterval) { clearInterval(holdInterval); holdInterval = null; }\n if (bumping) {\n bumping = false;\n onchange?.(value);\n }\n }\n</script>\n\n<label class=\"sh3-num\" class:sh3-num--invalid={invalid} class:sh3-num--sm={size === 'sm'}>\n {#if label}<span class=\"sh3-num__label\">{label}</span>{/if}\n <span class=\"sh3-num__row\">\n {#if prefix}<span class=\"sh3-num__affix\">{@render prefix()}</span>{/if}\n <input\n class=\"sh3-num__input\"\n type=\"number\"\n {min}\n {max}\n {step}\n {disabled}\n aria-invalid={invalid || undefined}\n value={value}\n oninput={(e) => {\n const raw = (e.currentTarget as HTMLInputElement).valueAsNumber;\n if (Number.isNaN(raw)) return;\n value = raw;\n oninput?.(raw);\n }}\n onblur={() => {\n commit(value);\n onchange?.(value);\n }}\n />\n {#if suffix}<span class=\"sh3-num__affix\">{@render suffix()}</span>{/if}\n <span class=\"sh3-num__steppers\">\n <button type=\"button\" {disabled}\n onpointerdown={() => startHold(1)}\n onpointerup={stopHold}\n onpointerleave={stopHold}\n aria-label=\"Increase\">▲</button>\n <button type=\"button\" {disabled}\n onpointerdown={() => startHold(-1)}\n onpointerup={stopHold}\n onpointerleave={stopHold}\n aria-label=\"Decrease\">▼</button>\n </span>\n </span>\n</label>\n\n<style>\n .sh3-num { display: inline-flex; flex-direction: column; gap: 4px; font-size: 0.8125rem; }\n .sh3-num__label { color: var(--shell-fg-muted); font-size: 0.75rem; }\n .sh3-num__row {\n display: inline-flex;\n align-items: stretch;\n background: var(--shell-input-bg);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-widget-radius);\n height: var(--shell-field-height-md);\n }\n .sh3-num--sm .sh3-num__row { height: var(--shell-field-height-sm); }\n .sh3-num__row:focus-within {\n border-color: var(--shell-input-border-focus);\n box-shadow: var(--shell-focus-ring);\n }\n .sh3-num--invalid .sh3-num__row { border-color: var(--shell-error); }\n .sh3-num__input {\n flex: 1 1 auto;\n min-width: 50px;\n padding: 0 var(--shell-field-pad-x);\n background: transparent;\n border: none;\n color: var(--shell-fg);\n font: inherit;\n outline: none;\n -moz-appearance: textfield;\n appearance: textfield;\n }\n /* Row owns the focus ring; suppress base.css's global input:focus-visible. */\n .sh3-num__input:focus,\n .sh3-num__input:focus-visible {\n outline: none;\n box-shadow: none;\n border: none;\n }\n .sh3-num__input::-webkit-outer-spin-button,\n .sh3-num__input::-webkit-inner-spin-button {\n -webkit-appearance: none;\n margin: 0;\n }\n .sh3-num__affix {\n display: inline-flex;\n align-items: center;\n padding: 0 6px;\n color: var(--shell-fg-muted);\n }\n .sh3-num__steppers {\n display: inline-flex;\n flex-direction: column;\n border-left: 1px solid var(--shell-border);\n }\n .sh3-num__steppers button {\n flex: 1;\n width: 18px;\n background: transparent;\n color: var(--shell-fg-muted);\n border: none;\n border-radius: 0;\n padding: 0;\n cursor: pointer;\n font-size: 8px;\n line-height: 1;\n }\n .sh3-num__steppers button:hover:not(:disabled) {\n background: var(--shell-bg-elevated);\n color: var(--shell-fg);\n filter: none;\n }\n .sh3-num__steppers button:disabled { cursor: not-allowed; opacity: 0.5; }\n .sh3-num__steppers button + button { border-top: 1px solid var(--shell-border); }\n</style>\n","export interface SegmentedOption {\n value: string;\n label: string;\n disabled?: boolean;\n}\n\nfunction activeOptions(opts: SegmentedOption[]): SegmentedOption[] {\n return opts.filter((o) => !o.disabled);\n}\n\nexport function nextValue(opts: SegmentedOption[], current: string): string {\n const active = activeOptions(opts);\n if (active.length === 0) return current;\n const idx = active.findIndex((o) => o.value === current);\n const next = active[(idx + 1 + active.length) % active.length];\n return next.value;\n}\n\nexport function prevValue(opts: SegmentedOption[], current: string): string {\n const active = activeOptions(opts);\n if (active.length === 0) return current;\n const idx = active.findIndex((o) => o.value === current);\n const prev = active[(idx - 1 + active.length) % active.length];\n return prev.value;\n}\n\nexport function firstValue(opts: SegmentedOption[]): string | undefined {\n return activeOptions(opts)[0]?.value;\n}\n\nexport function lastValue(opts: SegmentedOption[]): string | undefined {\n const a = activeOptions(opts);\n return a[a.length - 1]?.value;\n}\n","<script lang=\"ts\">\n import type { CommitOnlyEvents } from './_contract';\n import { type SegmentedOption, nextValue, prevValue, firstValue, lastValue } from './Segmented';\n\n let {\n options,\n value = $bindable(options[0]?.value ?? ''),\n size = 'md',\n disabled = false,\n onchange,\n }: {\n options: SegmentedOption[];\n value?: string;\n size?: 'sm' | 'md';\n disabled?: boolean;\n } & CommitOnlyEvents<string> = $props();\n\n function commit(next: string) {\n value = next;\n onchange?.(next);\n }\n\n function onKey(e: KeyboardEvent) {\n if (disabled) return;\n let next: string | undefined;\n switch (e.key) {\n case 'ArrowRight': case 'ArrowDown': next = nextValue(options, value); break;\n case 'ArrowLeft': case 'ArrowUp': next = prevValue(options, value); break;\n case 'Home': next = firstValue(options); break;\n case 'End': next = lastValue(options); break;\n default: return;\n }\n e.preventDefault();\n if (next !== undefined) commit(next);\n }\n</script>\n\n<div role=\"radiogroup\" tabindex=\"-1\" class=\"sh3-seg\" class:sh3-seg--sm={size === 'sm'} onkeydown={onKey}>\n {#each options as opt}\n <button\n type=\"button\"\n role=\"radio\"\n aria-checked={value === opt.value}\n tabindex={value === opt.value ? 0 : -1}\n disabled={disabled || opt.disabled}\n class:sh3-seg__btn--active={value === opt.value}\n onclick={() => { if (!opt.disabled && !disabled) commit(opt.value); }}\n >{opt.label}</button>\n {/each}\n</div>\n\n<style>\n .sh3-seg {\n display: inline-flex;\n background: var(--shell-bg-sunken);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-widget-radius-pill);\n padding: 2px;\n height: var(--shell-field-height-md);\n gap: 0;\n }\n .sh3-seg--sm { height: var(--shell-field-height-sm); }\n .sh3-seg button {\n background: transparent;\n color: var(--shell-fg-muted);\n border: none;\n padding: 0 var(--shell-field-pad-x);\n border-radius: var(--shell-widget-radius-pill);\n font-size: 0.8125rem;\n cursor: pointer;\n transition: background var(--shell-motion-fast) var(--shell-ease-standard),\n color var(--shell-motion-fast) var(--shell-ease-standard);\n }\n .sh3-seg button:hover:not(:disabled):not(.sh3-seg__btn--active) {\n color: var(--shell-fg);\n filter: none;\n }\n .sh3-seg__btn--active {\n background: var(--shell-accent);\n color: var(--shell-fg-on-accent);\n font-weight: 600;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25), inset 0 0 0 1px color-mix(in srgb, var(--shell-fg-on-accent) 25%, transparent);\n }\n .sh3-seg button:disabled { opacity: 0.5; cursor: not-allowed; }\n .sh3-seg button:focus-visible {\n outline: none;\n box-shadow: var(--shell-focus-ring);\n }\n</style>\n","export function toggleSingle(current: string, candidate: string): string {\n return current === candidate ? '' : candidate;\n}\n\nexport function toggleMultiple(current: string[], candidate: string): string[] {\n if (current.includes(candidate)) return current.filter((v) => v !== candidate);\n return [...current, candidate];\n}\n","<script lang=\"ts\">\n import type { Snippet } from 'svelte';\n import type { CommitOnlyEvents } from './_contract';\n import { toggleSingle, toggleMultiple } from './IconToggleGroup';\n\n type Option = { value: string; icon: Snippet; tooltip?: string };\n\n let {\n options,\n multiple = false,\n value = $bindable<string | string[]>(multiple ? [] : (options[0]?.value ?? '')),\n disabled = false,\n size = 'md',\n onchange,\n }: {\n options: Option[];\n multiple?: boolean;\n value?: string | string[];\n disabled?: boolean;\n size?: 'sm' | 'md';\n } & CommitOnlyEvents<string | string[]> = $props();\n\n function isActive(v: string): boolean {\n if (multiple && Array.isArray(value)) return value.includes(v);\n return value === v;\n }\n\n function onClick(v: string) {\n if (disabled) return;\n if (multiple) {\n const arr = Array.isArray(value) ? value : [];\n value = toggleMultiple(arr, v);\n } else {\n value = toggleSingle(typeof value === 'string' ? value : '', v);\n }\n onchange?.(value);\n }\n</script>\n\n<div role=\"group\" class=\"sh3-itg\" class:sh3-itg--sm={size === 'sm'}>\n {#each options as opt}\n <button\n type=\"button\"\n title={opt.tooltip}\n aria-label={opt.tooltip}\n aria-pressed={isActive(opt.value)}\n {disabled}\n class:sh3-itg__btn--active={isActive(opt.value)}\n onclick={() => onClick(opt.value)}\n >{@render opt.icon()}</button>\n {/each}\n</div>\n\n<style>\n .sh3-itg {\n display: inline-flex;\n background: var(--shell-bg-sunken);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-widget-radius);\n padding: 2px;\n gap: 2px;\n }\n .sh3-itg button {\n width: 26px; height: 26px;\n background: transparent;\n color: var(--shell-fg-muted);\n border: none;\n border-radius: var(--shell-radius-sm);\n cursor: pointer;\n display: inline-flex; align-items: center; justify-content: center;\n padding: 0;\n transition: background var(--shell-motion-fast) var(--shell-ease-standard),\n color var(--shell-motion-fast) var(--shell-ease-standard);\n }\n .sh3-itg--sm button { width: 22px; height: 22px; }\n .sh3-itg button:hover:not(:disabled):not(.sh3-itg__btn--active) {\n background: var(--shell-bg-elevated);\n color: var(--shell-fg);\n filter: none;\n }\n .sh3-itg__btn--active {\n background: var(--shell-accent);\n color: var(--shell-fg-on-accent);\n font-weight: 600;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25), inset 0 0 0 1px color-mix(in srgb, var(--shell-fg-on-accent) 25%, transparent);\n }\n .sh3-itg button:focus-visible { outline: none; box-shadow: var(--shell-focus-ring); }\n .sh3-itg button:disabled { opacity: 0.5; cursor: not-allowed; }\n</style>\n","export function valueToPercent(value: number, min: number, max: number): number {\n if (max === min) return 0;\n return ((value - min) / (max - min)) * 100;\n}\n\nexport function percentToValue(pct: number, min: number, max: number): number {\n return min + (pct / 100) * (max - min);\n}\n\nexport function snapToStep(\n value: number,\n base: number,\n step: number,\n bounds?: { min?: number; max?: number },\n): number {\n if (step <= 0) return value;\n const k = Math.round((value - base) / step);\n let v = base + k * step;\n if (bounds?.min !== undefined && v < bounds.min) v = bounds.min;\n if (bounds?.max !== undefined && v > bounds.max) v = bounds.max;\n return v;\n}\n","<script lang=\"ts\">\n import type { LiveInputEvents } from './_contract';\n import { valueToPercent } from './Slider';\n\n let {\n value = $bindable(0),\n min = 0,\n max = 100,\n step = 1,\n ticks,\n showValue = false,\n disabled = false,\n invalid = false,\n size = 'md',\n orientation = 'horizontal',\n oninput,\n onchange,\n }: {\n value?: number;\n min?: number;\n max?: number;\n step?: number;\n ticks?: number[];\n showValue?: boolean;\n disabled?: boolean;\n invalid?: boolean;\n size?: 'sm' | 'md';\n orientation?: 'horizontal' | 'vertical';\n } & LiveInputEvents<number> = $props();\n\n const pct = $derived(valueToPercent(value, min, max));\n</script>\n\n<div class=\"sh3-slider sh3-slider--{orientation}\"\n class:sh3-slider--sm={size === 'sm'}\n class:sh3-slider--invalid={invalid}>\n <div class=\"sh3-slider__track\">\n <div class=\"sh3-slider__fill\" style:--pct=\"{pct}%\"></div>\n {#if ticks}\n {#each ticks as t}\n <span class=\"sh3-slider__tick\" style:--tick-pct=\"{valueToPercent(t, min, max)}%\"></span>\n {/each}\n {/if}\n </div>\n <input\n type=\"range\"\n class=\"sh3-slider__native\"\n {min}\n {max}\n {step}\n {disabled}\n aria-invalid={invalid || undefined}\n bind:value\n oninput={() => oninput?.(value)}\n onchange={() => onchange?.(value)}\n />\n {#if showValue}\n <output class=\"sh3-slider__value\" style:--pct=\"{pct}%\">{value}</output>\n {/if}\n</div>\n\n<style>\n .sh3-slider {\n --thumb-size: 14px;\n position: relative;\n display: inline-block;\n }\n .sh3-slider--sm { --thumb-size: 12px; }\n .sh3-slider--horizontal { width: 200px; height: var(--thumb-size); }\n .sh3-slider--vertical { width: var(--thumb-size); height: 200px; }\n\n .sh3-slider__track {\n position: absolute;\n background: var(--shell-track-bg);\n border: 1px solid var(--shell-track-border);\n border-radius: var(--shell-widget-radius-pill);\n pointer-events: none;\n }\n .sh3-slider--horizontal .sh3-slider__track {\n top: 50%; left: 0; right: 0;\n height: 4px;\n transform: translateY(-50%);\n }\n .sh3-slider--vertical .sh3-slider__track {\n left: 50%; top: 0; bottom: 0;\n width: 4px;\n transform: translateX(-50%);\n }\n\n .sh3-slider__fill {\n position: absolute;\n background: var(--shell-track-fill);\n border-radius: inherit;\n }\n .sh3-slider--horizontal .sh3-slider__fill {\n left: 0; top: 0; bottom: 0;\n width: var(--pct);\n }\n .sh3-slider--vertical .sh3-slider__fill {\n bottom: 0; left: 0; right: 0;\n height: var(--pct);\n }\n\n .sh3-slider__tick {\n position: absolute;\n background: var(--shell-tick-bg);\n }\n .sh3-slider--horizontal .sh3-slider__tick {\n width: 1px; height: 8px; top: 50%;\n transform: translate(-50%, -50%);\n left: var(--tick-pct);\n }\n .sh3-slider--vertical .sh3-slider__tick {\n width: 8px; height: 1px; left: 50%;\n transform: translate(-50%, 50%);\n bottom: var(--tick-pct);\n }\n\n .sh3-slider__native {\n position: absolute;\n inset: 0;\n width: 100%;\n height: 100%;\n margin: 0;\n background: transparent;\n -webkit-appearance: none;\n appearance: none;\n cursor: pointer;\n }\n .sh3-slider--vertical .sh3-slider__native {\n writing-mode: vertical-lr;\n direction: rtl;\n }\n /* Browser default applies opacity:0.5 to <input>:disabled at the\n element level; that composites onto the thumb regardless of any\n pseudo-element opacity overrides. Pin to 1 here so the disabled\n thumb stays opaque and the muted-token recolor is what shows. */\n .sh3-slider__native:disabled {\n cursor: not-allowed;\n opacity: 1;\n }\n .sh3-slider--invalid .sh3-slider__track { border-color: var(--shell-error); }\n\n /* Disabled state: shift the fill + thumb to muted/border tokens\n instead of using opacity, so the thumb stays opaque (no see-through). */\n .sh3-slider:has(.sh3-slider__native:disabled) .sh3-slider__fill {\n background: var(--shell-border-strong);\n }\n\n .sh3-slider__native::-webkit-slider-thumb {\n -webkit-appearance: none;\n width: var(--thumb-size);\n height: var(--thumb-size);\n border-radius: 50%;\n background: var(--shell-thumb-bg);\n border: 2px solid var(--shell-thumb-border);\n box-shadow: var(--shell-thumb-shadow);\n cursor: pointer;\n opacity: 1;\n }\n .sh3-slider__native::-moz-range-thumb {\n width: var(--thumb-size);\n height: var(--thumb-size);\n border-radius: 50%;\n background: var(--shell-thumb-bg);\n border: 2px solid var(--shell-thumb-border);\n box-shadow: var(--shell-thumb-shadow);\n cursor: pointer;\n opacity: 1;\n }\n .sh3-slider__native:disabled::-webkit-slider-thumb {\n background: var(--shell-fg-subtle);\n border-color: var(--shell-border-strong);\n cursor: not-allowed;\n opacity: 1;\n }\n .sh3-slider__native:disabled::-moz-range-thumb {\n background: var(--shell-fg-subtle);\n border-color: var(--shell-border-strong);\n cursor: not-allowed;\n opacity: 1;\n }\n .sh3-slider__native::-webkit-slider-runnable-track,\n .sh3-slider__native::-moz-range-track {\n background: transparent;\n }\n .sh3-slider__native:focus-visible::-webkit-slider-thumb {\n box-shadow: var(--shell-focus-ring), var(--shell-thumb-shadow);\n }\n .sh3-slider__native:focus-visible::-moz-range-thumb {\n box-shadow: var(--shell-focus-ring), var(--shell-thumb-shadow);\n }\n\n .sh3-slider__value {\n position: absolute;\n font-size: 0.75rem;\n color: var(--shell-fg-muted);\n pointer-events: none;\n transform: translate(-50%, 0);\n }\n .sh3-slider--horizontal .sh3-slider__value {\n top: calc(100% + 4px);\n left: var(--pct);\n }\n .sh3-slider--vertical .sh3-slider__value {\n left: calc(100% + 6px);\n bottom: var(--pct);\n transform: translate(0, 50%);\n }\n</style>\n","export type Pair = [number, number];\n\nexport function constrainPair(current: Pair, which: 'low' | 'high', next: number): Pair {\n const [lo, hi] = current;\n if (which === 'low') {\n return [Math.min(next, hi), hi];\n }\n return [lo, Math.max(next, lo)];\n}\n","<script lang=\"ts\">\n import type { LiveInputEvents } from './_contract';\n import { valueToPercent } from './Slider';\n import { constrainPair, type Pair } from './RangeSlider';\n\n let {\n value = $bindable<Pair>([0, 100]),\n min = 0,\n max = 100,\n step = 1,\n disabled = false,\n invalid = false,\n size = 'md',\n oninput,\n onchange,\n }: {\n value?: Pair;\n min?: number;\n max?: number;\n step?: number;\n disabled?: boolean;\n invalid?: boolean;\n size?: 'sm' | 'md';\n } & LiveInputEvents<Pair> = $props();\n\n const lowPct = $derived(valueToPercent(value[0], min, max));\n const highPct = $derived(valueToPercent(value[1], min, max));\n\n function setLow(n: number) {\n value = constrainPair(value, 'low', n);\n oninput?.(value);\n }\n function setHigh(n: number) {\n value = constrainPair(value, 'high', n);\n oninput?.(value);\n }\n</script>\n\n<div class=\"sh3-range\" class:sh3-range--sm={size === 'sm'} class:sh3-range--invalid={invalid}>\n <div class=\"sh3-range__track\">\n <div class=\"sh3-range__fill\"\n style:--lo=\"{lowPct}%\"\n style:--hi=\"{highPct}%\"></div>\n </div>\n <input type=\"range\" class=\"sh3-range__native sh3-range__native--low\"\n {min} {max} {step} {disabled}\n value={value[0]}\n oninput={(e) => setLow(parseFloat((e.currentTarget as HTMLInputElement).value))}\n onchange={() => onchange?.(value)} />\n <input type=\"range\" class=\"sh3-range__native sh3-range__native--high\"\n {min} {max} {step} {disabled}\n value={value[1]}\n oninput={(e) => setHigh(parseFloat((e.currentTarget as HTMLInputElement).value))}\n onchange={() => onchange?.(value)} />\n</div>\n\n<style>\n .sh3-range {\n --thumb-size: 14px;\n position: relative;\n width: 200px; height: var(--thumb-size);\n }\n .sh3-range--sm { --thumb-size: 12px; }\n .sh3-range__track {\n position: absolute;\n top: 50%; left: 0; right: 0;\n height: 4px;\n transform: translateY(-50%);\n background: var(--shell-track-bg);\n border: 1px solid var(--shell-track-border);\n border-radius: var(--shell-widget-radius-pill);\n }\n .sh3-range__fill {\n position: absolute;\n top: 0; bottom: 0;\n left: var(--lo);\n width: calc(var(--hi) - var(--lo));\n background: var(--shell-track-fill);\n border-radius: inherit;\n }\n .sh3-range__native {\n position: absolute;\n top: 0; left: 0;\n width: 100%; height: 100%;\n margin: 0;\n background: transparent;\n -webkit-appearance: none;\n appearance: none;\n pointer-events: none;\n }\n /* See Slider.svelte — pin opacity at element level so disabled\n thumb stays opaque rather than translucent. */\n .sh3-range__native:disabled { opacity: 1; cursor: not-allowed; }\n .sh3-range__native::-webkit-slider-thumb {\n -webkit-appearance: none;\n width: var(--thumb-size); height: var(--thumb-size);\n border-radius: 50%;\n background: var(--shell-thumb-bg);\n border: 2px solid var(--shell-thumb-border);\n box-shadow: var(--shell-thumb-shadow);\n pointer-events: auto;\n cursor: pointer;\n opacity: 1;\n }\n .sh3-range__native::-moz-range-thumb {\n width: var(--thumb-size); height: var(--thumb-size);\n border-radius: 50%;\n background: var(--shell-thumb-bg);\n border: 2px solid var(--shell-thumb-border);\n box-shadow: var(--shell-thumb-shadow);\n pointer-events: auto;\n cursor: pointer;\n opacity: 1;\n }\n .sh3-range__native:disabled::-webkit-slider-thumb {\n background: var(--shell-fg-subtle);\n border-color: var(--shell-border-strong);\n cursor: not-allowed;\n opacity: 1;\n }\n .sh3-range__native:disabled::-moz-range-thumb {\n background: var(--shell-fg-subtle);\n border-color: var(--shell-border-strong);\n cursor: not-allowed;\n opacity: 1;\n }\n .sh3-range:has(.sh3-range__native:disabled) .sh3-range__fill {\n background: var(--shell-border-strong);\n }\n .sh3-range__native::-webkit-slider-runnable-track,\n .sh3-range__native::-moz-range-track {\n background: transparent;\n }\n .sh3-range--invalid .sh3-range__track { border-color: var(--shell-error); }\n</style>\n","<script lang=\"ts\">\n import type { LiveInputEvents } from './_contract';\n import Slider from './Slider.svelte';\n\n type Channel = { id: string; label: string; min?: number; max?: number; step?: number };\n\n let {\n orientation = 'horizontal',\n channels,\n values = $bindable<Record<string, number>>({}),\n showValues = false,\n disabled = false,\n size = 'md',\n oninput,\n onchange,\n }: {\n orientation?: 'horizontal' | 'vertical';\n channels: Channel[];\n values?: Record<string, number>;\n showValues?: boolean;\n disabled?: boolean;\n size?: 'sm' | 'md';\n } & LiveInputEvents<Record<string, number>> = $props();\n</script>\n\n<div class=\"sh3-sg sh3-sg--{orientation}\">\n {#each channels as ch (ch.id)}\n <div class=\"sh3-sg__channel\">\n <span class=\"sh3-sg__label\">{ch.label}</span>\n <Slider\n {orientation}\n min={ch.min ?? 0}\n max={ch.max ?? 100}\n step={ch.step ?? 1}\n {disabled}\n {size}\n showValue={showValues}\n bind:value={\n () => values[ch.id] ?? 0,\n (n: number) => values = { ...values, [ch.id]: n }\n }\n oninput={() => oninput?.(values)}\n onchange={() => onchange?.(values)}\n />\n </div>\n {/each}\n</div>\n\n<style>\n .sh3-sg { display: inline-flex; gap: var(--shell-pad-md); }\n .sh3-sg--vertical { flex-direction: row; align-items: end; }\n .sh3-sg--horizontal { flex-direction: column; }\n .sh3-sg__channel {\n display: flex; gap: 4px; align-items: center;\n }\n .sh3-sg--vertical .sh3-sg__channel { flex-direction: column-reverse; align-items: center; }\n .sh3-sg__label {\n font-size: 0.75rem;\n color: var(--shell-fg-muted);\n min-width: 60px;\n }\n .sh3-sg--vertical .sh3-sg__label { min-width: 0; text-align: center; }\n</style>\n","<script lang=\"ts\">\n import type { CommitOnlyEvents } from './_contract';\n import { shell } from '../../shellRuntime.svelte';\n\n let {\n value = $bindable('#000000'),\n label,\n disabled = false,\n size = 'md',\n onchange,\n }: {\n value?: string;\n label?: string;\n disabled?: boolean;\n size?: 'sm' | 'md';\n } & CommitOnlyEvents<string> = $props();\n\n let trigger: HTMLButtonElement | undefined;\n\n async function open() {\n if (disabled) return;\n const result = await shell.color.pick({ initial: value, anchor: trigger });\n if (result !== null && result !== undefined) {\n value = result;\n onchange?.(result);\n }\n }\n</script>\n\n<label class=\"sh3-swatch\" class:sh3-swatch--sm={size === 'sm'}>\n {#if label}<span class=\"sh3-swatch__label\">{label}</span>{/if}\n <button\n type=\"button\"\n class=\"sh3-swatch__btn\"\n bind:this={trigger}\n {disabled}\n onclick={open}\n aria-label=\"{label ?? 'Color'} (current {value})\"\n style:--swatch-color={value}\n ><span class=\"sh3-swatch__dot\"></span><span class=\"sh3-swatch__hex\">{value}</span></button>\n</label>\n\n<style>\n .sh3-swatch { display: inline-flex; flex-direction: column; gap: 4px; }\n .sh3-swatch__label { font-size: 0.75rem; color: var(--shell-fg-muted); }\n .sh3-swatch__btn {\n display: inline-flex; align-items: center; gap: 8px;\n height: var(--shell-field-height-md);\n padding: 0 var(--shell-field-pad-x);\n background: var(--shell-input-bg);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-widget-radius);\n color: var(--shell-fg);\n cursor: pointer;\n font: inherit;\n }\n .sh3-swatch--sm .sh3-swatch__btn { height: var(--shell-field-height-sm); }\n .sh3-swatch__btn:hover:not(:disabled) {\n background: var(--shell-bg-elevated);\n filter: none;\n }\n .sh3-swatch__btn:focus-visible { outline: none; box-shadow: var(--shell-focus-ring); }\n .sh3-swatch__btn:disabled { opacity: 0.55; cursor: not-allowed; }\n .sh3-swatch__dot {\n width: 16px; height: 16px;\n border: 1px solid var(--shell-border-strong);\n border-radius: var(--shell-radius-sm);\n background: var(--swatch-color);\n }\n .sh3-swatch__hex { font-family: var(--shell-font-mono); font-size: 0.75rem; }\n</style>\n","export type FilePickerValue = File | File[] | null;\n\nexport function extractValue(files: FileList | null, multiple: boolean): FilePickerValue {\n if (!files || files.length === 0) return multiple ? [] : null;\n if (multiple) return Array.from(files);\n return files[0];\n}\n\nexport function displayName(value: FilePickerValue): string {\n if (value === null) return '';\n if (Array.isArray(value)) {\n if (value.length === 0) return '';\n if (value.length === 1) return value[0].name;\n return `${value.length} files`;\n }\n return value.name;\n}\n","<script lang=\"ts\">\n import type { CommitOnlyEvents } from './_contract';\n import { extractValue, displayName, type FilePickerValue } from './FilePicker';\n\n let {\n value = $bindable<FilePickerValue>(null),\n multiple = false,\n accept,\n disabled = false,\n invalid = false,\n size = 'md',\n buttonLabel = 'Choose file...',\n onchange,\n }: {\n value?: FilePickerValue;\n multiple?: boolean;\n accept?: string;\n disabled?: boolean;\n invalid?: boolean;\n size?: 'sm' | 'md';\n buttonLabel?: string;\n } & CommitOnlyEvents<FilePickerValue> = $props();\n\n function onPick(e: Event) {\n const target = e.currentTarget as HTMLInputElement;\n value = extractValue(target.files, multiple);\n onchange?.(value);\n }\n\n const display = $derived(displayName(value));\n</script>\n\n<label class=\"sh3-fp\" class:sh3-fp--sm={size === 'sm'} class:sh3-fp--invalid={invalid}>\n <input\n class=\"sh3-fp__native\"\n type=\"file\"\n {accept}\n {multiple}\n {disabled}\n onchange={onPick}\n />\n <span class=\"sh3-fp__btn\" tabindex=\"-1\">{buttonLabel}</span>\n <span class=\"sh3-fp__name\">{display || 'no file'}</span>\n</label>\n\n<style>\n .sh3-fp {\n display: inline-flex;\n align-items: stretch;\n height: var(--shell-field-height-md);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-widget-radius);\n background: var(--shell-input-bg);\n overflow: hidden;\n cursor: pointer;\n font-size: 0.8125rem;\n }\n .sh3-fp--sm { height: var(--shell-field-height-sm); }\n .sh3-fp--invalid { border-color: var(--shell-error); }\n .sh3-fp:focus-within { box-shadow: var(--shell-focus-ring); border-color: var(--shell-input-border-focus); }\n\n .sh3-fp__native {\n position: absolute;\n width: 1px; height: 1px;\n opacity: 0;\n pointer-events: none;\n }\n .sh3-fp__btn {\n display: inline-flex; align-items: center;\n padding: 0 var(--shell-field-pad-x);\n background: var(--shell-bg-elevated);\n color: var(--shell-fg);\n border-right: 1px solid var(--shell-border);\n }\n .sh3-fp__name {\n display: inline-flex; align-items: center;\n padding: 0 var(--shell-field-pad-x);\n color: var(--shell-fg-muted);\n flex: 1; min-width: 0;\n overflow: hidden; text-overflow: ellipsis; white-space: nowrap;\n }\n</style>\n","export interface SelectOption {\n value: string;\n label: string;\n disabled?: boolean;\n}\n\nexport const SEARCH_THRESHOLD = 8;\n\nexport function shouldShowSearch(options: SelectOption[]): boolean {\n return options.length >= SEARCH_THRESHOLD;\n}\n\nexport function filterOptions(options: SelectOption[], query: string): SelectOption[] {\n if (!query) return options.slice();\n const q = query.toLowerCase();\n return options.filter((o) => o.label.toLowerCase().includes(q));\n}\n\nexport function matchTypeAhead(\n options: SelectOption[],\n buffer: string,\n current: number,\n): number {\n if (!buffer) return -1;\n const b = buffer.toLowerCase();\n const n = options.length;\n for (let i = 1; i <= n; i++) {\n const idx = (current + i) % n;\n if (options[idx].disabled) continue;\n if (options[idx].label.toLowerCase().startsWith(b)) return idx;\n }\n return -1;\n}\n\nexport function resolveValueLabel(\n options: SelectOption[],\n value: string | string[],\n multiple: boolean,\n): string {\n if (multiple && Array.isArray(value)) {\n return value\n .map((v) => options.find((o) => o.value === v)?.label ?? '')\n .filter(Boolean)\n .join(', ');\n }\n if (typeof value === 'string' && value) {\n return options.find((o) => o.value === value)?.label ?? '';\n }\n return '';\n}\n\nexport function toggleMulti(current: string[], v: string): string[] {\n if (current.includes(v)) return current.filter((x) => x !== v);\n return [...current, v];\n}\n","<script lang=\"ts\">\n import { tick } from 'svelte';\n import {\n type SelectOption,\n shouldShowSearch,\n filterOptions,\n matchTypeAhead,\n } from './Select';\n\n let {\n options,\n getValue,\n multiple,\n onSelect,\n onClose,\n close,\n }: {\n options: SelectOption[];\n /** Live read of the selected value(s). Returning a closure (rather\n * than passing value as a snapshot) is what lets the listbox\n * re-render checkmarks across multiple selections without unmounting. */\n getValue: () => string | string[];\n multiple: boolean;\n onSelect: (v: string) => void;\n /** Called by listbox-initiated close paths so the trigger can\n * restore its open-flag and focus. Outside-click and Escape\n * paths are handled by the popup manager via Select's wrap. */\n onClose?: () => void;\n close: () => void;\n } = $props();\n\n const value = $derived(getValue());\n\n function dismiss() {\n onClose?.();\n close();\n }\n\n const showSearch = $derived(shouldShowSearch(options));\n\n function initialActiveIdx(): number {\n if (multiple) return 0;\n const v = typeof value === 'string' ? value : '';\n const idx = options.findIndex((o) => o.value === v && !o.disabled);\n return idx >= 0 ? idx : 0;\n }\n\n let query = $state('');\n let activeIdx = $state(initialActiveIdx());\n let listEl = $state<HTMLDivElement | undefined>(undefined);\n let searchEl = $state<HTMLInputElement | undefined>(undefined);\n let typeAheadBuffer = '';\n let typeAheadTimer: ReturnType<typeof setTimeout> | null = null;\n\n const filtered = $derived(filterOptions(options, query));\n\n $effect(() => {\n if (activeIdx >= filtered.length) activeIdx = 0;\n void scrollActiveIntoView();\n });\n\n async function scrollActiveIntoView() {\n await tick();\n if (!listEl) return;\n const el = listEl.querySelector<HTMLElement>(`[data-idx=\"${activeIdx}\"]`);\n el?.scrollIntoView({ block: 'nearest' });\n }\n\n function isSelected(o: SelectOption): boolean {\n if (multiple && Array.isArray(value)) return value.includes(o.value);\n return value === o.value;\n }\n\n function commit(idx: number) {\n const o = filtered[idx];\n if (!o || o.disabled) return;\n onSelect(o.value);\n if (!multiple) dismiss();\n }\n\n function onListKey(e: KeyboardEvent) {\n if (filtered.length === 0) return;\n switch (e.key) {\n case 'ArrowDown':\n e.preventDefault();\n activeIdx = (activeIdx + 1) % filtered.length;\n break;\n case 'ArrowUp':\n e.preventDefault();\n activeIdx = (activeIdx - 1 + filtered.length) % filtered.length;\n break;\n case 'Home':\n e.preventDefault();\n activeIdx = 0;\n break;\n case 'End':\n e.preventDefault();\n activeIdx = filtered.length - 1;\n break;\n case 'Enter':\n e.preventDefault();\n commit(activeIdx);\n break;\n case ' ':\n case 'Space':\n e.preventDefault();\n commit(activeIdx);\n break;\n case 'Escape':\n e.preventDefault();\n dismiss();\n break;\n default:\n if (showSearch && document.activeElement === searchEl) return;\n if (e.key.length !== 1 || e.metaKey || e.ctrlKey || e.altKey) return;\n typeAheadBuffer += e.key;\n if (typeAheadTimer) clearTimeout(typeAheadTimer);\n typeAheadTimer = setTimeout(() => { typeAheadBuffer = ''; }, 500);\n const idx = matchTypeAhead(filtered, typeAheadBuffer, activeIdx);\n if (idx >= 0) activeIdx = idx;\n }\n }\n</script>\n\n<div\n class=\"sh3-listbox\"\n role=\"listbox\"\n aria-multiselectable={multiple}\n tabindex=\"-1\"\n onkeydown={onListKey}\n>\n {#if showSearch}\n <input\n bind:this={searchEl}\n class=\"sh3-listbox__search\"\n type=\"search\"\n placeholder=\"Filter…\"\n bind:value={query}\n />\n {/if}\n <div class=\"sh3-listbox__list\" bind:this={listEl}>\n {#each filtered as opt, i}\n <!-- svelte-ignore a11y_click_events_have_key_events -->\n <div\n role=\"option\"\n tabindex=\"-1\"\n aria-selected={isSelected(opt)}\n aria-disabled={opt.disabled}\n data-idx={i}\n class:sh3-listbox__opt--active={i === activeIdx}\n class:sh3-listbox__opt--selected={isSelected(opt)}\n onclick={() => commit(i)}\n onmouseenter={() => activeIdx = i}\n >\n {#if multiple}\n <span class=\"sh3-listbox__check\" class:sh3-listbox__check--on={isSelected(opt)} aria-hidden=\"true\"></span>\n {/if}\n <span class=\"sh3-listbox__label\">{opt.label}</span>\n </div>\n {/each}\n {#if filtered.length === 0}\n <div class=\"sh3-listbox__empty\">No matches</div>\n {/if}\n </div>\n</div>\n\n<style>\n .sh3-listbox {\n background: var(--shell-bg-elevated);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-widget-radius);\n box-shadow: var(--shell-shadow-sm);\n min-width: 180px;\n max-width: 320px;\n color: var(--shell-fg);\n font-size: 0.8125rem;\n overflow: hidden;\n }\n .sh3-listbox__search {\n width: 100%;\n height: 26px;\n padding: 0 8px;\n background: var(--shell-input-bg);\n border: none;\n border-bottom: 1px solid var(--shell-border);\n color: var(--shell-fg);\n font: inherit;\n outline: none;\n }\n .sh3-listbox__list {\n max-height: 280px;\n overflow-y: auto;\n padding: 4px 0;\n }\n .sh3-listbox__list > div {\n display: flex; align-items: center; gap: 6px;\n padding: 4px 10px;\n cursor: pointer;\n }\n .sh3-listbox__opt--active { background: var(--shell-bg); }\n .sh3-listbox__opt--selected { color: var(--shell-accent); }\n .sh3-listbox__opt--active.sh3-listbox__opt--selected { background: var(--shell-accent); color: var(--shell-fg-on-accent); }\n .sh3-listbox__list > div[aria-disabled=\"true\"] {\n color: var(--shell-fg-subtle);\n cursor: not-allowed;\n }\n .sh3-listbox__check {\n flex-shrink: 0;\n width: 12px;\n height: 12px;\n }\n .sh3-listbox__check--on::before {\n content: \"\";\n display: block;\n width: 100%;\n height: 100%;\n background: var(--shell-accent);\n clip-path: polygon(14% 44%, 0 60%, 40% 100%, 100% 20%, 85% 8%, 38% 70%);\n }\n .sh3-listbox__opt--active.sh3-listbox__opt--selected .sh3-listbox__check--on::before {\n background: var(--shell-fg-on-accent);\n }\n .sh3-listbox__empty {\n padding: 6px 10px;\n color: var(--shell-fg-muted);\n font-style: italic;\n }\n</style>\n","<script lang=\"ts\">\n import { tick } from 'svelte';\n import type { CommitOnlyEvents } from './_contract';\n import { shell } from '../../shellRuntime.svelte';\n import Listbox from './_select-listbox.svelte';\n import { type SelectOption, resolveValueLabel, toggleMulti } from './Select';\n\n let {\n options,\n multiple = false,\n value = $bindable<string | string[]>(multiple ? [] : ''),\n placeholder = 'Select…',\n label,\n disabled = false,\n invalid = false,\n size = 'md',\n onchange,\n }: {\n options: SelectOption[];\n multiple?: boolean;\n value?: string | string[];\n placeholder?: string;\n label?: string;\n disabled?: boolean;\n invalid?: boolean;\n size?: 'sm' | 'md';\n } & CommitOnlyEvents<string | string[]> = $props();\n\n let trigger = $state<HTMLButtonElement | undefined>(undefined);\n let nativeRef = $state<HTMLSelectElement | undefined>(undefined);\n let isOpen = $state(false);\n\n const displayLabel = $derived(resolveValueLabel(options, value, multiple));\n\n function onPopupClose() {\n isOpen = false;\n trigger?.focus();\n }\n\n async function open() {\n if (disabled || isOpen || !trigger) return;\n isOpen = true;\n const popupHandle = shell.popup.show(\n Listbox,\n { anchor: trigger },\n {\n options,\n // Closure read so the listbox sees Select's live value across\n // multiple selections without remount.\n getValue: () => value,\n multiple,\n onSelect: (v: string) => {\n if (multiple) {\n const arr = Array.isArray(value) ? value : [];\n value = toggleMulti(arr, v);\n } else {\n value = v;\n }\n onchange?.(value);\n },\n // Listbox calls this on its own close paths (selection in\n // single mode, Escape inside the listbox). Outside-click and\n // document-Escape go through the wrap below instead.\n onClose: onPopupClose,\n },\n );\n // popup.ts's outside-click + document-Escape route through\n // current.handle.close() — wrap that to also clear our state.\n const origClose = popupHandle.close;\n popupHandle.close = () => {\n origClose();\n onPopupClose();\n };\n await tick();\n const lb = document.querySelector<HTMLElement>('.sh3-listbox');\n lb?.focus();\n }\n\n function onTriggerKey(e: KeyboardEvent) {\n if (disabled || isOpen) return;\n switch (e.key) {\n case 'ArrowDown': case 'ArrowUp': case 'Enter': case ' ':\n e.preventDefault();\n open();\n break;\n }\n }\n\n function onNativeChange() {\n if (!nativeRef) return;\n if (multiple) {\n value = Array.from(nativeRef.selectedOptions).map((o) => o.value);\n } else {\n value = nativeRef.value;\n }\n onchange?.(value);\n }\n</script>\n\n<label class=\"sh3-select\" class:sh3-select--invalid={invalid} class:sh3-select--sm={size === 'sm'}>\n {#if label}<span class=\"sh3-select__label\">{label}</span>{/if}\n <button\n type=\"button\"\n class=\"sh3-select__btn\"\n bind:this={trigger}\n {disabled}\n aria-haspopup=\"listbox\"\n aria-expanded={isOpen}\n onclick={open}\n onkeydown={onTriggerKey}\n >\n <span class=\"sh3-select__display\" class:sh3-select__display--placeholder={!displayLabel}>\n {displayLabel || placeholder}\n </span>\n <span class=\"sh3-select__chevron\" aria-hidden=\"true\">▾</span>\n </button>\n\n <select\n bind:this={nativeRef}\n class=\"sh3-select__native\"\n {multiple}\n {disabled}\n tabindex={-1}\n aria-hidden=\"true\"\n onchange={onNativeChange}\n >\n {#each options as opt}\n <option value={opt.value} selected={\n multiple\n ? Array.isArray(value) && value.includes(opt.value)\n : value === opt.value\n }>{opt.label}</option>\n {/each}\n </select>\n</label>\n\n<style>\n .sh3-select { display: inline-flex; flex-direction: column; gap: 4px; font-size: 0.8125rem; position: relative; }\n .sh3-select__label { color: var(--shell-fg-muted); font-size: 0.75rem; }\n .sh3-select__btn {\n display: inline-flex; align-items: center; gap: 8px;\n height: var(--shell-field-height-md);\n min-width: 140px;\n padding: 0 var(--shell-field-pad-x);\n background: var(--shell-input-bg);\n color: var(--shell-fg);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-widget-radius);\n cursor: pointer;\n font: inherit;\n text-align: left;\n }\n .sh3-select--sm .sh3-select__btn { height: var(--shell-field-height-sm); }\n .sh3-select__btn:focus-visible { outline: none; box-shadow: var(--shell-focus-ring); border-color: var(--shell-input-border-focus); }\n .sh3-select__btn:disabled { opacity: 0.55; cursor: not-allowed; }\n .sh3-select--invalid .sh3-select__btn { border-color: var(--shell-error); }\n .sh3-select__display { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .sh3-select__display--placeholder { color: var(--shell-fg-muted); }\n .sh3-select__chevron { color: var(--shell-fg-muted); }\n .sh3-select__native {\n position: absolute;\n width: 1px; height: 1px;\n margin: 0; padding: 0;\n border: 0; opacity: 0;\n pointer-events: none;\n }\n</style>\n","export interface PickerItem {\n id: string;\n label: string;\n /** Optional secondary line shown beneath the label in muted style. */\n sublabel?: string;\n}\n\nexport interface PickerListProps {\n items: PickerItem[];\n value: string[];\n onchange?: (next: string[]) => void;\n loading?: boolean;\n error?: string | null;\n onRetry?: () => void;\n /** Empty-state message when items.length === 0 and not loading/error. */\n emptyText?: string;\n /** Search input is rendered when items.length >= this value. Default: 8. */\n searchThreshold?: number;\n disabled?: boolean;\n size?: 'sm' | 'md';\n}\n\n/** Case-insensitive substring match over label, id, and sublabel. */\nexport function filterItems(items: PickerItem[], query: string): PickerItem[] {\n if (!query) return items;\n const q = query.toLowerCase();\n return items.filter((it) => {\n if (it.label.toLowerCase().includes(q)) return true;\n if (it.id.toLowerCase().includes(q)) return true;\n if (it.sublabel && it.sublabel.toLowerCase().includes(q)) return true;\n return false;\n });\n}\n\n/** Toggle the given id in or out of value, returning a NEW array. */\nexport function toggle(value: string[], id: string): string[] {\n if (value.includes(id)) return value.filter((v) => v !== id);\n return [...value, id];\n}\n","<script lang=\"ts\">\n import type { CommitOnlyEvents } from './_contract';\n import { filterItems, toggle, type PickerItem } from './PickerList';\n\n let {\n items,\n value = $bindable<string[]>([]),\n loading = false,\n error = null,\n onRetry,\n emptyText = 'No items.',\n searchThreshold = 8,\n disabled = false,\n size = 'md',\n onchange,\n }: {\n items: PickerItem[];\n value?: string[];\n loading?: boolean;\n error?: string | null;\n onRetry?: () => void;\n emptyText?: string;\n searchThreshold?: number;\n disabled?: boolean;\n size?: 'sm' | 'md';\n } & CommitOnlyEvents<string[]> = $props();\n\n let query = $state('');\n const showSearch = $derived(items.length >= searchThreshold);\n const filtered = $derived(filterItems(items, query));\n const totalCount = $derived(items.length);\n const selectedCount = $derived(value.length);\n\n function toggleId(id: string) {\n if (disabled) return;\n const next = toggle(value, id);\n value = next;\n onchange?.(next);\n }\n</script>\n\n<div class=\"sh3-picker\" class:sh3-picker--sm={size === 'sm'} class:sh3-picker--disabled={disabled}>\n {#if showSearch}\n <input\n type=\"search\"\n class=\"sh3-picker__search\"\n placeholder=\"Filter…\"\n bind:value={query}\n {disabled}\n />\n {/if}\n\n <div class=\"sh3-picker__list\">\n {#if loading}\n <p class=\"sh3-picker__status\">Loading…</p>\n {:else if error}\n <p class=\"sh3-picker__status sh3-picker__status--error\">{error}</p>\n {#if onRetry}\n <button type=\"button\" class=\"sh3-picker__retry\" onclick={() => onRetry?.()}>Retry</button>\n {/if}\n {:else if items.length === 0}\n <p class=\"sh3-picker__status\">{emptyText}</p>\n {:else}\n {#each filtered as item (item.id)}\n <label class=\"sh3-picker__row\">\n <input\n type=\"checkbox\"\n checked={value.includes(item.id)}\n {disabled}\n onchange={() => toggleId(item.id)}\n />\n <span class=\"sh3-picker__row-text\">\n <span class=\"sh3-picker__row-label\">{item.label}</span>\n {#if item.sublabel}\n <span class=\"sh3-picker__row-sub\">{item.sublabel}</span>\n {/if}\n </span>\n </label>\n {/each}\n {/if}\n </div>\n\n <p class=\"sh3-picker__footer\">{selectedCount} of {totalCount} selected</p>\n</div>\n\n<style>\n .sh3-picker {\n display: flex;\n flex-direction: column;\n gap: 6px;\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-sm, 3px);\n padding: 6px;\n background: var(--shell-bg-elevated);\n }\n .sh3-picker__search {\n width: 100%;\n padding: 4px 6px;\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-sm, 3px);\n background: var(--shell-bg);\n color: var(--shell-fg);\n font: inherit;\n font-size: 12px;\n }\n .sh3-picker__list {\n display: flex;\n flex-direction: column;\n max-height: 200px;\n overflow-y: auto;\n }\n .sh3-picker__row {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 4px 6px;\n cursor: pointer;\n border-radius: var(--shell-radius-sm, 3px);\n }\n .sh3-picker__row:hover { background: var(--shell-bg); }\n .sh3-picker__row-text { display: flex; flex-direction: column; gap: 0; }\n .sh3-picker__row-label { font-size: 13px; }\n .sh3-picker__row-sub { font-size: 11px; color: var(--shell-fg-muted); }\n .sh3-picker__status {\n margin: 0;\n padding: 8px 6px;\n color: var(--shell-fg-muted);\n font-size: 12px;\n }\n .sh3-picker__status--error { color: var(--shell-error, #c33); }\n .sh3-picker__retry {\n align-self: flex-start;\n margin: 0 6px 8px;\n background: var(--shell-bg);\n color: var(--shell-fg);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-sm, 3px);\n padding: 2px 8px;\n font: inherit;\n font-size: 12px;\n cursor: pointer;\n }\n .sh3-picker__footer {\n margin: 0;\n font-size: 11px;\n color: var(--shell-fg-muted);\n text-align: right;\n }\n .sh3-picker--disabled .sh3-picker__row { cursor: not-allowed; opacity: 0.6; }\n</style>\n","<script lang=\"ts\">\n import type { CommitOnlyEvents } from './_contract';\n import PickerList from './PickerList.svelte';\n import type { PickerItem } from './PickerList';\n import { listRegisteredApps } from '../../apps/registry.svelte';\n\n /** Apps the framework ships and that bypass the project allowlist server-side. */\n const FRAMEWORK_APP_IDS = new Set(['sh3-admin-app', 'sh3-store-app']);\n\n let {\n value = $bindable<string[]>([]),\n onchange,\n disabled = false,\n size = 'md',\n }: {\n value?: string[];\n disabled?: boolean;\n size?: 'sm' | 'md';\n } & CommitOnlyEvents<string[]> = $props();\n\n const items = $derived<PickerItem[]>(\n listRegisteredApps()\n .filter((m) => !FRAMEWORK_APP_IDS.has(m.id) && !m.admin)\n .map((m) => ({ id: m.id, label: m.label, sublabel: m.id }))\n .sort((a, b) => a.label.localeCompare(b.label)),\n );\n\n function handleChange(next: string[]) {\n value = next;\n onchange?.(next);\n }\n</script>\n\n<PickerList\n {items}\n {value}\n onchange={handleChange}\n {disabled}\n {size}\n emptyText=\"No apps installed.\"\n/>\n","/*\n * Shared admin-users cache.\n *\n * Wraps a single GET /api/admin/users behind a $state slot so multiple\n * admin-form components (e.g., UserPicker instances inside ProjectManage,\n * a future invite-user dialog, etc.) share one fetch without prop-drilling\n * the user list. Concurrent calls reuse the in-flight promise; subsequent\n * calls after completion fetch fresh data.\n */\n\nimport type { AuthUser } from './types';\n\nexport const usersAdminState: {\n users: AuthUser[];\n loading: boolean;\n error: string | null;\n} = $state({ users: [], loading: false, error: null });\n\nlet inflight: Promise<void> | null = null;\n\nexport function refreshAdminUsers(): Promise<void> {\n if (inflight) return inflight;\n usersAdminState.loading = true;\n usersAdminState.error = null;\n inflight = (async () => {\n try {\n const res = await fetch('/api/admin/users', { credentials: 'include' });\n if (!res.ok) {\n usersAdminState.error = `GET /api/admin/users failed: ${res.status}`;\n return;\n }\n usersAdminState.users = (await res.json()) as AuthUser[];\n } catch (e) {\n usersAdminState.error = (e as Error).message;\n } finally {\n usersAdminState.loading = false;\n inflight = null;\n }\n })();\n return inflight;\n}\n\n/** Test-only reset. Clears state and any in-flight promise. */\nexport function __resetAdminUsersForTest(): void {\n usersAdminState.users = [];\n usersAdminState.loading = false;\n usersAdminState.error = null;\n inflight = null;\n}\n","<script lang=\"ts\">\n import type { CommitOnlyEvents } from './_contract';\n import PickerList from './PickerList.svelte';\n import type { PickerItem } from './PickerList';\n import { usersAdminState, refreshAdminUsers } from '../../auth/admin-users.svelte';\n\n let {\n value = $bindable<string[]>([]),\n onchange,\n disabled = false,\n size = 'md',\n }: {\n value?: string[];\n disabled?: boolean;\n size?: 'sm' | 'md';\n } & CommitOnlyEvents<string[]> = $props();\n\n // Kick a fetch if the cache is empty. The store dedupes concurrent calls,\n // so multiple UserPicker mounts share one request. After completion\n // subsequent mounts see the cached state.\n if (\n usersAdminState.users.length === 0 &&\n !usersAdminState.loading &&\n !usersAdminState.error\n ) {\n void refreshAdminUsers();\n }\n\n const items = $derived<PickerItem[]>(\n usersAdminState.users.map((u) => ({\n id: u.id,\n label: u.displayName || u.username,\n sublabel: u.username,\n })),\n );\n\n function handleChange(next: string[]) {\n value = next;\n onchange?.(next);\n }\n</script>\n\n<PickerList\n {items}\n {value}\n onchange={handleChange}\n loading={usersAdminState.loading}\n error={usersAdminState.error}\n onRetry={() => void refreshAdminUsers()}\n emptyText=\"No users found.\"\n {disabled}\n {size}\n/>\n","/*\n * Public framework API — the single import path shards and apps are\n * allowed to touch. The phase 9 package boundary turns this file (and\n * only this file) into the published entry point.\n *\n * What belongs here:\n * - Types that shards and apps consume (Shard, App, ShardContext, etc.)\n * - The `shell` runtime singleton (modal/popup/toast)\n * - Layout inspection/mutation helpers for advanced shards (added in\n * Task 12)\n * - Host actions callable from inside views (launchApp, returnToHome,\n * listRegisteredApps — added in Task 7 and Task 10)\n *\n * What does NOT belong here:\n * - `registerShard` / `registerApp` — those are host-only and live in\n * `host.ts`. Shards and apps must not register each other.\n * - Framework internals (state zone plumbing, layout manager internals,\n * shard activation machinery).\n *\n * Anything re-exported from this file is part of the public contract.\n * Phase 10 adds a validator that enforces the import-hygiene rule; for\n * now the convention is documented and honored by hand.\n */\n\n// Runtime singleton.\nexport { shell } from './shellRuntime.svelte';\nexport type { Shell } from './shellRuntime.svelte';\n\n// Shard contract types.\nexport type {\n Shard,\n ShardManifest,\n SourceShard,\n SourceShardManifest,\n ShardContext,\n ViewDeclaration,\n ViewFactory,\n ViewHandle,\n MountContext,\n} from './shards/types';\n\n// Layout tree types (apps reference these in their blueprints).\nexport type {\n LayoutNode,\n SplitNode,\n TabsNode,\n SlotNode,\n TabEntry,\n SplitDirection,\n SizeMode,\n LayoutTree,\n FloatEntry,\n LayoutPreset,\n CanonicalPreset,\n TreeRootRef as SlotLocation,\n} from './layout/types';\n\n// Action introspection types.\nexport type {\n ActiveActionDescriptor,\n BindingSource,\n AtomicScope,\n ActionScope,\n} from './actions/types';\n\nexport type { FloatManager, FloatOptions } from './overlays/float';\nexport type { ModalManager } from './overlays/modal';\nexport type { PopupManager } from './overlays/popup';\nexport type { ToastManager } from './overlays/toast';\nexport type { PresetManager } from './overlays/presets';\nexport type {\n OverlayHandle,\n ModalHandle,\n ModalOptions,\n PopupHandle,\n PopupOptions,\n PopupPlacement,\n ToastHandle,\n ToastOptions,\n ToastLevel,\n} from './overlays/types';\n\n// State zone types (shards and apps declare schemas against these).\nexport type { ZoneSchema, ZoneName, ZoneManager } from './state/types';\nexport { PERMISSION_STATE_MANAGE } from './state/types';\nexport type { StateZones } from './state/zones.svelte';\n\n// Environment state types (shards declare env schemas against this).\nexport type { EnvState } from './env/types';\n\n// App contract types (added in Task 6).\nexport type {\n App,\n AppManifest,\n SourceApp,\n SourceAppManifest,\n AppContext,\n} from './apps/types';\n\n// Host actions callable from inside views (shell home, status bar, etc.).\nexport { listRegisteredApps, getActiveApp } from './apps/registry.svelte';\nexport { launchApp, returnToHome, unregisterApp } from './apps/lifecycle';\n\n// Navigation — apps push in-app nav entries; framework drives back/forward.\nexport { pushNavEntry } from './navigation';\nexport type { NavEntry, NavEntryHandle } from './navigation';\n\n// Layout inspection / mutation for advanced shards (diagnostic, etc.).\nexport {\n inspectActiveLayout,\n spliceIntoActiveLayout,\n dockIntoActiveLayout,\n focusTab,\n focusView,\n collapseChild,\n expandChild,\n closeTab,\n popoutView,\n dockFloat,\n locateSlot,\n} from './layout/inspection';\n\n// Document zone types (shards use these to declare document handles).\nexport type {\n DocumentHandle,\n DocumentHandleOptions,\n DocumentFormat,\n DocumentMeta,\n DocumentChange,\n AutosaveController,\n} from './documents/types';\nexport {\n PERMISSION_DOCUMENTS_BROWSE,\n PERMISSION_DOCUMENTS_READ,\n PERMISSION_DOCUMENTS_WRITE,\n} from './documents/types';\nexport type { BrowseCapability } from './documents/browse';\n\n// Contribution-points runtime (shard-to-shard collaboration).\nexport type { ContributionsApi } from './contributions/types';\n\n// Document sync API — type-only contract (ADR-019 revised 2026-04-19).\n// Runtime lives in the installable sh3-sync shard.\nexport type {\n SyncPolicy,\n SyncPolicyRule,\n DocStatus,\n ConflictFile,\n ConflictBranch,\n} from './documents/sync-types';\nexport { PERMISSION_SYNC_PEER, PERMISSION_SYNC_POLICY } from './documents/sync-types';\n\n// Conflict manager view (shell.conflicts).\nexport type {\n ConflictItem,\n ConflictBranch as ConflictManagerBranch,\n ResolveOptions as ConflictResolveOptions,\n ResolveOutcome as ConflictResolveOutcome,\n ResolveDocumentsInput as ConflictResolveDocumentsInput,\n DocsResolveOutcome as ConflictDocsResolveOutcome,\n ConflictRenderer,\n ConflictRendererProps,\n ConflictsApi,\n} from './conflicts/api';\nexport {\n CONFLICT_RENDERER_POINT,\n ConflictPermissionError,\n ConflictSessionOrphanedError,\n} from './conflicts/api';\n\n// Color picker (shell.color).\nexport type {\n ColorPickOptions,\n ColorContribution,\n ColorApi,\n} from './color/api';\nexport { COLOR_PICKER_POINT } from './color/api';\n\n// Shard introspection — read-only reactive maps exposing which shards are\n// known to the host and which are currently active. Intended for diagnostic\n// and tooling shards that need to visualize framework state. Phase 9\n// addition: diagnostic used to reach `activate.svelte` directly via $lib;\n// the package boundary requires routing through the public surface.\nexport { registeredShards, activeShards, erroredShards } from './shards/activate.svelte';\nexport type { ShardErrorEntry } from './shards/activate.svelte';\n\n// Registry client types and functions (used by the store shard).\nexport type {\n RegistryIndex,\n PackageEntry,\n PackageVersion,\n RequiredDependency,\n InstalledPackage,\n InstallResult,\n PackageMeta,\n} from './registry/types';\nexport type { ResolvedPackage } from './registry/client';\nexport { fetchRegistries, fetchBundle, buildPackageMeta } from './registry/client';\nexport { validateRegistryIndex } from './registry/schema';\n\n// Key mint/revoke types — client shards that declare `keys:mint` get ctx.keys.\nexport {\n PERMISSION_KEYS_MINT,\n ScopeEscalationError,\n ConsentDeniedError,\n type ShardContextKeys,\n type ApiKeyPublic,\n type MintOpts,\n} from './keys/types';\nexport { registerConsentListener, resolveConsent, type ConsentRequest } from './keys/consent.svelte';\n// Revocation bus — subscribe to key revocation events (for advanced integrations).\nexport { subscribe as subscribeKeyRevocation } from './keys/revocation-bus.svelte';\n\n// Admin mode (framework-internal components read admin status).\nexport { isAdmin, isAuthenticated, isGuest, getUser, getAuthHeader } from './auth/index';\nexport type { AuthUser, AuthSession, BootConfig } from './auth/types';\n\n/** Runtime feature flags for target-dependent behavior. */\nexport const capabilities = {\n /** Whether this target supports hot-installing packages via dynamic import from blob URL. */\n hotInstall: typeof Blob !== 'undefined' && typeof URL.createObjectURL === 'function',\n} as const;\n\n// Server shard contract types (used by server-side shard bundles).\nexport type { ServerShard, ServerShardContext, TenantDocumentAPI } from './server-shard/types';\n\n// Verb contribution types (shards register verbs via ShardContext.registerVerb).\nexport type { Verb, VerbContext, ShellApi } from './verbs/types';\nexport type { Scrollback } from './shell-shard/scrollback.svelte';\nexport type { SessionClient } from './shell-shard/session-client.svelte';\nexport { listVerbs } from './shards/registry';\n\n// Package version.\nexport { VERSION } from './version';\n\n// Framework shard IDs — shards that are always present (built-in to sh3-core).\n// Used by the store UI to skip dependency checks for these well-known shards.\nexport const FRAMEWORK_SHARD_IDS: readonly string[] = [\n '__sh3core__',\n 'shell',\n 'sh3-store',\n 'sh3-admin',\n];\n\n// Theme token override API (shell-level theming support).\nexport {\n setTokenOverrides,\n clearTokenOverrides,\n getTokenOverrides,\n} from './theme';\n\n// UI primitives for shards and apps. Must live on the public shim surface\n// (api.ts) — not just index.ts — so dynamically loaded bundles can resolve\n// `import { Button } from 'sh3-core'` against the runtime shim in loader.ts.\nexport { default as Button } from './primitives/Button.svelte';\nexport { provideIcons, getIconSprite, type ButtonVariant } from './primitives/icon-context';\nexport { default as Collapsible } from './primitives/Collapsible.svelte';\n\n// Controllable widget primitives (ADR-022).\nexport { default as Field } from './primitives/widgets/Field.svelte';\nexport { default as Textarea } from './primitives/widgets/Textarea.svelte';\nexport { default as NumberInput } from './primitives/widgets/NumberInput.svelte';\nexport { default as Segmented } from './primitives/widgets/Segmented.svelte';\nexport type { SegmentedOption } from './primitives/widgets/Segmented';\nexport { default as IconToggleGroup } from './primitives/widgets/IconToggleGroup.svelte';\nexport { default as Slider } from './primitives/widgets/Slider.svelte';\nexport { default as RangeSlider } from './primitives/widgets/RangeSlider.svelte';\nexport { default as SliderGroup } from './primitives/widgets/SliderGroup.svelte';\nexport { default as ColorSwatch } from './primitives/widgets/ColorSwatch.svelte';\nexport { default as FilePicker } from './primitives/widgets/FilePicker.svelte';\nexport type { FilePickerValue } from './primitives/widgets/FilePicker';\nexport { default as Select } from './primitives/widgets/Select.svelte';\nexport type { SelectOption } from './primitives/widgets/Select';\nexport { default as AppPicker } from './primitives/widgets/AppPicker.svelte';\nexport { default as UserPicker } from './primitives/widgets/UserPicker.svelte';\n","export default \"__VITE_ASSET__ClcxO3Aw__\"","<script lang=\"ts\" module>\n /*\n * p5 is loaded from a CDN rather than bundled, to keep sh3-core's\n * footprint small. The promise is cached at module scope so repeated\n * mounts reuse a single <script> injection.\n */\n const P5_CDN = 'https://cdn.jsdelivr.net/npm/p5@1.11.13/lib/p5.min.js';\n let p5Promise: Promise<any> | null = null;\n\n function loadP5(): Promise<any> {\n if (p5Promise) return p5Promise;\n p5Promise = new Promise((resolve, reject) => {\n const existing = (window as any).p5;\n if (existing) {\n resolve(existing);\n return;\n }\n const s = document.createElement('script');\n s.src = P5_CDN;\n s.async = true;\n s.onload = () => resolve((window as any).p5);\n s.onerror = (err) => {\n p5Promise = null;\n reject(err);\n };\n document.head.appendChild(s);\n });\n return p5Promise;\n }\n</script>\n\n<script lang=\"ts\">\n import sh3Img from '../assets/SH3.png';\n\n const CHARS = '`.-\\':;,^\"~=+<>*?!/\\\\|()[]{}x1ltzrcvunsXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$';\n const ASCII_W = 64;\n const ASCII_H = Math.floor(64 / (442 / 193)); // ~28, matches image ratio\n const CELL_W = 8;\n const CELL_H = 7;\n const DISPLAY_H = 80; // rendered CSS height in px; width auto-derived from aspect ratio\n // Canvas keeps its native pixel buffer (ASCII_W*CELL_W × ASCII_H*CELL_H) for full\n // text resolution; CSS transform scales the painted output down to DISPLAY_H, and\n // the container is sized to the scaled dimensions so layout sees the visible size.\n const NATIVE_W = ASCII_W * CELL_W;\n const NATIVE_H = ASCII_H * CELL_H;\n const SCALE = DISPLAY_H / NATIVE_H;\n const DISPLAY_W = NATIVE_W * SCALE;\n\n let container = $state<HTMLDivElement | undefined>(undefined);\n let p5inst: any = null;\n let failed = $state(false);\n\n const buildSketch = () => (p: any) => {\n const rootStyle = getComputedStyle(document.documentElement);\n const accentColor = rootStyle.getPropertyValue('--shell-accent').trim();\n let gfx: any;\n let src: any;\n let ready = false;\n\n p.setup = () => {\n // Create the canvas synchronously in setup, otherwise p5 will auto-create\n // a default 100x100 canvas and a later createCanvas() call would produce\n // a SECOND canvas rather than replacing the first.\n p.createCanvas(NATIVE_W, NATIVE_H);\n\n p.noSmooth();\n p.noStroke();\n p.textAlign(p.CENTER, p.CENTER);\n p.textFont('monospace');\n p.textSize(10);\n p.textStyle(p.BOLD);\n\n src = p.loadImage(\n sh3Img,\n () => {\n gfx = p.createGraphics(ASCII_W, ASCII_H);\n gfx.pixelDensity(1);\n gfx.image(src, 0, 0, ASCII_W, ASCII_H);\n gfx.loadPixels();\n ready = true;\n },\n () => { failed = true; },\n );\n };\n\n p.draw = () => {\n if (!ready) return;\n const t = p.millis() * 0.001;\n let n: number;\n\n p.clear();\n p.background(0, 0);\n p.fill(accentColor);\n\n for (let y = 0; y < ASCII_H; y++) {\n for (let x = 0; x < ASCII_W; x++) {\n const i = (y * ASCII_W + x) * 4;\n if (gfx.pixels[i] < 64) {\n n = p.noise(x / ASCII_W * 2.0, y / ASCII_H * 2.0, t * 0.15);\n if (n > 0.33) continue;\n p.text(CHARS[Math.floor(n * CHARS.length * 0.25)], (x + 0.5) * CELL_W, (y + 0.5) * CELL_H);\n continue;\n }\n n = p.noise(x / ASCII_W * 4.0, y / ASCII_H * 4.0, t * 0.5);\n p.text(CHARS[Math.floor(n * CHARS.length)], (x + 0.5) * CELL_W, (y + 0.5) * CELL_H);\n }\n }\n };\n };\n\n $effect(() => {\n if (failed) return;\n let cancelled = false;\n loadP5()\n .then((P5) => {\n if (cancelled || !container) return;\n try {\n p5inst = new P5(buildSketch(), container);\n } catch (err) {\n console.error('[ShellTitle] p5 sketch failed to start', err);\n failed = true;\n }\n })\n .catch((err) => {\n console.error('[ShellTitle] failed to load p5 from CDN', err);\n failed = true;\n });\n\n return () => {\n cancelled = true;\n if (p5inst) {\n p5inst.remove();\n p5inst = null;\n }\n };\n });\n</script>\n\n{#if failed}\n <h1 class=\"shell-title-fallback\">SH3</h1>\n{:else}\n <div\n bind:this={container}\n class=\"shell-title\"\n style:width=\"{DISPLAY_W}px\"\n style:height=\"{DISPLAY_H}px\"\n style:--shell-title-scale={SCALE}\n ></div>\n{/if}\n\n<style>\n .shell-title {\n display: inline-block;\n line-height: 0;\n overflow: hidden;\n }\n /* canvas is injected by p5 at runtime, so scoped selectors don't reach it */\n .shell-title :global(canvas) {\n transform: scale(var(--shell-title-scale));\n transform-origin: top left;\n /* p5 sets inline width/height attributes on the canvas; override its inline\n style so layout doesn't get the intrinsic pixel-buffer size. */\n display: block;\n }\n .shell-title-fallback {\n margin: 0;\n font-size: 42px;\n color: var(--shell-accent);\n letter-spacing: 2px;\n }\n</style>\n","/*\n * Client wrapper for the /api/projects HTTP surface.\n *\n * Returns plain JSON objects; the shard layer is responsible for keeping\n * a reactive copy and for converting these to actions / views.\n */\n\nexport interface ProjectRecord {\n id: string;\n name: string;\n description?: string;\n members: string[];\n appAllowlist: string[];\n createdBy: string;\n createdAt: number;\n updatedAt: number;\n}\n\nasync function jsonFetch<T>(url: string, init?: RequestInit): Promise<T> {\n const res = await fetch(url, { credentials: 'include', ...init });\n if (!res.ok) throw new Error(`${init?.method ?? 'GET'} ${url} failed: ${res.status}`);\n return res.json() as Promise<T>;\n}\n\nexport const projectsApi = {\n async list(): Promise<ProjectRecord[]> {\n const body = await jsonFetch<{ projects: ProjectRecord[] }>('/api/projects', { method: 'GET' });\n return body.projects;\n },\n async listAll(): Promise<ProjectRecord[]> {\n const body = await jsonFetch<{ projects: ProjectRecord[] }>('/api/projects/all', { method: 'GET' });\n return body.projects;\n },\n async get(id: string): Promise<ProjectRecord> {\n return jsonFetch<ProjectRecord>(`/api/projects/${encodeURIComponent(id)}`, { method: 'GET' });\n },\n async create(input: Pick<ProjectRecord, 'name' | 'description' | 'members' | 'appAllowlist'>): Promise<ProjectRecord> {\n return jsonFetch<ProjectRecord>('/api/projects', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(input),\n });\n },\n async update(\n id: string,\n patch: Partial<Pick<ProjectRecord, 'name' | 'description' | 'members' | 'appAllowlist'>>,\n ): Promise<ProjectRecord> {\n return jsonFetch<ProjectRecord>(`/api/projects/${encodeURIComponent(id)}`, {\n method: 'PATCH',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(patch),\n });\n },\n async delete(id: string, opts?: { wipeData?: boolean }): Promise<void> {\n const qs = opts?.wipeData ? '?wipeData=1' : '';\n await jsonFetch<{ ok: true; wipedData: boolean }>(\n `/api/projects/${encodeURIComponent(id)}${qs}`,\n { method: 'DELETE' },\n );\n },\n};\n","<script lang=\"ts\">\n /*\n * Confirmation modal for project deletion. Mirrors ConfirmDialog's\n * shape (title + body + Cancel/Confirm) and adds a single checkbox\n * that opts in to also wiping the on-disk docs directory.\n *\n * Mounted via modalManager.open(); `close` is injected by the modal\n * manager. Cancel is the default-focused button so a stray Enter\n * does not trigger the destructive path.\n */\n\n let {\n projectName,\n projectId,\n onConfirm,\n onCancel,\n close,\n }: {\n projectName: string;\n projectId: string;\n onConfirm: (opts: { wipeData: boolean }) => void | Promise<void>;\n onCancel?: () => void;\n close: () => void;\n } = $props();\n\n let cancelBtn: HTMLButtonElement | undefined = $state();\n let busy = $state(false);\n let wipeData = $state(false);\n\n $effect(() => {\n cancelBtn?.focus();\n });\n\n async function handleConfirm(): Promise<void> {\n if (busy) return;\n busy = true;\n try {\n await onConfirm({ wipeData });\n } finally {\n close();\n }\n }\n\n function handleCancel(): void {\n if (busy) return;\n onCancel?.();\n close();\n }\n</script>\n\n<div class=\"delete-project-dialog\">\n <div class=\"delete-project-dialog__title\">Delete project '{projectName}'?</div>\n <div class=\"delete-project-dialog__body\">\n The project record will be removed and any members will lose access.\n Documents already written under the project's namespace remain on disk\n unless you tick the option below.\n </div>\n <label class=\"delete-project-dialog__opt\">\n <input type=\"checkbox\" bind:checked={wipeData} disabled={busy} />\n <span>\n Also delete project files\n <code class=\"delete-project-dialog__path\">&lt;dataDir&gt;/docs/{projectId}/</code>\n </span>\n </label>\n <div class=\"delete-project-dialog__actions\">\n <button\n type=\"button\"\n class=\"delete-project-dialog__btn\"\n data-delete-project-cancel\n bind:this={cancelBtn}\n onclick={handleCancel}\n disabled={busy}\n >\n Cancel\n </button>\n <button\n type=\"button\"\n class=\"delete-project-dialog__btn delete-project-dialog__btn--danger\"\n data-delete-project-confirm\n onclick={handleConfirm}\n disabled={busy}\n >\n Delete\n </button>\n </div>\n</div>\n\n<style>\n .delete-project-dialog {\n display: flex;\n flex-direction: column;\n gap: 16px;\n padding: 20px 24px;\n min-width: 400px;\n max-width: 520px;\n }\n .delete-project-dialog__title {\n font-size: 16px;\n font-weight: 600;\n color: var(--shell-fg);\n }\n .delete-project-dialog__body {\n font-size: 13px;\n color: var(--shell-fg-muted, var(--shell-fg));\n line-height: 1.5;\n }\n .delete-project-dialog__opt {\n display: flex;\n align-items: flex-start;\n gap: 8px;\n font-size: 13px;\n color: var(--shell-fg);\n cursor: pointer;\n }\n .delete-project-dialog__opt input { margin-top: 3px; }\n .delete-project-dialog__path {\n display: block;\n font-family: var(--shell-font-mono, monospace);\n font-size: 11px;\n color: var(--shell-fg-muted);\n background: var(--shell-bg-elevated);\n padding: 2px 6px;\n border-radius: var(--shell-radius-sm, 3px);\n margin-top: 2px;\n word-break: break-all;\n }\n .delete-project-dialog__actions {\n display: flex;\n justify-content: flex-end;\n gap: 8px;\n margin-top: 4px;\n }\n .delete-project-dialog__btn {\n font-size: 13px;\n padding: 6px 14px;\n border-radius: var(--shell-radius-sm, 4px);\n border: 1px solid var(--shell-border-strong);\n background: transparent;\n color: var(--shell-fg);\n cursor: pointer;\n }\n .delete-project-dialog__btn:disabled {\n opacity: 0.6;\n cursor: not-allowed;\n }\n .delete-project-dialog__btn--danger {\n color: var(--shell-error, #d32f2f);\n border-color: var(--shell-error, #d32f2f);\n }\n</style>\n","<script lang=\"ts\">\n /*\n * Admin-only float view for creating, editing, or deleting a project.\n *\n * Members and app allowlist are picked from live data via UserPicker\n * (over /api/admin/users) and AppPicker (over the client-side app\n * registry). The current user is pre-selected on the create path so\n * \"include myself\" works without looking up the underlying user id.\n */\n\n import { untrack } from 'svelte';\n import { projectsApi, type ProjectRecord } from './projectsApi';\n import { refreshProjects } from './projectsShard.svelte';\n import { getUser } from '../auth/auth.svelte';\n import AppPicker from '../primitives/widgets/AppPicker.svelte';\n import UserPicker from '../primitives/widgets/UserPicker.svelte';\n import { modalManager } from '../overlays/modal';\n import DeleteProjectDialog from './DeleteProjectDialog.svelte';\n\n interface Props {\n project?: ProjectRecord | null;\n onClose: () => void;\n }\n\n let { project = null, onClose }: Props = $props();\n\n const isEdit = $derived(project !== null);\n const me = $derived(getUser());\n\n // Form fields snapshot the project on mount; the modal is recreated per\n // open, so prop changes after mount aren't expected. untrack defers the\n // reactive read so Svelte 5 doesn't emit state_referenced_locally.\n let name = $state(untrack(() => project?.name ?? ''));\n let description = $state(untrack(() => project?.description ?? ''));\n let members = $state<string[]>(\n untrack(() => {\n if (project) return [...project.members];\n const userId = getUser()?.id;\n return userId ? [userId] : [];\n }),\n );\n let appAllowlist = $state<string[]>(\n untrack(() => (project ? [...project.appAllowlist] : [])),\n );\n let saving = $state(false);\n let error = $state<string | null>(null);\n\n async function save() {\n if (!name.trim()) {\n error = 'Name is required';\n return;\n }\n saving = true;\n error = null;\n const payload = {\n name: name.trim(),\n description: description.trim() || undefined,\n members,\n appAllowlist,\n };\n try {\n if (isEdit && project) {\n await projectsApi.update(project.id, payload);\n } else {\n await projectsApi.create(payload);\n }\n await refreshProjects();\n onClose();\n } catch (e) {\n error = (e as Error).message;\n } finally {\n saving = false;\n }\n }\n\n function remove() {\n if (!isEdit || !project) return;\n const target = project;\n modalManager.open(DeleteProjectDialog, {\n projectName: target.name,\n projectId: target.id,\n onConfirm: async ({ wipeData }: { wipeData: boolean }) => {\n saving = true;\n error = null;\n try {\n await projectsApi.delete(target.id, { wipeData });\n await refreshProjects();\n onClose();\n } catch (e) {\n error = (e as Error).message;\n } finally {\n saving = false;\n }\n },\n });\n }\n</script>\n\n<div class=\"project-manage\">\n <div class=\"body\">\n <h2>{isEdit ? `Edit ${project!.name}` : 'Create Project'}</h2>\n\n {#if isEdit}\n <p class=\"project-id\">ID: <code>{project!.id}</code></p>\n {/if}\n\n <label class=\"field\">\n <span>Name</span>\n <input type=\"text\" bind:value={name} placeholder=\"Acme Website\" disabled={saving} />\n </label>\n\n <label class=\"field\">\n <span>Description</span>\n <textarea bind:value={description} rows={2} disabled={saving}></textarea>\n </label>\n\n <label class=\"field\">\n <span>Members</span>\n <UserPicker bind:value={members} disabled={saving} />\n {#if me}\n <span class=\"hint\">\n Your id: <code>{me.id}</code> ({me.username ?? me.displayName})\n </span>\n {/if}\n </label>\n\n <label class=\"field\">\n <span>App allowlist</span>\n <AppPicker bind:value={appAllowlist} disabled={saving} />\n </label>\n\n {#if error}\n <p class=\"error\">{error}</p>\n {/if}\n </div>\n\n <div class=\"actions\">\n <button type=\"button\" class=\"primary\" onclick={save} disabled={saving}>\n {isEdit ? 'Save' : 'Create'}\n </button>\n <button type=\"button\" onclick={onClose} disabled={saving}>Cancel</button>\n {#if isEdit}\n <button type=\"button\" class=\"danger\" onclick={remove} disabled={saving}>Delete</button>\n {/if}\n </div>\n</div>\n\n<style>\n .project-manage {\n position: absolute;\n inset: 0;\n display: flex;\n flex-direction: column;\n font: inherit;\n color: var(--shell-fg);\n background: var(--shell-bg);\n }\n .body {\n flex: 1;\n overflow-y: auto;\n padding: 16px 16px 8px;\n }\n h2 { margin: 0 0 8px; font-size: 16px; }\n .project-id { font-size: 12px; color: var(--shell-fg-muted); margin: 0 0 16px; }\n .project-id code { font-family: var(--shell-font-mono, monospace); }\n .field {\n display: flex;\n flex-direction: column;\n gap: 4px;\n margin-bottom: 12px;\n font-size: 13px;\n }\n .field span { color: var(--shell-fg-muted); }\n .hint { font-size: 11px; color: var(--shell-fg-muted); }\n .hint code {\n font-family: var(--shell-font-mono, monospace);\n color: var(--shell-fg);\n background: var(--shell-bg-elevated);\n padding: 0 4px;\n border-radius: var(--shell-radius-sm, 3px);\n }\n .field input,\n .field textarea {\n background: var(--shell-bg-elevated);\n color: var(--shell-fg);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-sm, 3px);\n padding: 6px 8px;\n font: inherit;\n font-size: 13px;\n }\n .field textarea { resize: vertical; min-height: 60px; }\n .error { color: var(--shell-error, #c33); font-size: 13px; margin: 0 0 8px; }\n .actions {\n display: flex;\n gap: 8px;\n padding: 12px 16px;\n border-top: 1px solid var(--shell-border);\n background: var(--shell-bg);\n flex: 0 0 auto;\n }\n .actions button {\n background: var(--shell-bg-elevated);\n color: var(--shell-fg);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-sm, 3px);\n padding: 6px 14px;\n font: inherit;\n cursor: pointer;\n }\n .actions button:hover { border-color: var(--shell-accent); }\n .actions button.primary {\n background: var(--shell-accent);\n color: #fff;\n border-color: var(--shell-accent);\n }\n .actions button.danger { margin-left: auto; color: var(--shell-error, #c33); }\n .actions button:disabled { opacity: 0.5; cursor: not-allowed; }\n</style>\n","/*\n * `__projects__` shard — multi-member project scope module.\n *\n * Maintains a reactive list of projects the current user is a member of.\n * Refreshes on activate and on visibility-change so a project created in\n * one tab appears in another after it regains focus. Registers admin-only\n * actions that open the ProjectManage float view (create/edit/delete).\n */\n\nimport { mount, unmount } from 'svelte';\nimport type { Shard, ViewFactory, ViewHandle, MountContext } from '../shards/types';\nimport { projectsApi, type ProjectRecord } from './projectsApi';\nimport { VERSION } from '../version';\nimport ProjectManage from './ProjectManage.svelte';\nimport { floatManager } from '../overlays/float';\nimport { isAdmin } from '../auth/auth.svelte';\n\nexport const projectsState: {\n projects: ProjectRecord[];\n loading: boolean;\n error: string | null;\n} = $state({ projects: [], loading: false, error: null });\n\nexport async function refreshProjects(): Promise<void> {\n projectsState.loading = true;\n projectsState.error = null;\n try {\n projectsState.projects = await projectsApi.list();\n } catch (e) {\n projectsState.error = (e as Error).message;\n } finally {\n projectsState.loading = false;\n }\n}\n\nconst PROJECTS_MANAGE_VIEW = 'projects:manage';\n\n/*\n * The float manager drops `meta` for `dismissable: true` (per the bare\n * SlotNode wrapper in float.ts). Edit-mode needs to know which project\n * to load, so we stash the target on a module-level slot the factory\n * consumes on mount. Cleared after the factory has read it so a later\n * Create from the palette can't accidentally inherit a previous edit\n * target.\n */\nlet pendingTarget: ProjectRecord | null = null;\n\nfunction consumePendingTarget(): ProjectRecord | null {\n const t = pendingTarget;\n pendingTarget = null;\n return t;\n}\n\nexport function openProjectManage(project: ProjectRecord | null): void {\n pendingTarget = project;\n floatManager.open(PROJECTS_MANAGE_VIEW, {\n title: project ? `Edit ${project.name}` : 'Create Project',\n size: { w: 560, h: 620 },\n dismissable: true,\n });\n}\n\nexport const projectsShard: Shard = {\n manifest: {\n id: '__projects__',\n label: 'Projects',\n version: VERSION,\n views: [{ id: PROJECTS_MANAGE_VIEW, label: 'Project Manager' }],\n },\n activate(ctx) {\n void refreshProjects();\n if (typeof document !== 'undefined') {\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'visible') void refreshProjects();\n });\n }\n\n const factory: ViewFactory = {\n mount(container: HTMLElement, _mountCtx: MountContext): ViewHandle {\n const project = consumePendingTarget();\n // The float manager has already pushed an entry for this mount —\n // the most recent one whose viewId matches us is ours.\n const list = floatManager.list();\n const floatId = list.length > 0 ? list[list.length - 1].id : null;\n\n const close = () => {\n if (floatId) floatManager.close(floatId);\n };\n\n const instance = mount(ProjectManage, {\n target: container,\n props: { project, onClose: close },\n });\n return {\n unmount() {\n unmount(instance);\n },\n };\n },\n };\n ctx.registerView(PROJECTS_MANAGE_VIEW, factory);\n\n ctx.actions.register({\n id: 'sh3.project.create',\n label: 'Create Project…',\n scope: ['home', 'app'],\n paletteItem: true,\n disabled: () => !isAdmin(),\n run: () => {\n if (isAdmin()) openProjectManage(null);\n },\n });\n\n ctx.actions.register({\n id: 'sh3.project.manage',\n label: 'Manage Project…',\n scope: ['home', 'app'],\n submenu: true,\n paletteItem: true,\n disabled: () => !isAdmin(),\n });\n\n // Dynamic children: one per project in projectsState.projects, kept in\n // sync as projects are created/deleted. Mirrors the sh3.app.launch\n // pattern in sh3coreShard.\n const manageUnregisters = new Map<string, () => void>();\n $effect.root(() => {\n $effect(() => {\n const currentIds = new Set<string>();\n for (const project of projectsState.projects) {\n currentIds.add(project.id);\n if (manageUnregisters.has(project.id)) continue;\n const off = ctx.actions.register({\n id: `sh3.project.manage:${project.id}`,\n label: project.name,\n scope: ['home', 'app'],\n submenuOf: 'sh3.project.manage',\n run: () => {\n // Re-read the live record so renames since registration are\n // reflected in the form.\n const live = projectsState.projects.find((p) => p.id === project.id);\n if (live) openProjectManage(live);\n },\n });\n manageUnregisters.set(project.id, off);\n }\n for (const id of [...manageUnregisters.keys()]) {\n if (!currentIds.has(id)) {\n manageUnregisters.get(id)!();\n manageUnregisters.delete(id);\n }\n }\n });\n });\n },\n autostart() {\n /* register on the self-starting path so the project list is available\n on the home screen without an app launch. */\n },\n};\n","<script lang=\"ts\">\n /*\n * Projects section for ShellHome.\n *\n * Renders the list of projects the current user is a member of as\n * selectable cards. Selecting a project sets sessionState.activeProjectId\n * (which then filters the apps grid via the appAllowlist) and binds any\n * subsequently launched app's documents to the project scope.\n */\n\n import { projectsState, openProjectManage } from './projectsShard.svelte';\n import { sessionState, setActiveProjectId } from '../projects/session-state.svelte';\n import { isAdmin } from '../auth/auth.svelte';\n\n const visible = $derived(projectsState.projects.length > 0);\n const activeId = $derived(sessionState.activeProjectId);\n const elevated = $derived(isAdmin());\n\n function selectProject(id: string) {\n setActiveProjectId(activeId === id ? null : id);\n }\n\n function editProject(id: string, ev: MouseEvent) {\n ev.stopPropagation();\n const project = projectsState.projects.find((p) => p.id === id) ?? null;\n if (project) openProjectManage(project);\n }\n</script>\n\n{#if visible}\n <section class=\"projects-section\">\n <h2 class=\"projects-heading\">Projects</h2>\n <div class=\"projects-grid\">\n {#each projectsState.projects as project (project.id)}\n <div class=\"project-card-wrap\">\n <button\n type=\"button\"\n class=\"project-card\"\n class:active={activeId === project.id}\n onclick={() => selectProject(project.id)}\n title={project.description ?? `${project.members.length} member${project.members.length === 1 ? '' : 's'}`}\n >\n <span class=\"project-name\">{project.name}</span>\n <span class=\"project-meta\">{project.members.length} member{project.members.length === 1 ? '' : 's'}</span>\n </button>\n {#if elevated}\n <button\n type=\"button\"\n class=\"project-card-edit\"\n onclick={(ev) => editProject(project.id, ev)}\n aria-label=\"Edit project\"\n title=\"Edit project\"\n >⚙</button>\n {/if}\n </div>\n {/each}\n </div>\n </section>\n{/if}\n\n<style>\n .projects-section {\n width: 100%;\n max-width: 720px;\n margin-bottom: 28px;\n }\n .projects-heading {\n font-size: 13px;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.06em;\n color: var(--shell-fg-subtle);\n margin: 0 0 12px;\n }\n .projects-grid {\n display: grid;\n grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));\n gap: 10px;\n }\n .project-card-wrap { position: relative; }\n .project-card {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n gap: 4px;\n padding: 12px 14px;\n background: var(--shell-grad-bg-elevated, var(--shell-bg-elevated));\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-md);\n cursor: pointer;\n text-align: left;\n color: inherit;\n font: inherit;\n transition: border-color 120ms ease, transform 120ms ease;\n width: 100%;\n }\n .project-card-edit {\n position: absolute;\n top: 6px;\n right: 6px;\n background: transparent;\n border: 0;\n color: var(--shell-fg-muted);\n cursor: pointer;\n padding: 2px 6px;\n font-size: 14px;\n border-radius: var(--shell-radius-sm, 3px);\n }\n .project-card-edit:hover { color: var(--shell-fg); background: var(--shell-bg-elevated); }\n .project-card:hover {\n border-color: var(--shell-accent);\n transform: translateY(-1px);\n }\n .project-card.active {\n border-color: var(--shell-accent);\n box-shadow: 0 0 0 2px color-mix(in srgb, var(--shell-accent) 40%, transparent);\n }\n .project-name { font-weight: 600; font-size: 13px; }\n .project-meta { font-size: 11px; color: var(--shell-fg-muted); }\n</style>\n","// GENERATED — do not edit. See scripts/sync-icon-ids.ts\nexport const ICON_IDS = [\n 'activity',\n 'align-horizontal-justify-center',\n 'align-horizontal-justify-end',\n 'align-horizontal-justify-start',\n 'app-window',\n 'archive',\n 'archive-restore',\n 'axis-3d',\n 'box',\n 'brick-wall',\n 'bug',\n 'building-2',\n 'cable',\n 'calendar',\n 'camera',\n 'check',\n 'chevron-down',\n 'chevron-right',\n 'circle-check',\n 'circle-dot',\n 'circle-minus',\n 'circle-x',\n 'clipboard',\n 'clipboard-paste',\n 'clock',\n 'compass',\n 'component',\n 'copy',\n 'cpu',\n 'crop',\n 'crosshair',\n 'crown',\n 'dollar-sign',\n 'download',\n 'droplet',\n 'eraser',\n 'euro',\n 'external-link',\n 'eye',\n 'eye-off',\n 'file',\n 'file-archive',\n 'file-diff',\n 'file-plus',\n 'file-text',\n 'flame',\n 'flip-horizontal-2',\n 'flip-vertical-2',\n 'folder',\n 'folder-open',\n 'folder-plus',\n 'folder-tree',\n 'gallery-vertical-end',\n 'gamepad-2',\n 'gauge',\n 'gem',\n 'git-branch',\n 'git-commit-horizontal',\n 'git-merge',\n 'globe',\n 'grid-2x2',\n 'grid-3x3',\n 'group',\n 'hard-drive',\n 'heart',\n 'history',\n 'house',\n 'image',\n 'info',\n 'joystick',\n 'key',\n 'layers',\n 'layout-dashboard',\n 'layout-grid',\n 'layout-list',\n 'layout-panel-left',\n 'layout-panel-top',\n 'layout-template',\n 'lightbulb',\n 'link',\n 'list-ordered',\n 'list-tree',\n 'lock',\n 'log-out',\n 'magnet',\n 'mail',\n 'map',\n 'maximize',\n 'minimize',\n 'moon',\n 'mouse-pointer',\n 'move',\n 'move-3d',\n 'music',\n 'navigation',\n 'network',\n 'notebook-pen',\n 'palette',\n 'pause',\n 'pencil',\n 'pipette',\n 'play',\n 'plus',\n 'pointer',\n 'pound-sterling',\n 'receipt',\n 'redo-2',\n 'refresh-cw',\n 'rocket',\n 'rotate-3d',\n 'rotate-ccw',\n 'rotate-cw',\n 'ruler',\n 'save',\n 'scissors',\n 'scroll-text',\n 'search',\n 'send',\n 'server',\n 'settings',\n 'shield',\n 'skull',\n 'sliders-horizontal',\n 'snowflake',\n 'sparkles',\n 'square',\n 'square-terminal',\n 'star',\n 'sun',\n 'sword',\n 'table-properties',\n 'target',\n 'texture',\n 'timer',\n 'trash-2',\n 'triangle-alert',\n 'type',\n 'undo-2',\n 'ungroup',\n 'unity',\n 'upload',\n 'user',\n 'users',\n 'video',\n 'volume-2',\n 'wand-sparkles',\n 'wind',\n 'x',\n 'zap',\n 'zoom-in',\n 'zoom-out',\n] as const;\nexport type IconId = (typeof ICON_IDS)[number];\n","<script lang=\"ts\">\n /*\n * IconPicker — searchable grid of icon ids from the bundled lucide\n * sprite. The \"(none)\" tile clears the value. Composes the widget\n * commit-only event contract (CommitOnlyEvents<string | undefined>).\n */\n\n import type { CommitOnlyEvents } from './_contract';\n import { ICON_IDS } from '../../assets/iconIds.generated';\n import iconsUrl from '../../assets/icons.svg';\n\n type Props = {\n value?: string | undefined;\n label?: string;\n disabled?: boolean;\n } & CommitOnlyEvents<string | undefined>;\n\n let {\n value = $bindable(undefined),\n label,\n disabled = false,\n onchange,\n }: Props = $props();\n\n let query = $state('');\n\n const filtered = $derived(\n query.trim() === ''\n ? ICON_IDS\n : ICON_IDS.filter((id) => id.includes(query.trim().toLowerCase())),\n );\n\n function pick(id: string | undefined): void {\n if (disabled) return;\n value = id;\n onchange?.(id);\n }\n</script>\n\n<div class=\"sh3-icon-picker\" class:sh3-icon-picker--disabled={disabled}>\n {#if label}<span class=\"sh3-icon-picker__label\">{label}</span>{/if}\n <input\n type=\"search\"\n placeholder=\"Search icons…\"\n bind:value={query}\n {disabled}\n aria-label=\"Filter icons\"\n />\n <div class=\"sh3-icon-picker__grid\">\n <button\n type=\"button\"\n class=\"sh3-icon-picker__tile sh3-icon-picker__tile--none\"\n class:sh3-icon-picker__tile--selected={value === undefined}\n aria-label=\"No icon\"\n {disabled}\n onclick={() => pick(undefined)}\n >×</button>\n {#each filtered as id (id)}\n <button\n type=\"button\"\n class=\"sh3-icon-picker__tile\"\n class:sh3-icon-picker__tile--selected={value === id}\n aria-label={id}\n title={id}\n {disabled}\n onclick={() => pick(id)}\n >\n <svg viewBox=\"0 0 24 24\"><use href=\"{iconsUrl}#{id}\" /></svg>\n </button>\n {/each}\n </div>\n</div>\n\n<style>\n .sh3-icon-picker { display: flex; flex-direction: column; gap: 6px; }\n .sh3-icon-picker__label { font-size: 13px; color: var(--shell-fg-muted); }\n .sh3-icon-picker input[type=\"search\"] {\n background: var(--shell-bg-elevated);\n color: var(--shell-fg);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-sm, 3px);\n padding: 6px 8px; font: inherit; font-size: 13px;\n }\n .sh3-icon-picker__grid {\n display: grid;\n grid-template-columns: repeat(auto-fill, minmax(36px, 1fr));\n gap: 4px;\n max-height: 220px;\n overflow-y: auto;\n padding: 4px;\n background: var(--shell-bg);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-sm, 3px);\n }\n .sh3-icon-picker__tile {\n aspect-ratio: 1 / 1;\n display: flex;\n align-items: center;\n justify-content: center;\n background: var(--shell-bg-elevated);\n color: var(--shell-fg);\n border: 1px solid transparent;\n border-radius: var(--shell-radius-sm, 3px);\n cursor: pointer;\n padding: 0; font: inherit;\n }\n .sh3-icon-picker__tile--none { font-size: 16px; color: var(--shell-fg-muted); }\n .sh3-icon-picker__tile:hover { border-color: var(--shell-accent); }\n .sh3-icon-picker__tile--selected {\n outline: 2px solid var(--shell-accent);\n outline-offset: -2px;\n }\n .sh3-icon-picker__tile svg { width: 18px; height: 18px; }\n .sh3-icon-picker--disabled .sh3-icon-picker__tile { cursor: not-allowed; opacity: 0.5; }\n</style>\n","/*\n * Per-user-per-browser visual overrides for apps. The store + helpers\n * live separately from the shard so the state can be unit-tested without\n * booting the shard system, and so the AppAppearanceModal can import\n * get/set without creating an import cycle through the shard's modal\n * import.\n *\n * EXPLICITLY TEMPORARY. A future ADR is expected to add icon/color\n * fields to the app manifest itself.\n */\n\nimport type { StateZones } from '../state/zones.svelte';\nimport type { AppAppearance } from './types';\n\nexport interface AppearanceZoneSchema {\n user: { overrides: Record<string, AppAppearance> };\n}\n\nlet zoneState: StateZones<AppearanceZoneSchema> | null = null;\n\n/** Bind the shard's zone to this module. Called by the shard's activate. */\nexport function __bindZone(s: StateZones<AppearanceZoneSchema>): void {\n zoneState = s;\n}\n\n/** Unbind the zone (deactivate). */\nexport function __unbindZone(): void {\n zoneState = null;\n}\n\nfunction isEmpty(v: AppAppearance): boolean {\n return v.icon === undefined && v.color === undefined && v.label === undefined;\n}\n\nexport function getAppearance(appId: string): AppAppearance | undefined {\n const map = zoneState?.user.overrides;\n if (!map) return undefined;\n const v = map[appId];\n if (!v) return undefined;\n if (isEmpty(v)) return undefined;\n return v;\n}\n\nexport function setAppearance(\n appId: string,\n value: AppAppearance | undefined,\n): void {\n if (!zoneState) return;\n const map = zoneState.user.overrides;\n const next = { ...map };\n if (value === undefined || isEmpty(value)) {\n delete next[appId];\n } else {\n next[appId] = value;\n }\n zoneState.user.overrides = next;\n}\n\n/** Test-only: replace the bound zone with a memory shim. */\nexport function __resetForTests(): void {\n zoneState = {\n ephemeral: {} as never,\n session: {} as never,\n workspace: {} as never,\n user: { overrides: {} },\n } as never;\n}\n\n// Initialise the memory shim at module load so tests can call set/get\n// without first invoking activate. Production replaces this via\n// __bindZone() inside appearanceShard.activate().\n__resetForTests();\n","<script lang=\"ts\">\n /*\n * Customize — pick an icon and color override for a single app.\n * Reads the existing override on mount via untrack (Svelte 5 idiom for\n * one-shot prop reads), so editing the form doesn't subscribe to the\n * shard's reactive state. Save/Reset/Cancel are mutually exclusive.\n */\n\n import { untrack } from 'svelte';\n import IconPicker from '../primitives/widgets/IconPicker.svelte';\n import ColorSwatch from '../primitives/widgets/ColorSwatch.svelte';\n import iconsUrl from '../assets/icons.svg';\n import { listRegisteredApps } from '../api';\n import { getAppearance, setAppearance } from './appearanceState.svelte';\n\n interface Props {\n appId: string;\n appLabel: string;\n close: () => void;\n }\n\n let { appId, appLabel, close }: Props = $props();\n\n const initial = untrack(() => getAppearance(appId));\n const manifestIcon = untrack(\n () => listRegisteredApps().find((m) => m.id === appId)?.icon,\n );\n\n let icon = $state<string | undefined>(initial?.icon);\n let color = $state<string | undefined>(initial?.color);\n let label = $state<string>(initial?.label ?? '');\n let pickerOpen = $state<boolean>(initial?.icon !== undefined);\n\n const hasOverride = $derived(initial !== undefined);\n const effectiveLabel = $derived(label.trim() === '' ? appLabel : label.trim());\n const effectiveIcon = $derived(icon ?? manifestIcon ?? 'box');\n\n function save() {\n const trimmed = label.trim();\n setAppearance(appId, {\n icon,\n color,\n label: trimmed === '' ? undefined : trimmed,\n });\n close();\n }\n\n function reset() {\n setAppearance(appId, undefined);\n close();\n }\n</script>\n\n<div class=\"app-appearance\">\n <h2>Customize {appLabel}</h2>\n\n <div class=\"preview\">\n <div\n class=\"preview-card\"\n class:preview-card--tinted={color !== undefined}\n style:--card-color={color ?? 'transparent'}\n >\n <span class=\"preview-card-square\">\n <svg class=\"preview-card-icon\"><use href=\"{iconsUrl}#{effectiveIcon}\" /></svg>\n </span>\n <span class=\"preview-card-label\">{effectiveLabel}</span>\n </div>\n </div>\n\n <label class=\"row\"><span>Name <em>(empty = default)</em></span>\n <input\n type=\"text\"\n bind:value={label}\n placeholder={appLabel}\n class=\"name-input\"\n />\n </label>\n\n <div class=\"row\">\n <span>Icon</span>\n {#if !pickerOpen}\n <button type=\"button\" class=\"link\" onclick={() => (pickerOpen = true)}>\n Change icon\n </button>\n {:else}\n <IconPicker bind:value={icon} />\n <button type=\"button\" class=\"link link--align-right\" onclick={() => (pickerOpen = false)}>\n Hide picker\n </button>\n {/if}\n </div>\n\n <label class=\"row\"><span>Color</span>\n <ColorSwatch value={color ?? '#888888'} onchange={(v) => (color = v)} />\n </label>\n\n <div class=\"actions\">\n <button type=\"button\" class=\"primary\" onclick={save}>Save</button>\n <button type=\"button\" onclick={reset} disabled={!hasOverride}>Reset</button>\n <button type=\"button\" onclick={close}>Cancel</button>\n </div>\n</div>\n\n<style>\n .app-appearance {\n padding: 16px 20px;\n max-width: 460px;\n color: var(--shell-fg);\n background: var(--shell-bg);\n font: inherit;\n }\n h2 { margin: 0 0 12px; font-size: 16px; }\n .row { display: flex; flex-direction: column; gap: 4px; margin-bottom: 12px; font-size: 13px; }\n .row span { color: var(--shell-fg-muted); }\n .row span em { font-style: italic; opacity: 0.7; }\n .name-input {\n background: var(--shell-bg-elevated);\n color: var(--shell-fg);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-sm, 3px);\n padding: 6px 8px; font: inherit; font-size: 13px;\n }\n .link {\n align-self: flex-start;\n background: transparent;\n border: none;\n padding: 0;\n color: var(--shell-accent);\n font: inherit;\n font-size: 13px;\n cursor: pointer;\n text-decoration: underline;\n }\n .link--align-right { align-self: flex-end; margin-top: 4px; }\n .link:hover { color: var(--shell-fg); }\n .preview { display: flex; justify-content: center; margin-bottom: 16px; }\n .preview-card {\n display: flex; flex-direction: column;\n align-items: center; gap: 6px;\n max-width: 160px;\n }\n .preview-card-square {\n width: 64px; height: 64px;\n display: flex; align-items: center; justify-content: center;\n background: var(--shell-grad-bg-elevated, var(--shell-bg-elevated));\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-md);\n box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25), 0 1px 2px rgba(0, 0, 0, 0.15);\n }\n .preview-card--tinted .preview-card-square { background: var(--card-color); }\n .preview-card-icon { width: 28px; height: 28px; color: var(--shell-fg); }\n .preview-card-label {\n font-weight: 600; font-size: 11px; line-height: 1.2;\n text-align: center; word-break: break-word;\n overflow: hidden;\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: 2;\n line-clamp: 2;\n }\n .preview-card-icon { width: 24px; height: 24px; color: var(--shell-fg); }\n .preview-card-label { font-weight: 600; padding: 0 4px; line-height: 1.2; }\n .actions { display: flex; gap: 8px; margin-top: 16px; }\n .actions button {\n background: var(--shell-bg-elevated);\n color: var(--shell-fg);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-sm, 3px);\n padding: 6px 14px; font: inherit; cursor: pointer;\n }\n .actions button.primary { background: var(--shell-accent); color: #fff; border-color: var(--shell-accent); }\n .actions button:hover { border-color: var(--shell-accent); }\n .actions button:disabled { opacity: 0.5; cursor: not-allowed; }\n</style>\n","/*\n * `__app-appearance__` shard — owns the user-zone for per-app overrides\n * and registers the `app.customize` element-scope action. The state\n * itself lives in appearanceState.svelte.ts (so unit tests don't have\n * to boot a real ShardContext). This file binds the zone on activate\n * and unbinds on deactivate, and contributes the action.\n */\n\nimport type { Shard, ShardContext } from '../shards/types';\nimport type { Action, ActionDispatchContext } from '../actions/types';\nimport { VERSION } from '../version';\nimport { listRegisteredApps } from '../api';\nimport { getSelection } from '../actions/selection.svelte';\nimport { modalManager } from '../overlays/modal';\nimport AppAppearanceModal from './AppAppearanceModal.svelte';\nimport {\n __bindZone,\n __unbindZone,\n type AppearanceZoneSchema,\n} from './appearanceState.svelte';\nimport type { AppAppearance } from './types';\n\ninterface AppSelectionRef { appId: string; }\n\nfunction readSelection(): AppSelectionRef | null {\n const sel = getSelection();\n if (!sel || sel.type !== 'app') return null;\n return sel.ref as AppSelectionRef;\n}\n\nfunction runCustomize(_ctx: ActionDispatchContext) {\n const ref = readSelection();\n if (!ref) return;\n const m = listRegisteredApps().find((x) => x.id === ref.appId);\n const props = {\n appId: ref.appId,\n appLabel: m?.label ?? ref.appId,\n };\n modalManager.open<typeof props>(AppAppearanceModal as never, props);\n}\n\nexport const appearanceShard: Shard = {\n manifest: {\n id: '__app-appearance__',\n label: 'App Appearance',\n version: VERSION,\n views: [],\n },\n activate(ctx: ShardContext) {\n const zone = ctx.state<AppearanceZoneSchema>({\n user: { overrides: {} as Record<string, AppAppearance> },\n });\n __bindZone(zone);\n\n const customize: Action = {\n id: 'app.customize',\n label: 'Customize…',\n scope: { element: 'app' },\n contextItem: true,\n group: 'appearance',\n run: runCustomize,\n };\n ctx.actions.register(customize);\n },\n autostart() {\n // Self-start so the `app.customize` action is registered before the\n // user right-clicks a home card. No imperative work required.\n },\n deactivate(): void {\n __unbindZone();\n },\n};\n","<script lang=\"ts\">\n /*\n * Shell home — the view shown when no app is active.\n *\n * Layout: a title header, a filter bar, then one grid per visible\n * section (User apps always, Admin apps when elevated). Each app is\n * rendered as a square card; the whole card is the launch action.\n */\n\n import { listRegisteredApps, launchApp, isAdmin, VERSION } from '../api';\n import ShellTitle from './ShellTitle.svelte';\n import ProjectsSection from '../projects-shard/ProjectsSection.svelte';\n import { sessionState } from '../projects/session-state.svelte';\n import { projectsState } from '../projects-shard/projectsShard.svelte';\n import { shell } from '../shellRuntime.svelte';\n import { makeSelectionApi } from '../actions/selection.svelte';\n import { getAppearance } from '../app-appearance';\n import iconsUrl from '../assets/icons.svg';\n\n const homeSelection = makeSelectionApi('__sh3core__');\n\n function openAppContextMenu(event: MouseEvent, appId: string): void {\n event.preventDefault();\n homeSelection.set({ type: 'app', ref: { appId } });\n shell.actions.openContextMenu({\n x: event.clientX,\n y: event.clientY,\n scope: { element: 'app' },\n });\n }\n\n let filter = $state('');\n\n const apps = $derived(listRegisteredApps());\n const elevated = $derived(isAdmin());\n\n const activeProject = $derived(\n sessionState.activeProjectId\n ? projectsState.projects.find((p) => p.id === sessionState.activeProjectId) ?? null\n : null,\n );\n\n function matches(m: { id: string; label: string }, q: string): boolean {\n if (!q) return true;\n const needle = q.toLowerCase();\n return m.label.toLowerCase().includes(needle) || m.id.toLowerCase().includes(needle);\n }\n\n function inAllowlist(appId: string): boolean {\n if (!activeProject) return true;\n return activeProject.appAllowlist.includes(appId);\n }\n\n const userApps = $derived(\n apps.filter((m) => !m.admin && matches(m, filter) && inAllowlist(m.id)),\n );\n const adminApps = $derived(apps.filter((m) => m.admin && matches(m, filter)));\n const totalVisible = $derived(userApps.length + (elevated ? adminApps.length : 0));\n</script>\n\n<div class=\"shell-home\">\n <header class=\"shell-home-header\">\n <div class=\"shell-home-title-row\">\n <ShellTitle/>\n <span class=\"shell-home-version\">v{VERSION}</span>\n <span class=\"shell-home-alpha\">alpha</span>\n </div>\n <div class=\"shell-home-credit\">\n Art: by <a href=\"https://www.andbc.co/\" target=\"_blank\" rel=\"noopener noreferrer\">andbc</a>\n </div>\n </header>\n\n <div class=\"shell-home-filter\">\n <input\n type=\"search\"\n placeholder=\"Filter apps…\"\n bind:value={filter}\n aria-label=\"Filter apps by name\"\n class=\"shell-home-filter-input\"\n />\n </div>\n\n <ProjectsSection />\n\n {#if userApps.length > 0}\n <section class=\"shell-home-section\">\n <h2 class=\"shell-home-section-title\">Apps</h2>\n <div class=\"shell-home-grid\">\n {#each userApps as manifest (manifest.id)}\n {@const appearance = getAppearance(manifest.id)}\n <button\n type=\"button\"\n class=\"shell-home-card\"\n class:shell-home-card--tinted={appearance?.color}\n style:--card-color={appearance?.color ?? 'transparent'}\n data-sh3-scope=\"element:app\"\n onclick={() => launchApp(manifest.id)}\n oncontextmenu={(e) => openAppContextMenu(e, manifest.id)}\n >\n <span class=\"shell-home-card-square\">\n <svg class=\"shell-home-card-icon\"><use href=\"{iconsUrl}#{appearance?.icon ?? manifest.icon ?? 'box'}\" /></svg>\n </span>\n <span class=\"shell-home-card-label\">{appearance?.label ?? manifest.label}</span>\n </button>\n {/each}\n </div>\n </section>\n {/if}\n\n {#if elevated && adminApps.length > 0}\n <section class=\"shell-home-section\">\n <h2 class=\"shell-home-section-title\">Admin</h2>\n <div class=\"shell-home-grid\">\n {#each adminApps as manifest (manifest.id)}\n {@const appearance = getAppearance(manifest.id)}\n <button\n type=\"button\"\n class=\"shell-home-card\"\n class:shell-home-card--tinted={appearance?.color}\n style:--card-color={appearance?.color ?? 'transparent'}\n data-sh3-scope=\"element:app\"\n onclick={() => launchApp(manifest.id)}\n oncontextmenu={(e) => openAppContextMenu(e, manifest.id)}\n >\n <span class=\"shell-home-card-square\">\n <svg class=\"shell-home-card-icon\"><use href=\"{iconsUrl}#{appearance?.icon ?? manifest.icon ?? 'box'}\" /></svg>\n </span>\n <span class=\"shell-home-card-label\">{appearance?.label ?? manifest.label}</span>\n </button>\n {/each}\n </div>\n </section>\n {/if}\n\n {#if totalVisible === 0}\n <p class=\"shell-home-empty\">\n {#if apps.length === 0}\n No apps registered.\n {:else}\n No apps match “{filter}”.\n {/if}\n </p>\n {/if}\n</div>\n\n<style>\n .shell-home {\n position: absolute;\n inset: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: flex-start;\n padding: 48px 24px;\n overflow: auto;\n background: var(--shell-grad-bg, var(--shell-bg));\n color: var(--shell-fg);\n font-family: system-ui, sans-serif;\n }\n .shell-home-header {\n text-align: center;\n margin-bottom: 24px;\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 12px;\n }\n .shell-home-title-row {\n display: flex;\n align-items: baseline;\n gap: 6px;\n }\n .shell-home-credit {\n font-size: 11px;\n color: var(--shell-fg-muted);\n letter-spacing: 0.04em;\n margin-top: -4px;\n }\n .shell-home-credit a {\n color: var(--shell-fg-subtle);\n text-decoration: none;\n border-bottom: 1px dotted var(--shell-fg-muted);\n }\n .shell-home-credit a:hover {\n color: var(--shell-accent);\n border-bottom-color: var(--shell-accent);\n }\n .shell-home-version {\n font-size: 14px;\n color: var(--shell-fg-subtle);\n letter-spacing: 0.04em;\n }\n .shell-home-alpha {\n font-size: 10px;\n font-weight: 700;\n text-transform: uppercase;\n letter-spacing: 0.08em;\n color: #fff;\n background: var(--shell-accent);\n padding: 2px 8px;\n border-radius: 8px;\n position: relative;\n top: -1px;\n }\n .shell-home-filter {\n width: 100%;\n max-width: 720px;\n margin-bottom: 24px;\n }\n .shell-home-filter-input {\n width: 100%;\n padding: 10px 14px;\n font: inherit;\n font-size: 14px;\n color: var(--shell-fg);\n background: var(--shell-bg-elevated);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-md);\n outline: none;\n transition: border-color 120ms ease, box-shadow 120ms ease;\n }\n .shell-home-filter-input::placeholder {\n color: var(--shell-fg-muted);\n }\n .shell-home-filter-input:focus {\n border-color: var(--shell-accent);\n box-shadow: 0 0 0 2px color-mix(in srgb, var(--shell-accent) 25%, transparent);\n }\n .shell-home-empty {\n color: var(--shell-fg-muted);\n font-style: italic;\n }\n .shell-home-section {\n width: 100%;\n max-width: 720px;\n margin-bottom: 28px;\n }\n .shell-home-section-title {\n font-size: 13px;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.06em;\n color: var(--shell-fg-subtle);\n margin: 0 0 12px;\n }\n .shell-home-grid {\n display: grid;\n grid-template-columns: repeat(auto-fill, minmax(84px, 1fr));\n gap: 18px 14px;\n }\n .shell-home-card {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 6px;\n padding: 0;\n background: transparent;\n border: none;\n color: inherit;\n font: inherit;\n cursor: pointer;\n }\n .shell-home-card-square {\n width: 64px;\n height: 64px;\n display: flex;\n align-items: center;\n justify-content: center;\n background: var(--shell-grad-bg-elevated, var(--shell-bg-elevated));\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-md);\n box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25), 0 1px 2px rgba(0, 0, 0, 0.15);\n transition: transform 120ms ease, border-color 120ms ease, box-shadow 120ms ease, background 120ms ease;\n }\n .shell-home-card:hover .shell-home-card-square {\n border-color: var(--shell-accent);\n transform: translateY(-1px);\n box-shadow:\n 0 6px 14px rgba(0, 0, 0, 0.3),\n 0 0 0 1px color-mix(in srgb, var(--shell-accent) 35%, transparent),\n 0 4px 12px color-mix(in srgb, var(--shell-accent) 18%, transparent);\n }\n .shell-home-card:focus-visible {\n outline: none;\n }\n .shell-home-card:focus-visible .shell-home-card-square {\n border-color: var(--shell-accent);\n box-shadow: 0 0 0 2px color-mix(in srgb, var(--shell-accent) 40%, transparent);\n }\n .shell-home-card:active .shell-home-card-square {\n transform: translateY(0);\n }\n .shell-home-card-label {\n font-weight: 600;\n font-size: 11px;\n line-height: 1.2;\n text-align: center;\n overflow: hidden;\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: 2;\n line-clamp: 2;\n word-break: break-word;\n }\n .shell-home-card-icon {\n width: 28px;\n height: 28px;\n color: var(--shell-fg);\n }\n .shell-home-card--tinted .shell-home-card-square {\n background: var(--card-color);\n }\n</style>\n","<script lang=\"ts\">\n /**\n * Keys & Peers view — lists every API key minted for the current user's\n * tenant (admin keys excluded) and allows individual revocation.\n *\n * Reachable from settings. No create-key button; keys are only minted\n * in-shard via the consent flow.\n */\n\n import type { ApiKeyPublic } from '../../keys/types';\n import { subscribe as subscribeBus } from '../../keys/revocation-bus.svelte';\n\n let rows = $state<ApiKeyPublic[]>([]);\n let loadError = $state<string | null>(null);\n let loading = $state(true);\n let confirmingId = $state<string | null>(null);\n\n async function refresh(): Promise<void> {\n loadError = null;\n loading = true;\n try {\n const res = await fetch('/api/keys', { credentials: 'include' });\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n rows = await res.json();\n } catch (err) {\n loadError = err instanceof Error ? err.message : String(err);\n } finally {\n loading = false;\n }\n }\n\n async function revoke(id: string): Promise<void> {\n confirmingId = null;\n const res = await fetch(`/api/keys/${encodeURIComponent(id)}`, {\n method: 'DELETE',\n credentials: 'include',\n });\n if (res.ok || res.status === 404) {\n rows = rows.filter((r) => r.id !== id);\n }\n }\n\n function formatDate(iso: string): string {\n return new Date(iso).toLocaleDateString(undefined, {\n year: 'numeric', month: 'short', day: 'numeric',\n });\n }\n\n $effect(() => { refresh(); });\n\n // Refresh whenever any key is revoked (by this or another tab/shard).\n $effect(() => subscribeBus('*', () => { void refresh(); }));\n</script>\n\n<div class=\"keys-peers\">\n <div class=\"keys-peers-header\">\n <h2>Keys &amp; Peers</h2>\n </div>\n\n {#if loading}\n <p class=\"keys-peers-muted\">Loading...</p>\n {:else if loadError}\n <p class=\"keys-peers-error\">Failed to load: {loadError}</p>\n {:else if rows.length === 0}\n <p class=\"keys-peers-muted\">No keys yet. Shards will ask your permission before creating one.</p>\n {:else}\n <ul class=\"keys-peers-list\">\n {#each rows as row (row.id)}\n <li class=\"keys-peers-item\">\n <div class=\"keys-peers-info\">\n <span class=\"keys-peers-label\">{row.label}</span>\n <span class=\"keys-peers-meta\">\n Minted by: {row.mintedByShardId ?? 'system'}{row.peerRole || row.peerId ? ` \\u00B7 Peer: ${row.peerRole ?? '—'}${row.peerId ? ` (${row.peerId})` : ''}` : ''}\n </span>\n <span class=\"keys-peers-meta\">\n Scopes: {row.scopes.join(', ')}\n </span>\n <span class=\"keys-peers-meta\">\n Created: {formatDate(row.createdAt)} &middot; Expires: {row.expiresAt ? formatDate(row.expiresAt) : 'never'}\n </span>\n </div>\n <div class=\"keys-peers-actions\">\n {#if confirmingId === row.id}\n <button type=\"button\" class=\"keys-peers-btn-danger\" onclick={() => revoke(row.id)}>Confirm</button>\n <button type=\"button\" class=\"keys-peers-btn-secondary\" onclick={() => { confirmingId = null; }}>Cancel</button>\n {:else}\n <button type=\"button\" class=\"keys-peers-btn-danger\" onclick={() => { confirmingId = row.id; }}>Revoke</button>\n {/if}\n </div>\n </li>\n {/each}\n </ul>\n {/if}\n</div>\n\n<style>\n .keys-peers { padding: 24px; font-family: system-ui, sans-serif; color: var(--shell-fg); }\n .keys-peers-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }\n .keys-peers-header h2 { margin: 0; font-size: 18px; }\n .keys-peers-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }\n .keys-peers-item { display: flex; justify-content: space-between; align-items: flex-start; padding: 12px 16px; background: var(--shell-bg-elevated, #252540); border: 1px solid var(--shell-border, #3a3a5c); border-radius: var(--shell-radius, 6px); gap: 12px; }\n .keys-peers-info { display: flex; flex-direction: column; gap: 3px; min-width: 0; }\n .keys-peers-label { font-weight: 600; }\n .keys-peers-meta { font-size: 11px; color: var(--shell-fg-subtle); }\n .keys-peers-actions { display: flex; gap: 6px; flex-shrink: 0; align-items: flex-start; padding-top: 2px; }\n .keys-peers-btn-danger { background: transparent; color: var(--shell-error, #d32f2f); border: 1px solid var(--shell-error, #d32f2f); font-size: 12px; padding: 4px 10px; border-radius: var(--shell-radius, 6px); cursor: pointer; }\n .keys-peers-btn-secondary { background: transparent; color: var(--shell-fg-subtle); border: 1px solid var(--shell-border, #3a3a5c); font-size: 12px; padding: 4px 10px; border-radius: var(--shell-radius, 6px); cursor: pointer; }\n .keys-peers-muted { color: var(--shell-fg-muted); font-style: italic; }\n .keys-peers-error { color: var(--shell-error, #d32f2f); font-size: 13px; }\n</style>\n","<script lang=\"ts\">\n /*\n * ConfirmDialog — small reusable confirmation primitive for destructive\n * or otherwise non-trivial actions. Mounted via modalManager.open():\n *\n * modalManager.open(ConfirmDialog, {\n * title: 'Reset layout?',\n * body: 'This discards your customizations.',\n * confirmLabel: 'Reset',\n * confirmTone: 'danger',\n * onConfirm: () => doReset(),\n * });\n *\n * Backdrop click does NOT dismiss (no dismissOnBackdrop on the modal).\n * Escape dismisses via the modal manager's shared listener.\n * Default focus is the Cancel button so destructive actions don't fire on\n * stray Enter presses.\n */\n\n let {\n title,\n body,\n confirmLabel = 'Confirm',\n cancelLabel = 'Cancel',\n confirmTone = 'default',\n onConfirm,\n onCancel,\n close,\n }: {\n title: string;\n body: string;\n confirmLabel?: string;\n cancelLabel?: string;\n confirmTone?: 'default' | 'danger';\n onConfirm: () => void | Promise<void>;\n onCancel?: () => void;\n close: () => void;\n } = $props();\n\n let cancelBtn: HTMLButtonElement | undefined = $state();\n let busy = $state(false);\n\n $effect(() => {\n cancelBtn?.focus();\n });\n\n async function handleConfirm(): Promise<void> {\n if (busy) return;\n busy = true;\n try {\n await onConfirm();\n } finally {\n close();\n }\n }\n\n function handleCancel(): void {\n if (busy) return;\n onCancel?.();\n close();\n }\n</script>\n\n<div class=\"confirm-dialog\">\n <div class=\"confirm-dialog-title\">{title}</div>\n <div class=\"confirm-dialog-body\">{body}</div>\n <div class=\"confirm-dialog-actions\">\n <button\n type=\"button\"\n class=\"confirm-dialog-btn confirm-dialog-btn-cancel\"\n data-confirm-dialog-cancel\n bind:this={cancelBtn}\n onclick={handleCancel}\n disabled={busy}\n >\n {cancelLabel}\n </button>\n <button\n type=\"button\"\n class=\"confirm-dialog-btn\"\n class:confirm-dialog-btn-danger={confirmTone === 'danger'}\n class:confirm-dialog-btn-default={confirmTone === 'default'}\n data-confirm-dialog-confirm\n onclick={handleConfirm}\n disabled={busy}\n >\n {confirmLabel}\n </button>\n </div>\n</div>\n\n<style>\n .confirm-dialog {\n display: flex;\n flex-direction: column;\n gap: 16px;\n padding: 20px 24px;\n min-width: 360px;\n max-width: 480px;\n }\n .confirm-dialog-title {\n font-size: 16px;\n font-weight: 600;\n color: var(--shell-fg);\n }\n .confirm-dialog-body {\n font-size: 13px;\n color: var(--shell-fg-muted, var(--shell-fg));\n line-height: 1.5;\n }\n .confirm-dialog-actions {\n display: flex;\n justify-content: flex-end;\n gap: 8px;\n margin-top: 4px;\n }\n .confirm-dialog-btn {\n font-size: 13px;\n padding: 6px 14px;\n border-radius: var(--shell-radius-sm, 4px);\n border: 1px solid var(--shell-border-strong);\n background: transparent;\n color: var(--shell-fg);\n cursor: pointer;\n }\n .confirm-dialog-btn:disabled {\n opacity: 0.6;\n cursor: not-allowed;\n }\n .confirm-dialog-btn-default {\n background: var(--shell-bg-elevated);\n }\n .confirm-dialog-btn-danger {\n background: transparent;\n color: var(--shell-error, #d32f2f);\n border-color: var(--shell-error, #d32f2f);\n }\n</style>\n","/**\n * Runtime loader -- loads a pre-built ESM bundle from raw bytes via blob URL.\n *\n * The install API hands us an ArrayBuffer (the verified bundle), we wrap it\n * in a blob URL, dynamic-import it, then immediately revoke the URL so the\n * blob can be GC'd. The module's default export must carry a `manifest`\n * field; we use duck-typing to distinguish shards from apps.\n *\n * Bare specifier rewriting: bundles are built with external dependencies\n * (`sh3`, `svelte`, `svelte/internal/client`, etc.). Blob URLs can't\n * resolve bare specifiers, so we expose each dependency's runtime exports\n * at a stable blob URL (a \"shim\") and rewrite bare specifiers in the\n * bundle source before loading.\n */\n\nimport type { Shard } from '../shards/types';\nimport type { App } from '../apps/types';\nimport * as api from '../api';\nimport * as svelte from 'svelte';\n// @ts-expect-error — svelte/internal/client has no public type declarations\nimport * as svelteInternalClient from 'svelte/internal/client';\n\n// ---- shim infrastructure ---------------------------------------------------\n\n/**\n * Create a blob URL that re-exports every runtime key from a module\n * previously stashed on globalThis. The shim is created once and never\n * revoked — it must outlive every bundle that references it.\n */\n// JS reserved words that can't appear in destructuring or as bare export names.\nconst RESERVED = new Set([\n 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger',\n 'default', 'delete', 'do', 'else', 'enum', 'export', 'extends', 'false',\n 'finally', 'for', 'function', 'if', 'import', 'in', 'instanceof', 'let',\n 'new', 'null', 'return', 'super', 'switch', 'this', 'throw', 'true', 'try',\n 'typeof', 'var', 'void', 'while', 'with', 'yield',\n]);\n\nfunction createShimUrl(globalKey: string, mod: Record<string, unknown>): string {\n const names = Object.keys(mod);\n const safe = names.filter(n => !RESERVED.has(n));\n const reserved = names.filter(n => RESERVED.has(n));\n\n const lines: string[] = [`const __m__ = globalThis.${globalKey};`];\n\n // Safe names can use destructuring.\n if (safe.length > 0) {\n lines.push(`export const { ${safe.join(', ')} } = __m__;`);\n }\n\n // Reserved words need individual re-exports via a renamed binding.\n for (const name of reserved) {\n lines.push(`const __r_${name}__ = __m__['${name}']; export { __r_${name}__ as ${name} };`);\n }\n\n lines.push(`export default __m__.default;`);\n return URL.createObjectURL(new Blob([lines.join('\\n')], { type: 'application/javascript' }));\n}\n\n// Expose modules on globalThis so shims can read them.\nconst g = globalThis as Record<string, unknown>;\ng.__sh3__ = api;\ng.__sh3_svelte__ = svelte;\ng.__sh3_svelte_internal_client__ = svelteInternalClient;\n\n// Build shim URLs once at module load time.\nconst shimUrls: Record<string, string> = {\n 'sh3-core': createShimUrl('__sh3__', api as unknown as Record<string, unknown>),\n 'svelte': createShimUrl('__sh3_svelte__', svelte as unknown as Record<string, unknown>),\n 'svelte/internal/client': createShimUrl('__sh3_svelte_internal_client__', svelteInternalClient as unknown as Record<string, unknown>),\n};\n\n// `svelte/internal/disclose-version` is a side-effect-only import (no exports).\n// Create an empty shim so the import doesn't fail.\nshimUrls['svelte/internal/disclose-version'] = URL.createObjectURL(\n new Blob([''], { type: 'application/javascript' }),\n);\n\n// `sh3/tokens.css` — design tokens are already loaded by the host shell.\n// Bundles that import this path get a no-op so the import doesn't fail.\nshimUrls['sh3-core/tokens.css'] = URL.createObjectURL(\n new Blob([''], { type: 'application/javascript' }),\n);\n\n// ---- bare specifier rewriting ----------------------------------------------\n\n/**\n * Match bare specifier imports/re-exports:\n * from 'svelte/internal/client'\n * from \"sh3-core\"\n * import \"svelte/internal/disclose-version\"\n *\n * Captures the quote char and the specifier. Only rewrites specifiers\n * that have a shim URL registered above.\n */\nconst BARE_IMPORT_RE = /(?:from|import)\\s*(['\"])(sh3-core(?:\\/[^'\"]*)?|svelte(?:\\/[^'\"]*)?)\\1/g;\n\nfunction rewriteBareImports(source: string): string {\n return source.replace(BARE_IMPORT_RE, (match, _quote, specifier) => {\n const shim = shimUrls[specifier];\n if (!shim) return match; // unknown specifier — leave as-is\n // Preserve the keyword (from vs import) from the original match.\n const keyword = match.startsWith('from') ? 'from' : 'import';\n return `${keyword} '${shim}'`;\n });\n}\n\n// ----------------------------------------------------------------------------\n\n/**\n * Result of loading a bundle — may contain a shard, an app, or both.\n * Combo bundles (one shard + its companion app) are a supported pattern.\n */\nexport interface LoadedBundle {\n shards: Shard[];\n apps: App[];\n}\n\n/**\n * Load a pre-built ESM bundle from raw bytes.\n *\n * Scans all module exports (default + named) for objects with a `manifest`\n * property and classifies each as a shard or app. Combo bundles that export\n * both a shard and its companion app are supported.\n *\n * @param bytes - Raw bundle bytes (the verified ESM file contents).\n * @returns All shards and apps found in the module's exports.\n * @throws If the blob URL cannot be created or the import fails.\n */\nexport async function loadBundleModule(bytes: ArrayBuffer): Promise<LoadedBundle> {\n const source = new TextDecoder().decode(bytes);\n const rewritten = rewriteBareImports(source);\n const blob = new Blob([rewritten], { type: 'application/javascript' });\n const url = URL.createObjectURL(blob);\n try {\n const mod = await import(/* @vite-ignore */ url);\n const result: LoadedBundle = { shards: [], apps: [] };\n\n for (const value of Object.values(mod)) {\n if (!value || typeof value !== 'object' || !('manifest' in (value as Record<string, unknown>))) {\n continue;\n }\n const candidate = value as Shard | App;\n if (isShard(candidate)) result.shards.push(candidate);\n else if (isApp(candidate)) result.apps.push(candidate);\n }\n\n if (result.shards.length === 0 && result.apps.length === 0) {\n throw new Error(\n 'Bundle has no exports with a \"manifest\" property — expected at least one shard or app',\n );\n }\n return result;\n } finally {\n URL.revokeObjectURL(url);\n }\n}\n\n/**\n * Type guard: returns true if the loaded module is a shard.\n *\n * A shard has an `activate` function and `manifest.views` array. An app\n * has neither — it has `initialLayout` and `manifest.requiredShards`.\n */\nexport function isShard(mod: Shard | App): mod is Shard {\n return (\n 'activate' in mod &&\n typeof (mod as Shard).activate === 'function' &&\n Array.isArray((mod as Shard).manifest.views)\n );\n}\n\n/**\n * Type guard: returns true if the loaded module is an app.\n *\n * An app has `initialLayout` and `manifest.requiredShards`. A shard has\n * `activate` and `manifest.views` instead.\n */\nexport function isApp(mod: Shard | App): mod is App {\n return (\n 'initialLayout' in mod &&\n Array.isArray((mod as App).manifest.requiredShards)\n );\n}\n","/**\n * Package storage -- persists installed bundles and metadata.\n *\n * Uses IndexedDB, available in all target environments (browser, Tauri\n * WebView, Android WebView). Two object stores:\n * - \"bundles\" -- raw ArrayBuffer keyed by package id\n * - \"meta\" -- InstalledPackage records keyed by package id\n *\n * Designed to be swappable: a Tauri target could later substitute a\n * filesystem-backed implementation behind the same interface.\n */\n\nimport type { InstalledPackage } from './types';\n\nconst DB_NAME = 'sh3-packages';\nconst DB_VERSION = 1;\nconst BUNDLES_STORE = 'bundles';\nconst META_STORE = 'meta';\n\n/**\n * Opens (or creates) the sh3-packages IndexedDB database.\n * Called internally before every storage operation.\n */\nfunction openDb(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n request.onupgradeneeded = () => {\n const db = request.result;\n if (!db.objectStoreNames.contains(BUNDLES_STORE)) {\n db.createObjectStore(BUNDLES_STORE);\n }\n if (!db.objectStoreNames.contains(META_STORE)) {\n db.createObjectStore(META_STORE);\n }\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n\n/**\n * Wraps a single IDBObjectStore operation in a promise.\n * Opens a transaction on `store`, calls `fn` with the object store, and\n * resolves with the request result or rejects on error.\n */\nfunction tx<T>(\n db: IDBDatabase,\n store: string,\n mode: IDBTransactionMode,\n fn: (objectStore: IDBObjectStore) => IDBRequest<T>,\n): Promise<T> {\n return new Promise((resolve, reject) => {\n const transaction = db.transaction(store, mode);\n const objectStore = transaction.objectStore(store);\n const request = fn(objectStore);\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n\n/**\n * Persist a package bundle and its metadata.\n * Overwrites any existing record for the same `id`.\n */\nexport async function savePackage(\n id: string,\n bundle: ArrayBuffer,\n meta: InstalledPackage,\n): Promise<void> {\n const db = await openDb();\n await tx(db, BUNDLES_STORE, 'readwrite', (s) => s.put(bundle, id));\n await tx(db, META_STORE, 'readwrite', (s) => s.put(meta, id));\n db.close();\n}\n\n/**\n * Load the raw bundle bytes for an installed package.\n * Returns `null` if no bundle is stored for `id`.\n */\nexport async function loadBundle(id: string): Promise<ArrayBuffer | null> {\n const db = await openDb();\n const result = await tx(db, BUNDLES_STORE, 'readonly', (s) => s.get(id));\n db.close();\n return result ?? null;\n}\n\n/**\n * Load the metadata record for an installed package.\n * Returns `null` if no metadata is stored for `id`.\n */\nexport async function loadMeta(id: string): Promise<InstalledPackage | null> {\n const db = await openDb();\n const result = await tx(db, META_STORE, 'readonly', (s) => s.get(id));\n db.close();\n return (result as InstalledPackage) ?? null;\n}\n\n/**\n * List metadata for all installed packages.\n * Returns an empty array when nothing has been installed yet.\n */\nexport async function listInstalled(): Promise<InstalledPackage[]> {\n const db = await openDb();\n const result = await tx(db, META_STORE, 'readonly', (s) => s.getAll());\n db.close();\n return (result as InstalledPackage[]) ?? [];\n}\n\n/**\n * Remove a package's bundle and metadata from storage.\n * No-ops silently if the package was not installed.\n */\nexport async function removePackage(id: string): Promise<void> {\n const db = await openDb();\n await tx(db, BUNDLES_STORE, 'readwrite', (s) => s.delete(id));\n await tx(db, META_STORE, 'readwrite', (s) => s.delete(id));\n db.close();\n}\n","/**\n * Unified bundle registration — stamps loader-assigned metadata onto every\n * shard/app manifest from a loaded bundle, then registers each. Shared by\n * `installer.installPackage`, `installer.loadInstalledPackages`, and\n * `createShell` discoveredPackages so the three boot paths stay in sync.\n *\n * Per ADR-013, external package authors omit `version` from their source\n * manifests; the authoritative value comes from the persisted/server\n * metadata and must be stamped here before any consumer reads the manifest.\n */\n\nimport type { LoadedBundle } from './loader';\nimport { registerShard } from '../shards/activate.svelte';\nimport { registerApp } from '../apps/registry.svelte';\n\nexport interface BundleStampMeta {\n version: string;\n sourceRegistry: string;\n contractVersion: string;\n}\n\nexport function registerLoadedBundle(loaded: LoadedBundle, meta: BundleStampMeta): void {\n for (const shard of loaded.shards) {\n shard.manifest = { ...shard.manifest, version: meta.version };\n registerShard(shard);\n }\n for (const app of loaded.apps) {\n app.manifest = { ...app.manifest, version: meta.version };\n registerApp(app);\n }\n}\n","/**\n * Human-friendly descriptions for manifest-declared permissions.\n *\n * The app store's install/update confirmation modal renders each permission\n * via `describePermission`. Unknown permission IDs fall back to showing the\n * raw ID with a generic placeholder so newer packages don't crash older\n * cores.\n */\n\nimport type { LoadedBundle } from './loader';\n\nexport interface PermissionDescription {\n title: string;\n description: string;\n}\n\nexport const PERMISSION_DESCRIPTIONS: Record<string, PermissionDescription> = {\n 'state:manage': {\n title: 'Manage shell state zones',\n description: 'Read and write state zones belonging to other shards.',\n },\n 'documents:browse': {\n title: 'Browse tenant documents',\n description: 'Observe all documents stored by the current tenant.',\n },\n 'documents:read': {\n title: 'Read tenant documents',\n description:\n 'Read the content of any document in the current tenant, across all shards. Required for backup connectors that need to pull document bodies (not just metadata) out of other shards.',\n },\n 'documents:write': {\n title: 'Write tenant documents',\n description:\n 'Create and overwrite documents in any shard\\'s namespace within the current tenant. Required for restore-class connectors that re-import documents back into their owning shards.',\n },\n 'documents:sync': {\n title: 'Sync documents with peers',\n description: 'Participate in cross-peer document synchronization.',\n },\n 'sync:peer': {\n title: 'Act as a sync peer',\n description: 'Exchange document updates with remote peers.',\n },\n 'sync:policy': {\n title: 'Define sync policy',\n description: 'Configure which documents sync and with whom.',\n },\n 'keys:mint': {\n title: 'Mint API keys',\n description: 'Issue long-lived access tokens for this shell.',\n },\n};\n\nexport function describePermission(id: string): PermissionDescription {\n return PERMISSION_DESCRIPTIONS[id] ?? {\n title: id,\n description: 'Unknown permission.',\n };\n}\n\n/**\n * Compute the deduped union of declared permissions across every shard\n * and app exported by a bundle. For a plain shard or app bundle this is\n * just that manifest's permissions; for combos it merges both halves.\n */\nexport function extractBundlePermissions(loaded: LoadedBundle): string[] {\n const perms = new Set<string>();\n for (const s of loaded.shards) {\n for (const p of s.manifest.permissions ?? []) perms.add(p);\n }\n for (const a of loaded.apps) {\n for (const p of a.manifest.permissions ?? []) perms.add(p);\n }\n return [...perms];\n}\n","/**\n * Package installer -- coordinates storing, loading, and registering packages.\n *\n * This is the bridge between the store shard (which fetches and verifies\n * bundles) and the framework (which registers shards/apps). The install API\n * is host-only; shards and apps must not import from here.\n *\n * Flow:\n * 1. `installPackage(bundle, meta)` -- load module from bytes, verify\n * declared type matches actual type, persist to IndexedDB, evict any\n * existing registration, then register via the shared helper.\n * 2. `uninstallPackage(id)` -- deactivate if active, unregister app, remove\n * from storage.\n * 3. `loadInstalledPackages()` -- called at boot, re-loads all installed\n * packages from IndexedDB and registers them.\n */\n\nimport { loadBundleModule, type LoadedBundle } from './loader';\nimport { savePackage, loadBundle, listInstalled, removePackage } from './storage';\nimport { verifyIntegrity } from './integrity';\nimport { deactivateShard } from '../shards/activate.svelte';\nimport { unregisterApp } from '../apps/lifecycle';\nimport { registerLoadedBundle } from './register';\nimport { extractBundlePermissions } from './permission-descriptions';\nimport type { InstalledPackage, InstallResult, PackageMeta } from './types';\n\n/**\n * Install a package from raw bundle bytes and metadata.\n *\n * Loads the ESM module, verifies the declared type matches the actual module\n * shape, persists to IndexedDB, evicts any existing registration for the same\n * id, and registers with the framework via the shared helper. If registration\n * fails (e.g. a shard that was already glob-discovered), the package is still\n * persisted but `hotLoaded` is false.\n *\n * @param bundle - Raw verified ESM bundle bytes.\n * @param meta - Provenance metadata for the install record.\n * @returns Result object indicating success/failure and hot-load status.\n */\nexport async function installPackage(\n bundle: ArrayBuffer,\n meta: PackageMeta,\n options?: { loaded?: LoadedBundle },\n): Promise<InstallResult> {\n // 1. Verify bundle integrity before executing any code.\n if (!meta.integrity) {\n return {\n success: false,\n hotLoaded: false,\n error: 'Missing integrity hash — refusing to install unverified bundle',\n };\n }\n try {\n await verifyIntegrity(bundle, meta.integrity);\n } catch (err) {\n return {\n success: false,\n hotLoaded: false,\n error: `Integrity check failed: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n\n // 2. Load the module from verified bytes (or reuse the caller's copy).\n let loaded: LoadedBundle;\n if (options?.loaded) {\n loaded = options.loaded;\n } else {\n try {\n loaded = await loadBundleModule(bundle);\n } catch (err) {\n return {\n success: false,\n hotLoaded: false,\n error: `Failed to load bundle: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n }\n\n // 3. Verify the bundle contains the declared type.\n if (meta.type === 'shard' && loaded.shards.length === 0) {\n return {\n success: false,\n hotLoaded: false,\n error: `Package \"${meta.id}\" declared type \"shard\" but bundle contains no valid shard`,\n };\n }\n if (meta.type === 'app' && loaded.apps.length === 0) {\n return {\n success: false,\n hotLoaded: false,\n error: `Package \"${meta.id}\" declared type \"app\" but bundle contains no valid app`,\n };\n }\n\n // 4. Persist to IndexedDB. Permissions captured from manifest(s).\n const record: InstalledPackage = {\n id: meta.id,\n type: meta.type,\n version: meta.version,\n sourceRegistry: meta.sourceRegistry,\n contractVersion: meta.contractVersion,\n installedAt: new Date().toISOString(),\n permissions: extractBundlePermissions(loaded),\n };\n\n try {\n await savePackage(meta.id, bundle, record);\n } catch (err) {\n return {\n success: false,\n hotLoaded: false,\n error: `Failed to persist package: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n\n // 5. Evict any existing registration for this id before re-registering.\n // Without this, reinstall at the same version leaks activation state\n // (shards stay active) or app entries (apps silently replace but the\n // old module instance's module-scope state is never torn down).\n if (meta.type === 'shard' || meta.type === 'combo') {\n try { deactivateShard(meta.id); } catch { /* not active or not a shard */ }\n }\n if (meta.type === 'app' || meta.type === 'combo') {\n unregisterApp(meta.id);\n }\n\n // 6. Register all shards and apps from the bundle via the shared helper.\n let hotLoaded = true;\n try {\n registerLoadedBundle(loaded, {\n version: meta.version,\n sourceRegistry: meta.sourceRegistry,\n contractVersion: meta.contractVersion,\n });\n } catch (err) {\n console.warn(\n `[sh3] Package \"${meta.id}\" installed but registration failed (will retry on next boot):`,\n err instanceof Error ? err.message : err,\n );\n hotLoaded = false;\n }\n\n return { success: true, package: record, hotLoaded };\n}\n\n/**\n * Uninstall a package by id.\n *\n * If the package is a shard and currently active, deactivates it first.\n * Unregisters any app entry for the id, then removes both the bundle and\n * metadata from IndexedDB.\n *\n * @param id - The package id to uninstall.\n */\nexport async function uninstallPackage(id: string): Promise<void> {\n try { deactivateShard(id); } catch { /* no-op */ }\n unregisterApp(id);\n await removePackage(id);\n}\n\n/**\n * List all installed packages.\n *\n * Delegates directly to the storage layer. Returns metadata records only,\n * not the bundle bytes.\n */\nexport async function listInstalledPackages(): Promise<InstalledPackage[]> {\n return listInstalled();\n}\n\n/**\n * Load all installed packages from IndexedDB and register them.\n *\n * Called once at boot by `bootstrap()`, before any glob-discovered shards\n * or the shell shard are registered. Individual package failures are logged\n * as warnings but do not prevent the shell from booting.\n */\nexport async function loadInstalledPackages(): Promise<void> {\n let packages: InstalledPackage[];\n try {\n packages = await listInstalled();\n } catch (err) {\n console.warn(\n '[sh3] Failed to read installed packages from storage:',\n err instanceof Error ? err.message : err,\n );\n return;\n }\n\n for (const pkg of packages) {\n try {\n const bytes = await loadBundle(pkg.id);\n if (!bytes) {\n console.warn(`[sh3] No bundle found for installed package \"${pkg.id}\", skipping`);\n continue;\n }\n\n const loaded = await loadBundleModule(bytes);\n\n registerLoadedBundle(loaded, {\n version: pkg.version,\n sourceRegistry: pkg.sourceRegistry,\n contractVersion: pkg.contractVersion,\n });\n\n if (loaded.shards.length === 0 && loaded.apps.length === 0) {\n console.warn(`[sh3] Package \"${pkg.id}\" contains no valid shards or apps, skipping`);\n }\n } catch (err) {\n console.warn(\n `[sh3] Failed to load installed package \"${pkg.id}\":`,\n err instanceof Error ? err.message : err,\n );\n }\n }\n}\n","/*\n * Machine-readable contract descriptor.\n *\n * Imported as `import { contract } from 'sh3-core/contract'`. The validator\n * package reads this to know what import paths are legal, what fields\n * manifests must have, and which contract version is in play.\n *\n * Pure data — no runtime logic, no dependencies.\n */\n\nexport const contract = {\n version: 1,\n\n /** Import specifiers any shard/app source file may use. */\n shardImports: ['sh3-core', 'sh3-core/tokens.css'],\n\n /** Import specifiers restricted to the host entry point only. */\n hostImports: ['sh3-core/host'],\n\n /** Contract-level prefix. Any import starting with 'sh3-core' that is not\n * listed in shardImports or hostImports is illegal. */\n packagePrefix: 'sh3-core',\n\n shard: {\n /** Fields external authors must declare. */\n sourceRequiredFields: ['id', 'label', 'views'] as const,\n /** Fields the framework stamps at load time — must NOT appear in source. */\n runtimeRequiredFields: ['version'] as const,\n /** Union of both — the full runtime shape. Kept for backward compat. */\n requiredFields: ['id', 'label', 'version', 'views'] as const,\n views: {\n requiredFields: ['id', 'label'] as const,\n },\n },\n\n app: {\n /** Fields external authors must declare. */\n sourceRequiredFields: ['id', 'label', 'requiredShards', 'layoutVersion'] as const,\n /** Fields the framework stamps at load time — must NOT appear in source. */\n runtimeRequiredFields: ['version'] as const,\n /** Union of both — the full runtime shape. Kept for backward compat. */\n requiredFields: ['id', 'label', 'version', 'requiredShards', 'layoutVersion'] as const,\n },\n} as const;\n\nexport type Contract = typeof contract;\n","<script lang=\"ts\">\n /*\n * PermissionConfirmModal — confirmation modal for install and update flows.\n *\n * Install mode: lists the full declared permission set for the incoming\n * package.\n * Update mode: lists the permissions newly added or removed compared to\n * the currently installed version.\n *\n * Informational only — the buttons are Cancel / Confirm. Accepting grants\n * all declared permissions; denying aborts the operation with no state\n * change.\n */\n\n import { describePermission } from '../../registry/permission-descriptions';\n\n interface Props {\n mode: 'install' | 'update';\n pkg: { label: string; version: string; author?: string };\n fromVersion?: string;\n permissions?: string[];\n added?: string[];\n removed?: string[];\n onConfirm: () => void;\n onCancel: () => void;\n }\n\n const {\n mode,\n pkg,\n fromVersion,\n permissions = [],\n added = [],\n removed = [],\n onConfirm,\n onCancel,\n }: Props = $props();\n\n const confirmLabel = $derived(mode === 'install' ? 'Install' : 'Update');\n</script>\n\n<!-- svelte-ignore a11y_click_events_have_key_events -->\n<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->\n<div\n class=\"perm-modal-backdrop\"\n onclick={onCancel}\n onkeydown={(e) => { if (e.key === 'Escape') onCancel(); }}\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label=\"{confirmLabel} {pkg.label}\"\n tabindex=\"-1\"\n>\n <!-- svelte-ignore a11y_click_events_have_key_events -->\n <!-- svelte-ignore a11y_no_static_element_interactions -->\n <div class=\"perm-modal-panel\" onclick={(e) => e.stopPropagation()} role=\"document\">\n <header class=\"perm-modal-header\">\n <h3>{confirmLabel} {pkg.label}</h3>\n <div class=\"perm-modal-subtitle\">\n {#if mode === 'update' && fromVersion}\n {fromVersion} &rarr; {pkg.version}\n {:else}\n v{pkg.version}\n {/if}\n {#if pkg.author}\n <span class=\"perm-modal-author\">by {pkg.author}</span>\n {/if}\n </div>\n </header>\n\n <div class=\"perm-modal-body\">\n {#if mode === 'install'}\n {#if permissions.length === 0}\n <p class=\"perm-modal-empty\">\n This package requires no special permissions.\n </p>\n {:else}\n <p class=\"perm-modal-intro\">This package requests the following permissions:</p>\n <ul class=\"perm-modal-list\">\n {#each permissions as id (id)}\n {@const d = describePermission(id)}\n <li class=\"perm-modal-item\">\n <div class=\"perm-modal-item-title\">{d.title}</div>\n <div class=\"perm-modal-item-desc\">{d.description}</div>\n </li>\n {/each}\n </ul>\n {/if}\n {:else}\n {#if added.length > 0}\n <p class=\"perm-modal-intro\">New permissions in this update:</p>\n <ul class=\"perm-modal-list perm-modal-added\">\n {#each added as id (id)}\n {@const d = describePermission(id)}\n <li class=\"perm-modal-item\">\n <div class=\"perm-modal-item-title\">{d.title}</div>\n <div class=\"perm-modal-item-desc\">{d.description}</div>\n </li>\n {/each}\n </ul>\n {/if}\n {#if removed.length > 0}\n <p class=\"perm-modal-intro\">Permissions no longer requested:</p>\n <ul class=\"perm-modal-list perm-modal-removed\">\n {#each removed as id (id)}\n {@const d = describePermission(id)}\n <li class=\"perm-modal-item\">\n <div class=\"perm-modal-item-title\">{d.title}</div>\n <div class=\"perm-modal-item-desc\">{d.description}</div>\n </li>\n {/each}\n </ul>\n {/if}\n {/if}\n </div>\n\n <footer class=\"perm-modal-footer\">\n <button class=\"perm-modal-cancel\" onclick={onCancel}>Cancel</button>\n <button class=\"perm-modal-confirm\" onclick={onConfirm}>{confirmLabel}</button>\n </footer>\n </div>\n</div>\n\n<style>\n .perm-modal-backdrop {\n position: fixed;\n inset: 0;\n background: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 1000;\n }\n .perm-modal-panel {\n background: var(--shell-bg, #1e1e1e);\n color: var(--shell-fg, #e0e0e0);\n border: 1px solid var(--shell-border, #444);\n border-radius: var(--shell-radius-md);\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);\n min-width: 360px;\n max-width: 520px;\n max-height: 80vh;\n display: flex;\n flex-direction: column;\n font-family: var(--shell-font-ui);\n }\n .perm-modal-header {\n padding: 16px 20px 12px;\n border-bottom: 1px solid var(--shell-border, #444);\n }\n .perm-modal-header h3 {\n margin: 0 0 4px 0;\n font-size: 1.0625rem;\n font-weight: 600;\n }\n .perm-modal-subtitle {\n font-size: 0.8125rem;\n color: var(--shell-fg-muted, #888);\n }\n .perm-modal-author {\n margin-left: 8px;\n }\n .perm-modal-body {\n padding: 16px 20px;\n overflow-y: auto;\n flex: 1;\n }\n .perm-modal-intro {\n margin: 0 0 8px 0;\n font-size: 0.875rem;\n }\n .perm-modal-empty {\n margin: 0;\n font-size: 0.875rem;\n color: var(--shell-fg-muted, #888);\n font-style: italic;\n }\n .perm-modal-list {\n list-style: none;\n margin: 0 0 12px 0;\n padding: 0;\n display: flex;\n flex-direction: column;\n gap: 8px;\n }\n .perm-modal-item {\n padding: 8px 10px;\n background: var(--shell-input-bg, #2a2a2a);\n border: 1px solid var(--shell-border, #444);\n border-radius: var(--shell-radius-sm);\n }\n .perm-modal-item-title {\n font-size: 0.875rem;\n font-weight: 600;\n }\n .perm-modal-item-desc {\n font-size: 0.75rem;\n color: var(--shell-fg-muted, #888);\n margin-top: 2px;\n }\n .perm-modal-added .perm-modal-item {\n border-color: color-mix(in srgb, var(--shell-warning, #ff9800) 60%, var(--shell-border, #444));\n }\n .perm-modal-removed .perm-modal-item {\n opacity: 0.75;\n }\n .perm-modal-footer {\n padding: 12px 20px;\n border-top: 1px solid var(--shell-border, #444);\n display: flex;\n justify-content: flex-end;\n gap: 8px;\n }\n .perm-modal-cancel {\n padding: 6px 14px;\n background: transparent;\n color: var(--shell-fg, #e0e0e0);\n border: 1px solid var(--shell-border, #444);\n border-radius: var(--shell-radius);\n font-size: 0.8125rem;\n cursor: pointer;\n }\n .perm-modal-confirm {\n padding: 6px 14px;\n background: var(--shell-accent, #007acc);\n color: #fff;\n border: 1px solid var(--shell-accent, #007acc);\n border-radius: var(--shell-radius);\n font-size: 0.8125rem;\n cursor: pointer;\n font-weight: 600;\n }\n</style>\n","/*\n * Pure helpers that translate the registry's internal package-type triple\n * (`shard | app | combo`) into the two-value vocabulary the store UI shows\n * the user (`Shard | App`). `combo` is an internal distinction — a package\n * that ships both a shard and an app surface — and from a user's standpoint\n * a combo *is* an app, so it collapses to \"App\" everywhere user-facing.\n *\n * Kept as a separate module (rather than inline in StoreView) so the mapping\n * is unit-testable without mounting Svelte components.\n */\n\n/** Internal package types as carried by the registry index. */\nexport type PackageType = 'shard' | 'app' | 'combo';\n\n/** User-visible package types — the registry triple collapsed to a pair. */\nexport type DisplayPackageType = 'shard' | 'app';\n\n/** Type-filter values exposed by the browse-view dropdown. */\nexport type PackageTypeFilter = 'all' | DisplayPackageType;\n\n/**\n * Collapse the internal triple to the user-visible pair. Combo packages\n * fold into `app`.\n */\nexport function displayPackageType(type: PackageType): DisplayPackageType {\n return type === 'shard' ? 'shard' : 'app';\n}\n\n/**\n * Title-cased label for the type chip. Returns `\"Shard\"` or `\"App\"` —\n * never `\"Combo\"`.\n */\nexport function displayPackageTypeLabel(type: PackageType): 'Shard' | 'App' {\n return displayPackageType(type) === 'shard' ? 'Shard' : 'App';\n}\n\n/**\n * True if a package of `type` should be visible under the chosen filter.\n * Combos pass under both `\"all\"` and `\"app\"` (never under `\"shard\"`).\n */\nexport function packageMatchesTypeFilter(\n type: PackageType,\n filter: PackageTypeFilter,\n): boolean {\n if (filter === 'all') return true;\n return displayPackageType(type) === filter;\n}\n","<script lang=\"ts\">\n /*\n * StoreView — browse catalog view for the store shard.\n *\n * Displays a searchable, filterable grid of packages from configured\n * registries. Each card shows package metadata and an install button.\n */\n\n import { storeContext } from './storeShard.svelte';\n import { fetchBundle, fetchServerBundle, buildPackageMeta } from '../../registry/client';\n import { installPackage } from '../../registry/installer';\n import { loadBundleModule, type LoadedBundle } from '../../registry/loader';\n import { extractBundlePermissions } from '../../registry/permission-descriptions';\n import { serverInstallPackage } from '../../env/client';\n import { contract } from '../../contract';\n import type { ResolvedPackage } from '../../registry/client';\n import type { InstalledPackage } from '../../registry/types';\n import { FRAMEWORK_SHARD_IDS } from '../../api';\n import PermissionConfirmModal from './PermissionConfirmModal.svelte';\n import {\n displayPackageType,\n displayPackageTypeLabel,\n packageMatchesTypeFilter,\n type PackageTypeFilter,\n } from './storeTypes';\n\n let search = $state('');\n let typeFilter = $state<PackageTypeFilter>('all');\n let installingIds = $state<Set<string>>(new Set());\n let updatingIds = $state<Set<string>>(new Set());\n let installError = $state<string | null>(null);\n let newRegistryUrl = $state('');\n\n let installModal = $state<null | {\n pkg: ResolvedPackage;\n permissions: string[];\n loaded: LoadedBundle;\n bundle: ArrayBuffer;\n meta: ReturnType<typeof buildPackageMeta>;\n serverBundle: ArrayBuffer | undefined;\n }>(null);\n\n let updateModal = $state<null | {\n pkg: ResolvedPackage;\n fromVersion: string;\n added: string[];\n removed: string[];\n resolve: (ok: boolean) => void;\n }>(null);\n\n const ctx = storeContext;\n\n async function handleAddRegistry() {\n const url = newRegistryUrl.trim();\n if (!url) return;\n if (ctx.env.registries.includes(url)) return;\n try {\n await ctx.addRegistry(url);\n newRegistryUrl = '';\n ctx.refreshCatalog();\n ctx.refreshInstalled();\n } catch (err) {\n installError = err instanceof Error ? err.message : String(err);\n }\n }\n\n async function handleRemoveRegistry(url: string) {\n try {\n await ctx.removeRegistry(url);\n ctx.refreshCatalog();\n } catch (err) {\n installError = err instanceof Error ? err.message : String(err);\n }\n }\n\n const filtered = $derived.by(() => {\n const q = search.toLowerCase().trim();\n return ctx.state.ephemeral.catalog.filter((pkg: ResolvedPackage) => {\n if (!packageMatchesTypeFilter(pkg.entry.type, typeFilter)) return false;\n if (!q) return true;\n return (\n pkg.entry.id.toLowerCase().includes(q) ||\n pkg.entry.label.toLowerCase().includes(q) ||\n pkg.entry.description.toLowerCase().includes(q)\n );\n });\n });\n\n function isInstalled(id: string): boolean {\n return ctx.state.ephemeral.installed.some((p: InstalledPackage) => p.id === id);\n }\n\n function hasContractMismatch(pkg: ResolvedPackage): boolean {\n return String(pkg.latest.contractVersion) !== String(contract.version);\n }\n\n function hasUpdate(id: string): boolean {\n return id in ctx.state.ephemeral.updatable;\n }\n\n function installedVersion(id: string): string {\n return ctx.state.ephemeral.installed.find((p: InstalledPackage) => p.id === id)?.version ?? '';\n }\n\n function missingShards(pkg: ResolvedPackage, installed: InstalledPackage[]): string[] {\n const required = pkg.latest.requires?.map((r) => r.id) ?? [];\n if (required.length === 0) return [];\n const known = new Set<string>(FRAMEWORK_SHARD_IDS);\n for (const p of installed) {\n if (p.type === 'shard' || p.type === 'combo') known.add(p.id);\n }\n return required.filter((id: string) => !known.has(id));\n }\n\n async function handleUpdate(id: string) {\n if (updatingIds.has(id)) return;\n\n updatingIds = new Set([...updatingIds, id]);\n installError = null;\n\n try {\n await ctx.updatePackage(id, (added, removed) => {\n return new Promise<boolean>((resolve) => {\n const pkg = ctx.state.ephemeral.updatable[id];\n const installed = ctx.state.ephemeral.installed.find(\n (p: InstalledPackage) => p.id === id,\n );\n if (!pkg || !installed) {\n resolve(true);\n return;\n }\n updateModal = {\n pkg,\n fromVersion: installed.version,\n added,\n removed,\n resolve,\n };\n });\n });\n } catch (err) {\n installError = err instanceof Error ? err.message : String(err);\n } finally {\n const next = new Set(updatingIds);\n next.delete(id);\n updatingIds = next;\n }\n }\n\n function confirmUpdate() {\n const m = updateModal;\n if (!m) return;\n updateModal = null;\n m.resolve(true);\n }\n\n function cancelUpdate() {\n const m = updateModal;\n if (!m) return;\n updateModal = null;\n m.resolve(false);\n }\n\n async function handleInstall(pkg: ResolvedPackage) {\n const id = pkg.entry.id;\n if (installingIds.has(id)) return;\n\n installingIds = new Set([...installingIds, id]);\n installError = null;\n\n try {\n // 1. Fetch and integrity-verify the client bundle from the registry.\n const bundle = await fetchBundle(pkg.latest, pkg.sourceRegistry);\n const meta = buildPackageMeta(pkg, pkg.latest);\n\n // 2. Load the module once, extract permissions for the confirmation\n // modal, and reuse the loaded reference on install.\n const loaded = await loadBundleModule(bundle);\n const permissions = extractBundlePermissions(loaded);\n\n // 3. Fetch the server bundle upfront so the modal is the last blocker.\n let serverBundle: ArrayBuffer | undefined;\n if (pkg.latest.serverBundleUrl) {\n serverBundle = await fetchServerBundle(pkg.latest, pkg.sourceRegistry);\n }\n\n // 4. Show the confirmation modal. The actual install happens in\n // confirmInstall() once the user clicks Install.\n installModal = { pkg, permissions, loaded, bundle, meta, serverBundle };\n } catch (err) {\n installError = err instanceof Error ? err.message : String(err);\n const next = new Set(installingIds);\n next.delete(id);\n installingIds = next;\n }\n }\n\n async function confirmInstall() {\n const ctxModal = installModal;\n if (!ctxModal) return;\n installModal = null;\n\n const { pkg, loaded, bundle, meta, serverBundle } = ctxModal;\n const id = pkg.entry.id;\n\n try {\n const manifest = {\n id: meta.id,\n type: meta.type,\n label: pkg.entry.label,\n version: meta.version,\n contractVersion: meta.contractVersion,\n sourceRegistry: meta.sourceRegistry,\n requiredShards: pkg.latest.requires?.map((r) => r.id) ?? [],\n installedAt: new Date().toISOString(),\n };\n const serverResult = await serverInstallPackage(manifest, bundle, serverBundle);\n if (!serverResult.ok) {\n installError = serverResult.error ?? 'Server install failed';\n return;\n }\n\n const result = await installPackage(bundle, meta, { loaded });\n if (!result.success) {\n console.warn(`[sh3-store] Server install ok but local hot-load failed: ${result.error}`);\n }\n\n await ctx.refreshInstalled();\n } catch (err) {\n installError = err instanceof Error ? err.message : String(err);\n } finally {\n const next = new Set(installingIds);\n next.delete(id);\n installingIds = next;\n }\n }\n\n function cancelInstall() {\n if (!installModal) return;\n const id = installModal.pkg.entry.id;\n installModal = null;\n const next = new Set(installingIds);\n next.delete(id);\n installingIds = next;\n }\n\n function handleRefresh() {\n ctx.refreshCatalog();\n ctx.refreshInstalled();\n }\n</script>\n\n<div class=\"store-view\">\n <header class=\"store-header\">\n <h2>Package Store</h2>\n <div class=\"store-controls\">\n <input\n class=\"store-search\"\n type=\"text\"\n placeholder=\"Search packages...\"\n bind:value={search}\n />\n <select class=\"store-filter\" bind:value={typeFilter}>\n <option value=\"all\">All</option>\n <option value=\"shard\">Shards</option>\n <option value=\"app\">Apps</option>\n </select>\n <button\n class=\"store-refresh\"\n onclick={handleRefresh}\n disabled={ctx.state.ephemeral.loading}\n >\n {ctx.state.ephemeral.loading ? 'Loading...' : 'Refresh'}\n </button>\n </div>\n </header>\n\n {#if ctx.isAdmin && ctx.env.registries.length > 0}\n <div class=\"store-registries\">\n {#each ctx.env.registries as url}\n <div class=\"store-registry-entry\">\n <span class=\"store-registry-url\">{url}</span>\n <button class=\"store-registry-remove\" onclick={() => handleRemoveRegistry(url)}>\n Remove\n </button>\n </div>\n {/each}\n </div>\n {/if}\n\n {#if ctx.isAdmin}\n <form class=\"store-add-registry\" onsubmit={(e) => { e.preventDefault(); handleAddRegistry(); }}>\n <input\n class=\"store-registry-input\"\n type=\"url\"\n placeholder=\"Registry URL (e.g. https://sh3.example.com/registry.json)\"\n bind:value={newRegistryUrl}\n />\n <button type=\"submit\" class=\"store-add-btn\" disabled={!newRegistryUrl.trim()}>\n Add\n </button>\n </form>\n {/if}\n\n {#if ctx.state.ephemeral.error}\n <div class=\"store-error\">{ctx.state.ephemeral.error}</div>\n {/if}\n\n {#if installError}\n <div class=\"store-error\">{installError}</div>\n {/if}\n\n <div class=\"store-grid\">\n {#each filtered as pkg (pkg.entry.id)}\n {@const installed = isInstalled(pkg.entry.id)}\n {@const mismatch = hasContractMismatch(pkg)}\n {@const installing = installingIds.has(pkg.entry.id)}\n {@const updatable = hasUpdate(pkg.entry.id)}\n {@const updating = updatingIds.has(pkg.entry.id)}\n {@const missing = missingShards(pkg, ctx.state.ephemeral.installed)}\n {@const displayType = displayPackageType(pkg.entry.type)}\n <div class=\"store-card\">\n <div class=\"store-card-header\">\n <div class=\"store-card-icon\">\n {#if pkg.entry.icon}\n <img src={pkg.entry.icon} alt=\"\" class=\"store-icon-img\" />\n {:else}\n <span class=\"store-icon-placeholder\">\n {pkg.entry.type === 'shard' ? 'S' : 'A'}\n </span>\n {/if}\n </div>\n <div class=\"store-card-title\">\n <span class=\"store-card-label\">{pkg.entry.label}</span>\n <span\n class=\"store-card-badge\"\n class:badge-shard={displayType === 'shard'}\n class:badge-app={displayType === 'app'}\n >\n {displayPackageTypeLabel(pkg.entry.type)}\n </span>\n <span class=\"store-card-version\">{pkg.latest.version}</span>\n </div>\n </div>\n <p class=\"store-card-desc\">{pkg.entry.description}</p>\n <div class=\"store-card-author\">{pkg.entry.author.name}</div>\n {#if mismatch}\n <div class=\"store-card-warning\">\n Contract mismatch: package targets v{pkg.latest.contractVersion}, running v{contract.version}\n </div>\n {/if}\n <div class=\"store-card-actions\">\n {#if installed && updatable}\n <button\n class=\"store-update-btn\"\n onclick={() => handleUpdate(pkg.entry.id)}\n disabled={updating}\n >\n {updating ? 'Updating...' : `Update ${installedVersion(pkg.entry.id)} -> ${pkg.latest.version}`}\n </button>\n {:else if installed}\n <span class=\"store-installed-label\">Installed</span>\n {:else}\n <div class=\"store-install-wrap\">\n <button\n class=\"store-install-btn\"\n onclick={() => handleInstall(pkg)}\n disabled={installing || missing.length > 0}\n title={missing.length > 0 ? `Missing required shards: ${missing.join(', ')}` : undefined}\n >\n {installing ? 'Installing...' : 'Install'}\n </button>\n {#if missing.length > 0}\n <span class=\"store-card-missing\">requires: {missing.join(', ')}</span>\n {/if}\n </div>\n {/if}\n </div>\n </div>\n {/each}\n </div>\n\n {#if !ctx.state.ephemeral.loading && filtered.length === 0}\n <div class=\"store-empty\">\n {#if ctx.env.registries.length === 0}\n No packages found. {#if ctx.isAdmin}Add a registry URL above to get started.{:else}No registries configured.{/if}\n {:else}\n No packages match the current filter.\n {/if}\n </div>\n {/if}\n</div>\n\n{#if installModal}\n <PermissionConfirmModal\n mode=\"install\"\n pkg={{\n label: installModal.pkg.entry.label,\n version: installModal.pkg.latest.version,\n author: installModal.pkg.entry.author.name,\n }}\n permissions={installModal.permissions}\n onConfirm={confirmInstall}\n onCancel={cancelInstall}\n />\n{/if}\n\n{#if updateModal}\n <PermissionConfirmModal\n mode=\"update\"\n pkg={{\n label: updateModal.pkg.entry.label,\n version: updateModal.pkg.latest.version,\n author: updateModal.pkg.entry.author.name,\n }}\n fromVersion={updateModal.fromVersion}\n added={updateModal.added}\n removed={updateModal.removed}\n onConfirm={confirmUpdate}\n onCancel={cancelUpdate}\n />\n{/if}\n\n<style>\n .store-view {\n font-family: var(--shell-font-ui);\n color: var(--shell-fg, #e0e0e0);\n background: var(--shell-bg, #1e1e1e);\n padding: 16px;\n height: 100%;\n overflow-y: auto;\n box-sizing: border-box;\n }\n .store-header {\n margin-bottom: 16px;\n }\n .store-header h2 {\n margin: 0 0 8px 0;\n font-size: 1.25rem;\n font-weight: 600;\n }\n .store-controls {\n display: flex;\n gap: 8px;\n flex-wrap: wrap;\n }\n .store-search {\n flex: 1;\n min-width: 160px;\n padding: 6px 10px;\n background: var(--shell-input-bg, #2a2a2a);\n color: var(--shell-fg, #e0e0e0);\n border: 1px solid var(--shell-border, #444);\n border-radius: var(--shell-radius);\n font-family: inherit;\n font-size: 0.875rem;\n }\n .store-search::placeholder {\n color: var(--shell-fg-muted, #888);\n }\n .store-filter {\n padding: 6px 10px;\n background: var(--shell-input-bg, #2a2a2a);\n color: var(--shell-fg, #e0e0e0);\n border: 1px solid var(--shell-border, #444);\n border-radius: var(--shell-radius);\n font-family: inherit;\n font-size: 0.875rem;\n }\n .store-refresh:disabled {\n opacity: 0.6;\n cursor: not-allowed;\n }\n .store-error {\n padding: 8px 12px;\n margin-bottom: 12px;\n background: color-mix(in srgb, var(--shell-error, #d32f2f) 15%, transparent);\n color: var(--shell-error, #d32f2f);\n border: 1px solid var(--shell-error, #d32f2f);\n border-radius: var(--shell-radius);\n font-size: 0.8125rem;\n }\n .store-grid {\n display: grid;\n grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));\n gap: 12px;\n }\n .store-card {\n background: var(--shell-input-bg, #2a2a2a);\n border: 1px solid var(--shell-border, #444);\n border-radius: var(--shell-radius-md);\n padding: 14px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n }\n .store-card:hover {\n border-color: var(--shell-accent, #007acc);\n }\n .store-card-header {\n display: flex;\n align-items: center;\n gap: 10px;\n }\n .store-card-icon {\n width: 36px;\n height: 36px;\n flex-shrink: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .store-icon-img {\n width: 36px;\n height: 36px;\n border-radius: var(--shell-radius);\n object-fit: cover;\n }\n .store-icon-placeholder {\n width: 36px;\n height: 36px;\n display: flex;\n align-items: center;\n justify-content: center;\n background: var(--shell-accent, #007acc);\n color: #fff;\n border-radius: var(--shell-radius);\n font-weight: 700;\n font-size: 1rem;\n }\n .store-card-title {\n display: flex;\n align-items: center;\n gap: 6px;\n flex-wrap: wrap;\n }\n .store-card-label {\n font-weight: 600;\n font-size: 0.9375rem;\n }\n .store-card-badge {\n font-size: 0.6875rem;\n padding: 1px 6px;\n border-radius: var(--shell-radius-sm);\n text-transform: uppercase;\n font-weight: 600;\n letter-spacing: 0.04em;\n }\n .badge-shard {\n background: color-mix(in srgb, var(--shell-accent, #007acc) 25%, transparent);\n color: var(--shell-accent, #007acc);\n }\n .badge-app {\n background: color-mix(in srgb, var(--shell-success, #4caf50) 25%, transparent);\n color: var(--shell-success, #4caf50);\n }\n .store-card-version {\n font-size: 0.75rem;\n color: var(--shell-fg-muted, #888);\n }\n .store-card-desc {\n margin: 0;\n font-size: 0.8125rem;\n color: var(--shell-fg-muted, #888);\n line-height: 1.4;\n }\n .store-card-author {\n font-size: 0.75rem;\n color: var(--shell-fg-muted, #888);\n }\n .store-card-warning {\n font-size: 0.75rem;\n color: var(--shell-warning, #ff9800);\n padding: 4px 8px;\n background: color-mix(in srgb, var(--shell-warning, #ff9800) 10%, transparent);\n border-radius: var(--shell-radius-sm);\n }\n .store-card-actions {\n margin-top: auto;\n display: flex;\n justify-content: flex-end;\n }\n .store-install-btn {\n padding: 5px 14px;\n font-size: 0.8125rem;\n }\n .store-install-btn:disabled {\n opacity: 0.6;\n cursor: not-allowed;\n }\n .store-installed-label {\n font-size: 0.8125rem;\n color: var(--shell-success, #4caf50);\n font-weight: 600;\n }\n .store-install-wrap {\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n gap: 4px;\n }\n .store-card-missing {\n font-size: 0.75rem;\n color: var(--shell-warning, #ff9800);\n }\n .store-update-btn {\n padding: 5px 14px;\n background: var(--shell-warning, #fbbf24);\n color: var(--shell-fg-on-warning, #1a1b1e);\n font-size: 0.8125rem;\n }\n .store-update-btn:hover:not(:disabled) {\n filter: brightness(1.1);\n }\n .store-update-btn:disabled {\n opacity: 0.6;\n cursor: not-allowed;\n }\n .store-empty {\n text-align: center;\n padding: 32px 16px;\n color: var(--shell-fg-muted, #888);\n font-size: 0.875rem;\n }\n .store-registries {\n display: flex;\n flex-direction: column;\n gap: 4px;\n margin-bottom: 8px;\n }\n .store-registry-entry {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 4px 8px;\n background: var(--shell-input-bg, #2a2a2a);\n border: 1px solid var(--shell-border, #444);\n border-radius: var(--shell-radius);\n font-size: 0.8125rem;\n }\n .store-registry-url {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n color: var(--shell-fg-muted, #888);\n }\n .store-registry-remove {\n padding: 2px 8px;\n background: transparent;\n color: var(--shell-error, #d32f2f);\n border: 1px solid var(--shell-error, #d32f2f);\n border-radius: var(--shell-radius-sm);\n font-size: 0.75rem;\n flex-shrink: 0;\n margin-left: 8px;\n }\n .store-add-registry {\n display: flex;\n gap: 8px;\n margin-bottom: 12px;\n }\n .store-registry-input {\n flex: 1;\n padding: 6px 10px;\n background: var(--shell-input-bg, #2a2a2a);\n color: var(--shell-fg, #e0e0e0);\n border: 1px solid var(--shell-border, #444);\n border-radius: var(--shell-radius);\n font-family: inherit;\n font-size: 0.8125rem;\n }\n .store-registry-input::placeholder {\n color: var(--shell-fg-muted, #888);\n }\n .store-add-btn {\n font-size: 0.8125rem;\n white-space: nowrap;\n }\n .store-add-btn:disabled {\n opacity: 0.6;\n cursor: not-allowed;\n }\n</style>\n","/*\n * Store verbs — shell-accessible commands for the sh3-store shard.\n *\n * Registered during storeShard.activate() via ctx.registerVerb().\n * Auto-prefixed to sh3-store:install, sh3-store:uninstall, sh3-store:appinfo.\n */\n\nimport type { Verb, VerbContext } from '../../verbs/types';\nimport { storeContext } from './storeShard.svelte';\nimport { fetchBundle, fetchServerBundle, buildPackageMeta } from '../../registry/client';\nimport { installPackage } from '../../registry/installer';\nimport { serverInstallPackage } from '../../env/client';\nimport type { ResolvedPackage } from '../../registry/client';\nimport type { InstalledPackage } from '../../registry/types';\n\nfunction findInCatalog(id: string): ResolvedPackage | undefined {\n return storeContext.state.ephemeral.catalog.find(\n (p: ResolvedPackage) => p.entry.id === id,\n );\n}\n\nfunction findInstalled(id: string): InstalledPackage | undefined {\n return storeContext.state.ephemeral.installed.find(\n (p: InstalledPackage) => p.id === id,\n );\n}\n\nexport const installVerb: Verb = {\n name: 'install',\n summary: 'Install a package by id from the catalog.',\n async run(ctx: VerbContext, args: string[]) {\n const id = args[0];\n if (!id) {\n ctx.scrollback.push({\n kind: 'status',\n text: 'usage: sh3-store:install <package-id>',\n level: 'warn',\n ts: Date.now(),\n });\n return;\n }\n\n const existing = findInstalled(id);\n if (existing) {\n ctx.scrollback.push({\n kind: 'status',\n text: `${id} is already installed (v${existing.version})`,\n level: 'warn',\n ts: Date.now(),\n });\n return;\n }\n\n const pkg = findInCatalog(id);\n if (!pkg) {\n ctx.scrollback.push({\n kind: 'status',\n text: `package \"${id}\" not found in catalog — try refreshing the store`,\n level: 'error',\n ts: Date.now(),\n });\n return;\n }\n\n ctx.scrollback.push({\n kind: 'status',\n text: `installing ${id} v${pkg.latest.version}...`,\n level: 'info',\n ts: Date.now(),\n });\n\n try {\n const bundle = await fetchBundle(pkg.latest, pkg.sourceRegistry);\n const meta = buildPackageMeta(pkg, pkg.latest);\n\n let serverBundle: ArrayBuffer | undefined;\n if (pkg.latest.serverBundleUrl) {\n serverBundle = await fetchServerBundle(pkg.latest, pkg.sourceRegistry);\n }\n\n const manifest = {\n id: meta.id,\n type: meta.type,\n label: pkg.entry.label,\n version: meta.version,\n contractVersion: meta.contractVersion,\n sourceRegistry: meta.sourceRegistry,\n installedAt: new Date().toISOString(),\n requiredShards: pkg.latest.requires?.map((r) => r.id) ?? [],\n };\n\n const serverResult = await serverInstallPackage(manifest, bundle, serverBundle);\n if (!serverResult.ok) {\n let text = `install failed: ${serverResult.error ?? 'server error'}`;\n if (serverResult.code === 'missing-shards' && serverResult.missing) {\n const ids = serverResult.missing.map((m) => m.id).join(', ');\n text = `install failed: missing required shard(s): ${ids}`;\n }\n ctx.scrollback.push({\n kind: 'status',\n text,\n level: 'error',\n ts: Date.now(),\n });\n return;\n }\n\n const result = await installPackage(bundle, meta);\n if (!result.success) {\n ctx.scrollback.push({\n kind: 'status',\n text: `server ok but local hot-load failed: ${result.error}`,\n level: 'warn',\n ts: Date.now(),\n });\n }\n\n await storeContext.refreshInstalled();\n\n ctx.scrollback.push({\n kind: 'status',\n text: `installed ${id} v${pkg.latest.version}`,\n level: 'info',\n ts: Date.now(),\n });\n } catch (err) {\n ctx.scrollback.push({\n kind: 'status',\n text: `install failed: ${err instanceof Error ? err.message : String(err)}`,\n level: 'error',\n ts: Date.now(),\n });\n }\n },\n};\n\nexport const uninstallVerb: Verb = {\n name: 'uninstall',\n summary: 'Uninstall an installed package by id.',\n async run(ctx: VerbContext, args: string[]) {\n const id = args[0];\n if (!id) {\n ctx.scrollback.push({\n kind: 'status',\n text: 'usage: sh3-store:uninstall <package-id>',\n level: 'warn',\n ts: Date.now(),\n });\n return;\n }\n\n const existing = findInstalled(id);\n if (!existing) {\n ctx.scrollback.push({\n kind: 'status',\n text: `package \"${id}\" is not installed`,\n level: 'error',\n ts: Date.now(),\n });\n return;\n }\n\n ctx.scrollback.push({\n kind: 'status',\n text: `uninstalling ${id}...`,\n level: 'info',\n ts: Date.now(),\n });\n\n try {\n await storeContext.uninstallPackage(id);\n ctx.scrollback.push({\n kind: 'status',\n text: `uninstalled ${id}`,\n level: 'info',\n ts: Date.now(),\n });\n } catch (err) {\n ctx.scrollback.push({\n kind: 'status',\n text: `uninstall failed: ${err instanceof Error ? err.message : String(err)}`,\n level: 'error',\n ts: Date.now(),\n });\n }\n },\n};\n\nexport const updateVerb: Verb = {\n name: 'update',\n summary:\n 'Update an installed package (sh3-store:update <id> [version]). When ' +\n 'version is omitted, bumps to latest; with a version, installs that ' +\n 'exact version (downgrade or same-version reinstall allowed).',\n async run(ctx: VerbContext, args: string[]) {\n const id = args[0];\n const version = args[1];\n if (!id) {\n ctx.scrollback.push({\n kind: 'status',\n text: 'usage: sh3-store:update <package-id> [version]',\n level: 'warn',\n ts: Date.now(),\n });\n return;\n }\n\n const installed = findInstalled(id);\n if (!installed) {\n ctx.scrollback.push({\n kind: 'status',\n text: `package \"${id}\" is not installed`,\n level: 'error',\n ts: Date.now(),\n });\n return;\n }\n\n const fromVersion = installed.version;\n const action =\n version && version === fromVersion\n ? 'reinstalling'\n : version\n ? `updating ${id} from v${fromVersion} to v${version}`\n : `updating ${id} from v${fromVersion} to latest`;\n\n ctx.scrollback.push({\n kind: 'status',\n text: action.startsWith('reinstalling')\n ? `reinstalling ${id} v${version}…`\n : `${action}…`,\n level: 'info',\n ts: Date.now(),\n });\n\n // Verb path can't surface a modal. If the new bundle changes permissions,\n // auto-reject and tell the user to use the UI flow.\n const confirmReject = async (added: string[], removed: string[]) => {\n ctx.scrollback.push({\n kind: 'status',\n text:\n `permission change required (added: ${added.join(', ') || 'none'}; ` +\n `removed: ${removed.join(', ') || 'none'}) — open the store and use ` +\n `the Update button to review and apply.`,\n level: 'warn',\n ts: Date.now(),\n });\n return false;\n };\n\n try {\n await storeContext.updatePackage(id, confirmReject, version);\n const finalVersion = version ?? findInstalled(id)?.version ?? '?';\n ctx.scrollback.push({\n kind: 'status',\n text:\n version && version === fromVersion\n ? `reinstalled ${id} v${finalVersion}`\n : `updated ${id} v${finalVersion}`,\n level: 'info',\n ts: Date.now(),\n });\n } catch (err) {\n ctx.scrollback.push({\n kind: 'status',\n text: `update failed: ${err instanceof Error ? err.message : String(err)}`,\n level: 'error',\n ts: Date.now(),\n });\n }\n },\n};\n\nexport const appinfoVerb: Verb = {\n name: 'appinfo',\n summary: 'Show info about a package (installed status, version, catalog details).',\n async run(ctx: VerbContext, args: string[]) {\n const id = args[0];\n if (!id) {\n ctx.scrollback.push({\n kind: 'status',\n text: 'usage: sh3-store:appinfo <package-id>',\n level: 'warn',\n ts: Date.now(),\n });\n return;\n }\n\n const installed = findInstalled(id);\n const catalogEntry = findInCatalog(id);\n\n if (!installed && !catalogEntry) {\n ctx.scrollback.push({\n kind: 'status',\n text: `package \"${id}\" not found in catalog or installed list`,\n level: 'error',\n ts: Date.now(),\n });\n return;\n }\n\n const lines: string[] = [];\n lines.push(`--- ${id} ---`);\n\n if (installed) {\n lines.push(` installed: yes`);\n lines.push(` version: ${installed.version}`);\n lines.push(` type: ${installed.type}`);\n lines.push(` contract: v${installed.contractVersion}`);\n lines.push(` source: ${installed.sourceRegistry}`);\n if (installed.installedAt) {\n lines.push(` installed: ${installed.installedAt}`);\n }\n } else {\n lines.push(` installed: no`);\n }\n\n if (catalogEntry) {\n lines.push(` catalog: yes`);\n lines.push(` latest: ${catalogEntry.latest.version}`);\n lines.push(` label: ${catalogEntry.entry.label}`);\n lines.push(` author: ${catalogEntry.entry.author.name}`);\n lines.push(` desc: ${catalogEntry.entry.description}`);\n } else {\n lines.push(` catalog: no (not in any configured registry)`);\n }\n\n ctx.scrollback.push({\n kind: 'text',\n stream: 'stdout',\n chunks: [lines.join('\\n') + '\\n'],\n ts: Date.now(),\n });\n },\n};\n","/*\n * Store shard — framework-shipped shard for browsing and installing\n * packages.\n *\n * Contributes a single view:\n * - `sh3-store:browse` — searchable/filterable catalog of available packages\n *\n * Uninstall and update flows for already-installed packages live on the\n * shell home card's context menu (see `sh3core-shard/appActions.ts`); this\n * shard exposes the underlying operations as verbs (`installVerb`,\n * `uninstallVerb`, `updateVerb`, `appinfoVerb`) and via `storeContext`.\n *\n * Uses env state for registries (server-authoritative, admin-writable) and\n * an ephemeral zone for the live catalog / installed list / loading / error state.\n *\n * `.svelte.ts` because mounting Svelte components requires rune access.\n */\n\nimport { mount, unmount } from 'svelte';\nimport StoreView from './StoreView.svelte';\nimport { fetchRegistries, fetchBundle, fetchServerBundle, buildPackageMeta } from '../../registry/client';\nimport { installPackage, listInstalledPackages } from '../../registry/installer';\nimport { uninstallPackage as installerUninstallPackage } from '../../registry/installer';\nimport { loadBundle, loadMeta, savePackage } from '../../registry/storage';\nimport { loadBundleModule, type LoadedBundle } from '../../registry/loader';\nimport { extractBundlePermissions } from '../../registry/permission-descriptions';\nimport { serverInstallPackage, fetchServerPackages, serverUninstallPackage } from '../../env/client';\nimport { VERSION } from '../../version';\nimport { installVerb, uninstallVerb, appinfoVerb, updateVerb } from './verbs';\nimport type { Shard, ViewFactory, ViewHandle, MountContext, ShardContext } from '../../shards/types';\nimport type { StateZones } from '../../state/zones.svelte';\nimport type { ResolvedPackage } from '../../registry/client';\nimport type { InstalledPackage } from '../../registry/types';\nimport type { EnvState } from '../../env/types';\n\n/**\n * Compare two semver-like version strings.\n * Returns true only if `available` is strictly greater than `installed`.\n * Compares major.minor.patch left-to-right as integers.\n * Non-numeric segments are treated as 0.\n */\nfunction isNewerVersion(available: string, installed: string): boolean {\n const a = available.split('.').map((s) => parseInt(s, 10) || 0);\n const b = installed.split('.').map((s) => parseInt(s, 10) || 0);\n const len = Math.max(a.length, b.length);\n for (let i = 0; i < len; i++) {\n const av = a[i] ?? 0;\n const bv = b[i] ?? 0;\n if (av > bv) return true;\n if (av < bv) return false;\n }\n return false;\n}\n\n/**\n * Pick a version entry from a resolved package. When `requested` is\n * undefined returns `latest`; when set, finds the matching entry by\n * exact version string. Throws if the requested version is absent.\n */\nexport function pickVersion(\n pkg: ResolvedPackage,\n requested: string | undefined,\n): typeof pkg.latest {\n if (requested === undefined) return pkg.latest;\n const found = pkg.entry.versions.find((v) => v.version === requested);\n if (!found) {\n throw new Error(`version ${requested} not in catalog for ${pkg.entry.id}`);\n }\n return found;\n}\n\n/**\n * Compute added and removed permissions between two manifest snapshots.\n * Order within each array follows the input order of `newPerms` (for added)\n * and `oldPerms` (for removed). No duplicates — both inputs assumed unique.\n */\nexport function diffPermissions(\n oldPerms: string[],\n newPerms: string[],\n): { added: string[]; removed: string[] } {\n const oldSet = new Set(oldPerms);\n const newSet = new Set(newPerms);\n return {\n added: newPerms.filter((p) => !oldSet.has(p)),\n removed: oldPerms.filter((p) => !newSet.has(p)),\n };\n}\n\n/** Env state shape — server-authoritative config. */\ninterface StoreEnvSchema {\n [key: string]: unknown;\n registries: string[];\n}\n\n/** Schema shape for state zone typing. */\ninterface StoreZoneSchema {\n ephemeral: {\n catalog: ResolvedPackage[];\n installed: InstalledPackage[];\n updatable: Record<string, ResolvedPackage>;\n loading: boolean;\n error: string | null;\n };\n}\n\n/** Reactive context exposed to the view components. */\nexport interface StoreContext {\n env: EnvState<StoreEnvSchema>;\n state: StateZones<StoreZoneSchema>;\n isAdmin: boolean;\n refreshCatalog(): Promise<void>;\n refreshInstalled(): Promise<void>;\n updatePackage(\n id: string,\n confirmPermissionChange?: (\n added: string[],\n removed: string[],\n ) => Promise<boolean>,\n version?: string,\n ): Promise<void>;\n uninstallPackage(id: string): Promise<void>;\n addRegistry(url: string): Promise<void>;\n removeRegistry(url: string): Promise<void>;\n}\n\n/**\n * Module-level context set during activate(). Imported by the Svelte\n * view components so they can read/write store state and trigger refreshes.\n */\nexport let storeContext: StoreContext = undefined!;\n\nexport const storeShard: Shard = {\n manifest: {\n id: 'sh3-store',\n label: 'Package Store',\n version: VERSION,\n views: [\n { id: 'sh3-store:browse', label: 'Store' },\n ],\n },\n\n activate(ctx: ShardContext) {\n const env = ctx.env<StoreEnvSchema>({ registries: [] });\n\n const state = ctx.state<StoreZoneSchema>({\n ephemeral: {\n catalog: [] as ResolvedPackage[],\n installed: [] as InstalledPackage[],\n updatable: {} as Record<string, ResolvedPackage>,\n loading: false,\n error: null as string | null,\n },\n });\n\n function recomputeUpdatable(): void {\n const result: Record<string, ResolvedPackage> = {};\n for (const pkg of state.ephemeral.installed) {\n const catalogEntry = state.ephemeral.catalog.find(\n (c: ResolvedPackage) => c.entry.id === pkg.id,\n );\n if (catalogEntry && isNewerVersion(catalogEntry.latest.version, pkg.version)) {\n result[pkg.id] = catalogEntry;\n }\n }\n state.ephemeral.updatable = result;\n }\n\n async function refreshCatalog(): Promise<void> {\n state.ephemeral.loading = true;\n state.ephemeral.error = null;\n try {\n const results = await fetchRegistries(env.registries);\n state.ephemeral.catalog = results;\n recomputeUpdatable();\n } catch (err) {\n state.ephemeral.error =\n err instanceof Error ? err.message : String(err);\n } finally {\n state.ephemeral.loading = false;\n }\n }\n\n async function refreshInstalled(): Promise<void> {\n try {\n const serverPkgs = await fetchServerPackages();\n state.ephemeral.installed = serverPkgs.map((p) => ({\n id: p.id,\n type: p.type as 'shard' | 'app' | 'combo',\n version: p.version,\n sourceRegistry: p.sourceRegistry ?? '',\n contractVersion: p.contractVersion ?? '',\n installedAt: p.installedAt ?? '',\n permissions: [],\n }));\n recomputeUpdatable();\n } catch (err) {\n console.warn(\n '[sh3-store] Failed to list installed packages:',\n err instanceof Error ? err.message : err,\n );\n // Fall back to local list.\n try {\n const packages = await listInstalledPackages();\n state.ephemeral.installed = packages;\n recomputeUpdatable();\n } catch {\n // Nothing to show.\n }\n }\n }\n\n async function addRegistry(url: string): Promise<void> {\n const registries = [...env.registries];\n if (registries.includes(url)) return;\n registries.push(url);\n await ctx.envUpdate<StoreEnvSchema>({ registries });\n }\n\n async function removeRegistry(url: string): Promise<void> {\n const registries = env.registries.filter((r: string) => r !== url);\n await ctx.envUpdate<StoreEnvSchema>({ registries });\n }\n\n async function updatePackage(\n id: string,\n confirmPermissionChange?: (\n added: string[],\n removed: string[],\n ) => Promise<boolean>,\n version?: string,\n ): Promise<void> {\n // Source the catalog entry. Without an explicit version we use the\n // updatable map (which encodes the \"newer than installed\" check); with a\n // version we look up the package in the full catalog so downgrades and\n // same-version reinstalls work.\n let catalogEntry: ResolvedPackage | undefined;\n if (version === undefined) {\n catalogEntry = state.ephemeral.updatable[id];\n } else {\n catalogEntry = state.ephemeral.catalog.find((p) => p.entry.id === id);\n }\n if (!catalogEntry) return;\n\n const installedRecord = state.ephemeral.installed.find(\n (p: InstalledPackage) => p.id === id,\n );\n if (!installedRecord) return;\n\n const picked = pickVersion(catalogEntry, version);\n\n // 1. Fetch new bundle(s).\n const bundle = await fetchBundle(picked, catalogEntry.sourceRegistry);\n let serverBundle: ArrayBuffer | undefined;\n if (picked.serverBundleUrl) {\n serverBundle = await fetchServerBundle(picked, catalogEntry.sourceRegistry);\n }\n const meta = buildPackageMeta(catalogEntry, picked);\n\n // 2. Load the module once for permission extraction and install reuse.\n const loaded: LoadedBundle = await loadBundleModule(bundle);\n const newPerms = extractBundlePermissions(loaded);\n\n // 3. Look up the locally persisted old permissions (server-sourced\n // installed list doesn't carry permissions — per spec they live\n // in the local IndexedDB record).\n let oldPerms: string[] = [];\n try {\n const localMeta = await loadMeta(id);\n if (localMeta?.permissions) oldPerms = localMeta.permissions;\n } catch {\n // No local record (e.g. installed on a different browser); treat as\n // empty. The diff will show all new permissions as additions.\n }\n\n // 4. If the permission set changed and a confirmation callback was\n // provided, await the user's decision before touching the server.\n const { added, removed } = diffPermissions(oldPerms, newPerms);\n if ((added.length > 0 || removed.length > 0) && confirmPermissionChange) {\n const ok = await confirmPermissionChange(added, removed);\n if (!ok) return;\n }\n\n // 5. Snapshot current state for rollback. Preserve the locally-known\n // permissions so the rollback write still satisfies the InstalledPackage\n // contract (installedRecord came from the server-sourced list which\n // lacks permissions).\n const oldBundle = await loadBundle(id);\n const oldRecord: InstalledPackage = {\n ...installedRecord,\n permissions: oldPerms,\n };\n\n // 6. Push to server.\n const manifest = {\n id: meta.id,\n type: meta.type,\n label: catalogEntry.entry.label,\n version: meta.version,\n contractVersion: meta.contractVersion,\n sourceRegistry: meta.sourceRegistry,\n installedAt: new Date().toISOString(),\n requiredShards: picked.requires?.map((r) => r.id) ?? [],\n };\n\n const serverResult = await serverInstallPackage(manifest, bundle, serverBundle);\n if (!serverResult.ok) {\n let message = serverResult.error ?? 'Server update failed';\n if (serverResult.code === 'missing-shards' && serverResult.missing) {\n const ids = serverResult.missing.map((m) => m.id).join(', ');\n message = `missing required shard(s): ${ids}`;\n }\n throw new Error(message);\n }\n\n // 7. Install locally (overwrites IndexedDB + re-registers). Reuse the\n // already-loaded bundle so the ESM is not evaluated twice.\n const result = await installPackage(bundle, meta, { loaded });\n if (!result.success) {\n // Rollback: restore old bundle and metadata.\n if (oldBundle) {\n try {\n await savePackage(id, oldBundle, oldRecord);\n } catch (rollbackErr) {\n console.warn(\n `[sh3-store] Rollback failed for \"${id}\":`,\n rollbackErr instanceof Error ? rollbackErr.message : rollbackErr,\n );\n }\n }\n throw new Error(result.error ?? 'Local install failed during update');\n }\n\n await refreshInstalled();\n }\n\n async function uninstallPackage(id: string): Promise<void> {\n await serverUninstallPackage(id);\n await installerUninstallPackage(id);\n await refreshInstalled();\n }\n\n storeContext = {\n env,\n state,\n get isAdmin() { return ctx.isAdmin; },\n refreshCatalog,\n refreshInstalled,\n updatePackage,\n uninstallPackage,\n addRegistry,\n removeRegistry,\n };\n\n // --- View factories ---\n\n const browseFactory: ViewFactory = {\n mount(container: HTMLElement, _context: MountContext): ViewHandle {\n const instance = mount(StoreView, { target: container });\n return {\n unmount() {\n unmount(instance);\n },\n };\n },\n };\n\n ctx.registerView('sh3-store:browse', browseFactory);\n\n // Store verbs — registered as sh3-store:install, sh3-store:uninstall, sh3-store:appinfo\n ctx.registerVerb(installVerb);\n ctx.registerVerb(uninstallVerb);\n ctx.registerVerb(appinfoVerb);\n ctx.registerVerb(updateVerb);\n\n // refreshInstalled can run immediately (hits server, no env needed).\n refreshInstalled();\n },\n\n autostart() {\n // Runs after env hydration, so registries are populated.\n storeContext.refreshCatalog();\n },\n};\n","/*\n * Shared permission-diff confirmation flow for the `update` path. Opens\n * PermissionConfirmModal via modalManager and resolves to the user's choice.\n * Used by the home-card \"Check for updates\" context-menu action.\n */\n\nimport { modalManager } from '../../overlays/modal';\nimport PermissionConfirmModal from './PermissionConfirmModal.svelte';\n\nexport function openPermissionConfirmModal(\n pkg: { label: string; version: string },\n toVersion: string,\n added: string[],\n removed: string[],\n): Promise<boolean> {\n return new Promise((resolve) => {\n const props = {\n mode: 'update' as const,\n pkg: { label: pkg.label, version: toVersion },\n fromVersion: pkg.version,\n added,\n removed,\n onConfirm: () => {\n handle.close();\n resolve(true);\n },\n onCancel: () => {\n handle.close();\n resolve(false);\n },\n };\n const handle = modalManager.open<typeof props>(\n PermissionConfirmModal as never,\n props,\n );\n });\n}\n","<script lang=\"ts\">\n /*\n * Confirms an available update for an app launched via the home-card\n * \"Check for updates\" action. If the user clicks Update, onConfirm runs\n * (which performs the actual storeContext.updatePackage call); the\n * permission-diff prompt — when needed — is opened by updatePackage's\n * own confirmPermissionChange callback. Cancel just closes.\n */\n\n interface Props {\n appId: string;\n appLabel: string;\n fromVersion: string;\n toVersion: string;\n onConfirm: () => Promise<void>;\n close: () => void;\n }\n\n let { appId, appLabel, fromVersion, toVersion, onConfirm, close }: Props = $props();\n let busy = $state(false);\n let error = $state<string | null>(null);\n\n async function confirm() {\n if (busy) return;\n busy = true;\n error = null;\n try {\n await onConfirm();\n close();\n } catch (e) {\n error = (e as Error).message;\n } finally {\n busy = false;\n }\n }\n</script>\n\n<div class=\"app-update-modal\">\n <h2>Update available</h2>\n <p>\n <strong>{appLabel}</strong> can be updated from <code>v{fromVersion}</code>\n to <code>v{toVersion}</code>.\n </p>\n <p class=\"hint\">Package id: <code>{appId}</code></p>\n {#if error}<p class=\"error\">{error}</p>{/if}\n <div class=\"actions\">\n <button type=\"button\" class=\"primary\" onclick={confirm} disabled={busy}>\n {busy ? 'Updating…' : 'Update'}\n </button>\n <button type=\"button\" onclick={close} disabled={busy}>Cancel</button>\n </div>\n</div>\n\n<style>\n .app-update-modal {\n padding: 16px 20px;\n max-width: 460px;\n color: var(--shell-fg);\n background: var(--shell-bg);\n font: inherit;\n }\n h2 { margin: 0 0 8px; font-size: 16px; }\n p { margin: 4px 0; font-size: 13px; }\n .hint { color: var(--shell-fg-muted); font-size: 12px; }\n .error { color: var(--shell-error, #c33); }\n code {\n font-family: var(--shell-font-mono, monospace);\n background: var(--shell-bg-elevated);\n padding: 0 4px;\n border-radius: var(--shell-radius-sm, 3px);\n }\n .actions { display: flex; gap: 8px; margin-top: 16px; }\n .actions button {\n background: var(--shell-bg-elevated);\n color: var(--shell-fg);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-sm, 3px);\n padding: 6px 14px; font: inherit; cursor: pointer;\n }\n .actions button.primary {\n background: var(--shell-accent);\n color: #fff;\n border-color: var(--shell-accent);\n }\n .actions button:hover { border-color: var(--shell-accent); }\n .actions button:disabled { opacity: 0.5; cursor: not-allowed; }\n</style>\n","<script lang=\"ts\">\n /*\n * Confirms uninstall of an installed app launched from the home-card\n * Uninstall action. Modeled on DeleteProjectDialog. The actual uninstall\n * (server + local installer) is delegated to the caller via onConfirm.\n */\n\n interface Props {\n appId: string;\n appLabel: string;\n version: string;\n onConfirm: () => Promise<void>;\n close: () => void;\n }\n\n let { appId, appLabel, version, onConfirm, close }: Props = $props();\n let busy = $state(false);\n let error = $state<string | null>(null);\n\n async function confirm() {\n if (busy) return;\n busy = true;\n error = null;\n try {\n await onConfirm();\n close();\n } catch (e) {\n error = (e as Error).message;\n } finally {\n busy = false;\n }\n }\n</script>\n\n<div class=\"uninstall-dialog\">\n <h2>Uninstall {appLabel}?</h2>\n <p class=\"hint\">\n Package id: <code>{appId}</code> · current version: <code>v{version}</code>\n </p>\n <p>\n The package will be removed from this server. App data stored in your\n browser will remain until you clear it manually.\n </p>\n {#if error}<p class=\"error\">{error}</p>{/if}\n <div class=\"actions\">\n <button type=\"button\" class=\"danger\" onclick={confirm} disabled={busy}>\n {busy ? 'Uninstalling…' : 'Uninstall'}\n </button>\n <button type=\"button\" onclick={close} disabled={busy}>Cancel</button>\n </div>\n</div>\n\n<style>\n .uninstall-dialog {\n padding: 16px 20px;\n max-width: 460px;\n color: var(--shell-fg);\n background: var(--shell-bg);\n font: inherit;\n }\n h2 { margin: 0 0 8px; font-size: 16px; }\n p { margin: 4px 0; font-size: 13px; }\n .hint { color: var(--shell-fg-muted); font-size: 12px; }\n .error { color: var(--shell-error, #c33); }\n code {\n font-family: var(--shell-font-mono, monospace);\n background: var(--shell-bg-elevated);\n padding: 0 4px;\n border-radius: var(--shell-radius-sm, 3px);\n }\n .actions { display: flex; gap: 8px; margin-top: 16px; }\n .actions button {\n background: var(--shell-bg-elevated);\n color: var(--shell-fg);\n border: 1px solid var(--shell-border);\n border-radius: var(--shell-radius-sm, 3px);\n padding: 6px 14px; font: inherit; cursor: pointer;\n }\n .actions button.danger {\n background: var(--shell-error, #c33);\n color: #fff;\n border-color: var(--shell-error, #c33);\n }\n .actions button:hover { border-color: var(--shell-accent); }\n .actions button:disabled { opacity: 0.5; cursor: not-allowed; }\n</style>\n","/*\n * Element-scope actions for app cards. Wired by sh3coreShard.activate.\n * The element scope is { element: 'app' } and activates when right-click\n * on a host with data-sh3-scope=\"element:app\" sets a selection of type\n * 'app' (see ShellHome.svelte).\n *\n * Three actions are registered here:\n * - app.info : info-only row showing \"<id> v<version>\" (always disabled).\n * - app.checkUpdate : refresh catalog, then prompt update or toast up-to-date.\n * - app.uninstall : open uninstall confirm dialog.\n *\n * The fourth menu item (app.customize) is registered by the app-appearance\n * shard so its lifecycle is bound to that shard's activate/deactivate.\n *\n * Disabled predicate: !isAdmin || isBuiltin. Built-in means the app id is\n * NOT in storeContext.state.ephemeral.installed (those are framework-shipped\n * shards like sh3-store, sh3-shell, projects, etc.).\n */\n\nimport { listRegisteredApps } from '../api';\nimport { isAdmin } from '../auth/auth.svelte';\nimport { getSelection } from '../actions/selection.svelte';\nimport { storeContext } from '../app/store/storeShard.svelte';\nimport { openPermissionConfirmModal } from '../app/store/permissionConfirm';\nimport { modalManager } from '../overlays/modal';\nimport { toastManager } from '../overlays/toast';\nimport AppUpdateAvailableModal from '../app/store/AppUpdateAvailableModal.svelte';\nimport UninstallAppDialog from '../app/store/UninstallAppDialog.svelte';\nimport type { ShardContext } from '../shards/types';\nimport type { Action, ActionDispatchContext } from '../actions/types';\nimport type { InstalledPackage } from '../registry/types';\n\nexport interface AppActionGate {\n admin: boolean;\n builtin: boolean;\n}\n\nexport function computeAppActionDisabled(g: AppActionGate): boolean {\n return !g.admin || g.builtin;\n}\n\nexport function computeAppActionLabelSuffix(g: AppActionGate): string {\n if (!g.admin) return ' · admin only';\n if (g.builtin) return ' · built-in';\n return '';\n}\n\ninterface AppSelectionRef { appId: string; }\n\nfunction readSelection(): AppSelectionRef | null {\n const sel = getSelection();\n if (!sel || sel.type !== 'app') return null;\n return sel.ref as AppSelectionRef;\n}\n\nfunction findApp(appId: string) {\n return listRegisteredApps().find((m) => m.id === appId);\n}\n\nfunction isBuiltin(appId: string): boolean {\n return !storeContext.state.ephemeral.installed.some(\n (p: InstalledPackage) => p.id === appId,\n );\n}\n\nfunction gateFor(appId: string): AppActionGate {\n return { admin: isAdmin(), builtin: isBuiltin(appId) };\n}\n\nasync function runCheckUpdate(_ctx: ActionDispatchContext) {\n const ref = readSelection();\n if (!ref) return;\n const { appId } = ref;\n const checking = toastManager.notify('Checking for updates…', { duration: Infinity });\n try {\n await storeContext.refreshCatalog();\n } finally {\n checking.close();\n }\n const entry = storeContext.state.ephemeral.updatable[appId];\n const installed = storeContext.state.ephemeral.installed.find(\n (p: InstalledPackage) => p.id === appId,\n );\n const label = findApp(appId)?.label ?? appId;\n\n if (!entry || !installed) {\n toastManager.notify(`${label} is up to date`, { level: 'info', duration: 2500 });\n return;\n }\n\n const props = {\n appId,\n appLabel: label,\n fromVersion: installed.version,\n toVersion: entry.latest.version,\n onConfirm: async () => {\n try {\n await storeContext.updatePackage(appId, (added, removed) =>\n openPermissionConfirmModal(\n { label: installed.id, version: installed.version },\n entry.latest.version,\n added,\n removed,\n ),\n );\n toastManager.notify(`Updated to v${entry.latest.version}`, { level: 'success' });\n } catch (e) {\n toastManager.notify(\n `Update failed: ${(e as Error).message}`,\n { level: 'error', duration: 5000 },\n );\n throw e;\n }\n },\n };\n modalManager.open<typeof props>(AppUpdateAvailableModal as never, props);\n}\n\nfunction runUninstall(_ctx: ActionDispatchContext) {\n const ref = readSelection();\n if (!ref) return;\n const { appId } = ref;\n const installed = storeContext.state.ephemeral.installed.find(\n (p: InstalledPackage) => p.id === appId,\n );\n if (!installed) return;\n const label = findApp(appId)?.label ?? appId;\n\n const props = {\n appId,\n appLabel: label,\n version: installed.version,\n onConfirm: async () => {\n try {\n await storeContext.uninstallPackage(appId);\n toastManager.notify(`Uninstalled ${label}`, { level: 'success' });\n } catch (e) {\n toastManager.notify(\n `Uninstall failed: ${(e as Error).message}`,\n { level: 'error', duration: 5000 },\n );\n throw e;\n }\n },\n };\n modalManager.open<typeof props>(UninstallAppDialog as never, props);\n}\n\n/**\n * Register the three element-scope app actions on the given shard context.\n * Returns a disposer that unregisters all three (the framework expects the\n * shard's activate to keep the disposers alive across deactivate).\n */\nexport function registerAppActions(ctx: ShardContext): () => void {\n const infoLabel = (): string => {\n const ref = readSelection();\n if (!ref) return '';\n const m = findApp(ref.appId);\n if (!m) return ref.appId;\n return `${m.id} v${m.version}`;\n };\n\n const updateLabel = (): string => {\n const ref = readSelection();\n if (!ref) return 'Check for updates';\n return `Check for updates${computeAppActionLabelSuffix(gateFor(ref.appId))}`;\n };\n\n const uninstallLabel = (): string => {\n const ref = readSelection();\n if (!ref) return 'Uninstall…';\n return `Uninstall…${computeAppActionLabelSuffix(gateFor(ref.appId))}`;\n };\n\n const isDisabledForCurrent = (): boolean => {\n const ref = readSelection();\n if (!ref) return true;\n return computeAppActionDisabled(gateFor(ref.appId));\n };\n\n const actions: Action[] = [\n {\n id: 'app.info',\n label: infoLabel,\n scope: { element: 'app' },\n contextItem: true,\n group: 'info',\n disabled: true,\n },\n {\n id: 'app.checkUpdate',\n label: updateLabel,\n scope: { element: 'app' },\n contextItem: true,\n group: 'update',\n disabled: isDisabledForCurrent,\n run: runCheckUpdate,\n },\n {\n id: 'app.uninstall',\n label: uninstallLabel,\n scope: { element: 'app' },\n contextItem: true,\n group: 'uninstall',\n disabled: isDisabledForCurrent,\n run: runUninstall,\n },\n ];\n\n const disposers = actions.map((a) => ctx.actions.register(a));\n return () => disposers.forEach((d) => d());\n}\n","/*\n * SH3-core pseudo-shard — the framework-owned shard with reserved id\n * `__sh3core__`. Contributes exactly one view, `sh3core:home`, which the\n * layout manager's home tree references.\n *\n * Renamed from the former `__shell__` pseudo-shard on 2026-04-10 to free\n * the `shell` id and the `src/shell-shard/` directory for the new\n * user-facing shell-shard (terminal). See\n * `docs/superpowers/specs/2026-04-10-shell-shard-design.md` § Step 0.\n *\n * This shard uses the public contract same as any other shard (see\n * ADR-008 / the phase-8 shell-as-shard feasibility check). Its only\n * concession to being framework-owned is:\n * - The reserved id `__sh3core__`\n * - It is registered by `bootstrap()` itself, not by the glob loop\n *\n * Activation goes through the same `registerShard` / `activateShard`\n * pipeline as mock and diagnostic. `autostart` is a no-op, defined only\n * so activation is driven by the self-starting pass in bootstrap rather\n * than by requiring a special code path.\n *\n * `.svelte.ts` because mounting Svelte components requires rune access.\n */\n\nimport { mount, unmount } from 'svelte';\nimport ShellHome from './ShellHome.svelte';\nimport KeysAndPeers from '../shell/views/KeysAndPeers.svelte';\nimport ConfirmDialog from '../overlays/ConfirmDialog.svelte';\nimport type { Shard, ViewFactory, ViewHandle, MountContext } from '../api';\nimport { VERSION } from '../version';\nimport { __setBindingsZone } from '../actions/bindings-store';\nimport { registeredApps } from '../apps/registry.svelte';\nimport { launchApp } from '../apps/lifecycle';\nimport { resetActivePresetToDefault } from '../layout/store.svelte';\nimport { modalManager } from '../overlays/modal';\nimport { registerAppActions } from './appActions';\n\nexport const sh3coreShard: Shard = {\n manifest: {\n id: '__sh3core__',\n label: 'SH3 Core',\n version: VERSION,\n views: [\n { id: 'sh3core:home', label: 'Home' },\n { id: 'shell:keys-and-peers', label: 'Keys & Peers' },\n ],\n },\n activate(ctx) {\n const zones = ctx.state({\n user: {\n bindings: {} as Record<string, Record<string, string | null>>,\n },\n });\n __setBindingsZone(zones.user);\n\n ctx.actions.register({\n id: 'sh3.palette.open',\n label: 'Command Palette…',\n scope: ['home', 'app'],\n defaultShortcut: 'Mod+K',\n contextItem: false,\n paletteItem: false,\n run(_dispatchCtx) {\n // Lazy import to avoid circular module load at boot.\n import('../actions/listeners').then(({ openPalette }) => openPalette());\n },\n });\n\n ctx.actions.register({\n id: 'sh3.app.reset-layout',\n label: 'Reset Current Layout',\n scope: ['app'],\n paletteItem: true,\n contextItem: false,\n run() {\n modalManager.open(ConfirmDialog, {\n title: 'Reset layout?',\n body:\n 'This discards the current arrangement of the active preset and ' +\n 'rebuilds it from the app default. Floats will be removed.',\n confirmLabel: 'Reset',\n confirmTone: 'danger' as const,\n onConfirm: () => resetActivePresetToDefault(),\n });\n },\n });\n\n const factory: ViewFactory = {\n mount(container: HTMLElement, _context: MountContext): ViewHandle {\n const instance = mount(ShellHome, { target: container });\n return {\n unmount() {\n unmount(instance);\n },\n // Home does not need onResize — it uses absolute inset:0 layout.\n };\n },\n };\n\n const keysFactory: ViewFactory = {\n mount(container: HTMLElement, _context: MountContext): ViewHandle {\n const instance = mount(KeysAndPeers, { target: container });\n return { unmount() { unmount(instance); } };\n },\n };\n\n ctx.registerView('sh3core:home', factory);\n ctx.registerView('shell:keys-and-peers', keysFactory);\n\n registerAppActions(ctx);\n\n // Launcher parent — submenu drill host. No `run` needed: the\n // dispatcher's default behavior opens a sub-palette filtered to\n // `submenuOf === 'sh3.app.launch'`. The single parent replaces the\n // per-app palette entries that used to flood the idle palette.\n ctx.actions.register({\n id: 'sh3.app.launch',\n label: 'Launch app',\n scope: ['home', 'app'],\n submenu: true,\n paletteItem: true,\n });\n\n // Dynamic launcher children: one per registered app, kept in sync\n // as packages install/uninstall via the registry. Children inherit\n // the parent's surface placement, so they don't set paletteItem\n // themselves. Direct text match (e.g. typing the app name) still\n // surfaces them at the root palette via the scorer.\n const launcherUnregisters = new Map<string, () => void>();\n $effect.root(() => {\n $effect(() => {\n const currentIds = new Set<string>();\n for (const [id, app] of registeredApps) {\n currentIds.add(id);\n if (launcherUnregisters.has(id)) continue;\n const off = ctx.actions.register({\n id: `sh3.app.launch:${id}`,\n label: app.manifest.label,\n scope: ['home', 'app'],\n submenuOf: 'sh3.app.launch',\n run() {\n void launchApp(id);\n },\n });\n launcherUnregisters.set(id, off);\n }\n for (const id of [...launcherUnregisters.keys()]) {\n if (!currentIds.has(id)) {\n launcherUnregisters.get(id)!();\n launcherUnregisters.delete(id);\n }\n }\n });\n });\n },\n autostart() {\n // Intentionally empty. Defining this field is what puts the sh3core\n // pseudo-shard on the self-starting path at boot (see bootstrap),\n // so `sh3core:home` is available before any app launches.\n },\n};\n","import type { ShardManifest } from '../api';\nimport { VERSION } from '../version';\n\nexport const manifest: ShardManifest = {\n id: 'shell',\n label: 'Shell',\n version: VERSION,\n views: [{ id: 'shell:terminal', label: 'Shell', standalone: true }],\n // serverBundle intentionally omitted — this shard is a framework built-in\n // and is statically mounted at sh3-server boot. The existing contract in\n // sh3-core/src/shards/types.ts documents that framework-shipped shards do\n // not use this field.\n permissions: [],\n};\n","/*\n * Scrollback store for a single shell.terminal view instance.\n *\n * One instance per view mount. Holds ScrollbackEntry[], supports:\n * - push(entry): append or coalesce with the previous entry if both\n * are text entries with the same stream.\n * - clear(): wipe all entries (local only — does not affect other\n * attached views).\n * - cap at a per-view limit (default 2000) — oldest trimmed.\n *\n * Uses Svelte 5 runes. The backing array is $state() so consumers just\n * read .entries and reactivity Just Works™.\n */\n\nimport type { Component } from 'svelte';\n\n// Rich entries hold a Svelte component plus an untyped props bag. The caller\n// (a verb) is responsible for keeping the component and its props in sync.\n// Component<any> acknowledges that looseness at one site so verbs don't each\n// need to cast their concrete components at push time.\nexport type RichComponent = Component<any>;\n\nexport type ScrollbackEntry =\n | { kind: 'prompt'; id: string; cwd: string; line: string; ts: number }\n | { kind: 'text'; id: string; stream: 'stdout' | 'stderr'; chunks: string[]; ts: number }\n | { kind: 'rich'; id: string; component: RichComponent; props: Record<string, unknown>; ts: number }\n | { kind: 'status'; id: string; text: string; level: 'info' | 'warn' | 'error'; ts: number };\n\n// Distributes Omit over a discriminated union so TS narrowing still works.\n// Plain `Omit<ScrollbackEntry, 'id'>` would collapse the union.\ntype DistributiveOmit<T, K extends keyof any> = T extends unknown ? Omit<T, K> : never;\n\nconst DEFAULT_CAP = 2000;\n\nlet nextId = 0;\nfunction mkId(): string {\n return `e${++nextId}`;\n}\n\nexport class Scrollback {\n entries = $state<ScrollbackEntry[]>([]);\n private readonly cap: number;\n\n constructor(cap: number = DEFAULT_CAP) {\n this.cap = cap;\n }\n\n push(entry: DistributiveOmit<ScrollbackEntry, 'id'>): void {\n // Coalesce consecutive text entries of the same stream\n const last = this.entries[this.entries.length - 1];\n if (\n last &&\n last.kind === 'text' &&\n entry.kind === 'text' &&\n last.stream === entry.stream\n ) {\n last.chunks.push(...entry.chunks);\n return;\n }\n\n const full = { ...entry, id: mkId() } as ScrollbackEntry;\n this.entries.push(full);\n\n if (this.entries.length > this.cap) {\n this.entries.splice(0, this.entries.length - this.cap);\n }\n }\n\n clear(): void {\n this.entries.length = 0;\n }\n}\n","<script lang=\"ts\">\n interface Props {\n stream: 'stdout' | 'stderr';\n chunks: string[];\n }\n let { stream, chunks }: Props = $props();\n\n // v1: strip ANSI escapes; render plain text. ANSI-to-HTML is deferred.\n const ANSI_RE = /\\x1b\\[[0-9;?]*[ -/]*[@-~]/g;\n const text = $derived(chunks.join('').replace(ANSI_RE, ''));\n</script>\n\n<pre class=\"shell-text\" class:stderr={stream === 'stderr'}>{text}</pre>\n\n<style>\n .shell-text {\n margin: 0;\n padding: 0 8px;\n font-family: var(--shell-font-mono, monospace);\n white-space: pre-wrap;\n word-break: break-word;\n color: var(--shell-fg, #ddd);\n }\n .shell-text.stderr { color: var(--shell-fg-error, #f88); }\n</style>\n","<script lang=\"ts\">\n interface Props {\n cwd: string;\n line: string;\n }\n let { cwd, line }: Props = $props();\n</script>\n\n<div class=\"shell-prompt\">\n <span class=\"shell-prompt-cwd\">{cwd}</span>\n <span class=\"shell-prompt-arrow\">❯</span>\n <span class=\"shell-prompt-line\">{line}</span>\n</div>\n\n<style>\n .shell-prompt {\n padding: 4px 8px 0 8px;\n font-family: var(--shell-font-mono, monospace);\n display: flex;\n gap: 8px;\n }\n .shell-prompt-cwd { color: var(--shell-fg-muted, #888); }\n .shell-prompt-arrow { color: var(--shell-accent, #6cf); }\n .shell-prompt-line { color: var(--shell-fg, #ddd); }\n</style>\n","<script lang=\"ts\">\n interface Props {\n text: string;\n level: 'info' | 'warn' | 'error';\n }\n let { text, level }: Props = $props();\n</script>\n\n<div class=\"shell-status\" class:info={level === 'info'} class:warn={level === 'warn'} class:error={level === 'error'}>\n {text}\n</div>\n\n<style>\n .shell-status {\n padding: 2px 8px;\n font-family: var(--shell-font-mono, monospace);\n font-style: italic;\n }\n .shell-status.info { color: var(--shell-fg-muted, #888); }\n .shell-status.warn { color: var(--shell-fg-warn, #fc6); }\n .shell-status.error { color: var(--shell-fg-error, #f88); }\n</style>\n","<script lang=\"ts\">\n import type { Component } from 'svelte';\n\n interface Props {\n component: Component;\n componentProps: Record<string, unknown>;\n }\n let { component: C, componentProps }: Props = $props();\n</script>\n\n<div class=\"shell-rich\">\n <C {...componentProps} />\n</div>\n\n<style>\n .shell-rich {\n padding: 4px 8px;\n }\n</style>\n","<script lang=\"ts\">\n import type { Scrollback } from './scrollback.svelte';\n import TextEntry from './entries/TextEntry.svelte';\n import PromptEntry from './entries/PromptEntry.svelte';\n import StatusEntry from './entries/StatusEntry.svelte';\n import RichEntry from './entries/RichEntry.svelte';\n\n interface Props {\n scrollback: Scrollback;\n }\n let { scrollback }: Props = $props();\n\n let container: HTMLDivElement | null = $state(null);\n\n // Auto-scroll to bottom on new entries\n $effect(() => {\n // Depend on entries length so the effect re-runs\n const _len = scrollback.entries.length;\n void _len;\n if (container) {\n container.scrollTop = container.scrollHeight;\n }\n });\n</script>\n\n<div class=\"shell-scrollback\" bind:this={container}>\n {#each scrollback.entries as entry (entry.id)}\n {#if entry.kind === 'text'}\n <TextEntry stream={entry.stream} chunks={entry.chunks} />\n {:else if entry.kind === 'prompt'}\n <PromptEntry cwd={entry.cwd} line={entry.line} />\n {:else if entry.kind === 'status'}\n <StatusEntry text={entry.text} level={entry.level} />\n {:else if entry.kind === 'rich'}\n <RichEntry component={entry.component} componentProps={entry.props} />\n {/if}\n {/each}\n</div>\n\n<style>\n .shell-scrollback {\n flex: 1 1 auto;\n overflow-y: auto;\n background: var(--shell-bg, #111);\n color: var(--shell-fg, #ddd);\n }\n</style>\n","<script lang=\"ts\">\n import type { SessionClient } from './session-client.svelte';\n\n interface Props {\n cwd: string;\n locked: boolean; // true while a process is running\n history: string[]; // persisted history, newest last\n session: SessionClient;\n onSubmit: (line: string) => void; // called with the raw entered line\n }\n let { cwd, locked, history, session, onSubmit }: Props = $props();\n\n let draft = $state('');\n let historyIndex = $state<number | null>(null); // null = live draft\n let savedDraft = $state(''); // restored when user returns from history\n\n let input: HTMLInputElement | null = $state(null);\n\n function submit() {\n if (locked) return;\n const line = draft;\n if (!line.trim()) return;\n draft = '';\n historyIndex = null;\n onSubmit(line);\n }\n\n function navHistoryUp() {\n if (history.length === 0) return;\n if (historyIndex === null) {\n savedDraft = draft;\n historyIndex = history.length - 1;\n } else if (historyIndex > 0) {\n historyIndex--;\n }\n draft = history[historyIndex] ?? '';\n }\n\n function navHistoryDown() {\n if (historyIndex === null) return;\n if (historyIndex < history.length - 1) {\n historyIndex++;\n draft = history[historyIndex];\n } else {\n historyIndex = null;\n draft = savedDraft;\n }\n }\n\n function onKeyDown(e: KeyboardEvent) {\n if (locked) {\n if (e.ctrlKey && e.key === 'c') {\n e.preventDefault();\n session.send({ t: 'signal', sig: 'SIGINT' });\n return;\n }\n if (e.ctrlKey && e.key === 'd') {\n e.preventDefault();\n session.send({ t: 'signal', sig: 'EOF' });\n return;\n }\n // Drop all other input while locked\n e.preventDefault();\n return;\n }\n\n if (e.key === 'Enter') {\n e.preventDefault();\n submit();\n } else if (e.key === 'ArrowUp') {\n e.preventDefault();\n navHistoryUp();\n } else if (e.key === 'ArrowDown') {\n e.preventDefault();\n navHistoryDown();\n } else if (e.ctrlKey && e.key === 'c') {\n e.preventDefault();\n draft = '';\n historyIndex = null;\n } else if (e.ctrlKey && e.key === 'l') {\n e.preventDefault();\n draft = 'clear';\n submit();\n }\n }\n\n // Re-focus the input when the locked state flips to false\n $effect(() => {\n if (!locked && input) {\n input.focus();\n }\n });\n</script>\n\n<div class=\"shell-input\" class:locked>\n <span class=\"shell-input-cwd\">{cwd}</span>\n <span class=\"shell-input-arrow\">❯</span>\n <input\n bind:this={input}\n bind:value={draft}\n type=\"text\"\n disabled={locked}\n onkeydown={onKeyDown}\n spellcheck=\"false\"\n autocomplete=\"off\"\n autocapitalize=\"off\"\n class=\"shell-input-field\"\n />\n</div>\n\n<style>\n .shell-input {\n display: flex;\n gap: 8px;\n padding: 4px 8px;\n border-top: 1px solid var(--shell-border, #333);\n font-family: var(--shell-font-mono, monospace);\n }\n .shell-input-cwd { color: var(--shell-fg-muted, #888); }\n .shell-input-arrow { color: var(--shell-accent, #6cf); }\n .shell-input-field {\n padding: 0;\n flex: 1 1 auto;\n background: transparent;\n border: 0;\n outline: 0;\n color: var(--shell-fg, #ddd);\n font: inherit;\n }\n .shell-input.locked .shell-input-field {\n opacity: 0.5;\n cursor: default;\n }\n</style>\n","/*\n * Session client for shell-shard.\n *\n * One instance per view mount. Wraps a WebSocket to /api/shell/session.\n *\n * Responsibilities:\n * - Connect with exponential backoff on initial failure\n * - Type-safe send() / onMessage()\n * - Reconnect with replayFrom cursor on drop\n * - Queue history-log messages while disconnected; flush on reconnect\n * - Expose a reactive `connected` signal + latest known cwd/env\n *\n * The client does NOT parse message meaning beyond the `t` discriminator —\n * it's a transport, not a dispatcher. Higher layers (Terminal.svelte) read\n * messages via onMessage.\n */\n\nimport type { ClientMessage, ServerMessage } from './protocol';\n\nconst BACKOFFS = [1000, 2000, 5000, 10_000];\n\ntype MessageHandler = (msg: ServerMessage) => void;\n\nexport class SessionClient {\n private ws: WebSocket | null = null;\n private handlers: Set<MessageHandler> = new Set();\n private pendingHistoryLogs: ClientMessage[] = [];\n private lastSeq = 0;\n private backoffIndex = 0;\n private closed = false;\n\n connected = $state(false);\n cwd = $state('');\n env = $state<Record<string, string>>({});\n history = $state<string[]>([]);\n\n constructor(private readonly url: string) {}\n\n connect(): void {\n if (this.closed) return;\n try {\n this.ws = new WebSocket(this.url);\n } catch {\n this.scheduleReconnect();\n return;\n }\n\n this.ws.addEventListener('open', () => {\n this.backoffIndex = 0;\n this.connected = true;\n const hello: ClientMessage = this.lastSeq > 0\n ? { t: 'hello', replayFrom: this.lastSeq }\n : { t: 'hello' };\n this.sendRaw(hello);\n // Flush any queued history-log messages accumulated while offline\n for (const queued of this.pendingHistoryLogs) {\n this.sendRaw(queued);\n }\n this.pendingHistoryLogs = [];\n });\n\n this.ws.addEventListener('message', (evt) => {\n let msg: ServerMessage;\n try {\n msg = JSON.parse(evt.data) as ServerMessage;\n } catch {\n return; // ignore malformed\n }\n\n // Track latest seq for reconnect replay\n if (msg.t === 'event' && typeof msg.event.seq === 'number') {\n this.lastSeq = msg.event.seq;\n }\n if (msg.t === 'welcome') {\n this.cwd = msg.cwd;\n this.env = msg.env;\n this.lastSeq = msg.seq;\n }\n if (msg.t === 'cwd') {\n this.cwd = msg.cwd;\n }\n if (msg.t === 'history') {\n this.history = msg.lines;\n }\n\n for (const h of this.handlers) h(msg);\n });\n\n this.ws.addEventListener('close', () => {\n this.connected = false;\n this.ws = null;\n this.scheduleReconnect();\n });\n\n this.ws.addEventListener('error', () => {\n // close event will fire next\n });\n }\n\n private scheduleReconnect(): void {\n if (this.closed) return;\n const delay = BACKOFFS[Math.min(this.backoffIndex, BACKOFFS.length - 1)];\n this.backoffIndex++;\n setTimeout(() => this.connect(), delay);\n }\n\n send(msg: ClientMessage): void {\n if (msg.t === 'history-log' && !this.connected) {\n // Queue for flush on reconnect\n this.pendingHistoryLogs.push(msg);\n return;\n }\n this.sendRaw(msg);\n }\n\n private sendRaw(msg: ClientMessage): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;\n this.ws.send(JSON.stringify(msg));\n }\n\n onMessage(handler: MessageHandler): () => void {\n this.handlers.add(handler);\n return () => this.handlers.delete(handler);\n }\n\n close(): void {\n this.closed = true;\n this.ws?.close();\n this.ws = null;\n }\n}\n","/*\n * Verb resolution for shell-shard.\n *\n * The VerbRegistry class owns resolution logic (escape hatch, token\n * lookup, forward-to-server). Verb storage is the framework's job —\n * see shards/registry.ts. This class reads from the framework map\n * via getVerb() and listVerbs().\n */\n\nimport { getVerb, listVerbs } from '../shards/registry';\nimport type { Verb, VerbContext, Resolution, ShellApi } from '../verbs/types';\n\nexport type { Verb, VerbContext, Resolution, ShellApi };\n\nexport class VerbRegistry {\n list(): Verb[] {\n return listVerbs();\n }\n\n get(name: string): Verb | undefined {\n return getVerb(name);\n }\n\n resolve(line: string): Resolution {\n const trimmed = line.trim();\n if (!trimmed) return { kind: 'forward', line };\n\n // Escape hatch: '$ <rest>' always forwards\n if (trimmed.startsWith('$ ')) {\n return { kind: 'forward', line: trimmed.slice(2) };\n }\n if (trimmed === '$') {\n return { kind: 'forward', line: '' };\n }\n\n // First whitespace-separated token\n const space = trimmed.indexOf(' ');\n const head = space === -1 ? trimmed : trimmed.slice(0, space);\n const rest = space === -1 ? '' : trimmed.slice(space + 1);\n\n const verb = getVerb(head);\n if (!verb) return { kind: 'forward', line };\n\n // Simple space-split for args — verbs can re-tokenize if they need quoting\n const args = rest.length ? rest.split(/\\s+/) : [];\n return { kind: 'local', verb, args, line };\n }\n}\n","/**\n * Client for /api/fs/*. Read-only today.\n * Shared across all shell modes so verb implementations stay mode-agnostic.\n */\n\nexport interface FsEntry {\n name: string;\n kind: 'file' | 'dir';\n size: number;\n mtime: number;\n}\n\nexport interface FsStat {\n name: string;\n kind: 'file' | 'dir';\n size: number;\n mtime: number;\n}\n\nexport class TenantFsClient {\n constructor(private readonly base: string = '') {}\n\n async list(path: string): Promise<FsEntry[]> {\n const res = await this.#get('/api/fs/list', path);\n const body = await res.json() as { entries: FsEntry[] };\n return body.entries;\n }\n\n async stat(path: string): Promise<FsStat> {\n const res = await this.#get('/api/fs/stat', path);\n return await res.json() as FsStat;\n }\n\n async read(path: string): Promise<string> {\n const res = await this.#get('/api/fs/read', path);\n return await res.text();\n }\n\n async #get(route: string, path: string): Promise<Response> {\n const url = `${this.base}${route}?path=${encodeURIComponent(path)}`;\n const res = await fetch(url, { credentials: 'include' });\n if (!res.ok) {\n let msg = `HTTP ${res.status}`;\n try {\n const j = await res.json() as { error?: string };\n if (j.error) msg = j.error;\n } catch { /* non-json body */ }\n throw new Error(msg);\n }\n return res;\n }\n}\n","import type { ShellMode, ShellRole } from './types';\n\nexport class ShellModeRegistry {\n #modes = new Map<string, ShellMode>();\n\n register(mode: ShellMode): void {\n this.#modes.set(mode.id, mode);\n }\n\n get(id: string): ShellMode | undefined {\n return this.#modes.get(id);\n }\n\n list(role: ShellRole): ShellMode[] {\n const out: ShellMode[] = [];\n for (const m of this.#modes.values()) {\n if (m.requiresRole && m.requiresRole !== role) continue;\n out.push(m);\n }\n return out;\n }\n}\n","import { ShellModeRegistry } from './registry';\nimport type { ShellMode } from './types';\n\nexport const DEV_MODE: ShellMode = {\n id: 'dev',\n label: 'Dev',\n requiresRole: 'admin',\n transport: 'ws',\n autoRelocate: false,\n};\n\nexport const USER_MODE: ShellMode = {\n id: 'user',\n label: 'User',\n transport: 'none',\n autoRelocate: true,\n};\n\nexport function registerBuiltinModes(reg: ShellModeRegistry): void {\n reg.register(DEV_MODE);\n reg.register(USER_MODE);\n}\n","import type { ShellMode, ShellRole } from './types';\nimport type { ShellModeRegistry } from './registry';\n\nfunction key(userId: string): string {\n return `sh3.shell.lastMode.${userId}`;\n}\n\nexport function readLastMode(userId: string): string | null {\n try {\n return globalThis.localStorage?.getItem(key(userId)) ?? null;\n } catch {\n return null;\n }\n}\n\nexport function writeLastMode(userId: string, modeId: string): void {\n try {\n globalThis.localStorage?.setItem(key(userId), modeId);\n } catch {\n // Non-browser host or storage disabled — persistence is best-effort.\n }\n}\n\nexport function resolveInitialMode(\n reg: ShellModeRegistry,\n userId: string,\n role: ShellRole,\n): ShellMode {\n const persisted = readLastMode(userId);\n if (persisted) {\n const m = reg.get(persisted);\n if (m && (!m.requiresRole || m.requiresRole === role)) return m;\n }\n const fallback = role === 'admin' ? 'dev' : 'user';\n return reg.get(fallback)!;\n}\n","/*\n * makeDispatch — mode-aware verb dispatch factory for Terminal.svelte.\n *\n * Pure function (no Svelte reactivity) so it can be unit-tested independently.\n * The mode is passed as a getter so the dispatch closure always sees the\n * current mode without being reconstructed on every mode change.\n */\n\nimport type { VerbRegistry, ShellApi } from './registry';\nimport type { Scrollback } from './scrollback.svelte';\nimport type { SessionClient } from './session-client.svelte';\nimport type { TenantFsClient } from './tenant-fs-client';\nimport type { ShellMode } from './modes/types';\n\nexport interface DispatchDeps {\n mode: () => ShellMode;\n resolver: VerbRegistry;\n scrollback: Scrollback;\n session: SessionClient;\n shell: ShellApi;\n fs: TenantFsClient;\n cwd: () => string;\n}\n\nexport function makeDispatch(deps: DispatchDeps) {\n return async function dispatch(line: string): Promise<void> {\n const mode = deps.mode();\n deps.session.history.push(line);\n\n // User-mode $ escape: block server-shell access\n if (mode.transport === 'none' && line.trimStart().startsWith('$ ')) {\n deps.scrollback.push({ kind: 'prompt', cwd: deps.cwd(), line, ts: Date.now() });\n deps.scrollback.push({ kind: 'status', text: 'shell: server shell not available in user mode', level: 'error', ts: Date.now() });\n return;\n }\n\n const resolution = deps.resolver.resolve(line);\n\n if (resolution.kind === 'local') {\n // Log locally-dispatched verbs for shared history (ws only)\n if (mode.transport === 'ws') {\n deps.session.send({ t: 'history-log', line });\n }\n deps.scrollback.push({ kind: 'prompt', cwd: deps.cwd(), line, ts: Date.now() });\n try {\n await resolution.verb.run({\n shell: deps.shell,\n scrollback: deps.scrollback,\n session: deps.session,\n cwd: deps.cwd(),\n dispatch,\n fs: deps.fs,\n }, resolution.args);\n } catch (err) {\n deps.scrollback.push({\n kind: 'status',\n text: `shell: verb ${resolution.verb.name} threw — ${(err as Error).message}`,\n level: 'error',\n ts: Date.now(),\n });\n }\n return;\n }\n\n // forward path\n if (mode.transport === 'ws') {\n deps.session.send({ t: 'submit', line: resolution.line });\n } else {\n const firstToken = resolution.line.split(/\\s+/)[0] ?? '';\n deps.scrollback.push({ kind: 'prompt', cwd: deps.cwd(), line: resolution.line, ts: Date.now() });\n deps.scrollback.push({ kind: 'status', text: `unknown verb: ${firstToken}`, level: 'error', ts: Date.now() });\n }\n };\n}\n","import type { TenantFsClient } from './tenant-fs-client';\n\nexport interface RelocateInput {\n modeAutoRelocate: boolean;\n focusLocked: boolean;\n focusedShardId: string | null;\n currentShardId: string;\n}\n\nexport interface RelocateEffect {\n kind: 'noop' | 'relocate';\n path?: string;\n}\n\nexport async function computeRelocate(\n input: RelocateInput,\n fs: TenantFsClient,\n): Promise<RelocateEffect> {\n if (!input.modeAutoRelocate) return { kind: 'noop' };\n if (input.focusLocked) return { kind: 'noop' };\n if (input.focusedShardId === null) return { kind: 'noop' };\n if (input.focusedShardId === input.currentShardId) return { kind: 'noop' };\n const path = input.focusedShardId;\n try {\n const s = await fs.stat(path);\n if (s.kind !== 'dir') return { kind: 'noop' };\n } catch {\n return { kind: 'noop' };\n }\n return { kind: 'relocate', path };\n}\n","<script lang=\"ts\">\n import type { ToolbarSlotRegistry, ShellSlotCtx } from './slots';\n\n interface Props {\n registry: ToolbarSlotRegistry;\n ctx: ShellSlotCtx;\n slotProps?: Record<string, Record<string, unknown>>;\n }\n\n let { registry, ctx, slotProps = {} }: Props = $props();\n\n let slots = $derived(registry.list(ctx));\n</script>\n\n<div class=\"toolbar\">\n <div class=\"toolbar-slots\">\n {#each slots as s (s.id)}\n {@const Slot = s.component}\n <Slot {...(slotProps[s.id] ?? {})} />\n {/each}\n </div>\n</div>\n\n<style>\n .toolbar {\n display: flex;\n align-items: center;\n gap: 6px;\n padding: 4px 6px;\n background: var(--shell-bg-elevated, var(--shell-bg, #1a1a1a));\n border-bottom: 1px solid var(--shell-border, #333);\n flex-shrink: 0;\n }\n\n .toolbar-slots {\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n }\n</style>\n","import type { Component } from 'svelte';\nimport type { ShellMode, ShellRole } from '../modes/types';\n\nexport interface ShellSlotCtx {\n mode: ShellMode;\n role: ShellRole;\n}\n\nexport interface ToolbarSlot {\n id: string;\n order: number;\n visible(ctx: ShellSlotCtx): boolean;\n component: Component<any>;\n}\n\nexport class ToolbarSlotRegistry {\n #slots: ToolbarSlot[] = [];\n\n register(slot: ToolbarSlot): void {\n this.#slots = this.#slots.filter((s) => s.id !== slot.id).concat(slot);\n }\n\n list(ctx: ShellSlotCtx): ToolbarSlot[] {\n return this.#slots\n .filter((s) => s.visible(ctx))\n .sort((a, b) => a.order - b.order);\n }\n}\n","<script lang=\"ts\">\n import type { ShellMode, ShellRole } from '../../modes/types';\n import type { ShellModeRegistry } from '../../modes/registry';\n\n interface Props {\n mode: ShellMode;\n role: ShellRole;\n registry: ShellModeRegistry;\n onSelect: (id: string) => void;\n }\n\n let { mode, role, registry, onSelect }: Props = $props();\n\n let modes = $derived(registry.list(role));\n</script>\n\n{#if role === 'admin'}\n <div class=\"mode-bar\" role=\"toolbar\" aria-label=\"Shell mode\">\n {#each modes as m (m.id)}\n <button\n type=\"button\"\n class=\"mode-btn\"\n class:active={m.id === mode.id}\n aria-pressed={m.id === mode.id}\n onclick={() => onSelect(m.id)}\n >\n {m.label}\n </button>\n {/each}\n </div>\n{:else}\n <span class=\"mode-label\">{mode.label}</span>\n{/if}\n\n<style>\n .mode-bar {\n display: inline-flex;\n gap: 2px;\n padding: 1px;\n border: 1px solid var(--shell-border, #444);\n border-radius: 3px;\n }\n\n .mode-btn {\n background: none;\n border: none;\n color: var(--shell-fg-dim, var(--shell-fg-muted, #888));\n padding: 2px 8px;\n border-radius: 2px;\n cursor: pointer;\n font-size: 0.85em;\n line-height: 1.4;\n }\n\n .mode-btn:hover {\n background: var(--shell-hover, color-mix(in srgb, var(--shell-fg, #ddd) 10%, transparent));\n color: var(--shell-fg, #ddd);\n }\n\n .mode-btn.active {\n background: var(--shell-accent, #7c7cf0);\n color: var(--shell-bg, #1a1a2e);\n }\n\n .mode-label {\n font-size: 0.85em;\n color: var(--shell-fg-dim, var(--shell-fg-muted, #888));\n }\n</style>\n","<script lang=\"ts\">\n interface Props {\n locked: boolean;\n onToggle: () => void;\n }\n\n let { locked, onToggle }: Props = $props();\n</script>\n\n<button class=\"focus-lock-btn\" onclick={onToggle} title={locked ? 'Unlock focus' : 'Lock focus'}>\n {locked ? '🔒' : '🔓'}\n</button>\n\n<style>\n .focus-lock-btn {\n background: none;\n border: 1px solid var(--shell-border, #444);\n border-radius: 3px;\n cursor: pointer;\n padding: 2px 5px;\n font-size: 0.9em;\n line-height: 1;\n }\n\n .focus-lock-btn:hover {\n background: var(--shell-hover, #222);\n }\n</style>\n","<script lang=\"ts\">\n interface Props {\n target: string | null;\n }\n\n let { target }: Props = $props();\n</script>\n\n<span class=\"target-shard\" title=\"Target shard\">→ {target ?? '—'}</span>\n\n<style>\n .target-shard {\n font-size: 0.85em;\n color: var(--shell-fg-dim, #888);\n font-family: monospace;\n }\n</style>\n","<script lang=\"ts\">\n import { onMount, onDestroy, untrack } from 'svelte';\n import { Scrollback } from './scrollback.svelte';\n import ScrollbackView from './ScrollbackView.svelte';\n import InputLine from './InputLine.svelte';\n import { SessionClient } from './session-client.svelte';\n import { VerbRegistry, type ShellApi } from './registry';\n import type { ServerMessage } from './protocol';\n import { TenantFsClient } from './tenant-fs-client';\n import { ShellModeRegistry } from './modes/registry';\n import { registerBuiltinModes } from './modes/builtin';\n import { resolveInitialMode, writeLastMode } from './modes/prefs';\n import type { ShellMode, ShellRole } from './modes/types';\n import { makeDispatch } from './dispatch';\n import { computeRelocate } from './auto-relocate';\n import { activeLayout } from '../layout/store.svelte';\n import type { LayoutNode } from '../layout/types';\n import Toolbar from './toolbar/Toolbar.svelte';\n import { ToolbarSlotRegistry } from './toolbar/slots';\n import ModeSlot from './toolbar/slots/ModeSlot.svelte';\n import FocusLockSlot from './toolbar/slots/FocusLockSlot.svelte';\n import TargetShardSlot from './toolbar/slots/TargetShardSlot.svelte';\n\n interface Props {\n shell: ShellApi;\n wsUrl: string;\n userId: string;\n role: ShellRole;\n }\n let { shell, wsUrl, userId, role }: Props = $props();\n\n const scrollback = new Scrollback();\n const resolver = new VerbRegistry();\n const fs = new TenantFsClient();\n\n // Mode registry\n const modeRegistry = new ShellModeRegistry();\n registerBuiltinModes(modeRegistry);\n\n // Reactive current mode\n let mode = $state<ShellMode>(\n untrack(() => resolveInitialMode(modeRegistry, userId, role)),\n );\n\n function setMode(id: string): void {\n const next = modeRegistry.get(id);\n if (!next) return;\n if (next.requiresRole && next.requiresRole !== role) return;\n mode = next;\n writeLastMode(userId, id);\n if (next.transport !== 'ws') {\n scrollback.push({ kind: 'status', text: 'mode switch: reload to take effect for server-shell changes', level: 'info', ts: Date.now() });\n }\n }\n\n // wsUrl is a prop read at construction only. untrack prevents Svelte 5's\n // \"referenced outside a closure\" warning; the URL never changes at runtime.\n const session = untrack(() => new SessionClient(wsUrl));\n\n const dispatch = untrack(() => makeDispatch({\n mode: () => mode,\n resolver,\n scrollback,\n session,\n shell,\n fs,\n cwd: () => session.cwd,\n }));\n\n let locked = $state(false);\n\n // ---------------------------------------------------------------------------\n // Auto-relocate: track the focused shard and update session.cwd when focus\n // changes to a shard whose documents directory exists. focusLocked and\n // targetShard are read by Task 13's toolbar component via props.\n // ---------------------------------------------------------------------------\n\n let focusLocked = $state(false);\n let targetShard = $state<string | null>(null);\n\n // Toolbar slot registry\n const toolbarRegistry = new ToolbarSlotRegistry();\n toolbarRegistry.register({ id: 'mode', order: 10, visible: () => true, component: ModeSlot });\n toolbarRegistry.register({ id: 'focus-lock', order: 20, visible: (ctx) => ctx.mode.id === 'user', component: FocusLockSlot });\n toolbarRegistry.register({ id: 'target-shard', order: 30, visible: (ctx) => ctx.mode.id === 'user', component: TargetShardSlot });\n\n /** Walk the layout tree and return the viewId of the active tab in the first\n * TabsNode found (breadth-first). Returns null if the layout contains no\n * tabs node with a populated active tab. */\n function getActiveViewId(node: LayoutNode): string | null {\n if (node.type === 'tabs') {\n const entry = node.tabs[node.activeTab];\n return entry?.viewId ?? null;\n }\n if (node.type === 'split') {\n for (const child of node.children) {\n const found = getActiveViewId(child);\n if (found !== null) return found;\n }\n return null;\n }\n // slot node\n return node.viewId ?? null;\n }\n\n /** Derive the focused shard id from the currently-active layout. The shard\n * id is the prefix before the first ':' in a viewId (e.g. 'shell:terminal'\n * → 'shell'). Returns null when no view is active. */\n function getFocusedShardId(): string | null {\n try {\n const tree = activeLayout();\n const viewId = getActiveViewId(tree.docked);\n if (!viewId) return null;\n const colon = viewId.indexOf(':');\n return colon >= 0 ? viewId.slice(0, colon) : viewId;\n } catch {\n return null;\n }\n }\n\n $effect(() => {\n const focused = getFocusedShardId();\n const autoRelocate = mode.autoRelocate;\n const isFocusLocked = focusLocked;\n (async () => {\n const r = await computeRelocate({\n modeAutoRelocate: autoRelocate,\n focusLocked: isFocusLocked,\n focusedShardId: focused,\n currentShardId: 'shell',\n }, fs);\n if (r.kind === 'relocate' && r.path !== undefined) {\n session.cwd = r.path;\n }\n if (focused && focused !== 'shell') targetShard = focused;\n else if (!focused) targetShard = null;\n })();\n });\n\n function handleServerMessage(msg: ServerMessage) {\n if (msg.t !== 'event') return;\n const e = msg.event;\n switch (e.kind) {\n case 'prompt':\n scrollback.push({ kind: 'prompt', cwd: e.cwd, line: e.line, ts: e.ts });\n locked = true;\n break;\n case 'stdout':\n scrollback.push({ kind: 'text', stream: 'stdout', chunks: [e.data], ts: e.ts });\n break;\n case 'stderr':\n scrollback.push({ kind: 'text', stream: 'stderr', chunks: [e.data], ts: e.ts });\n break;\n case 'exit':\n // Match real-shell UX: stay silent on clean exit. Only surface\n // a status line on non-zero exit codes or signal-terminated\n // processes (SIGINT, spawn errors, etc.). `code === null` with\n // no signal happens on clean close too — treat as success.\n if (e.signal || (e.code !== null && e.code !== 0)) {\n scrollback.push({\n kind: 'status',\n text: e.signal\n ? `shell: process exited (${e.signal})`\n : `shell: process exited (${e.code})`,\n level: 'error',\n ts: e.ts,\n });\n }\n locked = false;\n break;\n case 'status':\n scrollback.push({ kind: 'status', text: e.text, level: e.level, ts: e.ts });\n break;\n }\n }\n\n let unsub: (() => void) | null = null;\n\n onMount(() => {\n unsub = session.onMessage(handleServerMessage);\n if (mode.transport === 'ws') {\n session.connect();\n }\n });\n\n onDestroy(() => {\n unsub?.();\n session.close();\n });\n</script>\n\n<div class=\"shell-terminal\">\n <Toolbar\n registry={toolbarRegistry}\n ctx={{ mode, role }}\n slotProps={{\n mode: { mode, role, registry: modeRegistry, onSelect: setMode },\n 'focus-lock': { locked: focusLocked, onToggle: () => (focusLocked = !focusLocked) },\n 'target-shard': { target: targetShard },\n }}\n />\n <ScrollbackView {scrollback} />\n <InputLine\n cwd={session.cwd}\n {locked}\n history={session.history}\n {session}\n onSubmit={dispatch}\n />\n</div>\n\n<style>\n .shell-terminal {\n display: flex;\n flex-direction: column;\n height: 100%;\n background: var(--shell-bg, #111);\n color: var(--shell-fg, #ddd);\n }\n</style>\n","<script lang=\"ts\">\n interface Props {\n data: { rows: Array<{ name: string; summary: string }>; onClickName: (name: string) => void };\n }\n let { data }: Props = $props();\n</script>\n\n<div class=\"shell-rich-help\">\n <table>\n <thead>\n <tr><th>Name</th><th>Summary</th></tr>\n </thead>\n <tbody>\n {#each data.rows as row (row.name)}\n <tr>\n <td><button type=\"button\" onclick={() => data.onClickName(row.name)}>{row.name}</button></td>\n <td>{row.summary}</td>\n </tr>\n {/each}\n </tbody>\n </table>\n</div>\n\n<style>\n .shell-rich-help table { border-collapse: collapse; width: 100%; }\n .shell-rich-help th, .shell-rich-help td { padding: 2px 8px; text-align: left; }\n .shell-rich-help button { background: none; border: 0; color: var(--shell-link, #6cf); cursor: pointer; padding: 0; font: inherit; }\n .shell-rich-help button:hover { text-decoration: underline; }\n</style>\n","import type { Verb, VerbContext } from '../../verbs/types';\nimport { listVerbs } from '../../shards/registry';\nimport HelpTable from '../rich/HelpTable.svelte';\n\nexport function makeHelpVerb(): Verb {\n return {\n name: 'help',\n summary: 'List verbs or show detail for one.',\n async run(ctx: VerbContext) {\n const rows = listVerbs().map((v) => ({ name: v.name, summary: v.summary }));\n ctx.scrollback.push({\n kind: 'rich',\n component: HelpTable,\n props: {\n data: {\n rows,\n onClickName: (name: string) => ctx.dispatch(name),\n },\n },\n ts: Date.now(),\n });\n },\n };\n}\n","import type { Verb, VerbContext } from '../../verbs/types';\n\nexport const clearVerb: Verb = {\n name: 'clear',\n summary: 'Clear the scrollback (local only — other views are unaffected).',\n async run(ctx: VerbContext) {\n ctx.scrollback.clear();\n },\n};\n","<script lang=\"ts\">\n interface Props {\n data: { lines: string[]; onClickLine: (line: string) => void };\n }\n let { data }: Props = $props();\n</script>\n\n<div class=\"shell-rich-history\">\n <ol>\n {#each data.lines as line, i (i)}\n <li><button type=\"button\" onclick={() => data.onClickLine(line)}>{line}</button></li>\n {/each}\n </ol>\n</div>\n\n<style>\n .shell-rich-history ol {\n list-style-position: inside;\n margin: 0;\n padding: 0;\n }\n .shell-rich-history li {\n padding: 2px 0;\n }\n .shell-rich-history button {\n background: none;\n border: 0;\n color: var(--shell-link, #6cf);\n cursor: pointer;\n padding: 0;\n font: inherit;\n text-align: left;\n }\n .shell-rich-history button:hover {\n text-decoration: underline;\n }\n</style>\n","import type { Verb, VerbContext } from '../../verbs/types';\nimport HistoryList from '../rich/HistoryList.svelte';\n\nexport const historyVerb: Verb = {\n name: 'history',\n summary: 'Show the last N history lines. Default 50.',\n async run(ctx: VerbContext, args: string[]) {\n const n = args[0] ? Math.max(1, parseInt(args[0], 10) || 50) : 50;\n const lines = ctx.session.history.slice(-n);\n ctx.scrollback.push({\n kind: 'rich',\n component: HistoryList,\n props: {\n data: {\n lines,\n onClickLine: (line: string) => ctx.dispatch(line),\n },\n },\n ts: Date.now(),\n });\n },\n};\n","<script lang=\"ts\">\n interface Props {\n data: { apps: Array<{ id: string; label: string }>; onClickApp: (id: string) => void };\n }\n let { data }: Props = $props();\n</script>\n\n<div class=\"shell-rich-apps\">\n <table>\n <thead>\n <tr><th>ID</th><th>Label</th></tr>\n </thead>\n <tbody>\n {#each data.apps as app (app.id)}\n <tr>\n <td><button type=\"button\" onclick={() => data.onClickApp(app.id)}>{app.id}</button></td>\n <td>{app.label}</td>\n </tr>\n {/each}\n </tbody>\n </table>\n</div>\n\n<style>\n .shell-rich-apps table { border-collapse: collapse; width: 100%; }\n .shell-rich-apps th, .shell-rich-apps td { padding: 2px 8px; text-align: left; }\n .shell-rich-apps button { background: none; border: 0; color: var(--shell-link, #6cf); cursor: pointer; padding: 0; font: inherit; }\n .shell-rich-apps button:hover { text-decoration: underline; }\n</style>\n","<script lang=\"ts\">\n interface Props {\n data: { id: string; label: string; shards: string[] };\n }\n let { data }: Props = $props();\n</script>\n\n<div class=\"shell-rich-appcard\">\n <h3>{data.label}</h3>\n <p><strong>ID:</strong> {data.id}</p>\n <p><strong>Shards:</strong> {data.shards.join(', ')}</p>\n</div>\n\n<style>\n .shell-rich-appcard {\n padding: 8px;\n border: 1px solid var(--shell-border, #444);\n }\n .shell-rich-appcard h3 {\n margin: 0 0 8px 0;\n }\n .shell-rich-appcard p {\n margin: 4px 0;\n }\n</style>\n","import type { Verb, VerbContext } from '../../verbs/types';\nimport AppsTable from '../rich/AppsTable.svelte';\nimport AppCard from '../rich/AppCard.svelte';\n\nexport const appsVerb: Verb = {\n name: 'apps',\n summary: 'List installed apps. Click a row to launch.',\n async run(ctx: VerbContext) {\n const apps = ctx.shell.listApps();\n ctx.scrollback.push({\n kind: 'rich',\n component: AppsTable,\n props: {\n data: {\n apps,\n onClickApp: (id: string) => {\n ctx.shell.launchApp(id);\n ctx.scrollback.push({\n kind: 'status',\n text: `shell: launched app ${id}`,\n level: 'info',\n ts: Date.now(),\n });\n },\n },\n },\n ts: Date.now(),\n });\n },\n};\n\nexport const appVerb: Verb = {\n name: 'app',\n summary: 'Show the currently active app.',\n async run(ctx: VerbContext) {\n const active = ctx.shell.getActiveApp();\n if (!active) {\n ctx.scrollback.push({\n kind: 'status',\n text: 'shell: no active app',\n level: 'info',\n ts: Date.now(),\n });\n return;\n }\n ctx.scrollback.push({\n kind: 'rich',\n component: AppCard,\n props: { data: { id: active.id, label: active.label, shards: [] } },\n ts: Date.now(),\n });\n },\n};\n","<script lang=\"ts\">\n interface Props {\n data: { shards: Array<{ id: string; label: string; version: string }> };\n }\n let { data }: Props = $props();\n</script>\n\n<div class=\"shell-rich-shards\">\n <table>\n <thead>\n <tr><th>ID</th><th>Label</th><th>Version</th></tr>\n </thead>\n <tbody>\n {#each data.shards as shard (shard.id)}\n <tr>\n <td>{shard.id}</td>\n <td>{shard.label}</td>\n <td>{shard.version}</td>\n </tr>\n {/each}\n </tbody>\n </table>\n</div>\n\n<style>\n .shell-rich-shards table { border-collapse: collapse; width: 100%; }\n .shell-rich-shards th, .shell-rich-shards td { padding: 2px 8px; text-align: left; }\n</style>\n","import type { Verb, VerbContext } from '../../verbs/types';\nimport ShardsTable from '../rich/ShardsTable.svelte';\n\nexport const shardsVerb: Verb = {\n name: 'shards',\n summary: 'List active shards.',\n async run(ctx: VerbContext) {\n const shards = ctx.shell.listShards();\n ctx.scrollback.push({\n kind: 'rich',\n component: ShardsTable,\n props: { data: { shards } },\n ts: Date.now(),\n });\n },\n};\n","<script lang=\"ts\">\n interface Props {\n data: { views: Array<{ slotId: string; viewId: string; label: string }>; onClose: (slotId: string) => void };\n }\n let { data }: Props = $props();\n</script>\n\n<div class=\"shell-rich-views\">\n <table>\n <thead>\n <tr><th>Slot ID</th><th>View ID</th><th>Label</th><th>Action</th></tr>\n </thead>\n <tbody>\n {#each data.views as view (view.slotId)}\n <tr>\n <td>{view.slotId}</td>\n <td>{view.viewId}</td>\n <td>{view.label}</td>\n <td><button type=\"button\" onclick={() => data.onClose(view.slotId)}>Close</button></td>\n </tr>\n {/each}\n </tbody>\n </table>\n</div>\n\n<style>\n .shell-rich-views table { border-collapse: collapse; width: 100%; }\n .shell-rich-views th, .shell-rich-views td { padding: 2px 8px; text-align: left; }\n .shell-rich-views button { background: none; border: 0; color: var(--shell-link, #6cf); cursor: pointer; padding: 0; font: inherit; }\n .shell-rich-views button:hover { text-decoration: underline; }\n</style>\n","import type { Verb, VerbContext } from '../../verbs/types';\nimport ViewsTable from '../rich/ViewsTable.svelte';\n\nexport const viewsVerb: Verb = {\n name: 'views',\n summary: 'List views currently mounted. Pass --standalone to list summonable views instead.',\n async run(ctx: VerbContext, args: string[]) {\n if (args.includes('--standalone')) {\n const standalones = ctx.shell.listStandaloneViews();\n if (standalones.length === 0) {\n ctx.scrollback.push({\n kind: 'status',\n text: 'shell: no standalone views are currently available.',\n level: 'info',\n ts: Date.now(),\n });\n return;\n }\n ctx.scrollback.push({\n kind: 'status',\n text: standalones\n .map((v) => ` ${v.viewId.padEnd(32)} ${v.label}`)\n .join('\\n'),\n level: 'info',\n ts: Date.now(),\n });\n return;\n }\n const views = ctx.shell.listViewsInCurrentLayout();\n ctx.scrollback.push({\n kind: 'rich',\n component: ViewsTable,\n props: {\n data: {\n views,\n onClose: (slotId: string) => {\n const result = ctx.shell.closeSlot(slotId);\n if (!result.ok) {\n ctx.scrollback.push({\n kind: 'status',\n text: `shell: close failed — ${result.error ?? 'unknown'}`,\n level: 'error',\n ts: Date.now(),\n });\n }\n },\n },\n },\n ts: Date.now(),\n });\n },\n};\n\nexport const openVerb: Verb = {\n name: 'open',\n summary: 'Open a view from any active shard into the current layout.',\n async run(ctx: VerbContext, args: string[]) {\n const viewId = args[0];\n if (!viewId) {\n ctx.scrollback.push({\n kind: 'status',\n text: 'usage: open <viewId>',\n level: 'warn',\n ts: Date.now(),\n });\n return;\n }\n const result = ctx.shell.openViewInCurrentLayout(viewId);\n if (!result.ok) {\n ctx.scrollback.push({\n kind: 'status',\n text: `shell: open failed — ${result.error ?? 'unknown'}`,\n level: 'error',\n ts: Date.now(),\n });\n } else {\n ctx.scrollback.push({\n kind: 'status',\n text: `shell: opened ${viewId}`,\n level: 'info',\n ts: Date.now(),\n });\n }\n },\n};\n\nexport const popoutVerb: Verb = {\n name: 'popout',\n summary: 'Pop a docked view out into a float by slot id.',\n async run(ctx: VerbContext, args: string[]) {\n const slotId = args[0];\n if (!slotId) {\n ctx.scrollback.push({\n kind: 'status',\n text: 'usage: popout <slotId>',\n level: 'warn',\n ts: Date.now(),\n });\n return;\n }\n const result = ctx.shell.popoutSlot(slotId);\n if (!result.ok) {\n ctx.scrollback.push({\n kind: 'status',\n text: `shell: popout failed — ${result.error ?? 'unknown'}`,\n level: 'error',\n ts: Date.now(),\n });\n } else {\n ctx.scrollback.push({\n kind: 'status',\n text: `shell: popped out ${slotId} → ${result.floatId}`,\n level: 'info',\n ts: Date.now(),\n });\n }\n },\n};\n\nexport const dockVerb: Verb = {\n name: 'dock',\n summary: 'Dock a float back into the current layout by float id. Run with no args to list floats.',\n async run(ctx: VerbContext, args: string[]) {\n const floatId = args[0];\n if (!floatId) {\n const floats = ctx.shell.listFloats();\n if (floats.length === 0) {\n ctx.scrollback.push({\n kind: 'status',\n text: 'shell: no active floats.',\n level: 'info',\n ts: Date.now(),\n });\n return;\n }\n ctx.scrollback.push({\n kind: 'status',\n text: floats\n .map((f) => ` ${f.floatId.padEnd(24)} ${f.viewId ?? '-'}\\t${f.label}`)\n .join('\\n'),\n level: 'info',\n ts: Date.now(),\n });\n return;\n }\n const result = ctx.shell.dockFloat(floatId);\n if (!result.ok) {\n ctx.scrollback.push({\n kind: 'status',\n text: `shell: dock failed — ${result.error ?? 'unknown'}`,\n level: 'error',\n ts: Date.now(),\n });\n } else {\n ctx.scrollback.push({\n kind: 'status',\n text: `shell: docked ${floatId}`,\n level: 'info',\n ts: Date.now(),\n });\n }\n },\n};\n\nexport const closeVerb: Verb = {\n name: 'close',\n summary: 'Close a view by slot id.',\n async run(ctx: VerbContext, args: string[]) {\n const slotId = args[0];\n if (!slotId) {\n ctx.scrollback.push({\n kind: 'status',\n text: 'usage: close <slotId>',\n level: 'warn',\n ts: Date.now(),\n });\n return;\n }\n const result = ctx.shell.closeSlot(slotId);\n if (!result.ok) {\n ctx.scrollback.push({\n kind: 'status',\n text: `shell: close failed — ${result.error ?? 'unknown'}`,\n level: 'error',\n ts: Date.now(),\n });\n }\n },\n};\n","<script lang=\"ts\">\n interface Props {\n data: { rows: Array<{ shardId: string; zones: string[] }> };\n }\n let { data }: Props = $props();\n</script>\n\n<div class=\"shell-rich-zones\">\n <table>\n <thead>\n <tr><th>Shard ID</th><th>Zones</th></tr>\n </thead>\n <tbody>\n {#each data.rows as row (row.shardId)}\n <tr>\n <td>{row.shardId}</td>\n <td>{row.zones.join(', ')}</td>\n </tr>\n {/each}\n </tbody>\n </table>\n</div>\n\n<style>\n .shell-rich-zones table { border-collapse: collapse; width: 100%; }\n .shell-rich-zones th, .shell-rich-zones td { padding: 2px 8px; text-align: left; }\n</style>\n","<script lang=\"ts\">\n interface Props {\n data: { value: unknown };\n }\n let { data }: Props = $props();\n</script>\n\n<div class=\"shell-rich-zonetree\">\n <pre>{JSON.stringify(data.value, null, 2)}</pre>\n</div>\n\n<style>\n .shell-rich-zonetree pre {\n overflow: auto;\n padding: 8px;\n background: var(--shell-bg, #000);\n color: var(--shell-fg, #fff);\n }\n</style>\n","import type { Verb, VerbContext } from '../../verbs/types';\nimport ZonesTable from '../rich/ZonesTable.svelte';\nimport ZoneTree from '../rich/ZoneTree.svelte';\n\nexport const zonesVerb: Verb = {\n name: 'zones',\n summary: 'List zones for the current user (optionally scoped to a shard).',\n async run(ctx: VerbContext, args: string[]) {\n const rows = ctx.shell.listZones(args[0]);\n ctx.scrollback.push({\n kind: 'rich',\n component: ZonesTable,\n props: { data: { rows } },\n ts: Date.now(),\n });\n },\n};\n\nexport const zoneVerb: Verb = {\n name: 'zone',\n summary: 'Dump the contents of a zone as a collapsible JSON tree.',\n async run(ctx: VerbContext, args: string[]) {\n const [shardId, zoneName] = args;\n if (!shardId || !zoneName) {\n ctx.scrollback.push({\n kind: 'status',\n text: 'usage: zone <shardId> <zoneName>',\n level: 'warn',\n ts: Date.now(),\n });\n return;\n }\n const value = ctx.shell.readZone(shardId, zoneName);\n ctx.scrollback.push({\n kind: 'rich',\n component: ZoneTree,\n props: { data: { value } },\n ts: Date.now(),\n });\n },\n};\n","/*\n * Session verbs: pwd, cd, whoami.\n *\n * cd validates the target path via ctx.fs.stat() then updates session.cwd\n * locally. The server still owns the authoritative cwd for forwarded\n * commands, but local verbs track it via session.cwd.\n *\n * envVerb lives in env.ts (separate Svelte import).\n */\n\nimport type { Verb, VerbContext } from '../../verbs/types';\n\n// ---------------------------------------------------------------------------\n// Path helpers\n// ---------------------------------------------------------------------------\n\nfunction joinRel(cwd: string, input: string): string {\n if (input.startsWith('/')) return normalizeRel(input.slice(1));\n const parts = [...cwd.split('/').filter(Boolean), ...input.split('/')];\n const stack: string[] = [];\n for (const p of parts) {\n if (p === '' || p === '.') continue;\n if (p === '..') { stack.pop(); continue; }\n stack.push(p);\n }\n return stack.join('/');\n}\n\nfunction normalizeRel(s: string): string {\n return s.split('/').filter((p) => p && p !== '.').join('/');\n}\n\n// ---------------------------------------------------------------------------\n// Verbs\n// ---------------------------------------------------------------------------\n\nexport const pwdVerb: Verb = {\n name: 'pwd',\n summary: 'Show the current working directory.',\n async run(ctx: VerbContext) {\n const rel = ctx.session.cwd || '';\n const display = rel.startsWith('/') ? rel : `/${rel}`;\n ctx.scrollback.push({\n kind: 'text',\n stream: 'stdout',\n chunks: [display + '\\n'],\n ts: Date.now(),\n });\n },\n};\n\nexport const cdVerb: Verb = {\n name: 'cd',\n summary: 'Change the session working directory.',\n async run(ctx: VerbContext, args: string[]) {\n const target = args[0] ?? '';\n if (target === '') {\n ctx.session.cwd = '';\n return;\n }\n const base = ctx.session.cwd;\n const candidate = joinRel(base, target);\n try {\n const s = await ctx.fs.stat(candidate);\n if (s.kind !== 'dir') {\n ctx.scrollback.push({\n kind: 'status',\n text: `cd: not a directory: ${target}`,\n level: 'error',\n ts: Date.now(),\n });\n return;\n }\n } catch (err) {\n ctx.scrollback.push({\n kind: 'status',\n text: `cd: ${(err as Error).message}`,\n level: 'error',\n ts: Date.now(),\n });\n return;\n }\n ctx.session.cwd = candidate;\n },\n};\n\nexport const whoamiVerb: Verb = {\n name: 'whoami',\n summary: 'Show the current admin user and session info.',\n async run(ctx: VerbContext) {\n const me = ctx.shell.whoAmI();\n ctx.scrollback.push({\n kind: 'text',\n stream: 'stdout',\n chunks: [`${me.userId}${me.admin ? ' (admin)' : ''}\\n`],\n ts: Date.now(),\n });\n },\n};\n","<script lang=\"ts\">\n interface Props {\n data: { env: Record<string, string> };\n }\n let { data }: Props = $props();\n</script>\n\n<div class=\"shell-rich-env\">\n <table>\n <thead>\n <tr><th>Key</th><th>Value</th></tr>\n </thead>\n <tbody>\n {#each Object.entries(data.env) as [key, value] (key)}\n <tr>\n <td>{key}</td>\n <td>{value}</td>\n </tr>\n {/each}\n </tbody>\n </table>\n</div>\n\n<style>\n .shell-rich-env table { border-collapse: collapse; width: 100%; }\n .shell-rich-env th, .shell-rich-env td { padding: 2px 8px; text-align: left; }\n</style>\n","import type { Verb, VerbContext } from '../../verbs/types';\nimport EnvTable from '../rich/EnvTable.svelte';\n\nexport const envVerb: Verb = {\n name: 'env',\n summary: 'Show the session environment.',\n async run(ctx: VerbContext) {\n const env = ctx.session.env;\n ctx.scrollback.push({\n kind: 'rich',\n component: EnvTable,\n props: { data: { env } },\n ts: Date.now(),\n });\n },\n};\n","import type { Verb } from '../../verbs/types';\n\nexport const lsVerb: Verb = {\n name: 'ls',\n summary: 'List the current directory.',\n async run(ctx) {\n let entries;\n try {\n entries = await ctx.fs.list(ctx.session.cwd);\n } catch (err) {\n ctx.scrollback.push({\n kind: 'status',\n text: `ls: ${(err as Error).message}`,\n level: 'error',\n ts: Date.now(),\n });\n return;\n }\n const lines = entries\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((e) => (e.kind === 'dir' ? `${e.name}/` : e.name))\n .join('\\n');\n ctx.scrollback.push({\n kind: 'text',\n stream: 'stdout',\n chunks: [lines || '(empty)'],\n ts: Date.now(),\n });\n },\n};\n","import type { Verb } from '../../verbs/types';\n\nexport const catVerb: Verb = {\n name: 'cat',\n summary: 'Read a file into the scrollback.',\n async run(ctx, args) {\n if (args.length === 0) {\n ctx.scrollback.push({\n kind: 'status',\n text: 'cat: missing file argument',\n level: 'error',\n ts: Date.now(),\n });\n return;\n }\n const path = args[0];\n const target = ctx.session.cwd ? `${ctx.session.cwd}/${path}` : path;\n try {\n const text = await ctx.fs.read(target);\n ctx.scrollback.push({\n kind: 'text',\n stream: 'stdout',\n chunks: [text],\n ts: Date.now(),\n });\n } catch (err) {\n ctx.scrollback.push({\n kind: 'status',\n text: `cat: ${(err as Error).message}`,\n level: 'error',\n ts: Date.now(),\n });\n }\n },\n};\n","/*\n * Platform detection and backend resolution.\n *\n * Called once at boot, before bootstrap(). Detects whether we're running\n * inside a Tauri webview by attempting to dynamically import the Tauri\n * store backend. If the import fails (web build, or Tauri APIs absent),\n * falls back to default localStorage backends.\n *\n * Also resolves localOwner — true in Tauri (user owns the device) or\n * when running in a dev build (as reported by esm-env's DEV). Production\n * web builds are never local-owner.\n *\n * Vite code-splits the Tauri path into a separate chunk that is never\n * loaded in web builds (the dynamic import fails at runtime).\n */\n\nimport { DEV } from 'esm-env';\nimport type { Backend } from '../state/types';\n\nexport interface PlatformBackends {\n workspace: Backend;\n user: Backend;\n}\n\nexport interface PlatformResult {\n backends: PlatformBackends | null;\n localOwner: boolean;\n}\n\nexport async function resolvePlatform(): Promise<PlatformResult> {\n try {\n const { TauriStoreBackend } = await import('./tauri-backend');\n\n const workspace = new TauriStoreBackend('workspace');\n const user = new TauriStoreBackend('user');\n\n // Ensure stores are loaded from disk before returning.\n await Promise.all([workspace.init(), user.init()]);\n\n return { backends: { workspace, user }, localOwner: true };\n } catch {\n // Not in Tauri — fall back to default web backends.\n // Local-owner if running in a dev build. `DEV` comes from esm-env,\n // which works with all bundlers (and at runtime in plain node), so\n // sh3-core stays compatible with non-Vite consumers.\n return { backends: null, localOwner: DEV };\n }\n}\n\n/**\n * Erase all persisted SH3 state for this user/device.\n *\n * Wipes:\n * - Tauri plugin-store files (`workspace.json`, `user.json`) when running\n * inside a Tauri webview\n * - localStorage keys with the `sh3:` prefix (web zones + theme overrides;\n * also active inside the Tauri webview)\n * - the `sh3-packages` IndexedDB database (installed bundle registry)\n *\n * Intentionally preserves the `sh3-documents` IndexedDB so user-authored\n * content survives a reset. Callers are expected to follow this with a\n * `location.reload()` so a clean boot picks up the cleared state.\n */\nexport async function wipeUserData(): Promise<void> {\n // Tauri stores live on disk via plugin-store; localStorage/IDB don't reach them.\n try {\n const { LazyStore } = await import('@tauri-apps/plugin-store');\n const workspace = new LazyStore('workspace.json', { defaults: {}, autoSave: true });\n const user = new LazyStore('user.json', { defaults: {}, autoSave: true });\n await workspace.clear();\n await user.clear();\n } catch {\n // Not in Tauri — nothing to clear on disk.\n }\n\n if (typeof localStorage !== 'undefined') {\n const keys: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const k = localStorage.key(i);\n if (k && k.startsWith('sh3:')) keys.push(k);\n }\n for (const k of keys) localStorage.removeItem(k);\n }\n\n if (typeof indexedDB !== 'undefined') {\n await new Promise<void>((resolve) => {\n const req = indexedDB.deleteDatabase('sh3-packages');\n req.onsuccess = () => resolve();\n // Swallow errors/blocked: a stale lock shouldn't abort the wipe;\n // the next boot will re-create the DB empty either way.\n req.onerror = () => resolve();\n req.onblocked = () => resolve();\n });\n }\n}\n","import type { Verb, VerbContext } from '../../verbs/types';\nimport { wipeUserData } from '../../platform/index';\n\nexport const resetVerb: Verb = {\n name: 'reset',\n summary: 'Wipe SH3 state and reload (preserves documents). Requires --confirm.',\n async run(ctx: VerbContext, args: string[]) {\n if (!args.includes('--confirm')) {\n ctx.scrollback.push({\n kind: 'status',\n text:\n 'reset: erases the package registry, all zone state (including Tauri stores), ' +\n 'and theme overrides, then reloads. Documents are preserved. ' +\n 'Re-run as `reset --confirm` to proceed.',\n level: 'warn',\n ts: Date.now(),\n });\n return;\n }\n\n ctx.scrollback.push({\n kind: 'status',\n text: 'reset: wiping data…',\n level: 'info',\n ts: Date.now(),\n });\n\n await wipeUserData();\n location.reload();\n },\n};\n","/*\n * Bundle of v1 verbs for shell-shard. Call registerV1Verbs(ctx) once\n * during shell-shard activate() to populate the framework verb registry.\n */\n\nimport type { ShardContext } from '../../shards/types';\nimport { makeHelpVerb } from './help';\nimport { clearVerb } from './clear';\nimport { historyVerb } from './history';\nimport { appsVerb, appVerb } from './apps';\nimport { shardsVerb } from './shards';\nimport { viewsVerb, openVerb, closeVerb, popoutVerb, dockVerb } from './views';\nimport { zonesVerb, zoneVerb } from './zones';\nimport { pwdVerb, cdVerb, whoamiVerb } from './session';\nimport { envVerb } from './env';\nimport { lsVerb } from './ls';\nimport { catVerb } from './cat';\nimport { resetVerb } from './reset';\n\nexport function registerV1Verbs(ctx: ShardContext): void {\n ctx.registerVerb(makeHelpVerb());\n ctx.registerVerb(clearVerb);\n ctx.registerVerb(historyVerb);\n ctx.registerVerb(appsVerb);\n ctx.registerVerb(appVerb);\n ctx.registerVerb(shardsVerb);\n ctx.registerVerb(viewsVerb);\n ctx.registerVerb(openVerb);\n ctx.registerVerb(closeVerb);\n ctx.registerVerb(popoutVerb);\n ctx.registerVerb(dockVerb);\n ctx.registerVerb(zonesVerb);\n ctx.registerVerb(zoneVerb);\n ctx.registerVerb(pwdVerb);\n ctx.registerVerb(cdVerb);\n ctx.registerVerb(envVerb);\n ctx.registerVerb(whoamiVerb);\n ctx.registerVerb(lsVerb);\n ctx.registerVerb(catVerb);\n ctx.registerVerb(resetVerb);\n}\n","/*\n * shell-shard — framework built-in providing the `shell.terminal` view.\n *\n * Client half of the terminal/REPL shard. See spec at\n * docs/superpowers/specs/2026-04-10-shell-shard-design.md.\n *\n * activate() is admin-gated: when ctx.isAdmin is false the shard activates\n * but registers no views, so non-admin users literally cannot mount the\n * terminal. The server WebSocket endpoint (/api/shell/session) also refuses\n * non-admin upgrades as a second line of defense.\n *\n * autostart() is defined so the shard activates at boot without requiring\n * a dedicated app to launch it first, matching the __sh3core__ pattern.\n */\n\nimport { mount, unmount } from 'svelte';\nimport { manifest } from './manifest';\nimport Terminal from './Terminal.svelte';\nimport type { Shard, ViewFactory, ViewHandle, MountContext, ShardContext } from '../api';\nimport { registerV1Verbs } from './verbs';\nimport type { ShellApi } from './registry';\nimport { listRegisteredApps, getActiveApp } from '../apps/registry.svelte';\nimport { launchApp } from '../apps/lifecycle';\nimport { registeredShards } from '../shards/activate.svelte';\nimport { inspectActiveLayout, focusView, closeTab, popoutView, dockFloat, dockIntoActiveLayout, locateSlot as locateSlotInActiveLayout } from '../layout/inspection';\nimport { floatManager } from '../overlays/float';\nimport { listStandaloneViews } from '../shards/activate.svelte';\nimport type { LayoutNode, TabEntry } from '../layout/types';\nimport { getUser, isAdmin } from '../auth/index';\n\n/** Walk a layout tree and collect all tab entries (slotId + viewId + label). */\nfunction collectTabEntries(node: LayoutNode): TabEntry[] {\n if (node.type === 'tabs') {\n return node.tabs.filter((t) => t.viewId !== null);\n }\n if (node.type === 'split') {\n return node.children.flatMap(collectTabEntries);\n }\n // slot node: wrap as a synthetic tab entry if it has a viewId\n if (node.viewId !== null) {\n return [{ slotId: node.slotId, viewId: node.viewId, label: node.viewId }];\n }\n return [];\n}\n\nfunction makeShellApi(_ctx: ShardContext): ShellApi {\n return {\n // → apps/registry.svelte: listRegisteredApps() returns AppManifest[]\n listApps() {\n return listRegisteredApps().map((m) => ({ id: m.id, label: m.label }));\n },\n\n // → apps/registry.svelte: getActiveApp() returns AppManifest | null\n getActiveApp() {\n const m = getActiveApp();\n return m ? { id: m.id, label: m.label } : null;\n },\n\n // → apps/lifecycle: launchApp() is async; fire-and-forget to keep ShellApi sync.\n // Verb handlers display feedback independently via scrollback.\n launchApp(id: string) {\n void launchApp(id);\n },\n\n // → shards/activate.svelte: registeredShards reactive map\n listShards() {\n return Array.from(registeredShards.values()).map((s) => ({\n id: s.manifest.id,\n label: s.manifest.label,\n version: s.manifest.version,\n }));\n },\n\n // → layout/inspection: inspectActiveLayout() + tree walk\n listViewsInCurrentLayout() {\n try {\n const { root } = inspectActiveLayout();\n return collectTabEntries(root.docked).map((t) => ({\n slotId: t.slotId,\n viewId: t.viewId ?? '',\n label: t.label,\n }));\n } catch {\n return [];\n }\n },\n\n // → layout/inspection: focusView(viewId). Falls back to dockIntoActiveLayout\n // for standalone views that aren't mounted yet — this is the single\n // \"summon\" entry point wired behind the `open` verb.\n openViewInCurrentLayout(viewId: string) {\n try {\n if (focusView(viewId)) return { ok: true };\n const standalone = listStandaloneViews().find((v) => v.viewId === viewId);\n if (standalone) {\n const slotId = `standalone:${viewId}:${Date.now()}`;\n const ok = dockIntoActiveLayout({ slotId, viewId, label: standalone.label });\n return ok ? { ok: true } : { ok: false, error: `could not dock \"${viewId}\" — no available slot` };\n }\n return { ok: false, error: `view \"${viewId}\" not found in current layout` };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },\n\n // → shards/activate.svelte: listStandaloneViews() walks activeShards\n listStandaloneViews() {\n return listStandaloneViews();\n },\n\n // → layout/inspection: popoutView(slotId) returns floatId | null\n popoutSlot(slotId: string) {\n try {\n const floatId = popoutView(slotId);\n return floatId ? { ok: true, floatId } : { ok: false, error: `slot \"${slotId}\" not found in docked tree` };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },\n\n // → layout/inspection: dockFloat(floatId) returns boolean\n dockFloat(floatId: string) {\n try {\n const ok = dockFloat(floatId);\n return ok ? { ok: true } : { ok: false, error: `float \"${floatId}\" not found or has no dockable content` };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },\n\n // → layout/inspection: locateSlot(slotId) returns TreeRootRef | null\n locateSlot(slotId: string) {\n try {\n return locateSlotInActiveLayout(slotId);\n } catch {\n return null;\n }\n },\n\n // → overlays/float: floatManager.list() returns FloatEntry[]\n listFloats() {\n return floatManager.list().map((f) => {\n const tabs = f.content.type === 'tabs' ? f.content : null;\n const active = tabs ? tabs.tabs[tabs.activeTab ?? 0] ?? tabs.tabs[0] : null;\n return {\n floatId: f.id,\n viewId: active?.viewId ?? null,\n label: f.title ?? active?.label ?? f.id,\n };\n });\n },\n\n // → layout/inspection: closeTab(slotId) is async (guarded close).\n // Fire-and-forget; the tab disappears asynchronously. ShellApi stays sync.\n closeSlot(slotId: string) {\n void closeTab(slotId);\n return { ok: true };\n },\n\n // TODO Phase 10: wire to zone manager when state:manage permission is available.\n // The shell manifest declares permissions: [] so ctx.zones is undefined.\n // A future permission grant + ctx.zones.list() would power these.\n listZones(_shardId?: string) { return []; },\n readZone(_shardId: string, _zoneName: string) { return null; },\n\n // → auth/index: getUser() + isAdmin()\n whoAmI() {\n const user = getUser();\n return {\n userId: user?.id ?? 'guest',\n admin: isAdmin(),\n };\n },\n };\n}\n\n/**\n * Test-only ShellApi constructor. Bypasses the admin gate and uses a\n * stub ShardContext. Only methods that do not consult `ctx` are\n * guaranteed to work — `locateSlot`, `listFloats`, `listApps`, etc.\n */\nexport function makeShellApiForTest(): ShellApi {\n return makeShellApi({} as ShardContext);\n}\n\nexport const shellShard: Shard = {\n manifest,\n activate(ctx: ShardContext) {\n registerV1Verbs(ctx);\n const shell = makeShellApi(ctx);\n\n // The AZERTY `²` key (top-left on FR keyboards, below Escape) opens the\n // terminal view — focusing it if already mounted, floating it otherwise.\n // Migrated from Shell.svelte's inline keydown handler as proof-of-concept\n // for the Actions framework (Task 23 / DF1). Registered here because this\n // shard owns the terminal view and is already admin-gated.\n ctx.actions.register({\n id: 'shell.terminal.toggle',\n label: 'Open Terminal',\n scope: ['home', 'app'],\n defaultShortcut: '²',\n allowInInputs: false,\n run() {\n if (!focusView('shell:terminal'))\n floatManager.open('shell:terminal', { title: 'Shell' });\n },\n });\n\n const factory: ViewFactory = {\n mount(container: HTMLElement, _context: MountContext): ViewHandle {\n const proto = typeof location !== 'undefined' && location.protocol === 'https:' ? 'wss' : 'ws';\n const host = typeof location !== 'undefined' ? location.host : 'localhost';\n const wsUrl = `${proto}://${host}/api/shell/session`;\n\n const user = getUser();\n const userId = user?.id ?? 'guest';\n const role = isAdmin() ? 'admin' as const : 'user' as const;\n\n const instance = mount(Terminal, {\n target: container,\n props: { shell, wsUrl, userId, role },\n });\n\n return {\n unmount() {\n unmount(instance);\n },\n closable: true,\n };\n },\n };\n ctx.registerView('shell:terminal', factory);\n },\n autostart() {\n // Intentionally empty — same pattern as __sh3core__.\n },\n};\n","/**\n * Built-in Store app — composes the sh3-store shard views into a\n * management interface for browsing, installing, and uninstalling\n * packages.\n *\n * Framework-shipped: registered in host.ts during bootstrap.\n * Admin-gated via manifest flag (ADR-011).\n */\n\nimport type { App } from '../../apps/types';\nimport { VERSION } from '../../version';\n\nexport const storeApp: App = {\n manifest: {\n id: 'sh3-store-app',\n label: 'Package Store',\n version: VERSION,\n requiredShards: ['sh3-store'],\n layoutVersion: 1,\n admin: true,\n },\n initialLayout: {\n type: 'tabs',\n activeTab: 0,\n tabs: [\n { slotId: 'store.browse', viewId: 'sh3-store:browse', label: 'Browse' },\n ],\n },\n};\n","<script lang=\"ts\">\n /**\n * Admin Users view — list, create, edit, delete users.\n */\n\n import type { AuthUser } from '../../auth/types';\n\n let users = $state<AuthUser[]>([]);\n let loading = $state(true);\n let error = $state<string | null>(null);\n\n // Create form\n let showCreate = $state(false);\n let newUsername = $state('');\n let newDisplayName = $state('');\n let newPassword = $state('');\n let newRole = $state<'admin' | 'user'>('user');\n let createError = $state<string | null>(null);\n\n // Edit state\n let editingId = $state<string | null>(null);\n let editDisplayName = $state('');\n let editRole = $state<'admin' | 'user'>('user');\n let editPassword = $state('');\n\n async function fetchUsers() {\n loading = true;\n error = null;\n try {\n const res = await fetch('/api/admin/users', { credentials: 'include' });\n if (!res.ok) throw new Error('Failed to fetch users');\n users = await res.json();\n } catch (err) {\n error = err instanceof Error ? err.message : 'Failed to load users';\n } finally {\n loading = false;\n }\n }\n\n async function createUser() {\n createError = null;\n try {\n const res = await fetch('/api/admin/users', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify({\n username: newUsername,\n displayName: newDisplayName || newUsername,\n password: newPassword,\n role: newRole,\n }),\n });\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n createError = body.error || 'Failed to create user';\n return;\n }\n newUsername = '';\n newDisplayName = '';\n newPassword = '';\n newRole = 'user';\n showCreate = false;\n await fetchUsers();\n } catch {\n createError = 'Network error';\n }\n }\n\n function startEdit(user: AuthUser) {\n editingId = user.id;\n editDisplayName = user.displayName;\n editRole = user.role;\n editPassword = '';\n }\n\n async function saveEdit() {\n if (!editingId) return;\n const patch: Record<string, unknown> = {\n displayName: editDisplayName,\n role: editRole,\n };\n if (editPassword.trim()) patch.password = editPassword;\n try {\n const res = await fetch(`/api/admin/users/${editingId}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify(patch),\n });\n if (!res.ok) return;\n editingId = null;\n await fetchUsers();\n } catch { /* ignore */ }\n }\n\n async function deleteUser(id: string) {\n try {\n await fetch(`/api/admin/users/${id}`, {\n method: 'DELETE',\n credentials: 'include',\n });\n await fetchUsers();\n } catch { /* ignore */ }\n }\n\n fetchUsers();\n</script>\n\n<div class=\"admin-users\">\n <div class=\"admin-users-header\">\n <h2>Users</h2>\n <button type=\"button\" class=\"admin-btn\" onclick={() => { showCreate = !showCreate; }}>\n {showCreate ? 'Cancel' : 'New user'}\n </button>\n </div>\n\n {#if showCreate}\n <form class=\"admin-create-form\" onsubmit={(e) => { e.preventDefault(); createUser(); }}>\n <input class=\"admin-input\" type=\"text\" placeholder=\"Username\" bind:value={newUsername} />\n <input class=\"admin-input\" type=\"text\" placeholder=\"Display name\" bind:value={newDisplayName} />\n <input class=\"admin-input\" type=\"password\" placeholder=\"Password\" bind:value={newPassword} />\n <select class=\"admin-input\" bind:value={newRole}>\n <option value=\"user\">User</option>\n <option value=\"admin\">Admin</option>\n </select>\n <button type=\"submit\" class=\"admin-btn\" disabled={!newUsername.trim() || !newPassword.trim()}>Create</button>\n {#if createError}<div class=\"admin-error\">{createError}</div>{/if}\n </form>\n {/if}\n\n {#if loading}\n <p class=\"admin-muted\">Loading...</p>\n {:else if error}\n <p class=\"admin-error\">{error}</p>\n {:else}\n <ul class=\"admin-user-list\">\n {#each users as user (user.id)}\n <li class=\"admin-user-item\">\n {#if editingId === user.id}\n <form class=\"admin-edit-form\" onsubmit={(e) => { e.preventDefault(); saveEdit(); }}>\n <input class=\"admin-input\" type=\"text\" bind:value={editDisplayName} />\n <input class=\"admin-input\" type=\"password\" placeholder=\"New password (leave empty to keep)\" bind:value={editPassword} />\n <select class=\"admin-input\" bind:value={editRole}>\n <option value=\"user\">User</option>\n <option value=\"admin\">Admin</option>\n </select>\n <div class=\"admin-edit-actions\">\n <button type=\"submit\" class=\"admin-btn\">Save</button>\n <button type=\"button\" class=\"admin-btn-secondary\" onclick={() => { editingId = null; }}>Cancel</button>\n </div>\n </form>\n {:else}\n <div class=\"admin-user-info\">\n <span class=\"admin-user-name\">{user.displayName}</span>\n <span class=\"admin-user-meta\">{user.username} · {user.role}</span>\n </div>\n <div class=\"admin-user-actions\">\n <button type=\"button\" class=\"admin-btn-secondary\" onclick={() => startEdit(user)}>Edit</button>\n <button type=\"button\" class=\"admin-btn-danger\" onclick={() => deleteUser(user.id)}>Delete</button>\n </div>\n {/if}\n </li>\n {/each}\n </ul>\n {/if}\n</div>\n\n<style>\n .admin-users { padding: 24px; font-family: system-ui, sans-serif; color: var(--shell-fg); }\n .admin-users-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }\n .admin-users-header h2 { margin: 0; font-size: 18px; }\n .admin-create-form, .admin-edit-form { display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; max-width: 400px; }\n .admin-input { padding: 8px 12px; background: var(--shell-bg, #1a1a2e); color: var(--shell-fg); border: 1px solid var(--shell-border, #3a3a5c); border-radius: var(--shell-radius, 6px); font-size: 13px; }\n .admin-btn { font-weight: 600; font-size: 13px; }\n .admin-btn:disabled { opacity: 0.6; cursor: not-allowed; }\n .admin-btn-secondary { background: transparent; color: var(--shell-fg-subtle); border: 1px solid var(--shell-border); font-size: 12px; }\n .admin-btn-danger { background: transparent; color: var(--shell-error, #d32f2f); border: 1px solid var(--shell-error, #d32f2f); font-size: 12px; }\n .admin-user-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }\n .admin-user-item { display: flex; justify-content: space-between; align-items: center; padding: 12px 16px; background: var(--shell-bg-elevated, #252540); border: 1px solid var(--shell-border, #3a3a5c); border-radius: var(--shell-radius, 6px); }\n .admin-user-info { display: flex; flex-direction: column; gap: 2px; }\n .admin-user-name { font-weight: 600; }\n .admin-user-meta { font-size: 11px; color: var(--shell-fg-subtle); }\n .admin-user-actions { display: flex; gap: 6px; }\n .admin-edit-actions { display: flex; gap: 6px; }\n .admin-error { color: var(--shell-error, #d32f2f); font-size: 13px; }\n .admin-muted { color: var(--shell-fg-muted); font-style: italic; }\n</style>\n","<script lang=\"ts\">\n /**\n * Admin Auth Settings view — toggle auth-related global settings.\n */\n\n import type { GlobalSettings } from '../../auth/types';\n\n let settings = $state<GlobalSettings | null>(null);\n let loading = $state(true);\n let saving = $state(false);\n let error = $state<string | null>(null);\n\n async function fetchSettings() {\n loading = true;\n try {\n const res = await fetch('/api/admin/settings', { credentials: 'include' });\n if (!res.ok) throw new Error('Failed to fetch settings');\n settings = await res.json();\n } catch (err) {\n error = err instanceof Error ? err.message : 'Failed to load settings';\n } finally {\n loading = false;\n }\n }\n\n async function save() {\n if (!settings) return;\n saving = true;\n error = null;\n try {\n const res = await fetch('/api/admin/settings', {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify(settings),\n });\n if (!res.ok) throw new Error('Failed to save settings');\n settings = await res.json();\n } catch (err) {\n error = err instanceof Error ? err.message : 'Failed to save';\n } finally {\n saving = false;\n }\n }\n\n fetchSettings();\n</script>\n\n<div class=\"admin-auth\">\n <h2>Auth Settings</h2>\n\n {#if loading}\n <p class=\"admin-muted\">Loading...</p>\n {:else if settings}\n <div class=\"admin-auth-fields\">\n <label class=\"admin-toggle\">\n <input type=\"checkbox\" bind:checked={settings.auth.required} />\n <span>Require sign-in</span>\n <span class=\"admin-hint\">When enabled, unauthenticated visitors see a sign-in wall.</span>\n </label>\n\n <label class=\"admin-toggle\">\n <input type=\"checkbox\" bind:checked={settings.auth.guestAllowed} />\n <span>Allow guest browsing</span>\n <span class=\"admin-hint\">When sign-in is required, guests can still browse with session-only data.</span>\n </label>\n\n <label class=\"admin-toggle\">\n <input type=\"checkbox\" bind:checked={settings.auth.selfRegistration} />\n <span>Self-registration</span>\n <span class=\"admin-hint\">Visitors can create their own accounts from the sign-in screen.</span>\n </label>\n\n <label class=\"admin-field\">\n <span>Session lifetime (hours)</span>\n <input type=\"number\" class=\"admin-input admin-input-sm\" min=\"1\" max=\"8760\" bind:value={settings.auth.sessionTTL} />\n </label>\n\n <button type=\"button\" class=\"admin-btn\" onclick={save} disabled={saving}>\n {saving ? 'Saving...' : 'Save'}\n </button>\n </div>\n\n {#if error}\n <div class=\"admin-error\">{error}</div>\n {/if}\n {/if}\n</div>\n\n<style>\n .admin-auth { padding: 24px; font-family: system-ui, sans-serif; color: var(--shell-fg); }\n .admin-auth h2 { margin: 0 0 16px; font-size: 18px; }\n .admin-auth-fields { display: flex; flex-direction: column; gap: 16px; max-width: 480px; }\n .admin-toggle { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; cursor: pointer; }\n .admin-toggle input { accent-color: var(--shell-accent, #7c7cf0); }\n .admin-hint { flex-basis: 100%; font-size: 11px; color: var(--shell-fg-muted); margin-left: 24px; }\n .admin-field { display: flex; flex-direction: column; gap: 4px; }\n .admin-field span { font-size: 13px; }\n .admin-input { padding: 8px 12px; background: var(--shell-bg); color: var(--shell-fg); border: 1px solid var(--shell-border); border-radius: var(--shell-radius, 6px); font-size: 13px; }\n .admin-input-sm { max-width: 120px; }\n .admin-btn { padding: 8px 16px; font-weight: 600; align-self: flex-start; }\n .admin-btn:disabled { opacity: 0.6; cursor: not-allowed; }\n .admin-error { margin-top: 8px; color: var(--shell-error, #d32f2f); font-size: 13px; }\n .admin-muted { color: var(--shell-fg-muted); font-style: italic; }\n</style>\n","<script lang=\"ts\">\n /**\n * Admin System view — server status, restart, and package-bundle cache policy.\n */\n\n const SNAP_POINTS: Array<{ value: number; label: string }> = [\n { value: 0, label: 'Off (no-store)' },\n { value: 5, label: '5s (dev)' },\n { value: 60, label: '1 min' },\n { value: 3600, label: '1 hour' },\n { value: 86400, label: '1 day' },\n { value: 31536000, label: '1 year' },\n ];\n\n let version = $state('...');\n let restarting = $state(false);\n let restartError = $state<string | null>(null);\n\n let cacheMaxAge = $state(31536000);\n let loadedMaxAge = $state(31536000);\n let savingCache = $state(false);\n let cacheError = $state<string | null>(null);\n\n const dirty = $derived(cacheMaxAge !== loadedMaxAge);\n const humanized = $derived(humanize(cacheMaxAge));\n\n function humanize(sec: number): string {\n if (sec === 0) return '0 seconds (off — browsers never cache)';\n if (sec < 60) return `${sec} seconds`;\n if (sec < 3600) return `${Math.round(sec / 60)} minutes`;\n if (sec < 86400) return `${Math.round(sec / 3600)} hours`;\n if (sec < 31536000) return `${Math.round(sec / 86400)} days`;\n return `${Math.round(sec / 31536000)} years`;\n }\n\n async function fetchVersion() {\n try {\n const res = await fetch('/api/version');\n if (res.ok) {\n const body = await res.json();\n version = body.version;\n }\n } catch { /* ignore */ }\n }\n\n async function fetchSettings() {\n try {\n const res = await fetch('/api/admin/settings', { credentials: 'include' });\n if (res.ok) {\n const body = await res.json();\n const age = body.packages?.cacheMaxAge ?? 31536000;\n cacheMaxAge = age;\n loadedMaxAge = age;\n }\n } catch { /* ignore */ }\n }\n\n async function saveCache() {\n savingCache = true;\n cacheError = null;\n try {\n const res = await fetch('/api/admin/settings', {\n method: 'PUT',\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ packages: { cacheMaxAge } }),\n });\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n cacheError = body.error || 'Save failed';\n } else {\n const body = await res.json();\n loadedMaxAge = body.packages?.cacheMaxAge ?? cacheMaxAge;\n cacheMaxAge = loadedMaxAge;\n }\n } catch {\n cacheError = 'Network error';\n } finally {\n savingCache = false;\n }\n }\n\n async function restart() {\n restarting = true;\n restartError = null;\n try {\n const res = await fetch('/api/admin/restart', {\n method: 'POST',\n credentials: 'include',\n });\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n restartError = body.error || 'Restart failed';\n restarting = false;\n }\n // If 202, server will restart — page will reconnect\n } catch {\n restartError = 'Network error';\n restarting = false;\n }\n }\n\n fetchVersion();\n fetchSettings();\n</script>\n\n<div class=\"admin-system\">\n <h2>System</h2>\n\n <div class=\"admin-system-info\">\n <div class=\"admin-system-row\">\n <span class=\"admin-system-label\">Server version</span>\n <span>{version}</span>\n </div>\n </div>\n\n <section class=\"admin-system-section\">\n <h3>Package bundle cache</h3>\n <p class=\"admin-system-hint\">\n Controls the <code>Cache-Control</code> header on <code>/packages/:id/client.js</code>.\n Set to <strong>0</strong> during development so drop-in bundle replacements take effect on F5.\n Use a long value in production.\n </p>\n\n <input\n type=\"range\"\n min=\"0\"\n max=\"31536000\"\n step=\"1\"\n bind:value={cacheMaxAge}\n disabled={savingCache}\n />\n <div class=\"admin-system-readout\">\n <code>{cacheMaxAge}</code> — {humanized}\n </div>\n\n <div class=\"admin-system-snaps\">\n {#each SNAP_POINTS as snap (snap.value)}\n <button\n type=\"button\"\n class=\"admin-snap\"\n class:active={cacheMaxAge === snap.value}\n onclick={() => (cacheMaxAge = snap.value)}\n disabled={savingCache}\n >\n {snap.label}\n </button>\n {/each}\n </div>\n\n <div class=\"admin-system-actions\">\n <button\n type=\"button\"\n class=\"admin-btn\"\n onclick={saveCache}\n disabled={!dirty || savingCache}\n >\n {savingCache ? 'Saving...' : 'Save'}\n </button>\n <button\n type=\"button\"\n class=\"admin-btn-ghost\"\n onclick={() => (cacheMaxAge = loadedMaxAge)}\n disabled={!dirty || savingCache}\n >\n Reset\n </button>\n {#if cacheError}\n <div class=\"admin-error\">{cacheError}</div>\n {/if}\n </div>\n </section>\n\n <section class=\"admin-system-section\">\n <h3>Server control</h3>\n <div class=\"admin-system-actions\">\n <button type=\"button\" class=\"admin-btn-danger\" onclick={restart} disabled={restarting}>\n {restarting ? 'Restarting...' : 'Restart server'}\n </button>\n {#if restartError}\n <div class=\"admin-error\">{restartError}</div>\n {/if}\n </div>\n </section>\n</div>\n\n<style>\n .admin-system { padding: 24px; font-family: system-ui, sans-serif; color: var(--shell-fg); }\n .admin-system h2 { margin: 0 0 16px; font-size: 18px; }\n .admin-system h3 { margin: 0 0 8px; font-size: 14px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--shell-fg-subtle); }\n .admin-system-info { margin-bottom: 24px; }\n .admin-system-row { display: flex; gap: 12px; padding: 8px 0; border-bottom: 1px solid var(--shell-border, #3a3a5c); font-size: 13px; }\n .admin-system-label { color: var(--shell-fg-subtle); min-width: 140px; }\n .admin-system-section { margin-bottom: 24px; padding-bottom: 16px; border-bottom: 1px solid var(--shell-border, #3a3a5c); }\n .admin-system-section:last-child { border-bottom: none; }\n .admin-system-hint { font-size: 13px; color: var(--shell-fg-subtle); margin: 0 0 12px; }\n .admin-system-readout { font-size: 13px; margin: 8px 0 12px; }\n .admin-system-snaps { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 12px; }\n .admin-snap { padding: 4px 10px; font-size: 12px; background: transparent; border: 1px solid var(--shell-border, #3a3a5c); color: var(--shell-fg); cursor: pointer; border-radius: var(--shell-radius-sm, 3px); }\n .admin-snap.active { background: var(--shell-accent, #4a7bd4); color: var(--shell-bg); border-color: var(--shell-accent, #4a7bd4); }\n .admin-snap:disabled { opacity: 0.5; cursor: not-allowed; }\n .admin-system-actions { display: flex; flex-direction: row; gap: 8px; align-items: center; flex-wrap: wrap; }\n .admin-btn { padding: 8px 16px; background: var(--shell-accent, #4a7bd4); color: var(--shell-bg); border: 1px solid var(--shell-accent, #4a7bd4); font-weight: 600; cursor: pointer; border-radius: var(--shell-radius-sm, 3px); }\n .admin-btn:disabled { opacity: 0.5; cursor: not-allowed; }\n .admin-btn-ghost { padding: 8px 16px; background: transparent; color: var(--shell-fg); border: 1px solid var(--shell-border, #3a3a5c); cursor: pointer; border-radius: var(--shell-radius-sm, 3px); }\n .admin-btn-ghost:disabled { opacity: 0.5; cursor: not-allowed; }\n .admin-btn-danger { padding: 8px 16px; background: transparent; color: var(--shell-error, #d32f2f); border: 1px solid var(--shell-error, #d32f2f); font-weight: 600; cursor: pointer; border-radius: var(--shell-radius-sm, 3px); }\n .admin-btn-danger:disabled { opacity: 0.6; cursor: not-allowed; }\n .admin-error { color: var(--shell-error, #d32f2f); font-size: 13px; }\n input[type=\"range\"] { width: 100%; max-width: 480px; }\n</style>\n","<script lang=\"ts\">\n /**\n * Admin API Keys view — list, create, reveal, revoke API keys.\n */\n\n interface ApiKeyPublic {\n id: string;\n label: string;\n createdAt: string;\n }\n\n let keys = $state<ApiKeyPublic[]>([]);\n let loading = $state(true);\n let error = $state<string | null>(null);\n\n // Create form\n let showCreate = $state(false);\n let newLabel = $state('');\n let createError = $state<string | null>(null);\n\n // Just-created key — the raw bearer value is returned once by the server.\n // Displayed until the admin dismisses it, then never recoverable.\n let justCreated = $state<{ id: string; key: string } | null>(null);\n\n // Delete confirmation\n let confirmingId = $state<string | null>(null);\n\n async function fetchKeys() {\n loading = true;\n error = null;\n try {\n const res = await fetch('/api/admin/keys', { credentials: 'include' });\n if (!res.ok) throw new Error('Failed to fetch keys');\n keys = await res.json();\n } catch (err) {\n error = err instanceof Error ? err.message : 'Failed to load keys';\n } finally {\n loading = false;\n }\n }\n\n async function createKey() {\n createError = null;\n try {\n const res = await fetch('/api/admin/keys', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify({ label: newLabel }),\n });\n if (!res.ok) {\n const body = await res.json().catch(() => ({}));\n createError = body.error || 'Failed to create key';\n return;\n }\n const created: { id: string; key: string } = await res.json();\n justCreated = { id: created.id, key: created.key };\n newLabel = '';\n showCreate = false;\n await fetchKeys();\n } catch {\n createError = 'Network error';\n }\n }\n\n async function revokeKey(id: string) {\n confirmingId = null;\n try {\n await fetch(`/api/admin/keys/${id}`, {\n method: 'DELETE',\n credentials: 'include',\n });\n if (justCreated?.id === id) justCreated = null;\n await fetchKeys();\n } catch { /* ignore */ }\n }\n\n function formatDate(iso: string): string {\n return new Date(iso).toLocaleDateString(undefined, {\n year: 'numeric', month: 'short', day: 'numeric',\n });\n }\n\n fetchKeys();\n</script>\n\n<div class=\"admin-keys\">\n <div class=\"admin-keys-header\">\n <h2>API Keys</h2>\n <button type=\"button\" class=\"admin-btn\" onclick={() => { showCreate = !showCreate; }}>\n {showCreate ? 'Cancel' : 'New key'}\n </button>\n </div>\n\n {#if justCreated}\n <div class=\"admin-key-created\">\n <div class=\"admin-key-created-label\">New key — copy now, it won't be shown again:</div>\n <code class=\"admin-key-value\">{justCreated.key}</code>\n <button type=\"button\" class=\"admin-btn-secondary\" onclick={() => { justCreated = null; }}>Dismiss</button>\n </div>\n {/if}\n\n {#if showCreate}\n <form class=\"admin-create-form\" onsubmit={(e) => { e.preventDefault(); createKey(); }}>\n <input class=\"admin-input\" type=\"text\" placeholder=\"Key label\" bind:value={newLabel} />\n <button type=\"submit\" class=\"admin-btn\" disabled={!newLabel.trim()}>Create</button>\n {#if createError}<div class=\"admin-error\">{createError}</div>{/if}\n </form>\n {/if}\n\n {#if loading}\n <p class=\"admin-muted\">Loading...</p>\n {:else if error}\n <p class=\"admin-error\">{error}</p>\n {:else if keys.length === 0}\n <p class=\"admin-muted\">No API keys. Create one to enable external access.</p>\n {:else}\n <ul class=\"admin-key-list\">\n {#each keys as k (k.id)}\n <li class=\"admin-key-item\">\n <div class=\"admin-key-info\">\n <span class=\"admin-key-label\">{k.label}</span>\n <span class=\"admin-key-meta\">{k.id} &middot; {formatDate(k.createdAt)}</span>\n </div>\n <div class=\"admin-key-actions\">\n {#if confirmingId === k.id}\n <button type=\"button\" class=\"admin-btn-danger\" onclick={() => revokeKey(k.id)}>Confirm</button>\n <button type=\"button\" class=\"admin-btn-secondary\" onclick={() => { confirmingId = null; }}>Cancel</button>\n {:else}\n <button type=\"button\" class=\"admin-btn-danger\" onclick={() => { confirmingId = k.id; }}>Revoke</button>\n {/if}\n </div>\n </li>\n {/each}\n </ul>\n {/if}\n</div>\n\n<style>\n .admin-keys { padding: 24px; font-family: system-ui, sans-serif; color: var(--shell-fg); }\n .admin-keys-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }\n .admin-keys-header h2 { margin: 0; font-size: 18px; }\n .admin-create-form { display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; max-width: 400px; }\n .admin-input { padding: 8px 12px; background: var(--shell-bg, #1a1a2e); color: var(--shell-fg); border: 1px solid var(--shell-border, #3a3a5c); border-radius: var(--shell-radius, 6px); font-size: 13px; }\n .admin-btn { font-weight: 600; font-size: 13px; }\n .admin-btn:disabled { opacity: 0.6; cursor: not-allowed; }\n .admin-btn-secondary { background: transparent; color: var(--shell-fg-subtle); border: 1px solid var(--shell-border); font-size: 12px; }\n .admin-btn-danger { background: transparent; color: var(--shell-error, #d32f2f); border: 1px solid var(--shell-error, #d32f2f); font-size: 12px; }\n .admin-key-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }\n .admin-key-item { display: flex; justify-content: space-between; align-items: center; padding: 12px 16px; background: var(--shell-bg-elevated, #252540); border: 1px solid var(--shell-border, #3a3a5c); border-radius: var(--shell-radius, 6px); }\n .admin-key-info { display: flex; flex-direction: column; gap: 2px; }\n .admin-key-label { font-weight: 600; }\n .admin-key-meta { font-size: 11px; color: var(--shell-fg-subtle); }\n .admin-key-value { font-size: 12px; color: var(--shell-fg-muted); background: var(--shell-bg, #1a1a2e); padding: 2px 6px; border-radius: 3px; margin-top: 2px; word-break: break-all; }\n .admin-key-actions { display: flex; gap: 6px; flex-shrink: 0; }\n .admin-muted { color: var(--shell-fg-muted); font-style: italic; }\n .admin-error { color: var(--shell-error, #d32f2f); font-size: 13px; }\n</style>\n","/*\n * Admin shard — framework-shipped shard for user management,\n * auth settings, system controls, and API key management.\n *\n * Contributes four views:\n * - `sh3-admin:users` — user CRUD\n * - `sh3-admin:auth` — auth settings toggles\n * - `sh3-admin:system` — restart + status\n * - `sh3-admin:keys` — API key lifecycle\n *\n * `.svelte.ts` because mounting Svelte components requires rune access.\n */\n\nimport { mount, unmount } from 'svelte';\nimport UsersView from './UsersView.svelte';\nimport AuthSettingsView from './AuthSettingsView.svelte';\nimport SystemView from './SystemView.svelte';\nimport ApiKeysView from './ApiKeysView.svelte';\nimport { VERSION } from '../../version';\nimport type { Shard, ViewFactory, ViewHandle, MountContext, ShardContext } from '../../shards/types';\n\n/** Module-level server URL, set during activate. */\nexport let adminServerUrl = '';\n\nexport const adminShard: Shard = {\n manifest: {\n id: 'sh3-admin',\n label: 'Admin',\n version: VERSION,\n views: [\n { id: 'sh3-admin:users', label: 'Users' },\n { id: 'sh3-admin:auth', label: 'Auth Settings' },\n { id: 'sh3-admin:system', label: 'System' },\n { id: 'sh3-admin:keys', label: 'API Keys' },\n ],\n },\n\n activate(ctx: ShardContext) {\n const usersFactory: ViewFactory = {\n mount(container: HTMLElement, _context: MountContext): ViewHandle {\n const instance = mount(UsersView, { target: container });\n return { unmount() { unmount(instance); } };\n },\n };\n\n const authFactory: ViewFactory = {\n mount(container: HTMLElement, _context: MountContext): ViewHandle {\n const instance = mount(AuthSettingsView, { target: container });\n return { unmount() { unmount(instance); } };\n },\n };\n\n const systemFactory: ViewFactory = {\n mount(container: HTMLElement, _context: MountContext): ViewHandle {\n const instance = mount(SystemView, { target: container });\n return { unmount() { unmount(instance); } };\n },\n };\n\n const keysFactory: ViewFactory = {\n mount(container: HTMLElement, _context: MountContext): ViewHandle {\n const instance = mount(ApiKeysView, { target: container });\n return { unmount() { unmount(instance); } };\n },\n };\n\n ctx.registerView('sh3-admin:users', usersFactory);\n ctx.registerView('sh3-admin:auth', authFactory);\n ctx.registerView('sh3-admin:system', systemFactory);\n ctx.registerView('sh3-admin:keys', keysFactory);\n },\n};\n","/**\n * Built-in Admin app — user management, auth settings, and system controls.\n * Framework-shipped: registered in host.ts during bootstrap.\n * Admin-gated via manifest flag (ADR-011).\n */\n\nimport type { App } from '../../apps/types';\nimport { VERSION } from '../../version';\n\nexport const adminApp: App = {\n manifest: {\n id: 'sh3-admin-app',\n label: 'Admin',\n version: VERSION,\n requiredShards: ['sh3-admin'],\n layoutVersion: 1,\n admin: true,\n },\n initialLayout: {\n type: 'tabs',\n activeTab: 0,\n tabs: [\n { slotId: 'admin.users', viewId: 'sh3-admin:users', label: 'Users' },\n { slotId: 'admin.auth', viewId: 'sh3-admin:auth', label: 'Auth' },\n { slotId: 'admin.system', viewId: 'sh3-admin:system', label: 'System' },\n { slotId: 'admin.keys', viewId: 'sh3-admin:keys', label: 'Keys' },\n ],\n },\n};\n","/*\n * One-time migration of persisted keys that were written under the former\n * `__shell__` pseudo-shard id. Runs once per browser, gated by a\n * localStorage flag. Idempotent — safe to call on every boot.\n *\n * Scope:\n * 1. localStorage: sh3:user:__shell__:theme → sh3:user:__sh3core__:theme\n * 2. workspace state zone: every key beginning with `__shell__:`\n * (includes `__shell__:last-app` and `__shell__:app:<appId>` entries)\n * is copied to `__sh3core__:<rest>` and the old key is deleted.\n *\n * See docs/superpowers/specs/2026-04-10-shell-shard-design.md § Step 0.\n */\n\nconst FLAG_KEY = 'sh3:migrations:shell-rename:done';\nconst OLD_PREFIX = '__shell__:';\nconst NEW_PREFIX = '__sh3core__:';\nconst OLD_THEME_KEY = 'sh3:user:__shell__:theme';\nconst NEW_THEME_KEY = 'sh3:user:__sh3core__:theme';\n\nexport interface WorkspaceZoneStore {\n keys(): string[];\n read(key: string): unknown;\n write(key: string, value: unknown): void;\n delete(key: string): void;\n}\n\n/**\n * Run the `__shell__` → `__sh3core__` rename migration. Call once at boot,\n * before any shard activates. If the flag is already set, returns immediately.\n *\n * @param zone An adapter around the workspace state-zone backend used for\n * iterating and rewriting persisted shard-prefixed keys.\n * @param storage The localStorage-like object (pass `globalThis.localStorage`\n * in the browser; pass a mock in tests).\n */\nexport function runShellRenameMigration(\n zone: WorkspaceZoneStore,\n storage: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>,\n): void {\n if (storage.getItem(FLAG_KEY)) {\n return;\n }\n\n // 1. Migrate localStorage theme key\n const theme = storage.getItem(OLD_THEME_KEY);\n if (theme !== null && storage.getItem(NEW_THEME_KEY) === null) {\n storage.setItem(NEW_THEME_KEY, theme);\n storage.removeItem(OLD_THEME_KEY);\n }\n\n // 2. Migrate workspace state zone keys with the old prefix\n for (const key of zone.keys()) {\n if (!key.startsWith(OLD_PREFIX)) continue;\n const newKey = NEW_PREFIX + key.slice(OLD_PREFIX.length);\n const value = zone.read(key);\n zone.write(newKey, value);\n zone.delete(key);\n }\n\n storage.setItem(FLAG_KEY, '1');\n}\n","/*\n * Web platform emitter for the navigation back-cascade.\n *\n * Browser back/forward (and mouse X1/X2 buttons, which the browser maps\n * to history navigation) all funnel through `popstate`. The event itself\n * doesn't report direction, so we maintain a three-state \"sandwich\":\n *\n * position 0: { sh3: 'anchor' } ← popstate here = back was pressed\n * position 1: { sh3: 'main' } ← resting position\n * position 2: { sh3: 'forward-bumper' } ← popstate here = forward was pressed\n *\n * On every consumed signal we re-anchor to 'main' so the user never\n * navigates out of SH3 via the back/forward chord.\n *\n * Page reload re-runs install. The two extra synthetic history entries\n * are accepted noise; no URL changes.\n *\n * Known limitation: third-party `pushState` (HMR, libraries) clobbers the\n * forward-bumper. SH3 framework code must not call pushState directly.\n */\n\nimport { dispatchBack, dispatchForward } from './back-stack';\n\nlet installed = false;\nlet listener: ((e: PopStateEvent) => void) | null = null;\n\nexport function installWebEmitter(): void {\n if (installed) return;\n installed = true;\n\n listener = (e: PopStateEvent) => {\n const tag = (e.state as { sh3?: string } | null)?.sh3;\n if (tag === 'anchor') {\n dispatchBack();\n history.forward();\n } else if (tag === 'forward-bumper') {\n dispatchForward();\n history.back();\n }\n // tag === 'main' (or undefined) → echo from our own correction; ignore.\n };\n window.addEventListener('popstate', listener);\n\n history.replaceState({ sh3: 'anchor' }, '');\n history.pushState({ sh3: 'main' }, '');\n history.pushState({ sh3: 'forward-bumper' }, '');\n history.back();\n}\n\n/** @internal — test cleanup. Removes the listener; does not unwind history. */\nexport function __uninstallWebEmitterForTest(): void {\n if (listener) {\n window.removeEventListener('popstate', listener);\n listener = null;\n }\n installed = false;\n}\n","/*\n * Host surface — functions `main.ts` (and only main.ts) calls.\n *\n * Registration APIs (`registerShard`, `registerApp`) are data-only and\n * safe to call at any time; a future runtime loader uses them identically\n * to hot-install registration at runtime.\n *\n * `bootstrap()` runs the post-registration boot sequence: it registers\n * framework-owned shards and apps (filtering any the host excludes via\n * BootstrapConfig), walks the registered-shards map and activates every\n * self-starting shard, then reads the last-app user-zone entry and\n * either launches that app or leaves the shell on home.\n *\n * This file is intentionally NOT re-exported through `api.ts`. The\n * import-hygiene rule is: shards and apps import from `api.ts`, the host\n * imports from `host.ts`.\n */\n\nimport {\n registerShard as registerShardInternal,\n activateShard,\n registeredShards,\n} from './shards/activate.svelte';\nimport { addAutostartShard } from './actions/state.svelte';\nimport { registerApp, registeredApps } from './apps/registry.svelte';\nimport { launchApp, readLastApp, clearLastApp } from './apps/lifecycle';\nimport { sh3coreShard } from './sh3core-shard/sh3coreShard.svelte';\nimport { shellShard } from './shell-shard/shellShard.svelte';\nimport { storeShard } from './app/store/storeShard.svelte';\nimport { projectsShard } from './projects-shard/projectsShard.svelte';\nimport { appearanceShard } from './app-appearance';\nimport { __setBackend, backends } from './state/zones.svelte';\nimport { loadInstalledPackages } from './registry/installer';\nimport { setLocalOwner } from './auth/index';\nimport { storeApp } from './app/store/storeApp';\nimport { adminShard } from './app/admin/adminShard.svelte';\nimport { adminApp } from './app/admin/adminApp';\nimport {\n runShellRenameMigration,\n type WorkspaceZoneStore,\n} from './migrations/shell-rename';\nimport { setLifecycleHandlers } from './navigation/back-stack';\nimport { installWebEmitter } from './navigation/platform-web';\nimport { returnToHome } from './apps/lifecycle';\nexport { __setBackend };\nexport { setLocalOwner };\n\nexport { __setActiveScope, __setTenantId, __setDocumentBackend } from './documents/config';\n\nexport function registerShard(shard: Parameters<typeof registerShardInternal>[0]): void {\n registerShardInternal(shard);\n}\n\nexport { registerApp };\n\nexport interface BootstrapConfig {\n /** Framework shard IDs to skip registration for */\n excludeShards?: string[];\n}\n\n/**\n * Adapter from the workspace-zone backend to the minimal KV shape the\n * `__shell__` → `__sh3core__` migration needs. Kept local to host.ts so\n * the migration module stays backend-agnostic.\n */\nfunction createWorkspaceZoneAdapter(): WorkspaceZoneStore {\n const backend = backends.workspace;\n return {\n keys: () => backend.list(),\n read: (key: string) => backend.read(key),\n write: (key: string, value: unknown) => backend.write(key, value),\n delete: (key: string) => backend.delete(key),\n };\n}\n\nexport async function bootstrap(config?: BootstrapConfig): Promise<void> {\n // Run before anything touches the workspace zone so renamed keys are\n // already in place when shards activate.\n if (typeof globalThis.localStorage !== 'undefined') {\n runShellRenameMigration(createWorkspaceZoneAdapter(), globalThis.localStorage);\n // Per ADR-002 amendment, app workspace state is keyed by (scopeId, appId).\n // Rewrite legacy unkeyed entries to the personal scope namespace.\n const { migrateLegacyWorkspaceKeys } = await import('./apps/workspace-rekey');\n const { getActiveScopeId } = await import('./documents/config');\n migrateLegacyWorkspaceKeys(getActiveScopeId());\n }\n\n const exShards = new Set(config?.excludeShards);\n\n // 1. Framework-owned shards\n const frameworkShards = [sh3coreShard, shellShard, storeShard, adminShard, projectsShard, appearanceShard];\n for (const shard of frameworkShards) {\n if (!exShards.has(shard.manifest.id)) {\n registerShardInternal(shard);\n }\n }\n\n // 2. Framework-shipped apps\n const frameworkApps = [storeApp, adminApp];\n for (const app of frameworkApps) {\n registerApp(app);\n }\n\n // 3. Load any packages installed in a previous session from IndexedDB\n await loadInstalledPackages();\n\n // 4. Activate every self-starting shard. Track them in the dispatcher's\n // autostartShards set so the `'app'` action scope treats their actions as\n // ambient (active even inside apps that don't list them as required).\n for (const [id, shard] of registeredShards) {\n if (shard.autostart) {\n addAutostartShard(id);\n try {\n await activateShard(id, { phase: 'autostart' });\n } catch {\n // Already logged + recorded in erroredShards by activateShard.\n // One bad self-starting shard must not prevent the shell from booting.\n }\n }\n }\n\n // 5. Read the last-active app from the user zone. If auto-launch fails,\n // clear the slot so the next reload lands on home instead of looping\n // into the same failure. No toast — the user did not initiate this.\n const lastId = readLastApp();\n if (lastId && registeredApps.has(lastId)) {\n try {\n await launchApp(lastId);\n } catch (err) {\n console.error(`[sh3] Auto-launch of \"${lastId}\" failed:`, err);\n clearLastApp();\n }\n }\n\n // 6. Wire navigation lifecycle handlers and install the web back/forward\n // emitter. Order: after autostart shards and the optional last-app\n // launch, so the emitter's synthetic history entries don't interleave\n // with boot-time launches. The window/history guard makes bootstrap\n // safe to call from non-DOM environments (Node tests, future SSR).\n setLifecycleHandlers({ returnToHome, launchApp });\n if (typeof window !== 'undefined' && typeof history !== 'undefined') {\n installWebEmitter();\n }\n}\n\nexport { installPackage, listInstalledPackages } from './registry/installer';\n","<script lang=\"ts\">\n /*\n * ResizableSplitter — a generic N-pane split container with drag handles.\n *\n * Used by <LayoutRenderer> to implement `split` nodes. Also available as a\n * standalone primitive for shards that need internal split UI.\n *\n * Sizing model mirrors docs/design/layout.md:\n * - Each pane has a size value + a mode ('fr' | 'px').\n * - 'fr' panes are proportional flex-grow children and absorb window\n * resize deltas and drag deltas against each other.\n * - 'px' panes are pixel-pinned (flex: 0 0 Npx) and stay fixed during\n * window resize; dragging a handle adjacent to a px pane resizes the\n * px pane in absolute pixels.\n *\n * `sizes` is bindable so the parent (layout tree) can observe user drags.\n * Phase 2 does not yet persist sizes — phase 7 wires that up.\n */\n\n import type { Snippet } from 'svelte';\n import type { SizeMode, SplitDirection } from '../layout/types';\n\n const MIN_PX = 40;\n const COLLAPSED_PX = 28;\n\n let {\n direction,\n sizes,\n pinned,\n collapsed,\n fixed,\n count,\n pane,\n onResize,\n onCollapseToggle,\n }: {\n direction: SplitDirection;\n /**\n * Per-pane sizes, read-only. The splitter computes flex bases\n * from this array but does not mutate it — writes go out through\n * `onResize`. Treating sizes as read-only keeps the primitive\n * decoupled from how the caller stores its layout, and sidesteps\n * Svelte 5's `ownership_invalid_mutation` warning that fires when\n * a child component writes into a prop it didn't own.\n */\n sizes: number[];\n pinned?: SizeMode[];\n /** Per-pane collapsed state. Omitted entries default to false. */\n collapsed?: boolean[];\n /**\n * Per-pane fixed flag. A fixed pane has no collapse widget and\n * the handles on either side of it are frozen (non-interactive,\n * rendered thinner). A non-fixed pane whose every neighbor is\n * fixed also loses its collapse widget.\n */\n fixed?: boolean[];\n /** Number of panes — `sizes.length` should match. */\n count: number;\n /** Snippet invoked once per pane with the pane index. */\n pane: Snippet<[number]>;\n /**\n * Called whenever the splitter wants to update a pane's size.\n * The parent is expected to write the value back into whatever\n * it stores sizes in. A single per-index callback (rather than a\n * whole-array setter) matches the drag math, which updates at\n * most two panes per move, and avoids allocating a new array on\n * every pointermove frame.\n */\n onResize?: (index: number, value: number) => void;\n /** Called when a collapsed pane's header is clicked to toggle. */\n onCollapseToggle?: (index: number, collapsed: boolean) => void;\n } = $props();\n\n let container: HTMLDivElement;\n\n const modeOf = (i: number): SizeMode => pinned?.[i] ?? 'fr';\n const isCollapsed = (i: number): boolean => collapsed?.[i] ?? false;\n const isFixed = (i: number): boolean => fixed?.[i] ?? false;\n const isHandleFrozen = (i: number): boolean => isFixed(i) || isFixed(i + 1);\n\n function canCollapse(i: number): boolean {\n if (isFixed(i)) return false;\n const left = i > 0 ? !isFixed(i - 1) : false;\n const right = i < count - 1 ? !isFixed(i + 1) : false;\n return left || right;\n }\n\n /** CSS `flex` shorthand for pane i. */\n function flexFor(i: number): string {\n if (isCollapsed(i)) return `0 0 ${COLLAPSED_PX}px`;\n if (modeOf(i) === 'px') return `0 0 ${Math.max(MIN_PX, sizes[i])}px`;\n // Proportional: grow = sizes[i], shrink = 1, basis = 0\n return `${Math.max(0.0001, sizes[i])} 1 0`;\n }\n\n type DragState = {\n handleIndex: number; // boundary between child handleIndex and handleIndex+1\n startClient: number; // pointer x/y at drag start\n startSizes: number[]; // sizes snapshot at drag start\n containerPx: number; // container length along split axis\n totalFr: number; // sum of 'fr' sizes at drag start\n frAvailPx: number; // pixels available to fr children at drag start\n };\n\n let drag: DragState | null = $state(null);\n\n function beginDrag(e: PointerEvent, handleIndex: number) {\n // Disable resize handles adjacent to collapsed or fixed panes.\n if (isCollapsed(handleIndex) || isCollapsed(handleIndex + 1)) return;\n if (isHandleFrozen(handleIndex)) return;\n\n e.preventDefault();\n (e.target as HTMLElement).setPointerCapture(e.pointerId);\n\n const rect = container.getBoundingClientRect();\n const containerPx = direction === 'horizontal' ? rect.width : rect.height;\n\n // Sum fr weights and subtract pixel-pinned pane sizes to get the pixel\n // space the fr children collectively occupy.\n let totalFr = 0;\n let pxUsed = 0;\n for (let i = 0; i < sizes.length; i++) {\n if (modeOf(i) === 'fr') totalFr += sizes[i];\n else pxUsed += Math.max(MIN_PX, sizes[i]);\n }\n\n drag = {\n handleIndex,\n startClient: direction === 'horizontal' ? e.clientX : e.clientY,\n startSizes: sizes.slice(),\n containerPx,\n totalFr,\n frAvailPx: Math.max(1, containerPx - pxUsed),\n };\n }\n\n function moveDrag(e: PointerEvent) {\n if (!drag) return;\n const client = direction === 'horizontal' ? e.clientX : e.clientY;\n const deltaPx = client - drag.startClient;\n\n const a = drag.handleIndex;\n const b = a + 1;\n const modeA = modeOf(a);\n const modeB = modeOf(b);\n\n // Send updates through onResize rather than mutating the prop\n // directly. Writing into `sizes` would trip Svelte 5's ownership\n // warning; the parent owns the array and re-derives it for us.\n const frPerPx = drag.totalFr / drag.frAvailPx;\n\n if (modeA === 'fr' && modeB === 'fr') {\n // Convert delta px to fr; clamp both sides to MIN_PX worth of fr.\n // Positive deltaFr grows pane a and shrinks pane b, so:\n // - upper bound: deltaFr ≤ startSizes[b] - minFr (stop when b hits min)\n // - lower bound: deltaFr ≥ -(startSizes[a] - minFr) (stop when a hits min)\n const minFr = MIN_PX * frPerPx;\n const deltaFr = deltaPx * frPerPx;\n const maxDelta = drag.startSizes[b] - minFr;\n const minDelta = -(drag.startSizes[a] - minFr);\n const clamped = Math.min(Math.max(deltaFr, minDelta), maxDelta);\n onResize?.(a, drag.startSizes[a] + clamped);\n onResize?.(b, drag.startSizes[b] - clamped);\n } else if (modeA === 'px' && modeB === 'fr') {\n const maxDelta = drag.frAvailPx - MIN_PX; // fr side must keep MIN_PX\n const minDelta = MIN_PX - drag.startSizes[a];\n onResize?.(\n a,\n drag.startSizes[a] + Math.min(Math.max(deltaPx, minDelta), maxDelta),\n );\n } else if (modeA === 'fr' && modeB === 'px') {\n const maxDelta = drag.startSizes[b] - MIN_PX;\n const minDelta = -(drag.frAvailPx - MIN_PX);\n onResize?.(\n b,\n drag.startSizes[b] - Math.min(Math.max(deltaPx, minDelta), maxDelta),\n );\n } else {\n // both px\n const maxDelta = drag.startSizes[b] - MIN_PX;\n const minDelta = -(drag.startSizes[a] - MIN_PX);\n const clamped = Math.min(Math.max(deltaPx, minDelta), maxDelta);\n onResize?.(a, drag.startSizes[a] + clamped);\n onResize?.(b, drag.startSizes[b] - clamped);\n }\n }\n\n function endDrag(e: PointerEvent) {\n if (!drag) return;\n (e.target as HTMLElement).releasePointerCapture(e.pointerId);\n drag = null;\n }\n</script>\n\n<div\n class=\"splitter\"\n class:horizontal={direction === 'horizontal'}\n class:vertical={direction === 'vertical'}\n bind:this={container}\n>\n {#each Array(count) as _, i (i)}\n <div\n class=\"splitter-pane\"\n class:collapsed={isCollapsed(i)}\n style=\"flex: {flexFor(i)};\"\n >\n {#if isCollapsed(i)}\n <button\n type=\"button\"\n class=\"collapse-header\"\n class:horizontal={direction === 'horizontal'}\n class:vertical={direction === 'vertical'}\n onclick={() => onCollapseToggle?.(i, false)}\n aria-label=\"Expand pane\"\n >\n <span class=\"collapse-icon\">{direction === 'horizontal' ? '▸' : '▾'}</span>\n </button>\n {:else}\n {#if onCollapseToggle && canCollapse(i)}\n <button\n type=\"button\"\n class=\"collapse-header expanded\"\n class:horizontal={direction === 'horizontal'}\n class:vertical={direction === 'vertical'}\n data-testid=\"collapse-toggle-{i}\"\n onclick={() => onCollapseToggle?.(i, true)}\n aria-label=\"Collapse pane\"\n >\n <span class=\"collapse-icon\">{direction === 'horizontal' ? '◂' : '▴'}</span>\n </button>\n {/if}\n <div class=\"pane-content\">\n {@render pane(i)}\n </div>\n {/if}\n </div>\n {#if i < count - 1}\n <!-- svelte-ignore a11y_no_static_element_interactions -->\n <div\n class=\"splitter-handle\"\n class:dragging={drag?.handleIndex === i}\n class:disabled={isCollapsed(i) || isCollapsed(i + 1)}\n class:frozen={isHandleFrozen(i)}\n data-testid=\"splitter-handle-{i}\"\n onpointerdown={(e) => beginDrag(e, i)}\n onpointermove={moveDrag}\n onpointerup={endDrag}\n onpointercancel={endDrag}\n ondblclick={() => {\n if (isHandleFrozen(i)) return;\n if (!canCollapse(i) && !isCollapsed(i)) return;\n onCollapseToggle?.(i, !isCollapsed(i));\n }}\n role=\"separator\"\n aria-orientation={direction === 'horizontal' ? 'vertical' : 'horizontal'}\n ></div>\n {/if}\n {/each}\n</div>\n\n<style>\n .splitter {\n display: flex;\n width: 100%;\n height: 100%;\n min-width: 0;\n min-height: 0;\n }\n .splitter.horizontal { flex-direction: row; }\n .splitter.vertical { flex-direction: column; }\n\n .splitter-pane {\n position: relative;\n min-width: 0;\n min-height: 0;\n overflow: hidden;\n display: flex;\n }\n .horizontal > .splitter-pane { flex-direction: row; }\n .vertical > .splitter-pane { flex-direction: column; }\n .splitter-pane.collapsed {\n overflow: visible;\n }\n .pane-content {\n flex: 1 1 0;\n position: relative;\n min-width: 0;\n min-height: 0;\n overflow: hidden;\n }\n\n .collapse-header {\n appearance: none;\n flex: 0 0 auto;\n display: flex;\n align-items: center;\n justify-content: center;\n background: var(--shell-grad-bg-elevated, var(--shell-bg-elevated));\n border: none;\n color: var(--shell-fg-muted);\n cursor: pointer;\n padding: 0;\n font-size: 10px;\n }\n .collapse-header:hover {\n color: var(--shell-fg);\n background: var(--shell-accent-muted);\n }\n /* Suppress misleading hover feedback during drag-reorganize. */\n :global(body[data-dragging]) .collapse-header {\n pointer-events: none;\n }\n .collapse-header.horizontal {\n width: 100%;\n height: 100%;\n writing-mode: vertical-rl;\n }\n .collapse-header.vertical {\n width: 100%;\n height: 100%;\n }\n .collapse-header.expanded.horizontal {\n width: 16px;\n height: 100%;\n border-right: 1px solid var(--shell-border);\n }\n .collapse-header.expanded.vertical {\n width: 100%;\n height: 16px;\n border-bottom: 1px solid var(--shell-border);\n }\n\n .splitter-handle {\n flex: 0 0 auto;\n background: var(--shell-border);\n transition: background-color 120ms ease;\n touch-action: none;\n }\n .splitter-handle:hover,\n .splitter-handle.dragging {\n background: var(--shell-accent);\n }\n :global(body[data-dragging]) .splitter-handle {\n pointer-events: none;\n }\n .splitter-handle.disabled {\n cursor: default;\n pointer-events: none;\n }\n .splitter-handle.frozen {\n cursor: default;\n pointer-events: none;\n background: var(--shell-border);\n opacity: 0.5;\n }\n .splitter-handle.frozen:hover {\n background: var(--shell-border);\n }\n\n .horizontal > .splitter-handle {\n width: 4px;\n cursor: col-resize;\n }\n .vertical > .splitter-handle {\n height: 4px;\n cursor: row-resize;\n }\n .horizontal > .splitter-handle.frozen { width: 1px; }\n .vertical > .splitter-handle.frozen { height: 1px; }\n</style>\n","<script lang=\"ts\" module>\n /**\n * Controller plugged in by a layout-aware parent to turn tab drags\n * into layout mutations. The primitive itself is layout-agnostic:\n * it just calls `onPointerDown` when a tab is grabbed, and asks the\n * controller to hit-test the strip during a drag via `onStripHover`.\n */\n export interface TabDragController {\n onPointerDown(index: number, event: PointerEvent, element: HTMLElement): void;\n onStripHover(\n stripRect: DOMRect,\n pointerX: number,\n pointerY: number,\n tabRects: DOMRect[],\n ): number | null;\n onStripLeave(): void;\n readonly isDragging: boolean;\n }\n\n /**\n * Pure helper: given an insert index and the tab button rects,\n * compute the indicator's position in strip-local coordinates.\n */\n export function computeIndicatorRect(\n insertIndex: number,\n tabEls: (HTMLButtonElement | undefined)[],\n stripEl: HTMLDivElement | undefined,\n ): { left: number; top: number; height: number } | null {\n if (!stripEl) return null;\n const stripRect = stripEl.getBoundingClientRect();\n const els = tabEls.filter((el): el is HTMLButtonElement => !!el);\n if (els.length === 0) {\n return { left: 4, top: 2, height: stripRect.height - 4 };\n }\n const clamped = Math.max(0, Math.min(insertIndex, els.length));\n let leftViewport: number;\n if (clamped === els.length) {\n const last = els[els.length - 1].getBoundingClientRect();\n leftViewport = last.right;\n } else {\n const at = els[clamped].getBoundingClientRect();\n leftViewport = at.left;\n }\n return {\n left: leftViewport - stripRect.left - 1,\n top: 2,\n height: stripRect.height - 4,\n };\n }\n</script>\n\n<script lang=\"ts\">\n /*\n * TabbedPanel — a tab strip over a single active body.\n *\n * Scope: render a strip of tab labels, click to switch active tab,\n * render every tab's body (hiding inactive ones via `display: none`).\n * If a `dragController` is provided, tab pointerdown starts a drag\n * and the strip becomes a drop zone with an insertion indicator.\n *\n * All body snippets are rendered concurrently so every tab's\n * SlotContainer stays alive while the tab is inactive. The\n * re-parenting contract relies on this — see slotHostPool.ts.\n */\n\n import type { Snippet } from 'svelte';\n\n let {\n labels,\n icons,\n body,\n activeTab,\n onActiveChange,\n dragController,\n clickGuard,\n closable,\n dirty,\n onClose,\n tabIds,\n }: {\n labels: string[];\n icons?: (string | undefined)[];\n /** Snippet invoked once per tab with its index. */\n body: Snippet<[number]>;\n activeTab: number;\n /** Called when the user picks a different tab. The parent is\n * expected to write the new value back into whatever it is\n * storing activeTab in. We use a callback rather than a\n * $bindable prop because the parent's activeTab typically lives\n * inside a larger $state object (a LayoutNode), and `bind:` on a\n * sub-property trips Svelte 5's ownership warning. */\n onActiveChange?: (index: number) => void;\n dragController?: TabDragController;\n /** Optional: called by the tab click handler; if it returns true,\n * the click is ignored. Used to swallow the synthetic click that\n * fires on the source tab after a drag commit. */\n clickGuard?: () => boolean;\n /** Per-tab closability. True if the tab can be closed. */\n closable?: (boolean | undefined)[];\n /** Per-tab dirty state. True if the tab has unsaved changes. */\n dirty?: (boolean | undefined)[];\n /** Called when the user clicks a tab's close button. */\n onClose?: (index: number) => void;\n /** Optional stable ids for each tab (e.g. slotId). Used as data-testid suffixes on close buttons. */\n tabIds?: (string | undefined)[];\n } = $props();\n\n function select(i: number) {\n if (clickGuard?.()) return;\n onActiveChange?.(i);\n }\n\n function handleClose(i: number, e: Event) {\n e.stopPropagation(); // Don't also trigger tab selection.\n onClose?.(i);\n }\n\n let stripEl: HTMLDivElement | undefined = $state();\n const tabEls: (HTMLButtonElement | undefined)[] = $state([]);\n let hoverInsertIndex: number | null = $state(null);\n\n function onTabPointerDown(i: number, e: PointerEvent) {\n if (!dragController) return;\n const el = tabEls[i];\n if (!el) return;\n dragController.onPointerDown(i, e, el);\n }\n\n function onStripPointerMove(e: PointerEvent) {\n if (!dragController || !dragController.isDragging || !stripEl) return;\n const stripRect = stripEl.getBoundingClientRect();\n const rects = tabEls\n .filter((el): el is HTMLButtonElement => !!el)\n .map((el) => el.getBoundingClientRect());\n hoverInsertIndex = dragController.onStripHover(stripRect, e.clientX, e.clientY, rects);\n }\n\n function onStripPointerLeave() {\n if (!dragController) return;\n hoverInsertIndex = null;\n dragController.onStripLeave();\n }\n</script>\n\n<div class=\"tabbed-panel\">\n <!-- svelte-ignore a11y_no_static_element_interactions -->\n <div\n class=\"tab-strip\"\n role=\"tablist\"\n tabindex=\"-1\"\n bind:this={stripEl}\n onpointermove={onStripPointerMove}\n onpointerleave={onStripPointerLeave}\n >\n {#each labels as label, i (i)}\n <button\n type=\"button\"\n class=\"tab\"\n class:active={activeTab === i}\n role=\"tab\"\n aria-selected={activeTab === i}\n bind:this={tabEls[i]}\n onclick={() => select(i)}\n onpointerdown={(e) => onTabPointerDown(i, e)}\n onauxclick={(e) => { if (e.button === 1 && closable?.[i]) handleClose(i, e); }}\n >\n {#if dirty?.[i]}\n <span class=\"tab-dirty\" title=\"Unsaved changes\"></span>\n {/if}\n {#if icons?.[i]}<span class=\"tab-icon\">{icons[i]}</span>{/if}\n <span class=\"tab-label\">{label}</span>\n {#if closable?.[i]}\n <span\n class=\"tab-close\"\n role=\"button\"\n tabindex=\"-1\"\n title=\"Close\"\n data-testid={tabIds?.[i] ? `tab-close-${tabIds[i]}` : undefined}\n onclick={(e) => handleClose(i, e)}\n onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') handleClose(i, e); }}\n >&#x2715;</span>\n {/if}\n </button>\n {/each}\n {#if hoverInsertIndex !== null && dragController?.isDragging}\n {@const rect = computeIndicatorRect(hoverInsertIndex, tabEls, stripEl)}\n {#if rect}\n <div\n class=\"drop-indicator\"\n style=\"left: {rect.left}px; height: {rect.height}px; top: {rect.top}px;\"\n ></div>\n {/if}\n {/if}\n </div>\n\n <div class=\"tab-body\" role=\"tabpanel\">\n {#each labels as _label, i (i)}\n <div class=\"tab-body-pane\" class:active={activeTab === i}>\n {@render body(i)}\n </div>\n {/each}\n </div>\n</div>\n\n<style>\n .tabbed-panel {\n display: flex;\n flex-direction: column;\n width: 100%;\n height: 100%;\n min-width: 0;\n min-height: 0;\n background: var(--shell-grad-bg, var(--shell-bg));\n }\n\n .tab-strip {\n position: relative;\n flex: 0 0 auto;\n display: flex;\n gap: 1px;\n background: var(--shell-grad-bg-sunken, var(--shell-bg-sunken));\n border-bottom: 1px solid var(--shell-border);\n padding: 0 var(--shell-pad-sm);\n user-select: none;\n }\n\n .tab {\n appearance: none;\n background: transparent;\n border: none;\n color: var(--shell-fg-muted);\n font: inherit;\n font-size: 12px;\n padding: var(--shell-pad-sm) var(--shell-pad-md);\n margin-top: 2px;\n display: inline-flex;\n align-items: center;\n gap: var(--shell-pad-sm);\n cursor: pointer;\n border-top: 2px solid transparent;\n border-radius: 2px 2px 0 0;\n /* While dragging we still need pointerdown on tabs, but we want\n the browser's native drag image suppressed — PointerEvent path\n doesn't start an HTML5 drag, but preventing text selection here\n avoids spurious selection rectangles during a drag. */\n touch-action: none;\n }\n .tab:hover {\n color: var(--shell-fg);\n background: var(--shell-grad-bg-elevated, var(--shell-bg-elevated));\n }\n .tab.active {\n color: var(--shell-fg);\n background: var(--shell-grad-bg, var(--shell-bg));\n border-top-color: var(--shell-accent);\n }\n .tab-icon { font-size: 11px; }\n .tab-label { white-space: nowrap; }\n\n .tab-dirty {\n width: 8px;\n height: 8px;\n border-radius: 50%;\n background: var(--shell-accent);\n flex-shrink: 0;\n }\n .tab-close {\n display: inline-flex;\n font-size: 10px;\n line-height: 1;\n padding: 2px;\n border-radius: var(--shell-radius-sm);\n color: var(--shell-fg-muted);\n cursor: pointer;\n flex-shrink: 0;\n margin-left: auto;\n }\n .tab-close:hover {\n color: var(--shell-fg);\n background: var(--shell-bg-sunken);\n }\n\n .drop-indicator {\n position: absolute;\n width: 2px;\n background: var(--shell-accent);\n box-shadow: 0 0 6px var(--shell-accent);\n pointer-events: none;\n border-radius: 1px;\n }\n\n .tab-body {\n flex: 1 1 auto;\n position: relative;\n min-width: 0;\n min-height: 0;\n overflow: hidden;\n }\n .tab-body-pane {\n position: absolute;\n inset: 0;\n min-width: 0;\n min-height: 0;\n display: none;\n }\n .tab-body-pane.active {\n display: block;\n }\n</style>\n","<script lang=\"ts\">\n /*\n * SlotContainer — the leaf of the layout tree and the hand-off point\n * between the framework and shard-contributed views.\n *\n * Phase 6 change: the mounted view no longer lives inside this\n * component's own DOM. Instead, the slot host is owned by the\n * `slotHostPool` module and SlotContainer merely attaches (and later\n * releases) the pooled host to its own wrapper. This is what makes\n * drag-to-reorganize survive: when a tab moves, the old SlotContainer\n * tears down and a new one mounts, but the pooled host (and the view\n * mounted into it) is re-parented to the new wrapper without being\n * destroyed. See slotHostPool.ts for the refcount / deferred-destroy\n * details.\n *\n * Responsibilities:\n * 1. Acquire the pooled host for `node.slotId` on mount and append\n * it to the wrapper.\n * 2. Release the pooled host on unmount. The pool decides whether\n * that's a genuine destroy or the first half of a re-parent.\n * 3. If no factory is registered for the viewId (empty slot or the\n * shard providing it hasn't activated yet), render a placeholder\n * in the wrapper alongside the empty host. A local ResizeObserver\n * feeds the placeholder's dimensions readout.\n *\n * The view's own onResize delivery is NOT SlotContainer's job — the\n * pool owns a ResizeObserver on each host that outlives this component\n * across re-parents. See slotHostPool.ts.\n *\n * Note on the placeholder: the pool creates a host even when there is\n * no factory, so the placeholder is layered *on top* of the empty\n * host. That keeps the acquire/release path uniform — phase 7's\n * \"factory registered after layout render\" case will just replace the\n * host's contents without rewriting SlotContainer.\n */\n\n import type { SlotNode } from './types';\n import { getView } from '../shards/registry';\n import { acquireSlotHost, releaseSlotHost } from './slotHostPool.svelte';\n\n let {\n node,\n label = '',\n meta,\n }: { node: SlotNode; label?: string; meta?: Record<string, unknown> } = $props();\n\n let wrapper: HTMLDivElement | undefined = $state();\n let width = $state(0);\n let height = $state(0);\n // Whether a factory is registered — drives the placeholder. The pool\n // owns the actual mount call; we mirror the registry lookup here just\n // to decide whether to show the \"no factory\" hint.\n const hasFactory = $derived(node.viewId ? !!getView(node.viewId) : false);\n\n $effect(() => {\n if (!wrapper) return;\n\n // Capture slotId AND wrapper at effect-run time so the cleanup closure\n // releases the correct slot from the correct wrapper. Both can change\n // before cleanup fires:\n // - node.slotId reads the new value (Svelte updates state before\n // running the effect's cleanup), so we'd release the wrong slot.\n // - the wrapper binding can be re-pointed by Svelte if the component\n // is reused. Capturing locks the release to the wrapper this\n // effect actually appended into — important for the pool's \"only\n // detach if still in our wrapper\" guard.\n const currentSlotId = node.slotId;\n const wrapperEl = wrapper;\n const host = acquireSlotHost(\n currentSlotId,\n node.viewId,\n label || node.viewId || currentSlotId,\n meta,\n );\n wrapperEl.appendChild(host);\n\n // Local observer exists only to drive the placeholder's dims text;\n // the view's own onResize is delivered by the pool.\n const ro = new ResizeObserver((entries) => {\n for (const entry of entries) {\n const box = entry.contentRect;\n width = Math.round(box.width);\n height = Math.round(box.height);\n }\n });\n ro.observe(wrapperEl);\n\n return () => {\n ro.disconnect();\n releaseSlotHost(currentSlotId, wrapperEl);\n };\n });\n</script>\n\n<div\n class=\"slot\"\n data-slot-id={node.slotId}\n data-view-id={node.viewId ?? ''}\n bind:this={wrapper}\n>\n {#if !hasFactory}\n <div class=\"slot-placeholder\">\n <div class=\"slot-id\">{node.slotId}</div>\n <div class=\"slot-meta\">\n {#if node.viewId}\n no factory for <code>{node.viewId}</code>\n {:else}\n <em>empty slot</em>\n {/if}\n </div>\n <div class=\"slot-dims\">{width} × {height}</div>\n </div>\n {/if}\n</div>\n\n<style>\n .slot {\n position: relative;\n width: 100%;\n height: 100%;\n min-width: 0;\n min-height: 0;\n overflow: hidden;\n }\n .slot-placeholder {\n position: absolute;\n inset: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: var(--shell-pad-sm);\n color: var(--shell-fg-muted);\n font-size: 12px;\n text-align: center;\n padding: var(--shell-pad-md);\n background:\n repeating-linear-gradient(\n 45deg,\n var(--shell-bg) 0 10px,\n var(--shell-bg-elevated) 10px 20px\n );\n border: 1px dashed var(--shell-border-strong);\n pointer-events: none;\n }\n .slot-id {\n color: var(--shell-fg);\n font-family: var(--shell-font-mono);\n font-size: 13px;\n }\n .slot-meta code {\n font-family: var(--shell-font-mono);\n color: var(--shell-accent);\n }\n .slot-dims {\n font-family: var(--shell-font-mono);\n color: var(--shell-fg-subtle);\n font-size: 11px;\n }\n</style>\n","/*\n * Tab drag engine — state machine + global listeners + commit.\n *\n * Lifecycle:\n * 1. TabbedPanel fires `beginTabDrag(slotId, entry, pointerEvent)`\n * from pointerdown on a tab. The engine records the starting\n * pointer position and the source slotId but does NOT enter the\n * \"dragging\" phase yet.\n * 2. A global pointermove listener watches for movement exceeding\n * DRAG_THRESHOLD_PX. Clicks that never cross the threshold are\n * not drags — they fall through to the tab's own click handler.\n * 3. On threshold cross, the engine transitions to `dragging` and\n * starts tracking the pointer; the status (visible ghost, drop\n * indicators) is driven by the reactive state.\n * 4. pointerup commits a drop target (if one is currently hovered)\n * and tears down. No commit if the user released over nothing.\n *\n * State shape:\n * The engine exposes a single `dragState` $state object. Components\n * subscribe by reading its fields in a $derived or $effect. The\n * fields:\n * - phase: 'idle' | 'pending' | 'dragging'\n * - source: { slotId, entry } | null\n * - pointer: { x, y } current viewport coords while dragging\n * - target: DropTarget | null — where the commit would land now\n *\n * Drop targets:\n * Two kinds:\n * { kind: 'strip', tabsNode, insertIndex } — between tabs in a strip\n * { kind: 'split', path, side } — quadrant split of a node at path\n * The owning components compute these from their bounding rects and\n * call `setDropTarget` / `clearDropTarget` when the pointer enters /\n * leaves. Multiple overlapping targets: the one most recently set\n * wins (innermost component takes priority because it fires last).\n *\n * Commit:\n * `commit()` is called on pointerup. It looks at dragState.target\n * and runs the appropriate ops mutation against the shared root.\n * The root is handed to the engine on init (via `initDragEngine`)\n * because the engine is a module-level singleton and the root comes\n * from the composition layer.\n */\n\nimport type { LayoutNode, TabEntry, TabsNode, TreeRootRef } from './types';\nimport {\n cleanupTree,\n insertTabIntoTabs,\n moveTabWithinTabs,\n removeTabBySlotId,\n splitNodeAtPath,\n type LayoutPath,\n type SplitSide,\n} from './ops';\nimport { layoutStore } from './store.svelte';\nimport { isEmptyContent } from './floats';\n\nexport type DropTarget =\n | {\n kind: 'strip';\n root: TreeRootRef;\n tabsNode: TabsNode;\n /** Insertion index within tabsNode.tabs (0..length). */\n insertIndex: number;\n }\n | {\n kind: 'split';\n root: TreeRootRef;\n path: LayoutPath;\n side: SplitSide;\n };\n\ninterface DragSource {\n slotId: string;\n entry: TabEntry;\n sourceRoot: TreeRootRef;\n /** The tab's viewport rect at drag start — used to offset the ghost. */\n startRect: DOMRect;\n /** Pointer offset inside the tab at drag start. */\n offsetX: number;\n offsetY: number;\n}\n\ninterface DragState {\n phase: 'idle' | 'pending' | 'dragging';\n source: DragSource | null;\n pointerX: number;\n pointerY: number;\n target: DropTarget | null;\n}\n\nexport const dragState: DragState = $state({\n phase: 'idle',\n source: null,\n pointerX: 0,\n pointerY: 0,\n target: null,\n});\n\n/**\n * True for exactly one macrotask after a drag ends, so the synthetic\n * `click` the browser fires on the original tab (right after\n * pointerup) can be ignored. Consumers check `suppressNextClick()` at\n * the top of their click handler. Without this, the stale click would\n * call the tab's `select(i)` on an index that no longer maps to the\n * same tab after the layout mutation.\n */\nlet clickSuppressedUntil = 0;\nexport function suppressNextClick(): boolean {\n return performance.now() < clickSuppressedUntil;\n}\n\nconst DRAG_THRESHOLD_PX = 4;\n\nlet pendingStartX = 0;\nlet pendingStartY = 0;\n\n/**\n * Begin a potential tab drag. Call from pointerdown on a tab element.\n * This does not yet enter the dragging phase — movement past the\n * threshold is required.\n */\nexport function beginTabDrag(\n slotId: string,\n entry: TabEntry,\n sourceRoot: TreeRootRef,\n event: PointerEvent,\n tabElement: HTMLElement,\n): void {\n if (dragState.phase !== 'idle') return;\n const rect = tabElement.getBoundingClientRect();\n dragState.phase = 'pending';\n dragState.source = {\n slotId,\n entry,\n sourceRoot,\n startRect: rect,\n offsetX: event.clientX - rect.left,\n offsetY: event.clientY - rect.top,\n };\n dragState.pointerX = event.clientX;\n dragState.pointerY = event.clientY;\n dragState.target = null;\n pendingStartX = event.clientX;\n pendingStartY = event.clientY;\n installGlobalListeners();\n}\n\nfunction installGlobalListeners(): void {\n window.addEventListener('pointermove', onPointerMove, true);\n window.addEventListener('pointerup', onPointerUp, true);\n window.addEventListener('pointercancel', onPointerCancel, true);\n // Lock selection / text caret during drag. Restored in teardown.\n document.body.style.userSelect = 'none';\n // Signal to non-drag-aware components that a drag is in progress,\n // so they can suppress misleading hover states via CSS.\n document.body.dataset.dragging = '';\n}\n\nfunction removeGlobalListeners(): void {\n window.removeEventListener('pointermove', onPointerMove, true);\n window.removeEventListener('pointerup', onPointerUp, true);\n window.removeEventListener('pointercancel', onPointerCancel, true);\n document.body.style.userSelect = '';\n delete document.body.dataset.dragging;\n}\n\nfunction onPointerMove(e: PointerEvent): void {\n dragState.pointerX = e.clientX;\n dragState.pointerY = e.clientY;\n\n if (dragState.phase === 'pending') {\n const dx = e.clientX - pendingStartX;\n const dy = e.clientY - pendingStartY;\n if (dx * dx + dy * dy >= DRAG_THRESHOLD_PX * DRAG_THRESHOLD_PX) {\n dragState.phase = 'dragging';\n }\n }\n}\n\nfunction onPointerUp(_e: PointerEvent): void {\n const wasDragging = dragState.phase === 'dragging';\n if (wasDragging) {\n commit();\n // Swallow the synthetic click that fires on the source tab\n // immediately after pointerup. A few ms is plenty — the click\n // is dispatched synchronously or on the next microtask.\n clickSuppressedUntil = performance.now() + 50;\n }\n teardown();\n}\n\nfunction onPointerCancel(_e: PointerEvent): void {\n teardown();\n}\n\nfunction rootNode(ref: TreeRootRef): LayoutNode | null {\n const tree = layoutStore.tree;\n if (ref.kind === 'docked') return tree.docked;\n const f = tree.floats.find((e) => e.id === ref.floatId);\n return f ? f.content : null;\n}\n\n/**\n * If `ref` points at a float whose content is now empty (no bound leaf\n * slots), remove the float from the tree. No-op for docked refs and for\n * floats that still contain a bound view. Called after a commit that\n * removed a tab from a float's content.\n */\nfunction autoCloseEmptyFloat(ref: TreeRootRef): void {\n if (ref.kind !== 'float') return;\n const tree = layoutStore.tree;\n const idx = tree.floats.findIndex((f) => f.id === ref.floatId);\n if (idx < 0) return;\n if (isEmptyContent(tree.floats[idx].content)) {\n tree.floats.splice(idx, 1);\n }\n}\n\nfunction commit(): void {\n const { source, target } = dragState;\n if (!source || !target) return;\n\n const sourceRoot = rootNode(source.sourceRoot);\n const targetRoot = rootNode(target.root);\n if (!sourceRoot || !targetRoot) return;\n\n // Same-group strip drop: atomic move. The two-step remove/insert\n // flow splices the reactive tabs array twice; splice's internal\n // `[[Delete]]` trips Svelte's proxy deleteProperty trap, which can\n // flush reactive consumers while the array is transiently length\n // `N - 1`. A LayoutRenderer `$derived` evaluated in that window\n // sees the shrunk array and the index-`N - 1` snippet body reads an\n // `undefined` entry — which crashes at `.slotId`. `moveTabWithinTabs`\n // avoids the intermediate state by building the next array off-proxy\n // and reassigning `tabs` in one shot. See the helper's doc comment.\n //\n // LayoutRenderer's `onStripHover` normalizes the insert index for\n // same-strip drags into post-removal coordinates, so we can pass\n // `target.insertIndex` straight through.\n if (target.kind === 'strip') {\n const srcIdx = target.tabsNode.tabs.findIndex(\n (t) => t.slotId === source.slotId,\n );\n if (srcIdx >= 0) {\n moveTabWithinTabs(target.tabsNode, srcIdx, target.insertIndex);\n cleanupTree(sourceRoot);\n if (targetRoot !== sourceRoot) cleanupTree(targetRoot);\n autoCloseEmptyFloat(source.sourceRoot);\n return;\n }\n }\n\n // Cross-group strip drop or split drop: remove from SOURCE root, then\n // insert/split into the target.\n const removed = removeTabBySlotId(sourceRoot, source.slotId);\n if (!removed) return;\n\n if (target.kind === 'strip') {\n insertTabIntoTabs(target.tabsNode, removed, target.insertIndex);\n } else {\n splitNodeAtPath(targetRoot, target.path, removed, target.side);\n }\n\n cleanupTree(sourceRoot);\n if (targetRoot !== sourceRoot) cleanupTree(targetRoot);\n autoCloseEmptyFloat(source.sourceRoot);\n}\n\nfunction teardown(): void {\n dragState.phase = 'idle';\n dragState.source = null;\n dragState.target = null;\n removeGlobalListeners();\n}\n\n/**\n * Called by drop zone components when the pointer is over them. The\n * last call wins, so innermost / most-specific zones should call this\n * on pointermove over their geometry. `clearDropTarget` is called when\n * the pointer leaves.\n */\nexport function setDropTarget(target: DropTarget): void {\n if (dragState.phase !== 'dragging') return;\n dragState.target = target;\n}\n\nexport function clearDropTarget(match?: (target: DropTarget) => boolean): void {\n if (dragState.phase !== 'dragging') return;\n if (!dragState.target) return;\n if (match && !match(dragState.target)) return;\n dragState.target = null;\n}\n\n/**\n * Test-only reset. Returns dragState to its idle initial value and\n * removes any pointer listeners attached during a prior drag.\n */\nexport function __resetDragStateForTest(): void {\n removeGlobalListeners();\n dragState.phase = 'idle';\n dragState.source = null;\n dragState.target = null;\n dragState.pointerX = 0;\n dragState.pointerY = 0;\n clickSuppressedUntil = 0;\n pendingStartX = 0;\n pendingStartY = 0;\n}\n","<script lang=\"ts\">\n /*\n * SlotDropZone — an overlay covering a slot's body that, during a\n * drag, reports 4-quadrant split-drop targets to the drag engine\n * and draws a colored quadrant highlight matching the hovered side.\n *\n * Sits in the tab-body pane (for tab leaves) or directly over a\n * standalone slot container. Does not intercept pointer events when\n * no drag is active; during a drag, it captures pointermove to\n * compute the hovered quadrant.\n *\n * Quadrant math:\n * The body is divided into 4 triangles meeting at the center, so\n * each triangle maps the nearest edge to a split side. Top → top\n * split (vertical, new tab above). Same for bottom / left / right.\n * The inner \"center\" region is deliberately absent in phase 6 —\n * we don't support \"merge into same tabs group\" via body drop,\n * only via strip drop. This keeps the UX unambiguous: body = split,\n * strip = merge.\n *\n * Fixed positions:\n * When the SplitNode parent of this zone's path has fixed=true at the\n * relevant index, the zone reports no targets and renders no highlight or\n * hit boxes. The strip drop is computed elsewhere (LayoutRenderer\n * .onStripHover) and is not affected by this guard. See\n * docs/superpowers/specs/2026-04-28-fixed-slot-drop-protection-design.md.\n */\n\n import { dragState, setDropTarget, clearDropTarget, type DropTarget } from './drag.svelte';\n import type { LayoutPath, SplitSide } from './ops';\n import { isPathFixedByParent } from './ops';\n import type { LayoutNode, TreeRootRef } from './types';\n import { layoutStore } from './store.svelte';\n\n let {\n rootRef,\n path,\n }: {\n rootRef: TreeRootRef;\n /** Path of the node this zone covers, used when reporting the drop. */\n path: LayoutPath;\n } = $props();\n\n let zoneEl: HTMLDivElement | undefined = $state();\n let hoveredSide: SplitSide | null = $state(null);\n\n // Don't capture pointer events unless a drag is in progress — otherwise\n // the zone would shadow the slot's own interactions.\n const active = $derived(dragState.phase === 'dragging');\n\n /**\n * True when the parent split of this zone's path has fixed=true at the\n * relevant index. While true, the zone does not report split targets and\n * does not render the quadrant highlight or hit boxes.\n */\n const parentFixed = $derived.by(() => {\n let root: LayoutNode | null;\n if (rootRef.kind === 'docked') {\n root = layoutStore.root;\n } else {\n const entry = layoutStore.tree.floats.find((f) => f.id === rootRef.floatId);\n root = entry?.content ?? null;\n }\n return root ? isPathFixedByParent(root, path) : false;\n });\n\n function quadrantFor(x: number, y: number, rect: DOMRect): SplitSide {\n const cx = rect.left + rect.width / 2;\n const cy = rect.top + rect.height / 2;\n const dx = x - cx;\n const dy = y - cy;\n // Triangles: compare which signed half-plane the point falls in,\n // determined by the cell aspect ratio so the diagonals meet at the\n // center regardless of shape.\n const nx = dx / rect.width;\n const ny = dy / rect.height;\n if (Math.abs(nx) > Math.abs(ny)) {\n return nx < 0 ? 'left' : 'right';\n }\n return ny < 0 ? 'top' : 'bottom';\n }\n\n function onMove(e: PointerEvent) {\n if (!zoneEl) return;\n if (parentFixed) {\n if (hoveredSide !== null) {\n hoveredSide = null;\n clearDropTarget((t) => t.kind === 'split' && t.path.join('/') === path.join('/'));\n }\n return;\n }\n const rect = zoneEl.getBoundingClientRect();\n // If pointer is outside the zone (pointercapture from elsewhere),\n // clear.\n if (\n e.clientX < rect.left ||\n e.clientX > rect.right ||\n e.clientY < rect.top ||\n e.clientY > rect.bottom\n ) {\n if (hoveredSide !== null) {\n hoveredSide = null;\n clearDropTarget((t) => t.kind === 'split' && t.path.join('/') === path.join('/'));\n }\n return;\n }\n const side = quadrantFor(e.clientX, e.clientY, rect);\n if (side !== hoveredSide) {\n hoveredSide = side;\n const target: DropTarget = { kind: 'split', root: rootRef, path: [...path], side };\n setDropTarget(target);\n }\n }\n\n function onLeave() {\n if (hoveredSide !== null) {\n hoveredSide = null;\n clearDropTarget((t) => t.kind === 'split' && t.path.join('/') === path.join('/'));\n }\n }\n</script>\n\n<!-- svelte-ignore a11y_no_static_element_interactions -->\n<div\n class=\"slot-drop-zone\"\n class:active\n class:locked={parentFixed}\n bind:this={zoneEl}\n onpointermove={onMove}\n onpointerleave={onLeave}\n>\n {#if !parentFixed}\n {#if hoveredSide}\n <div class=\"quad-highlight quad-{hoveredSide}\"></div>\n {/if}\n {#if active}\n <div class=\"quad-target quad-left\" data-testid=\"drop-zone-left\"></div>\n <div class=\"quad-target quad-right\" data-testid=\"drop-zone-right\"></div>\n <div class=\"quad-target quad-top\" data-testid=\"drop-zone-top\"></div>\n <div class=\"quad-target quad-bottom\" data-testid=\"drop-zone-bottom\"></div>\n {/if}\n {/if}\n</div>\n\n<style>\n .slot-drop-zone {\n position: absolute;\n inset: 0;\n pointer-events: none;\n }\n .slot-drop-zone.active {\n pointer-events: auto;\n }\n .quad-highlight {\n position: absolute;\n background: var(--shell-accent);\n opacity: 0.18;\n border: 1px dashed var(--shell-accent);\n pointer-events: none;\n transition: inset 80ms ease;\n }\n .quad-highlight.quad-left { top: 0; bottom: 0; left: 0; right: 50%; }\n .quad-highlight.quad-right { top: 0; bottom: 0; left: 50%; right: 0; }\n .quad-highlight.quad-top { left: 0; right: 0; top: 0; bottom: 50%; }\n .quad-highlight.quad-bottom { left: 0; right: 0; top: 50%; bottom: 0; }\n\n /* Invisible hit-target overlays for each quadrant — present only during a\n drag so they don't intercept normal pointer events. These give Playwright\n (and pointer-based UI) a stable target area per side without relying on\n the hover-driven highlight. */\n .quad-target {\n position: absolute;\n pointer-events: none; /* the parent zone handles pointermove */\n }\n .quad-target.quad-left { top: 0; bottom: 0; left: 0; right: 50%; }\n .quad-target.quad-right { top: 0; bottom: 0; left: 50%; right: 0; }\n .quad-target.quad-top { left: 0; right: 0; top: 0; bottom: 50%; }\n .quad-target.quad-bottom { left: 0; right: 0; top: 50%; bottom: 0; }\n</style>\n","<script lang=\"ts\">\n /*\n * LayoutRenderer — recursive walker for a LayoutNode tree.\n *\n * Dispatches on the node kind:\n * split → <ResizableSplitter> with one recursive <Self> per pane\n * tabs → <TabbedPanel> with one <SlotContainer> per tab, a\n * SlotDropZone overlay, and a drag controller wired to\n * the drag engine\n * slot → <SlotContainer> wrapped in a SlotDropZone\n *\n * Props: only `path` — a list of child indices from the root. The\n * node itself is resolved as a $derived from `layoutStore.root` by\n * walking the path. This is how we sidestep Svelte 5's\n * `ownership_invalid_mutation` warning for a recursive component:\n * - Passing `node` as a prop would make every mutation (e.g.\n * `node.activeTab = i`) a write to a child-received prop, which\n * the ownership tracker flags regardless of whether the\n * underlying $state lives in a component or in a module.\n * - Passing only `path` and deriving `node` locally means\n * mutations go through a $derived of module state — no prop is\n * involved, no ownership warning fires.\n *\n * `path` is a plain array, not reactive state, so there is no\n * ownership concern on it. Each recursive call builds a new child\n * path via `[...path, i]`.\n */\n\n import type { TabsNode, LayoutNode, TreeRootRef } from './types';\n import ResizableSplitter from '../primitives/ResizableSplitter.svelte';\n import TabbedPanel, { type TabDragController } from '../primitives/TabbedPanel.svelte';\n import SlotContainer from './SlotContainer.svelte';\n import SlotDropZone from './SlotDropZone.svelte';\n import Self from './LayoutRenderer.svelte';\n import { layoutStore } from './store.svelte';\n import { nodeAtPath } from './ops';\n import { isSlotClosable, isSlotDirty } from './slotHostPool.svelte';\n import { closeTab } from './inspection';\n import {\n dragState,\n beginTabDrag,\n setDropTarget,\n clearDropTarget,\n suppressNextClick,\n } from './drag.svelte';\n\n let {\n path = [],\n rootRef = { kind: 'docked' } as TreeRootRef,\n }: { path?: number[]; rootRef?: TreeRootRef } = $props();\n\n /**\n * Resolve the current node by walking `layoutStore.root` along the\n * path. $derived tracks the reads so Svelte re-runs this when the\n * layout mutates. If the path becomes invalid mid-mutation (a\n * cleanup pass can collapse nodes out from under a recursive\n * renderer), we render null.\n */\n const node = $derived.by(() => {\n let rootNode: LayoutNode | null;\n if (rootRef.kind === 'docked') {\n rootNode = layoutStore.root;\n } else {\n const entry = layoutStore.tree.floats.find((f) => f.id === rootRef.floatId);\n rootNode = entry?.content ?? null;\n }\n return rootNode ? nodeAtPath(rootNode, path) : null;\n });\n\n /**\n * Build a TabDragController bound to the current tabs node.\n * Rebuilt whenever `node` changes identity (mutation can replace\n * the node at this path with a new one during cleanup).\n */\n function makeController(tabsNode: TabsNode): TabDragController {\n return {\n get isDragging() {\n return dragState.phase === 'dragging';\n },\n onPointerDown(index, event, element) {\n const entry = tabsNode.tabs[index];\n if (!entry) return;\n beginTabDrag(entry.slotId, entry, rootRef, event, element);\n },\n onStripHover(stripRect, pointerX, pointerY, tabRects) {\n if (pointerY < stripRect.top || pointerY > stripRect.bottom) {\n clearDropTarget((t) => t.kind === 'strip' && t.tabsNode === tabsNode);\n return null;\n }\n let insertIndex = tabRects.length;\n for (let i = 0; i < tabRects.length; i++) {\n const r = tabRects[i];\n const mid = r.left + r.width / 2;\n if (pointerX < mid) {\n insertIndex = i;\n break;\n }\n }\n // Normalize for same-strip reorder so the engine's commit\n // doesn't double-count the removal shift: if the source tab\n // lives in this strip at index < insertIndex, subtract one.\n const source = dragState.source;\n if (source) {\n const srcIdx = tabsNode.tabs.findIndex((t) => t.slotId === source.slotId);\n if (srcIdx >= 0 && srcIdx < insertIndex) insertIndex -= 1;\n }\n setDropTarget({ kind: 'strip', root: rootRef, tabsNode, insertIndex });\n return insertIndex;\n },\n onStripLeave() {\n clearDropTarget((t) => t.kind === 'strip' && t.tabsNode === tabsNode);\n },\n };\n }\n\n // Narrowing helpers — Svelte templates can't narrow a $derived\n // across block boundaries, so we re-cast inside each branch below.\n // These getters are just there to make the template readable.\n function asSplit(n: LayoutNode) {\n return n.type === 'split' ? n : null;\n }\n function asTabs(n: LayoutNode) {\n return n.type === 'tabs' ? n : null;\n }\n function asSlot(n: LayoutNode) {\n return n.type === 'slot' ? n : null;\n }\n\n /** Build per-tab closable flags from reactive pool state. */\n function tabClosable(tabs: import('./types').TabEntry[]): (boolean | undefined)[] {\n return tabs.map((t) => isSlotClosable(t.slotId) || undefined);\n }\n\n /** Build per-tab dirty flags for TabbedPanel from live pool state. */\n function tabDirty(tabs: import('./types').TabEntry[]): (boolean | undefined)[] {\n return tabs.map((t) => isSlotDirty(t.slotId) || undefined);\n }\n\n /** Handle close button click from TabbedPanel. */\n function handleTabClose(tabs: import('./types').TabEntry[], index: number) {\n const entry = tabs[index];\n if (entry) closeTab(entry.slotId);\n }\n\n /** Svelte action: mount a custom empty renderer into the element. */\n function mountEmptyRenderer(node: HTMLElement, renderer: (el: HTMLElement) => void) {\n renderer(node);\n }\n\n /**\n * Drop handler for empty persistent tab groups. The whole area acts as\n * a single \"insert as first tab\" target — no quadrant splits.\n */\n function onEmptyTabsDrop(_e: PointerEvent, tabsNode: import('./types').TabsNode) {\n if (dragState.phase !== 'dragging') return;\n setDropTarget({ kind: 'strip', root: rootRef, tabsNode, insertIndex: 0 });\n }\n\n function onEmptyTabsLeave() {\n clearDropTarget((t) => t.kind === 'strip' && t.insertIndex === 0);\n }\n</script>\n\n{#if node}\n {#if node.type === 'split'}\n {@const split = asSplit(node)!}\n <ResizableSplitter\n direction={split.direction}\n sizes={split.sizes}\n pinned={split.pinned}\n collapsed={split.collapsed}\n fixed={split.fixed}\n count={split.children.length}\n pane={splitPane}\n onResize={(i, v) => (split.sizes[i] = v)}\n onCollapseToggle={(i, v) => {\n if (!split.collapsed) split.collapsed = split.children.map(() => false);\n split.collapsed[i] = v;\n }}\n />\n {#snippet splitPane(i: number)}\n <Self {rootRef} path={[...path, i]} />\n {/snippet}\n {:else if node.type === 'tabs'}\n {@const tabs = asTabs(node)}\n {#if tabs && tabs.tabs.length > 0}\n {@const controller = makeController(tabs)}\n <TabbedPanel\n labels={tabs.tabs.map((t) => t.label)}\n icons={tabs.tabs.map((t) => t.icon)}\n activeTab={tabs.activeTab}\n onActiveChange={(i) => (tabs.activeTab = i)}\n body={tabBody}\n dragController={controller}\n clickGuard={suppressNextClick}\n closable={tabClosable(tabs.tabs)}\n dirty={tabDirty(tabs.tabs)}\n onClose={(i) => handleTabClose(tabs.tabs, i)}\n tabIds={tabs.tabs.map((t) => t.slotId)}\n />\n {#snippet tabBody(i: number)}\n {@const entry = tabs?.tabs[i]}\n {#if entry}\n <div class=\"tab-slot-wrapper\">\n <SlotContainer\n node={{ type: 'slot', slotId: entry.slotId, viewId: entry.viewId }}\n label={entry.label}\n meta={entry.meta}\n />\n <SlotDropZone {rootRef} path={path} />\n </div>\n {/if}\n {/snippet}\n {:else if tabs?.persistent}\n <div class=\"empty-tabs-placeholder\">\n {#if tabs.emptyRenderer}\n <div class=\"empty-tabs-custom\" use:mountEmptyRenderer={tabs.emptyRenderer}></div>\n {:else}\n <div class=\"empty-tabs-default\">\n <!-- svelte-ignore a11y_no_static_element_interactions -->\n <div\n class=\"empty-tabs-drop\"\n onpointermove={(e) => onEmptyTabsDrop(e, tabs)}\n onpointerleave={onEmptyTabsLeave}\n ></div>\n </div>\n {/if}\n </div>\n {/if}\n {:else}\n {@const slot = asSlot(node)!}\n <div class=\"leaf-slot-wrapper\">\n <SlotContainer node={slot} />\n <SlotDropZone {rootRef} path={path} />\n </div>\n {/if}\n{/if}\n\n<style>\n .tab-slot-wrapper,\n .leaf-slot-wrapper {\n position: absolute;\n inset: 0;\n min-width: 0;\n min-height: 0;\n }\n .empty-tabs-placeholder {\n width: 100%;\n height: 100%;\n min-width: 0;\n min-height: 0;\n position: relative;\n }\n .empty-tabs-default {\n position: absolute;\n inset: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n color: var(--shell-fg-muted);\n font-size: 12px;\n background:\n repeating-linear-gradient(\n 45deg,\n var(--shell-bg) 0 10px,\n var(--shell-bg-elevated) 10px 20px\n );\n border: 1px dashed var(--shell-border-strong);\n }\n .empty-tabs-custom {\n position: absolute;\n inset: 0;\n }\n .empty-tabs-drop {\n position: absolute;\n inset: 0;\n pointer-events: auto;\n }\n</style>\n","<script lang=\"ts\">\n /*\n * DragPreview — the ghost tab rendered on overlay layer 2 during a\n * drag-reorganize gesture.\n *\n * The composition root mounts this component once into the drag-\n * preview layer root. It reads `dragState` and renders itself only\n * while `phase === 'dragging'`. Position tracks `dragState.pointerX`\n * / `pointerY` minus the drag source's initial grab offset, so the\n * ghost appears \"held\" at the same point on the tab where the user\n * started dragging.\n *\n * Pointer events are disabled on the ghost itself — it must not\n * intercept elementsFromPoint checks used by drop zones.\n */\n\n import { dragState } from './drag.svelte';\n\n const visible = $derived(dragState.phase === 'dragging' && !!dragState.source);\n const left = $derived(\n dragState.source ? dragState.pointerX - dragState.source.offsetX : 0,\n );\n const top = $derived(\n dragState.source ? dragState.pointerY - dragState.source.offsetY : 0,\n );\n const width = $derived(dragState.source?.startRect.width ?? 0);\n const height = $derived(dragState.source?.startRect.height ?? 0);\n const label = $derived(dragState.source?.entry.label ?? '');\n const icon = $derived(dragState.source?.entry.icon);\n</script>\n\n{#if visible}\n <div\n class=\"drag-preview\"\n style=\"left: {left}px; top: {top}px; width: {width}px; height: {height}px;\"\n >\n {#if icon}<span class=\"drag-preview-icon\">{icon}</span>{/if}\n <span class=\"drag-preview-label\">{label}</span>\n </div>\n{/if}\n\n<style>\n .drag-preview {\n position: absolute;\n display: inline-flex;\n align-items: center;\n gap: var(--shell-pad-sm);\n padding: var(--shell-pad-sm) var(--shell-pad-md);\n background: var(--shell-grad-bg-elevated, var(--shell-bg-elevated));\n color: var(--shell-fg);\n border: 1px solid var(--shell-accent);\n border-radius: var(--shell-radius-sm);\n box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);\n font-size: 12px;\n font-family: var(--shell-font-ui);\n pointer-events: none;\n opacity: 0.9;\n /* The layer root inherits its z-index from --shell-z-layer-2 via\n Shell.svelte; we don't set z-index here. */\n }\n .drag-preview-icon { font-size: 11px; }\n .drag-preview-label { white-space: nowrap; }\n</style>\n","/*\n * Dismiss-listener registry for dismissable (\"picker\") floats.\n *\n * Each `FloatFrame` whose entry is dismissable registers its root DOM\n * element here on mount and unregisters on destroy. A singleton\n * `pointerdown` listener is installed on `document` as soon as the\n * registry becomes non-empty and removed when it empties.\n *\n * On pointerdown, every registered entry whose element does not contain\n * the event target is closed via floatManager.close. The listener uses\n * capture=true so it runs before any in-view click handlers; the picker's\n * own action handlers fire on `click`/`pointerup` and are unaffected.\n */\n\nimport { floatManager } from './float';\n\nconst registry = new Map<string, HTMLElement>();\nlet listenerAttached = false;\n\nfunction onDocumentPointerDown(event: PointerEvent): void {\n if (registry.size === 0) return;\n const target = event.target as Node | null;\n if (!target) return;\n\n // Snapshot ids — we mutate the registry (via close → unregister) while iterating.\n const ids = Array.from(registry.keys());\n for (const id of ids) {\n const el = registry.get(id);\n if (!el) continue;\n if (!el.contains(target)) {\n floatManager.close(id);\n }\n }\n}\n\nfunction ensureListener(): void {\n if (listenerAttached) return;\n if (typeof document === 'undefined') return;\n document.addEventListener('pointerdown', onDocumentPointerDown, true);\n listenerAttached = true;\n}\n\nfunction teardownListenerIfEmpty(): void {\n if (!listenerAttached) return;\n if (registry.size > 0) return;\n document.removeEventListener('pointerdown', onDocumentPointerDown, true);\n listenerAttached = false;\n}\n\n/** Register a dismissable float's root element. Idempotent per id. */\nexport function registerDismissableFrame(id: string, el: HTMLElement): void {\n registry.set(id, el);\n ensureListener();\n}\n\n/** Unregister on frame destroy. Idempotent; safe to call for unknown ids. */\nexport function unregisterDismissableFrame(id: string): void {\n registry.delete(id);\n teardownListenerIfEmpty();\n}\n\n/** Test-only inspector: is the singleton listener currently attached? */\nexport function __isDismissListenerAttachedForTest(): boolean {\n return listenerAttached;\n}\n\n/** Test-only reset. Clears the registry and detaches the listener. */\nexport function __resetDismissRegistryForTest(): void {\n registry.clear();\n teardownListenerIfEmpty();\n}\n","<!--\n Single floating panel frame.\n\n Renders:\n - Header bar (title + close button, receives pointerdown for drag).\n - Body that mounts the float's content subtree via LayoutRenderer\n using rootRef={{ kind: 'float', floatId: entry.id }} so the\n renderer reads from layoutStore.tree.floats[...].content instead\n of layoutStore.root.\n\n Behavior:\n - Pointer drag on header mutates entry.position in place. The entry\n is a live reference from layoutStore.tree.floats, so mutation\n reactivity flows through the workspace-zone proxy.\n - Click anywhere on the frame raises it (calls floatManager.focus).\n - Close button calls floatManager.close.\n-->\n<script lang=\"ts\">\n import LayoutRenderer from '../layout/LayoutRenderer.svelte';\n import { floatManager, getFloatParentHost } from './float';\n import { registerDismissableFrame, unregisterDismissableFrame } from './floatDismiss';\n import type { FloatEntry } from '../layout/types';\n\n interface Props {\n entry: FloatEntry;\n }\n const { entry }: Props = $props();\n\n let dragging = $state(false);\n let dragOffset = { x: 0, y: 0 };\n let frameEl: HTMLDivElement | undefined = $state();\n\n $effect(() => {\n if (!entry.dismissable) return;\n if (!frameEl) return;\n registerDismissableFrame(entry.id, frameEl);\n return () => unregisterDismissableFrame(entry.id);\n });\n\n // Portal the frame into the anchor's enclosing overlay host when one was\n // resolved at open() time. This puts the frame inside the opener's\n // stacking context — so a picker opened from inside a modal stacks above\n // that modal without writing any z-index. The Svelte component lifecycle\n // is unaffected; we're only relocating the rendered DOM node.\n $effect(() => {\n if (!frameEl) return;\n const host = getFloatParentHost(entry.id);\n if (!host) return;\n const original = frameEl.parentNode;\n host.appendChild(frameEl);\n return () => {\n if (frameEl?.parentNode === host && original) original.appendChild(frameEl);\n };\n });\n\n function onHeaderPointerDown(e: PointerEvent): void {\n if (e.button !== 0) return;\n if ((e.target as HTMLElement).closest('.sh3-float-close')) return;\n const target = e.currentTarget as HTMLElement;\n target.setPointerCapture(e.pointerId);\n dragging = true;\n dragOffset = { x: e.clientX - entry.position.x, y: e.clientY - entry.position.y };\n floatManager.focus(entry.id);\n }\n\n function onHeaderPointerMove(e: PointerEvent): void {\n if (!dragging) return;\n entry.position.x = e.clientX - dragOffset.x;\n entry.position.y = e.clientY - dragOffset.y;\n }\n\n function onHeaderPointerUp(e: PointerEvent): void {\n if (!dragging) return;\n dragging = false;\n const target = e.currentTarget as HTMLElement;\n if (target.hasPointerCapture(e.pointerId)) {\n target.releasePointerCapture(e.pointerId);\n }\n }\n\n function onFrameClick(): void {\n floatManager.focus(entry.id);\n }\n\n function onClose(e: MouseEvent): void {\n e.stopPropagation();\n floatManager.close(entry.id);\n }\n</script>\n\n<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->\n<!-- svelte-ignore a11y_click_events_have_key_events -->\n<div\n class=\"sh3-float-frame\"\n data-shell-overlay-host=\"float\"\n bind:this={frameEl}\n style:left=\"{entry.position.x}px\"\n style:top=\"{entry.position.y}px\"\n style:width=\"{entry.size.w}px\"\n style:height=\"{entry.size.h}px\"\n onclick={onFrameClick}\n role=\"dialog\"\n aria-label={entry.title ?? 'Float panel'}\n tabindex=\"-1\"\n>\n {#if entry.title}\n <!-- svelte-ignore a11y_no_static_element_interactions -->\n <header\n class=\"sh3-float-header\"\n onpointerdown={onHeaderPointerDown}\n onpointermove={onHeaderPointerMove}\n onpointerup={onHeaderPointerUp}\n onpointercancel={onHeaderPointerUp}\n >\n <span class=\"sh3-float-title\">{entry.title}</span>\n <button class=\"sh3-float-close\" onclick={onClose} aria-label=\"Close float\">×</button>\n </header>\n {/if}\n <div class=\"sh3-float-body\">\n <LayoutRenderer rootRef={{ kind: 'float', floatId: entry.id }} path={[]} />\n </div>\n</div>\n\n<style>\n .sh3-float-frame {\n position: absolute;\n display: flex;\n flex-direction: column;\n background: var(--shell-grad-bg-elevated, var(--shell-bg-elevated));\n color: var(--shell-fg);\n border: 1px solid var(--shell-border-strong);\n border-radius: var(--shell-radius);\n box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);\n pointer-events: auto;\n }\n .sh3-float-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 4px 8px;\n background: var(--shell-grad-bg-sunken, var(--shell-bg-sunken));\n cursor: move;\n user-select: none;\n border-bottom: 1px solid var(--shell-border-strong);\n border-top-left-radius: var(--shell-radius);\n border-top-right-radius: var(--shell-radius);\n flex-shrink: 0;\n }\n .sh3-float-title {\n font-size: 12px;\n color: var(--shell-fg);\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n .sh3-float-close {\n background: transparent;\n border: none;\n color: var(--shell-fg);\n font-size: 16px;\n line-height: 1;\n cursor: pointer;\n padding: 0 4px;\n flex-shrink: 0;\n }\n .sh3-float-body {\n flex: 1;\n position: relative;\n overflow: hidden;\n min-height: 0;\n }\n</style>\n","<!--\n Layer 1 overlay root — iterates the active LayoutTree's floats and\n renders a FloatFrame for each. Mounted into the layer-1 DOM root by\n Shell.svelte. Reactivity flows from the workspace-zone proxy through\n layoutStore.floats into this component, so mutations (open, close,\n position changes, reorder) re-render automatically.\n-->\n<script lang=\"ts\">\n import { layoutStore } from '../layout/store.svelte';\n import FloatFrame from './FloatFrame.svelte';\n\n const floats = $derived(layoutStore.floats);\n</script>\n\n<div class=\"sh3-float-layer\">\n {#each floats as entry (entry.id)}\n <FloatFrame {entry} />\n {/each}\n</div>\n\n<style>\n .sh3-float-layer {\n position: absolute;\n inset: 0;\n pointer-events: none;\n /* Children are pointer-events: auto so the layer itself passes through. */\n }\n</style>\n","<script lang=\"ts\">\n /**\n * GuestBanner — persistent bar shown when browsing as guest.\n * Clicking \"Sign in\" opens a modal-like overlay with the sign-in form.\n */\n\n import { isGuest, login } from './index';\n\n let showSignIn = $state(false);\n let username = $state('');\n let password = $state('');\n let error = $state<string | null>(null);\n let loading = $state(false);\n\n async function handleLogin() {\n if (!username.trim() || !password.trim() || loading) return;\n loading = true;\n error = null;\n const result = await login(username.trim(), password.trim());\n loading = false;\n if (result.ok) {\n showSignIn = false;\n } else {\n error = result.error;\n }\n }\n</script>\n\n<div class=\"guest-banner-slot\">\n{#if isGuest()}\n <div class=\"guest-banner\">\n <span class=\"guest-banner-text\">Browsing as guest. Sign in to save your work.</span>\n <button type=\"button\" class=\"guest-banner-action\" onclick={() => { showSignIn = true; }}>\n Sign in\n </button>\n </div>\n\n {#if showSignIn}\n <div class=\"guest-signin-overlay\" role=\"dialog\">\n <div class=\"guest-signin-card\">\n <form class=\"guest-signin-form\" onsubmit={(e) => { e.preventDefault(); handleLogin(); }}>\n <input class=\"guest-signin-input\" type=\"text\" placeholder=\"Username\" bind:value={username} disabled={loading} autocomplete=\"username\" />\n <input class=\"guest-signin-input\" type=\"password\" placeholder=\"Password\" bind:value={password} disabled={loading} autocomplete=\"current-password\" />\n <div class=\"guest-signin-actions\">\n <button type=\"submit\" class=\"guest-signin-btn\" disabled={loading || !username.trim() || !password.trim()}>\n {loading ? 'Signing in...' : 'Sign in'}\n </button>\n <button type=\"button\" class=\"guest-signin-cancel\" onclick={() => { showSignIn = false; error = null; }}>\n Cancel\n </button>\n </div>\n </form>\n {#if error}\n <div class=\"guest-signin-error\">{error}</div>\n {/if}\n </div>\n </div>\n {/if}\n{/if}\n</div>\n\n<style>\n .guest-banner {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 12px;\n padding: 6px var(--shell-pad-md, 12px);\n background: color-mix(in srgb, var(--shell-accent, #7c7cf0) 15%, transparent);\n border-bottom: 1px solid var(--shell-border, #3a3a5c);\n font-size: 12px;\n color: var(--shell-fg, #e0e0e0);\n }\n .guest-banner-action {\n padding: 3px 10px;\n color: var(--shell-bg, #1a1a2e);\n font-size: 11px;\n font-weight: 600;\n }\n .guest-signin-overlay {\n position: fixed;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n background: rgba(0, 0, 0, 0.5);\n z-index: 9999;\n }\n .guest-signin-card {\n display: flex;\n flex-direction: column;\n gap: 12px;\n padding: 32px;\n background: var(--shell-bg-elevated, #252540);\n border: 1px solid var(--shell-border, #3a3a5c);\n border-radius: var(--shell-radius-lg, 12px);\n min-width: 300px;\n }\n .guest-signin-form {\n display: flex;\n flex-direction: column;\n gap: 10px;\n }\n .guest-signin-input {\n padding: 8px 12px;\n background: var(--shell-bg, #1a1a2e);\n color: var(--shell-fg, #e0e0e0);\n border: 1px solid var(--shell-border, #3a3a5c);\n border-radius: var(--shell-radius, 6px);\n font-size: 13px;\n }\n .guest-signin-input::placeholder { color: var(--shell-fg-muted, #888); }\n .guest-signin-actions { display: flex; gap: 8px; }\n .guest-signin-btn {\n flex: 1;\n padding: 8px;\n color: var(--shell-bg, #1a1a2e);\n font-weight: 600;\n }\n .guest-signin-btn:disabled { opacity: 0.6; cursor: not-allowed; }\n .guest-signin-cancel {\n padding: 8px 12px;\n background: transparent;\n color: var(--shell-fg-subtle, #aaa);\n border: 1px solid var(--shell-border, #3a3a5c);\n }\n .guest-signin-error {\n padding: 6px 10px;\n font-size: 12px;\n color: var(--shell-error, #d32f2f);\n background: color-mix(in srgb, var(--shell-error, #d32f2f) 10%, transparent);\n border-radius: var(--shell-radius, 6px);\n }\n</style>\n","<!--\n Shell-owned consent dialog. Listens for consent requests and routes the\n user's Approve/Deny back into the runtime via resolveConsent().\n\n Mounted once by the shell at boot; never by shards.\n\n Security: all shard-provided strings (shardId, label, scope, peerId)\n are rendered as plain text via Svelte's default interpolation — no @html.\n-->\n<script lang=\"ts\">\n import { registerConsentListener, resolveConsent, type ConsentRequest } from './consent.svelte';\n\n let current = $state<ConsentRequest | null>(null);\n\n $effect(() => {\n const off = registerConsentListener((req) => { current = req; });\n return off;\n });\n\n function approve(): void {\n if (!current) return;\n resolveConsent(current.requestId, true);\n current = null;\n }\n\n function deny(): void {\n if (!current) return;\n resolveConsent(current.requestId, false);\n current = null;\n }\n</script>\n\n{#if current}\n <div class=\"sh3-consent-backdrop\" role=\"dialog\" aria-modal=\"true\" aria-label=\"Key creation consent\">\n <div class=\"sh3-consent-card\">\n <h2 class=\"sh3-consent-title\">\n <span>{current.shardId}</span> wants to create a key\n </h2>\n <dl class=\"sh3-consent-fields\">\n <dt>Label</dt>\n <dd>{current.label}</dd>\n <dt>Scopes</dt>\n <dd class=\"sh3-consent-scopes\">\n {#each current.scopes as s (s)}\n <code class=\"sh3-consent-scope\">{s}</code>\n {/each}\n </dd>\n {#if current.peerRole || current.peerId}\n <dt>Peer</dt>\n <dd>{current.peerRole ?? '—'}{current.peerId ? ` · ${current.peerId}` : ''}</dd>\n {/if}\n {#if current.expiresIn}\n <dt>Expires in</dt>\n <dd>{Math.round(current.expiresIn / 1000)}s</dd>\n {/if}\n </dl>\n <div class=\"sh3-consent-actions\">\n <!-- Deny has autofocus — safe default per spec -->\n <!-- svelte-ignore a11y_autofocus -->\n <button type=\"button\" class=\"sh3-consent-deny\" onclick={deny} autofocus>Deny</button>\n <button type=\"button\" class=\"sh3-consent-approve\" onclick={approve}>Approve</button>\n </div>\n </div>\n </div>\n{/if}\n\n<style>\n .sh3-consent-backdrop {\n position: fixed;\n inset: 0;\n background: rgba(0, 0, 0, 0.55);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 9999;\n }\n\n .sh3-consent-card {\n background: var(--shell-bg-elevated, #222);\n color: var(--shell-fg, #eee);\n border: 1px solid var(--shell-border, #444);\n padding: 1.5rem;\n border-radius: 8px;\n min-width: 360px;\n max-width: 520px;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);\n }\n\n .sh3-consent-title {\n margin: 0 0 1rem;\n font-size: 1rem;\n font-weight: 600;\n color: var(--shell-fg, #eee);\n }\n\n .sh3-consent-title span {\n color: var(--shell-accent, #7eb8f7);\n }\n\n .sh3-consent-fields {\n margin: 0 0 1rem;\n display: grid;\n grid-template-columns: auto 1fr;\n column-gap: 0.75rem;\n row-gap: 0.25rem;\n align-items: baseline;\n }\n\n .sh3-consent-fields dt {\n font-weight: 600;\n color: var(--shell-fg-muted, #aaa);\n font-size: 0.8rem;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n padding-top: 0.35rem;\n }\n\n .sh3-consent-fields dd {\n margin: 0;\n padding-top: 0.35rem;\n word-break: break-word;\n }\n\n .sh3-consent-scopes {\n display: flex;\n flex-wrap: wrap;\n gap: 0.25rem;\n }\n\n .sh3-consent-scope {\n display: inline-block;\n padding: 0.1rem 0.35rem;\n background: rgba(255, 255, 255, 0.08);\n border: 1px solid rgba(255, 255, 255, 0.12);\n border-radius: 3px;\n font-size: 0.82em;\n font-family: var(--shell-font-mono, monospace);\n }\n\n .sh3-consent-actions {\n display: flex;\n justify-content: flex-end;\n gap: 0.5rem;\n margin-top: 1.25rem;\n }\n\n .sh3-consent-deny,\n .sh3-consent-approve {\n padding: 0.4rem 1rem;\n border-radius: 4px;\n font-size: 0.875rem;\n cursor: pointer;\n border: 1px solid transparent;\n transition: opacity 0.1s;\n }\n\n .sh3-consent-deny {\n background: transparent;\n color: var(--shell-fg-muted, #aaa);\n border-color: var(--shell-border, #444);\n }\n\n .sh3-consent-deny:hover {\n color: var(--shell-fg, #eee);\n border-color: var(--shell-fg-muted, #aaa);\n }\n\n .sh3-consent-approve {\n background: var(--shell-accent, #7eb8f7);\n color: #000;\n border-color: var(--shell-accent, #7eb8f7);\n }\n\n .sh3-consent-approve:hover {\n opacity: 0.85;\n }\n</style>\n","<script lang=\"ts\">\n /*\n * BrandSlot — top-bar context indicator. Mode resolves from the\n * (activeAppId, breadcrumbAppId, activeProjectId) triple:\n *\n * brand → SH3\n * app → [App Name]\n * breadcrumb → SH3 › [App Name] (clickable app)\n * project-home → SH3 › [Project] (clickable SH3 → exit project)\n * project-app → [Project] › [App] (no SH3 — use home button to exit)\n * project-breadcrumb → SH3 › [Project] › [App] (clickable SH3, project, app)\n */\n import { getLiveDispatcherState } from './actions/state.svelte';\n import { launchApp, returnToHome } from './apps/lifecycle';\n import { getBreadcrumbAppId, getRegisteredApp } from './apps/registry.svelte';\n import { sessionState, setActiveProjectId } from './projects/session-state.svelte';\n import { projectsState } from './projects-shard/projectsShard.svelte';\n\n const activeAppId = $derived(getLiveDispatcherState().activeAppId);\n const breadcrumbId = $derived(getBreadcrumbAppId());\n const projectId = $derived(sessionState.activeProjectId);\n\n const activeLabel = $derived(\n activeAppId ? getRegisteredApp(activeAppId)?.manifest.label ?? activeAppId : null,\n );\n const breadcrumbLabel = $derived(\n breadcrumbId ? getRegisteredApp(breadcrumbId)?.manifest.label ?? breadcrumbId : null,\n );\n const projectLabel = $derived(\n projectId ? projectsState.projects.find((p) => p.id === projectId)?.name ?? projectId : null,\n );\n\n type Mode = 'brand' | 'app' | 'breadcrumb' | 'project-home' | 'project-app' | 'project-breadcrumb';\n\n const mode: Mode = $derived.by(() => {\n if (projectId) {\n if (activeAppId) return 'project-app';\n if (breadcrumbId) return 'project-breadcrumb';\n return 'project-home';\n }\n if (activeAppId) return 'app';\n if (breadcrumbId) return 'breadcrumb';\n return 'brand';\n });\n\n function reopenApp() {\n if (breadcrumbId) void launchApp(breadcrumbId);\n }\n\n function exitProject() {\n setActiveProjectId(null);\n }\n\n function reenterProjectHome() {\n if (activeAppId) void returnToHome();\n }\n</script>\n\n<div class=\"sh3-brand-slot\">\n {#if mode === 'brand'}\n <span class=\"sh3-brand\">SH3</span>\n {:else if mode === 'app'}\n <span class=\"sh3-brand sh3-brand-app\">{activeLabel}</span>\n {:else if mode === 'breadcrumb'}\n <span class=\"sh3-brand\">SH3</span>\n <span class=\"sh3-brand-sep\" aria-hidden=\"true\">›</span>\n <button type=\"button\" class=\"sh3-brand-crumb\" onclick={reopenApp}>{breadcrumbLabel}</button>\n {:else if mode === 'project-home'}\n <button type=\"button\" class=\"sh3-brand sh3-brand-clickable\" onclick={exitProject} title=\"Exit project\">SH3</button>\n <span class=\"sh3-brand-sep\" aria-hidden=\"true\">›</span>\n <span class=\"sh3-brand-project\">{projectLabel}</span>\n {:else if mode === 'project-app'}\n <span class=\"sh3-brand sh3-brand-project\">{projectLabel}</span>\n <span class=\"sh3-brand-sep\" aria-hidden=\"true\">›</span>\n <span class=\"sh3-brand sh3-brand-app\">{activeLabel}</span>\n {:else if mode === 'project-breadcrumb'}\n <button type=\"button\" class=\"sh3-brand sh3-brand-clickable\" onclick={exitProject} title=\"Exit project\">SH3</button>\n <span class=\"sh3-brand-sep\" aria-hidden=\"true\">›</span>\n <button type=\"button\" class=\"sh3-brand-crumb\" onclick={reenterProjectHome}>{projectLabel}</button>\n <span class=\"sh3-brand-sep\" aria-hidden=\"true\">›</span>\n <button type=\"button\" class=\"sh3-brand-crumb\" onclick={reopenApp}>{breadcrumbLabel}</button>\n {/if}\n</div>\n\n<style>\n .sh3-brand-slot {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n }\n .sh3-brand {\n font-weight: 600;\n color: var(--shell-accent);\n letter-spacing: 0.5px;\n }\n .sh3-brand-app {\n color: var(--shell-fg);\n }\n .sh3-brand-project {\n color: var(--shell-fg);\n }\n .sh3-brand-sep {\n color: var(--shell-fg-muted);\n margin: 0 4px;\n }\n .sh3-brand-crumb {\n background: transparent;\n border: 0;\n color: var(--shell-fg);\n font: inherit;\n cursor: pointer;\n padding: 2px 6px;\n border-radius: var(--shell-radius-sm, 3px);\n }\n .sh3-brand-crumb:hover {\n background: var(--shell-bg-elevated);\n }\n .sh3-brand-clickable {\n background: transparent;\n border: 0;\n font: inherit;\n cursor: pointer;\n padding: 2px 6px;\n border-radius: var(--shell-radius-sm, 3px);\n }\n .sh3-brand-clickable:hover {\n background: var(--shell-bg-elevated);\n }\n</style>\n","/*\n * Canonical menu bar containers. Used by the menu bar when the active\n * app does not declare its own `manifest.menus`. Frozen — consumers must\n * not mutate.\n */\nimport type { MenuContainer } from '../apps/types';\n\nexport const DEFAULT_MENU_CONTAINERS: readonly MenuContainer[] = Object.freeze([\n { id: 'file', label: 'File' },\n { id: 'edit', label: 'Edit' },\n { id: 'view', label: 'View' },\n { id: 'window', label: 'Window' },\n { id: 'help', label: 'Help' },\n]);\n","/*\n * Pure model layer for the menu bar: resolves container list for the\n * active app, and resolves per-container item lists by filtering the\n * action registry by `menuItem` + scope-activation. Mirrors the\n * de-duplication semantics of contextMenuModel.\n */\n\nimport type { ActionEntry } from './registry';\nimport type { DispatcherState } from './dispatcher.svelte';\nimport { effectiveShortcut } from './bindings';\nimport { innermostActiveScope } from './scope-helpers';\nimport { resolveLabel } from './types';\nimport type { MenuContainer } from '../apps/types';\nimport { DEFAULT_MENU_CONTAINERS } from './defaultMenuContainers';\n\nexport interface MenuBarItem {\n id: string;\n label: string;\n shortcut: string | null;\n group: string;\n icon: string | undefined;\n /** True iff `Action.checked` evaluates truthy at derive time. */\n checked: boolean;\n /** True iff `Action.disabled` evaluates truthy at derive time. */\n disabled: boolean;\n /** True iff `Action.submenu === true`. */\n submenu: boolean;\n}\n\nfunction evalFlag(v: boolean | (() => boolean) | undefined): boolean {\n if (v === undefined) return false;\n return typeof v === 'function' ? !!v() : !!v;\n}\n\n/**\n * Resolved container list for the currently-active app:\n * - activeAppId == null → returns []\n * - declared has entries → returns declared, sorted by `order`\n * ascending then declaration order\n * for ties / undefined\n * - declared is undefined → returns a copy of DEFAULT_MENU_CONTAINERS\n *\n * Callers can render unconditionally; the empty-array case naturally\n * suppresses the menu bar at home.\n */\nexport function resolveMenuContainers(\n activeAppId: string | null,\n declared: readonly MenuContainer[] | undefined,\n): MenuContainer[] {\n if (activeAppId == null) return [];\n if (declared == null) return DEFAULT_MENU_CONTAINERS.slice();\n const indexed = declared.map((c, i) => ({ c, i }));\n indexed.sort((a, b) => {\n const ao = a.c.order;\n const bo = b.c.order;\n if (ao != null && bo != null) return ao - bo || a.i - b.i;\n if (ao != null) return -1;\n if (bo != null) return 1;\n return a.i - b.i;\n });\n return indexed.map((x) => x.c);\n}\n\n/**\n * Items targeting `containerId`, filtered by current scope activation\n * and de-duplicated to the innermost active scope per action id (mirrors\n * contextMenuModel).\n */\nexport function resolveMenuItems(\n entries: readonly ActionEntry[],\n state: DispatcherState,\n containerId: string,\n): MenuBarItem[] {\n const out: MenuBarItem[] = [];\n const seen = new Set<string>();\n for (const entry of entries) {\n if (entry.action.menuItem !== containerId) continue;\n if (entry.action.submenuOf !== undefined) continue;\n if (seen.has(entry.action.id)) continue;\n const winning = innermostActiveScope(entry.action.scope, state, entry.ownerShardId);\n if (!winning) continue;\n seen.add(entry.action.id);\n out.push({\n id: entry.action.id,\n label: resolveLabel(entry.action),\n shortcut: effectiveShortcut(entry.action, state.bindings, state.platform),\n group: entry.action.group ?? '',\n icon: entry.action.icon,\n checked: evalFlag(entry.action.checked),\n disabled: evalFlag(entry.action.disabled),\n submenu: entry.action.submenu === true,\n });\n }\n return out;\n}\n\n/**\n * Items belonging to a submenu — entries whose `submenuOf` equals\n * `parentId` and whose scope is active. Same `MenuBarItem` shape as\n * top-level container items. Order is registration order, matching the\n * top-level resolver's behavior. De-duplicated by id (multi-scope\n * children resolve to one row, mirroring `resolveMenuItems`).\n */\nexport function resolveSubmenuItems(\n entries: readonly ActionEntry[],\n state: DispatcherState,\n parentId: string,\n): MenuBarItem[] {\n const out: MenuBarItem[] = [];\n const seen = new Set<string>();\n for (const entry of entries) {\n if (entry.action.submenuOf !== parentId) continue;\n if (seen.has(entry.action.id)) continue;\n const winning = innermostActiveScope(entry.action.scope, state, entry.ownerShardId);\n if (!winning) continue;\n seen.add(entry.action.id);\n out.push({\n id: entry.action.id,\n label: resolveLabel(entry.action),\n shortcut: effectiveShortcut(entry.action, state.bindings, state.platform),\n group: entry.action.group ?? '',\n icon: entry.action.icon,\n checked: evalFlag(entry.action.checked),\n disabled: evalFlag(entry.action.disabled),\n submenu: entry.action.submenu === true,\n });\n }\n return out;\n}\n","<script lang=\"ts\">\n /*\n * MenuButton — one menu bar container. A button that opens a popup\n * containing an ActionPanel rendered with this container's items.\n * Items are passed in (the parent MenuBar resolves them via\n * menuBarModel.resolveMenuItems).\n *\n * Submenu drill: when an invoked row's action has `submenu: true`, the\n * button mounts a sibling ActionPanel inside the same popup host (rather\n * than dispatching). popupManager is non-stacking by design, so we\n * intentionally do NOT call popupManager.show again — outside-click on\n * the parent host still closes the entire stack at once.\n */\n import { mount, unmount, type Component } from 'svelte';\n import { popupManager } from '../overlays/popup';\n import type { PopupHandle } from '../overlays/types';\n import ActionPanel, { type ActionPanelSection } from './ActionPanel.svelte';\n import { listActions } from './registry';\n import { getLiveDispatcherState } from './state.svelte';\n import type { DispatcherState } from './dispatcher.svelte';\n import { resolveSubmenuItems, type MenuBarItem } from './menuBarModel';\n import { resolveLabel } from './types';\n import type { MenuContainer } from '../apps/types';\n\n let { container, items }: {\n container: MenuContainer;\n items: MenuBarItem[];\n } = $props();\n\n let buttonEl: HTMLButtonElement | undefined = $state();\n\n function makeSections(list: MenuBarItem[]): ActionPanelSection[] {\n const buckets = new Map<string, MenuBarItem[]>();\n const order: string[] = [];\n for (const item of list) {\n const key = item.group || '';\n if (!buckets.has(key)) {\n buckets.set(key, []);\n order.push(key);\n }\n buckets.get(key)!.push(item);\n }\n return order.map((k) => ({ id: `group:${k || '_default'}`, items: buckets.get(k)! }));\n }\n\n function dispatchLeaf(id: string, state: DispatcherState, handle: PopupHandle) {\n const entry = listActions().find((e) => e.action.id === id);\n if (!entry || typeof entry.action.run !== 'function') return;\n try {\n void entry.action.run({\n action: { id, label: resolveLabel(entry.action) },\n appId: state.activeAppId,\n viewId: state.focusedViewId ?? undefined,\n selection: state.selection ?? undefined,\n invokedVia: 'palette',\n dispatch: () => {},\n });\n } catch (err) {\n console.error(`[sh3] menu-bar action \"${id}\" threw:`, err);\n }\n handle.close();\n }\n\n function openSubmenu(parentId: string, state: DispatcherState, handle: PopupHandle) {\n const root = document.querySelector('.sh3-popup-host') as HTMLElement | null;\n if (!root) return;\n const sub = document.createElement('div');\n sub.className = 'sh3-popup-submenu';\n sub.style.position = 'absolute';\n sub.style.pointerEvents = 'auto';\n const activeRow = root.querySelector('.sh3-ctx-active') as HTMLElement | null;\n const anchorRect = (activeRow ?? root).getBoundingClientRect();\n sub.style.left = `${anchorRect.right + 2}px`;\n sub.style.top = `${anchorRect.top}px`;\n root.appendChild(sub);\n\n const subItems = resolveSubmenuItems(listActions(), state, parentId);\n const subCmp = mount(ActionPanel as unknown as Component<Record<string, unknown>>, {\n target: sub,\n props: {\n sections: makeSections(subItems),\n onInvoke: (cid: string) => dispatchLeaf(cid, state, handle),\n onDismiss: () => {\n unmount(subCmp);\n sub.remove();\n },\n },\n });\n }\n\n function openPopup() {\n if (!buttonEl) return;\n const state = getLiveDispatcherState();\n const handle = popupManager.show(\n ActionPanel,\n { anchor: buttonEl, placement: 'bottom-start' },\n {\n sections: makeSections(items),\n onInvoke: (id: string) => {\n const entry = listActions().find((e) => e.action.id === id);\n if (!entry) return;\n if (entry.action.submenu === true) {\n openSubmenu(id, state, handle);\n return;\n }\n dispatchLeaf(id, state, handle);\n },\n onDismiss: () => popupManager.close(),\n },\n );\n }\n\n const iconPosition = $derived(container.iconPosition ?? 'before');\n</script>\n\n<button\n type=\"button\"\n class=\"sh3-menubar-button\"\n bind:this={buttonEl}\n onclick={openPopup}\n>\n {#if container.icon && iconPosition === 'before'}\n <span class=\"sh3-menubar-icon\" data-icon={container.icon}></span>\n {/if}\n <span class=\"sh3-menubar-label\">{container.label}</span>\n {#if container.icon && iconPosition === 'after'}\n <span class=\"sh3-menubar-icon\" data-icon={container.icon}></span>\n {/if}\n</button>\n\n<style>\n .sh3-menubar-button {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 0 var(--shell-pad-md);\n height: 100%;\n background: transparent;\n color: var(--shell-fg);\n border: 0;\n font: inherit;\n cursor: default;\n }\n .sh3-menubar-button:hover {\n background: var(--shell-bg-elevated);\n }\n .sh3-menubar-icon {\n width: 14px;\n height: 14px;\n display: inline-block;\n }\n</style>\n","<script lang=\"ts\">\n /*\n * MenuBar — top-bar row of menu containers. Renders one MenuButton per\n * container in the active app's manifest.menus (or DEFAULT_MENU_CONTAINERS\n * fallback). Skips containers whose resolved item list is empty.\n * Renders nothing when no app is active.\n */\n import MenuButton from './MenuButton.svelte';\n import { resolveMenuContainers, resolveMenuItems } from './menuBarModel';\n import { getLiveDispatcherState } from './state.svelte';\n import { listActions } from './registry';\n import { getRegisteredApp } from '../apps/registry.svelte';\n\n // Snapshot the live dispatcher state on each derive — `getLiveDispatcherState`\n // reads from $state internals, so this re-derives whenever activeAppId, focus,\n // bindings, or selection change. Mirrors the listeners.ts call pattern.\n const state = $derived(getLiveDispatcherState());\n const activeAppId = $derived(state.activeAppId);\n\n const declaredMenus = $derived.by(() => {\n if (!activeAppId) return undefined;\n return getRegisteredApp(activeAppId)?.manifest.menus;\n });\n\n const containers = $derived(resolveMenuContainers(activeAppId, declaredMenus));\n\n // Per-container item lists. Recomputes whenever actions or scope state\n // change — same reactivity model as the palette/context menu.\n const containerItems = $derived.by(() => {\n const out: { container: typeof containers[number]; items: ReturnType<typeof resolveMenuItems> }[] = [];\n const entries = listActions();\n for (const c of containers) {\n const items = resolveMenuItems(entries, state, c.id);\n if (items.length > 0) out.push({ container: c, items });\n }\n return out;\n });\n</script>\n\n<!--\n Always render the wrapper so it reliably occupies its 1fr grid cell\n in the shell tabbar (and pushes user chrome to the rightmost column).\n Empty when no app is active or no container has visible items.\n-->\n<div class=\"sh3-menubar\" role=\"menubar\">\n {#each containerItems as { container, items } (container.id)}\n <MenuButton {container} {items} />\n {/each}\n</div>\n\n<style>\n .sh3-menubar {\n display: inline-flex;\n align-items: center;\n height: 100%;\n }\n</style>\n","<script lang=\"ts\">\n /*\n * <Shell> — top-level chrome component.\n *\n * Owns the tab bar, status bar, docked content area (layer 0), and the\n * six overlay roots (layers 1-6). This is a stub implementation for\n * phase 1: the content area is empty and the overlay roots are present\n * but unmanaged. Layout tree rendering arrives in phase 2; overlay layer\n * managers arrive in phase 5.\n *\n * The six overlay roots are mounted here (not lazily) so that layer\n * managers in later phases have stable DOM targets to portal into.\n */\n\n import './tokens.css';\n import './primitives/base.css';\n import LayoutRenderer from './layout/LayoutRenderer.svelte';\n import DragPreview from './layout/DragPreview.svelte';\n import FloatLayer from './overlays/FloatLayer.svelte';\n import type { OverlayLayer } from './overlays/types';\n import { registerLayerRoot, unregisterLayerRoot } from './overlays/roots';\n import { bindFloatStore, unbindFloatStore } from './overlays/float';\n import { returnToHome, isAdmin } from './api';\n import { getActiveRoot, layoutStore } from './layout/store.svelte';\n import { syncMountedViewIdsFromLayout } from './actions/state.svelte';\n import { isAuthenticated, isLocalOwner, getUser, logout } from './auth/index';\n import iconsUrl from './assets/icons.svg';\n import GuestBanner from './auth/GuestBanner.svelte';\n import ConsentDialog from './keys/ConsentDialog.svelte';\n import { startServerSideStream } from './keys/revocation-bus.svelte';\n import BrandSlot from './BrandSlot.svelte';\n import MenuBar from './actions/MenuBar.svelte';\n\n const authenticated = $derived(isAuthenticated());\n const user = $derived(getUser());\n const elevated = $derived(isAdmin());\n // True when the layout manager is rendering the home root. We can't use\n // getActiveApp() here: returnToHome() keeps the app warm (activeApp.id\n // stays set) and only flips the layout store's activeRoot back to 'home'.\n const onHome = $derived(getActiveRoot() === 'home');\n\n // Layer metadata — order matches the stack in docs/design/layout.md.\n // Index 0 here is layer 1 (floating panels); layer 0 is the content area.\n const overlayLayers: { layer: number; name: OverlayLayer }[] = [\n { layer: 1, name: 'floating' },\n { layer: 2, name: 'drag-preview' },\n { layer: 3, name: 'popup' },\n { layer: 4, name: 'modal' },\n { layer: 5, name: 'toast' },\n { layer: 6, name: 'command' },\n ];\n\n // Populated by bind:this during render; registered with the overlay\n // module via $effect after mount so layer managers (shell.modal,\n // shell.popup, shell.toast) can find their target DOM roots.\n const overlayRoots: Partial<Record<OverlayLayer, HTMLDivElement>> = $state({});\n\n $effect(() => {\n for (const { name } of overlayLayers) {\n const el = overlayRoots[name];\n if (el) registerLayerRoot(name, el);\n }\n return () => {\n for (const { name } of overlayLayers) unregisterLayerRoot(name);\n };\n });\n\n $effect(() => {\n const tree = layoutStore.tree;\n bindFloatStore(tree.floats, () => ({\n w: window.innerWidth,\n h: window.innerHeight,\n }));\n return () => unbindFloatStore();\n });\n\n // Keep the actions dispatcher's `mountedViewIds` set in sync with the\n // live layout tree, so `view:<viewId>` scope checks (context menu,\n // palette, keyboard) see currently-mounted views. Deep Svelte 5\n // reactivity means this re-runs on any tree mutation.\n $effect(() => {\n void layoutStore.tree;\n syncMountedViewIdsFromLayout();\n });\n\n // Open the server-sent events stream for key revocations.\n // Forwards server-side revocations to the local revocation bus so that\n // onKeyRevoked fires on the owning shard even when the user revokes from\n // the Keys & Peers shell view (not via the shard's own ctx.keys.revoke).\n //\n // Gated on isAuthenticated() because /api/keys/events requires a tenant\n // (via tenantRequired middleware) — opening it as a guest produces a 401\n // that Firefox surfaces as \"can't establish a connection.\" The effect\n // re-runs on login/logout thanks to currentSession being $state.\n $effect(() => {\n if (!isAuthenticated()) return;\n const stop = startServerSideStream();\n return stop;\n });\n</script>\n\n<div class=\"shell\">\n <header class=\"shell-tabbar\" data-shell-region=\"tabbar\">\n <button\n type=\"button\"\n class=\"shell-tabbar-home-button\"\n onclick={() => returnToHome()}\n disabled={onHome}\n title=\"Home\"\n >\n <svg class=\"shell-tabbar-home-icon\" aria-hidden=\"true\">\n <use href=\"{iconsUrl}#house\" />\n </svg>\n </button>\n <BrandSlot />\n <MenuBar />\n {#if authenticated && user}\n <div class=\"shell-tabbar-user\">\n <span class=\"shell-tabbar-user-name\">{user.displayName}</span>\n <span class=\"shell-tabbar-tag\">{elevated ? 'admin' : 'user'}</span>\n {#if !isLocalOwner()}\n <button\n type=\"button\"\n class=\"shell-tabbar-signout\"\n onclick={() => logout()}\n title=\"Sign out\"\n >\n <svg class=\"shell-tabbar-signout-icon\" aria-hidden=\"true\">\n <use href=\"{iconsUrl}#log-out\" />\n </svg>\n </button>\n {/if}\n </div>\n {/if}\n </header>\n\n <GuestBanner />\n\n <main class=\"shell-content\" data-shell-region=\"content\" data-shell-layer=\"0\">\n <LayoutRenderer />\n </main>\n\n <footer class=\"shell-statusbar\" data-shell-region=\"statusbar\">\n <!-- alpha tag moved to ShellHome title row -->\n </footer>\n\n <!--\n Overlay roots. Each is absolutely positioned over the entire shell with\n pointer-events: none by default; layer managers enable pointer events on\n the specific surfaces they portal in.\n -->\n <div class=\"shell-overlays\" aria-hidden=\"true\">\n {#each overlayLayers as { layer, name } (layer)}\n <div\n class=\"shell-overlay-root\"\n data-shell-overlay={name}\n data-shell-layer={layer}\n style=\"z-index: var(--shell-z-layer-{layer});\"\n bind:this={overlayRoots[name]}\n >\n {#if name === 'floating'}\n <FloatLayer />\n {:else if name === 'drag-preview'}\n <DragPreview />\n {/if}\n </div>\n {/each}\n </div>\n\n <!--\n Shell-owned consent dialog for ctx.keys.mint().\n Mounted unconditionally so the listener is always registered; it renders\n nothing until a shard calls ctx.keys.mint().\n z-index 9999 (inline in the component) keeps it above all overlay layers.\n -->\n <ConsentDialog />\n</div>\n\n<style>\n .shell {\n display: grid;\n grid-template-rows: var(--shell-tabbar-height) auto 1fr var(--shell-statusbar-height);\n height: 100%;\n width: 100%;\n position: relative;\n background: var(--shell-grad-bg, var(--shell-bg));\n color: var(--shell-fg);\n }\n\n .shell-tabbar {\n display: grid;\n grid-template-columns: auto auto 1fr auto;\n align-items: center;\n gap: var(--shell-pad-md);\n padding: 0 var(--shell-pad-md);\n background: var(--shell-grad-bg-elevated, var(--shell-bg-elevated));\n border-bottom: 1px solid var(--shell-border);\n user-select: none;\n }\n\n .shell-content {\n position: relative;\n overflow: hidden;\n background: var(--shell-grad-bg, var(--shell-bg));\n min-width: 0;\n min-height: 0;\n }\n .shell-statusbar {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 0 var(--shell-pad-md);\n background: var(--shell-grad-bg-sunken, var(--shell-bg-sunken));\n border-top: 1px solid var(--shell-border);\n color: var(--shell-fg-muted);\n font-size: 11px;\n user-select: none;\n }\n\n .shell-overlays {\n position: absolute;\n inset: 0;\n pointer-events: none;\n }\n .shell-overlay-root {\n position: absolute;\n inset: 0;\n pointer-events: none;\n }\n\n .shell-tabbar-home-button {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 24px;\n height: 24px;\n padding: 0;\n background: transparent;\n color: var(--shell-fg-muted);\n border: 1px solid var(--shell-border);\n }\n .shell-tabbar-home-button:hover:not(:disabled) {\n color: var(--shell-fg);\n border-color: var(--shell-fg-muted);\n }\n .shell-tabbar-home-button:disabled {\n color: var(--shell-fg-subtle);\n border-color: var(--shell-border);\n cursor: default;\n }\n .shell-tabbar-home-icon {\n width: 14px;\n height: 14px;\n }\n\n .shell-tabbar-user {\n display: flex;\n align-items: center;\n gap: 6px;\n }\n .shell-tabbar-user-name {\n font-size: 12px;\n color: var(--shell-fg-subtle);\n }\n .shell-tabbar-tag {\n font-size: 9px;\n font-weight: 700;\n text-transform: uppercase;\n letter-spacing: 0.08em;\n color: var(--shell-fg-on-accent);\n background: var(--shell-accent);\n padding: 1px 6px;\n border-radius: var(--shell-radius-md);\n }\n .shell-tabbar-signout {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 24px;\n height: 24px;\n padding: 0;\n background: transparent;\n color: var(--shell-fg-muted);\n border: 1px solid var(--shell-border);\n }\n .shell-tabbar-signout:hover {\n color: var(--shell-fg);\n border-color: var(--shell-fg-muted);\n }\n .shell-tabbar-signout-icon {\n width: 14px;\n height: 14px;\n }\n</style>\n","<script lang=\"ts\">\n /**\n * SignInWall — standalone sign-in screen shown before shell boots.\n * Mounted directly to the target element by createShell().\n */\n\n import { login, register } from './index';\n\n interface Props {\n selfRegistration: boolean;\n onSuccess: () => void;\n }\n\n let { selfRegistration, onSuccess }: Props = $props();\n\n let mode = $state<'login' | 'register'>('login');\n let username = $state('');\n let password = $state('');\n let displayName = $state('');\n let error = $state<string | null>(null);\n let loading = $state(false);\n\n async function handleLogin() {\n if (!username.trim() || !password.trim() || loading) return;\n loading = true;\n error = null;\n const result = await login(username.trim(), password.trim());\n loading = false;\n if (result.ok) {\n onSuccess();\n } else {\n error = result.error;\n }\n }\n\n async function handleRegister() {\n if (!username.trim() || !password.trim() || loading) return;\n loading = true;\n error = null;\n const result = await register(\n username.trim(),\n password.trim(),\n displayName.trim() || undefined,\n );\n loading = false;\n if (result.ok) {\n onSuccess();\n } else {\n error = result.error;\n }\n }\n\n function switchMode(m: 'login' | 'register') {\n mode = m;\n error = null;\n }\n</script>\n\n<div class=\"signin-wall\">\n <div class=\"signin-card\">\n <h1 class=\"signin-brand\">SH3</h1>\n\n {#if mode === 'login'}\n <form class=\"signin-form\" onsubmit={(e) => { e.preventDefault(); handleLogin(); }}>\n <input\n class=\"signin-input\"\n type=\"text\"\n placeholder=\"Username\"\n bind:value={username}\n disabled={loading}\n autocomplete=\"username\"\n />\n <input\n class=\"signin-input\"\n type=\"password\"\n placeholder=\"Password\"\n bind:value={password}\n disabled={loading}\n autocomplete=\"current-password\"\n />\n <button type=\"submit\" class=\"signin-btn\" disabled={loading || !username.trim() || !password.trim()}>\n {loading ? 'Signing in...' : 'Sign in'}\n </button>\n </form>\n {#if selfRegistration}\n <button type=\"button\" class=\"signin-link\" onclick={() => switchMode('register')}>\n Create an account\n </button>\n {/if}\n {:else}\n <form class=\"signin-form\" onsubmit={(e) => { e.preventDefault(); handleRegister(); }}>\n <input\n class=\"signin-input\"\n type=\"text\"\n placeholder=\"Username\"\n bind:value={username}\n disabled={loading}\n autocomplete=\"username\"\n />\n <input\n class=\"signin-input\"\n type=\"text\"\n placeholder=\"Display name (optional)\"\n bind:value={displayName}\n disabled={loading}\n />\n <input\n class=\"signin-input\"\n type=\"password\"\n placeholder=\"Password\"\n bind:value={password}\n disabled={loading}\n autocomplete=\"new-password\"\n />\n <button type=\"submit\" class=\"signin-btn\" disabled={loading || !username.trim() || !password.trim()}>\n {loading ? 'Creating...' : 'Create account'}\n </button>\n </form>\n <button type=\"button\" class=\"signin-link\" onclick={() => switchMode('login')}>\n Back to sign in\n </button>\n {/if}\n\n {#if error}\n <div class=\"signin-error\">{error}</div>\n {/if}\n </div>\n</div>\n\n<style>\n .signin-wall {\n position: absolute;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n background: var(--shell-grad-bg, var(--shell-bg, #1a1a2e));\n color: var(--shell-fg, #e0e0e0);\n font-family: system-ui, sans-serif;\n }\n .signin-card {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n padding: 48px 40px;\n background: var(--shell-grad-bg-elevated, var(--shell-bg-elevated, #252540));\n border: 1px solid var(--shell-border, #3a3a5c);\n border-radius: var(--shell-radius-lg, 12px);\n min-width: 320px;\n }\n .signin-brand {\n margin: 0 0 8px;\n font-size: 42px;\n color: var(--shell-accent, #7c7cf0);\n letter-spacing: 2px;\n }\n .signin-form {\n display: flex;\n flex-direction: column;\n gap: 12px;\n width: 100%;\n }\n .signin-input {\n padding: 10px 14px;\n background: var(--shell-bg, #1a1a2e);\n color: var(--shell-fg, #e0e0e0);\n border: 1px solid var(--shell-border, #3a3a5c);\n border-radius: var(--shell-radius, 6px);\n font-size: 14px;\n }\n .signin-input::placeholder {\n color: var(--shell-fg-muted, #888);\n }\n .signin-btn {\n padding: 10px 16px;\n color: var(--shell-bg, #1a1a2e);\n font-weight: 600;\n font-size: 14px;\n }\n .signin-btn:disabled {\n opacity: 0.6;\n cursor: not-allowed;\n }\n .signin-link {\n background: none;\n color: var(--shell-accent, #7c7cf0);\n font-size: 13px;\n padding: 0;\n }\n .signin-link:hover {\n text-decoration: underline;\n }\n .signin-error {\n padding: 8px 12px;\n font-size: 13px;\n color: var(--shell-error, #d32f2f);\n background: color-mix(in srgb, var(--shell-error, #d32f2f) 10%, transparent);\n border-radius: var(--shell-radius, 6px);\n width: 100%;\n text-align: center;\n }\n</style>\n","/*\n * createShell — public factory for booting an SH3 shell.\n *\n * Consumers call this from their own main.ts instead of manually\n * importing registerShard / registerApp / bootstrap / Shell. The\n * factory handles platform detection, boot config, auth gating,\n * registration, bootstrap, and mounting in the correct order.\n */\n\nimport { mount, unmount } from 'svelte';\nimport { Shell } from './index';\nimport {\n registerShard,\n registerApp,\n bootstrap,\n __setBackend,\n setLocalOwner,\n} from './host';\nimport type { Shard, App } from './index';\nimport { resolvePlatform } from './platform/index';\nimport { hydrateTokenOverrides } from './theme';\nimport { __setEnvServerUrl } from './env/index';\nimport { __setActiveScope } from './documents/config';\nimport { initFromBoot } from './auth/index';\nimport type { BootConfig } from './auth/types';\nimport SignInWall from './auth/SignInWall.svelte';\nimport { loadBundleModule } from './registry/loader';\nimport { registerLoadedBundle } from './registry/register';\nimport { attachGlobalListeners } from './actions/listeners';\n\nexport interface ShellConfig {\n /** Framework shard IDs to exclude (all included by default) */\n excludeShards?: string[];\n /** Additional shards to register */\n shards?: Shard[];\n /** Additional apps to register */\n apps?: App[];\n /**\n * Packages discovered by the server at boot.\n * The frontend fetches this list from /api/packages and passes it here.\n */\n discoveredPackages?: Array<{\n id: string;\n type: string;\n version: string;\n bundleUrl: string;\n sourceRegistry?: string;\n contractVersion?: string;\n }>;\n /** Mount target — CSS selector or element (defaults to '#app') */\n target?: string | HTMLElement;\n /** Server base URL ('' for same-origin) */\n serverUrl?: string;\n}\n\nexport async function createShell(config?: ShellConfig): Promise<void> {\n const sUrl = config?.serverUrl ?? '';\n\n // 1. Platform detection\n const platform = await resolvePlatform();\n if (platform.backends) {\n __setBackend('workspace', platform.backends.workspace);\n __setBackend('user', platform.backends.user);\n }\n if (platform.localOwner) {\n setLocalOwner();\n }\n\n __setEnvServerUrl(sUrl);\n hydrateTokenOverrides();\n\n // 2. Resolve mount target early (needed for both sign-in wall and shell)\n const target =\n typeof config?.target === 'string'\n ? document.querySelector(config.target)\n : config?.target ?? document.getElementById('app');\n if (!target) {\n throw new Error('SH3: mount target not found');\n }\n\n // 3. Fetch boot config (skip for local-owner platforms like Tauri/dev)\n let bootConfig: BootConfig | null = null;\n if (!platform.localOwner) {\n try {\n const res = await fetch(`${sUrl}/api/boot`, { credentials: 'include' });\n if (res.ok) {\n bootConfig = await res.json();\n }\n } catch {\n // Server unreachable — boot without auth (offline mode)\n }\n }\n\n // 4. Auth decision point\n if (platform.localOwner) {\n // Local-owner (Tauri/dev): no auth, no sign-in, scope is 'local'.\n // setLocalOwner() already called above — admin is assumed.\n __setActiveScope('local');\n } else if (bootConfig) {\n initFromBoot(sUrl, bootConfig);\n __setActiveScope(bootConfig.tenantId);\n\n const { auth, session } = bootConfig;\n\n // Hard gate: no session, auth required, no guest allowed → sign-in wall\n if (!session && auth.required && !auth.guestAllowed) {\n await showSignInWall(target as HTMLElement, bootConfig);\n // After successful sign-in, re-fetch boot config\n const res = await fetch(`${sUrl}/api/boot`, { credentials: 'include' });\n if (res.ok) {\n bootConfig = await res.json();\n initFromBoot(sUrl, bootConfig!);\n __setActiveScope(bootConfig!.tenantId);\n }\n }\n }\n\n // 5. Load server-discovered packages\n if (config?.discoveredPackages?.length) {\n for (const pkg of config.discoveredPackages) {\n try {\n const res = await fetch(pkg.bundleUrl);\n if (!res.ok) {\n console.warn(`[sh3] Failed to fetch discovered package \"${pkg.id}\": HTTP ${res.status}`);\n continue;\n }\n const bytes = await res.arrayBuffer();\n const loaded = await loadBundleModule(bytes);\n registerLoadedBundle(loaded, {\n version: pkg.version,\n sourceRegistry: pkg.sourceRegistry ?? '',\n contractVersion: pkg.contractVersion ?? '',\n });\n console.log(`[sh3] Loaded discovered package: ${pkg.id}`);\n } catch (err) {\n console.warn(`[sh3] Failed to load discovered package \"${pkg.id}\":`, err);\n }\n }\n }\n\n // 6. Register consumer-provided shards and apps\n if (config?.shards) {\n for (const shard of config.shards) registerShard(shard);\n }\n if (config?.apps) {\n for (const app of config.apps) registerApp(app);\n }\n\n // 7. Bootstrap\n const bootstrapConfig: { excludeShards?: string[] } = {};\n if (config?.excludeShards) bootstrapConfig.excludeShards = config.excludeShards;\n await bootstrap(bootstrapConfig);\n\n // 8. Attach document-level keyboard / focus listeners\n attachGlobalListeners();\n\n // 9. Mount the shell\n mount(Shell, { target });\n}\n\n/**\n * Show the sign-in wall and wait until the user authenticates.\n * Returns a promise that resolves after successful login.\n */\nfunction showSignInWall(\n target: HTMLElement,\n bootConfig: BootConfig,\n): Promise<void> {\n return new Promise((resolve) => {\n const instance = mount(SignInWall, {\n target,\n props: {\n selfRegistration: bootConfig.auth.selfRegistration,\n onSuccess: () => {\n unmount(instance);\n resolve();\n },\n },\n });\n });\n}\n","import { createShell, __setDocumentBackend, __setEnvServerUrl } from 'sh3-core/host';\nimport { HttpDocumentBackend } from 'sh3-core/host';\nimport 'sh3-core/tokens.css';\n\nconst serverUrl = window.location.origin;\n\n// Configure env state to use this server.\n__setEnvServerUrl(serverUrl);\n\n// Configure document backend — tenantId is now set by createShell\n// from the boot config, not hardcoded here.\n__setDocumentBackend(new HttpDocumentBackend(serverUrl));\n\n// Fetch server-discovered packages\nlet discoveredPackages: Array<{ id: string; type: string; version: string; bundleUrl: string; sourceRegistry?: string; contractVersion?: string }> = [];\ntry {\n const res = await fetch('/api/packages');\n if (res.ok) discoveredPackages = await res.json();\n} catch {\n // Server may not be available (e.g. standalone build)\n}\n\nawait createShell({ discoveredPackages, serverUrl });\n"],"file":"assets/index-DmBBvfu7.js"}